Skip to content

A full-featured download manager.

fix(downloads): stabilize task controls and completion display (#2100)

Dr_rOotbd2ee38b50cb
diff --git a/e2e/downloads-visibility.spec.ts b/e2e/downloads-visibility.spec.ts
new file mode 100644
index 00000000..7c27c310
--- /dev/null
+++ b/e2e/downloads-visibility.spec.ts
@@ -0,0 +1,157 @@
+import type { ElectronApplication, Locator } from '@playwright/test'
+import { Events } from '@shared/protocol/events'
+import { type DownloadTask, TaskStatus } 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'
+
+function makeTasks(count: number): DownloadTask[] {
+ return Array.from({ length: count }, (_, index) => {
+ const active = index >= count - 4
+ return makeDownloadTask({
+ id: `visibility-${index}`,
+ name: `${active ? 'Active tail' : 'Completed history'} ${index}.bin`,
+ status: active ? TaskStatus.Downloading : TaskStatus.Completed,
+ progress: active ? 0.995 : 1,
+ totalBytes: 1_000_000,
+ sizeWhenDone: 1_000_000,
+ downloadedBytes: active ? 995_000 : 1_000_000,
+ downloadSpeed: active ? 64_000 : 0,
+ connections: active ? 1 : 0,
+ fileCount: 1,
+ })
+ })
+}
+
+async function publish(app: ElectronApplication, tasks: DownloadTask[]) {
+ await app.evaluate(
+ ({ webContents }, payload) => {
+ for (const contents of webContents.getAllWebContents()) {
+ if (!contents.isDestroyed())
+ contents.send(payload.channel, payload.tasks)
+ }
+ },
+ { channel: Events.TaskUpdated, tasks }
+ )
+}
+
+async function expectUsable(row: Locator) {
+ await expect(row).toBeVisible()
+ await expect
+ .poll(() =>
+ row.evaluate((element) => {
+ const list = element.closest('[data-testid="virtual-list-container"]')
+ if (!list?.firstElementChild) return false
+ const rect = element.getBoundingClientRect()
+ const viewport = list.getBoundingClientRect()
+ const header = list.firstElementChild!.getBoundingClientRect()
+ const hit = document.elementFromPoint(
+ rect.left + 120,
+ rect.top + rect.height / 2
+ )
+ return (
+ rect.top >= header.bottom - 1 &&
+ rect.bottom <= viewport.bottom + 1 &&
+ hit?.closest('[role="option"]') === element
+ )
+ })
+ )
+ .toBe(true)
+}
+
+for (const { count, width, height, zoom } of [
+ { count: 26, width: 1280, height: 900, zoom: 1 },
+ { count: 200, width: 1000, height: 600, zoom: 1 },
+ { count: 26, width: 1000, height: 667, zoom: 1.5 },
+]) {
+ test(`all downloads keeps tail tasks reachable with ${count} tasks at ${zoom}x DPI`, async ({
+ electronApp,
+ mainWindow,
+ }, testInfo) => {
+ await expect(async () => waitForEngineReady(mainWindow)).toPass({
+ timeout: 30_000,
+ })
+ await setTaskInspectorContentSize(electronApp, mainWindow, width, height)
+ const cdp = await mainWindow.context().newCDPSession(mainWindow)
+ await cdp.send('Emulation.setDeviceMetricsOverride', {
+ width,
+ height,
+ deviceScaleFactor: zoom,
+ mobile: false,
+ })
+ await mainWindow
+ .getByRole('link', { name: 'Downloads', exact: true })
+ .click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ const tasks = makeTasks(count)
+ await publish(electronApp, tasks)
+ await expect(
+ mainWindow.getByText(`${count}/${count}`, { exact: true })
+ ).toBeVisible()
+ const list = mainWindow.getByTestId('virtual-list-container')
+ await list.evaluate((element) => {
+ element.scrollTop = element.scrollHeight
+ })
+ const tail = mainWindow.getByRole('option', {
+ name: new RegExp(`Active tail ${count - 1}\\.bin`),
+ })
+ await expectUsable(tail)
+ await expect(tail).toContainText('99%')
+ await tail.click({ position: { x: 120, y: 24 } })
+ const drawer = mainWindow.getByRole('dialog', {
+ name: 'Downloads',
+ 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 testInfo.attach('all-downloads-with-inspector', {
+ body: await mainWindow.screenshot({ animations: 'disabled' }),
+ contentType: 'image/png',
+ })
+
+ // 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
+ .getByRole('button', { name: 'All Downloads', exact: true })
+ .click()
+ await mainWindow.getByRole('menuitem', { name: /^Active/ }).click()
+ await expectUsable(tail)
+ await mainWindow
+ .getByRole('button', { name: 'Active Downloads', exact: true })
+ .click()
+ await mainWindow.getByRole('menuitem', { name: /^All/ }).click()
+ await expectUsable(tail)
+ await mainWindow.keyboard.press('Escape')
+ await expect(drawer).toHaveCount(0)
+ await expectUsable(tail)
+
+ // Data updates must keep every task reachable without a route change.
+ const added = makeDownloadTask({
+ ...tasks.at(-1)!,
+ id: 'new-tail',
+ name: 'New active tail.bin',
+ })
+ await publish(electronApp, [...tasks, added])
+ await list.evaluate((element) => {
+ element.scrollTop = element.scrollHeight
+ })
+ await expectUsable(
+ mainWindow.getByRole('option', { name: /New active tail\.bin/ })
+ )
+ await expect
+ .poll(() =>
+ mainWindow.evaluate(
+ () => document.documentElement.scrollHeight <= innerHeight
+ )
+ )
+ .toBe(true)
+ })
+}
diff --git a/e2e/fixtures/electron-app.ts b/e2e/fixtures/electron-app.ts
index 3e5bdd56..ac0741c0 100644
--- a/e2e/fixtures/electron-app.ts
+++ b/e2e/fixtures/electron-app.ts
@@ -1,4 +1,4 @@
-import { mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -32,7 +32,10 @@ export const test = base.extend<MotrixFixtures>({
// signature for "no upstream fixtures consumed".
// biome-ignore lint/correctness/noEmptyPattern: playwright fixture signature
userDataDir: async ({}, use) => {
- const dir = await mkdtemp(path.join(tmpdir(), 'motrix-e2e-'))
+ // Finalization rejects symlink ancestors; macOS tmpdir can start at /var.
+ const dir = await realpath(
+ await mkdtemp(path.join(tmpdir(), 'motrix-e2e-'))
+ )
try {
await use(dir)
} finally {
diff --git a/e2e/task-inspector-activity.spec.ts b/e2e/task-inspector-activity.spec.ts
index 6c7b27e0..12a40925 100644
--- a/e2e/task-inspector-activity.spec.ts
+++ b/e2e/task-inspector-activity.spec.ts
@@ -347,7 +347,7 @@ async function presentActiveReference(
test.describe('Task Inspector Activity', () => {
test.setTimeout(180_000)
- test('fits Activity inside the minimum 914 by 672 window without vertical scrolling', async ({
+ test('keeps Activity and the selected download reachable inside the minimum 914 by 672 window', async ({
userDataDir,
}) => {
const { app, page } = await launchSeededApp(userDataDir)
@@ -387,7 +387,51 @@ test.describe('Task Inspector Activity', () => {
})
expect(geometry.overflowY).toBe('auto')
- expect(geometry.scrollHeight).toBeLessThanOrEqual(geometry.clientHeight)
+ expect(geometry.clientHeight).toBeGreaterThan(0)
+ const drawer = page.getByRole('dialog', {
+ name: 'Downloads',
+ 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.
+ 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
+ )
+ )
+ .toBe(true)
+ expect(
+ await page.evaluate(() => document.documentElement.scrollHeight)
+ ).toBeLessThanOrEqual(viewport.height)
expect(geometry.chartFrameLeft).toBeCloseTo(geometry.surfaceInnerLeft, 0)
expect(geometry.chartFrameRight).toBeCloseTo(
geometry.surfaceInnerRight,
diff --git a/e2e/task-lifecycle.spec.ts b/e2e/task-lifecycle.spec.ts
index 1de64bc2..c06a93a8 100644
--- a/e2e/task-lifecycle.spec.ts
+++ b/e2e/task-lifecycle.spec.ts
@@ -72,7 +72,16 @@ test.describe('task lifecycle', () => {
// Body (~4s) + finalize round-trip (rename `.motrix` → final).
await expect
- .poll(async () => (await readTask())?.status, { timeout: 20_000 })
+ .poll(
+ async () => {
+ const task = await readTask()
+ if (task?.status === 'error') {
+ throw new Error(task.errorMessage ?? 'Download failed')
+ }
+ return task?.status
+ },
+ { timeout: 20_000 }
+ )
.toBe('completed')
// Final state checks — fail fast if status flipped to Completed
diff --git a/src/core/engine/aria2/aria2-pause-state.ts b/src/core/engine/aria2/aria2-pause-state.ts
new file mode 100644
index 00000000..124030ba
--- /dev/null
+++ b/src/core/engine/aria2/aria2-pause-state.ts
@@ -0,0 +1,99 @@
+import type { Aria2RawStatus } from './types'
+
+// Graceful BT shutdown can span several polls while tracker requests drain.
+// Bound the optimistic state if the engine never confirms the accepted pause.
+const PAUSE_SETTLE_TIMEOUT_MS = 30_000
+
+interface PendingPause {
+ expiresAt: number
+ confirmedBy?: number
+}
+
+/** Reconcile accepted pauses across single queries and polling multicalls. */
+export class Aria2PauseState {
+ private pending = new Map<string, PendingPause>()
+
+ clear(): void {
+ this.pending.clear()
+ }
+
+ reconcile(
+ method: string,
+ params: unknown[],
+ result: unknown,
+ sequence: number
+ ): unknown {
+ const gid = typeof params[0] === 'string' ? params[0] : undefined
+ switch (method) {
+ case 'aria2.pause':
+ case 'aria2.forcePause':
+ if (gid && result === gid) {
+ this.pending.set(gid, {
+ expiresAt: performance.now() + PAUSE_SETTLE_TIMEOUT_MS,
+ })
+ }
+ break
+ case 'aria2.unpause':
+ case 'aria2.remove':
+ case 'aria2.forceRemove':
+ case 'aria2.removeDownloadResult':
+ if (gid) this.pending.delete(gid)
+ break
+ case 'aria2.unpauseAll':
+ this.clear()
+ break
+ case 'aria2.tellStatus':
+ return this.reconcileStatus(result, sequence, gid)
+ case 'aria2.tellActive':
+ case 'aria2.tellWaiting':
+ case 'aria2.tellStopped':
+ if (Array.isArray(result)) {
+ return result.map((task) => this.reconcileStatus(task, sequence))
+ }
+ }
+ return result
+ }
+
+ private reconcileStatus(
+ result: unknown,
+ sequence: number,
+ requestedGid?: string
+ ): unknown {
+ if (!result || typeof result !== 'object') return result
+ const task = result as Partial<Aria2RawStatus>
+ const gid = task.gid ?? requestedGid
+ if (!gid || !task.status) return result
+ const pause = this.pending.get(gid)
+ if (!pause) return result
+ if (
+ performance.now() >= pause.expiresAt ||
+ task.status === 'error' ||
+ task.status === 'complete' ||
+ task.status === 'removed'
+ ) {
+ this.pending.delete(gid)
+ return result
+ }
+ if (task.status === 'paused') {
+ // Retain confirmation for older requests that are still in flight.
+ pause.confirmedBy = Math.max(pause.confirmedBy ?? 0, sequence)
+ return result
+ }
+ if (pause.confirmedBy !== undefined && sequence > pause.confirmedBy) {
+ // A query newer than the confirming query can observe an external resume.
+ this.pending.delete(gid)
+ return result
+ }
+
+ const paused = { ...task, status: 'paused' }
+ // Preserve key-filtered RPC response shapes and accumulated progress.
+ for (const key of [
+ 'downloadSpeed',
+ 'uploadSpeed',
+ 'connections',
+ ] as const) {
+ if (key in task) paused[key] = '0'
+ }
+ return paused
+ }
+}
diff --git a/src/core/engine/aria2/aria2-rpc-client.test.ts b/src/core/engine/aria2/aria2-rpc-client.test.ts
index 66e93248..e414a4ea 100644
--- a/src/core/engine/aria2/aria2-rpc-client.test.ts
+++ b/src/core/engine/aria2/aria2-rpc-client.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Aria2RpcClient } from './aria2-rpc-client'
import type { JsonRpcProtocol } from './json-rpc-protocol'
import type { WebSocketTransport } from './web-socket-transport'
@@ -76,6 +76,178 @@ describe('Aria2RpcClient', () => {
)
})
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ describe('accepted pause reconciliation', () => {
+ const active = {
+ gid: 'gid1',
+ status: 'active',
+ completedLength: '512',
+ downloadSpeed: '128',
+ uploadSpeed: '64',
+ connections: '3',
+ }
+ const pollCalls = [
+ { method: 'aria2.getGlobalStat', params: [] },
+ { method: 'aria2.tellActive', params: [] },
+ { method: 'aria2.tellWaiting', params: [0, 1000] },
+ ]
+
+ it('keeps a graceful BT pause stable across reconciliation and subsequent polls', async () => {
+ fakeProtocol.nextResult = 'gid1'
+ await client.pause('gid1')
+ fakeProtocol.nextResult = active
+ expect(await client.tellStatus('gid1')).toMatchObject({
+ status: 'paused',
+ completedLength: '512',
+ downloadSpeed: '0',
+ uploadSpeed: '0',
+ connections: '0',
+ })
+
+ for (let tick = 0; tick < 3; tick++) {
+ fakeProtocol.nextResult = [{ numActive: '1' }, [active], []]
+ const result = await client.multicall(pollCalls)
+ expect(result[1]).toEqual([
+ {
+ ...active,
+ status: 'paused',
+ downloadSpeed: '0',
+ uploadSpeed: '0',
+ connections: '0',
+ },
+ ])
+ }
+ expect(active.status).toBe('active')
+ expect(
+ fakeProtocol.calls.some((call) => call.method === 'aria2.forcePause')
+ ).toBe(false)
+ })
+
+ it('shields an older poll after pause confirmation but accepts a later external resume', async () => {
+ const poll = Promise.withResolvers<unknown[]>()
+ vi.spyOn(fakeProtocol, 'multicall').mockReturnValueOnce(poll.promise)
+ const oldPoll = client.multicall(pollCalls)
+ fakeProtocol.nextResult = 'gid1'
+ await client.pause('gid1')
+ fakeProtocol.nextResult = { ...active, status: 'paused' }
+ await client.tellStatus('gid1')
+
+ poll.resolve([{}, [active], []])
+ expect((await oldPoll)[1]).toEqual([
+ expect.objectContaining({ status: 'paused' }),
+ ])
+
+ fakeProtocol.nextResult = [active]
+ expect(await client.tellActive()).toEqual([active])
+ })
+
+ it('does not hide activity when the pause RPC fails', async () => {
+ vi.spyOn(fakeProtocol, 'call').mockRejectedValueOnce(
+ new Error('pause failed')
+ )
+ await expect(client.pause('gid1')).rejects.toThrow('pause failed')
+ fakeProtocol.nextResult = active
+ expect(await client.tellStatus('gid1')).toEqual(active)
+ })
+
+ it('tracks only successful entries in a pause batch', async () => {
+ const failed = { status: 'rejected', reason: new Error('pause failed') }
+ fakeProtocol.nextResult = [{ status: 'fulfilled', value: 'gid1' }, failed]
+ expect(
+ await client.multicallSettled([
+ { method: 'aria2.pause', params: ['gid1'] },
+ { method: 'aria2.pause', params: ['gid2'] },
+ ])
+ ).toEqual(fakeProtocol.nextResult)
+
+ const other = { ...active, gid: 'gid2' }
+ fakeProtocol.nextResult = [
+ { status: 'fulfilled', value: [active, other] },
+ ]
+ expect(
+ await client.multicallSettled([
+ { method: 'aria2.tellActive', params: [] },
+ ])
+ ).toEqual([
+ {
+ status: 'fulfilled',
+ value: [expect.objectContaining({ status: 'paused' }), other],
+ },
+ ])
+ })
+
+ it.each(['error', 'complete', 'removed'])(
+ 'lets %s supersede a pending pause',
+ async (status) => {
+ fakeProtocol.nextResult = 'gid1'
+ await client.pause('gid1')
+ const terminal = { ...active, status }
+ fakeProtocol.nextResult = terminal
+ expect(await client.tellStatus('gid1')).toEqual(terminal)
+ fakeProtocol.nextResult = active
+ expect(await client.tellStatus('gid1')).toEqual(active)
+ }
+ )
+
+ it('releases the pause after a successful resume, retaining it after a rejected resume', async () => {
+ fakeProtocol.nextResult = 'gid1'
+ await client.pause('gid1')
+ vi.spyOn(fakeProtocol, 'call').mockRejectedValueOnce(
+ new Error('still stopping')
+ )
+ await expect(client.unpause('gid1')).rejects.toThrow('still stopping')
+ fakeProtocol.nextResult = active
+ expect(await client.tellStatus('gid1')).toMatchObject({
+ status: 'paused',
+ })
+
+ fakeProtocol.nextResult = 'gid1'
+ await client.unpause('gid1')
+ fakeProtocol.nextResult = active
+ expect(await client.tellStatus('gid1')).toEqual(active)
+ })
+
+ it('expires an unconfirmed pause so a stuck engine cannot remain hidden', async () => {
+ vi.useFakeTimers()
+ fakeProtocol.nextResult = 'gid1'
+ await client.pause('gid1')
+ await vi.advanceTimersByTimeAsync(30_000)
+ fakeProtocol.nextResult = active
+ expect(await client.tellStatus('gid1')).toEqual(active)
+ })
+
+ it('clears pending pauses across engine disconnection', async () => {
+ fakeProtocol.nextResult = 'gid1'
+ await client.pause('gid1')
+ client.disconnect()
+ fakeProtocol.nextResult = active
+ expect(await client.tellStatus('gid1')).toEqual(active)
+ })
+
+ it('preserves partial query fields and leaves other tasks alone', async () => {
+ fakeProtocol.nextResult = 'gid1'
+ await client.pause('gid1')
+ fakeProtocol.nextResult = { status: 'active' }
+ expect(await client.tellStatus('gid1', ['status'])).toEqual({
+ status: 'paused',
+ })
+ fakeProtocol.nextResult = { bitfield: 'ff' }
+ expect(await client.tellStatus('gid1', ['bitfield'])).toEqual({
+ bitfield: 'ff',
+ })
+ const other = { ...active, gid: 'gid2' }
+ fakeProtocol.nextResult = [active, other]
+ expect(await client.tellWaiting(0, 1000)).toEqual([
+ expect.objectContaining({ gid: 'gid1', status: 'paused' }),
+ other,
+ ])
+ })
+ })
+
describe('connect / disconnect', () => {
it('preserves cookie values, boolean types and millisecond expiry in authenticated RPC parameters', async () => {
const cookies = [
diff --git a/src/core/engine/aria2/aria2-rpc-client.ts b/src/core/engine/aria2/aria2-rpc-client.ts
index a47b492d..7e2b6c90 100644
--- a/src/core/engine/aria2/aria2-rpc-client.ts
+++ b/src/core/engine/aria2/aria2-rpc-client.ts
@@ -1,4 +1,5 @@
import type { DownloadCookie } from '../engine-adapter'
+import { Aria2PauseState } from './aria2-pause-state'
import type { JsonRpcProtocol } from './json-rpc-protocol'
import type {
Aria2HistoryCount,
@@ -30,6 +31,8 @@ const SECRET_EXEMPT_METHODS = new Set([
export class Aria2RpcClient {
private notificationHandlers = new Map<string, Set<EventHandler>>()
+ private pauseState = new Aria2PauseState()
+ private requestSequence = 0
constructor(
private transport: WebSocketTransport,
@@ -44,6 +47,7 @@ export class Aria2RpcClient {
// ─── Connection ──────────────────────────────────────────────
async connect(port: number, retries = 10, delayMs = 500): Promise<void> {
+ this.pauseState.clear()
const url = `ws://127.0.0.1:${port}/jsonrpc`
for (let attempt = 0; attempt < retries; attempt++) {
try {
@@ -57,6 +61,7 @@ export class Aria2RpcClient {
}
disconnect(): void {
+ this.pauseState.clear()
this.transport.disconnect()
}
@@ -75,11 +80,13 @@ export class Aria2RpcClient {
return this.secret === '' ? params : [`token:${this.secret}`, ...params]
}
- private call<T>(method: string, params: unknown[]): Promise<T> {
+ private async call<T>(method: string, params: unknown[]): Promise<T> {
+ const sequence = ++this.requestSequence
const finalParams = SECRET_EXEMPT_METHODS.has(method)
? params
: this.withSecret(params)
- return this.protocol.call<T>(method, finalParams)
+ const result = await this.protocol.call<T>(method, finalParams)
+ return this.pauseState.reconcile(method, params, result, sequence) as T
}
// ─── Download management ─────────────────────────────────────
@@ -270,7 +277,8 @@ export class Aria2RpcClient {
// ─── Batch (performance) ─────────────────────────────────────
- multicall(calls: Aria2MethodCall[]): Promise<unknown[]> {
+ async multicall(calls: Aria2MethodCall[]): Promise<unknown[]> {
+ const sequence = ++this.requestSequence
// Each sub-call needs the same secret-injection treatment as a
// single `call()`. Without it aria2 returns `{faultCode:1,
// faultString:"Unauthorized"}` for every entry; the protocol
@@ -283,7 +291,15 @@ export class Aria2RpcClient {
? c.params
: this.withSecret(c.params),
}))
- return this.protocol.multicall(withSecret)
+ const results = await this.protocol.multicall(withSecret)
+ return results.map((result, index) =>
+ this.pauseState.reconcile(
+ calls[index].method,
+ calls[index].params,
+ result,
+ sequence
+ )
+ )
}
/**
@@ -292,16 +308,30 @@ export class Aria2RpcClient {
* Required for any batch of MUTATING calls, where a swallowed fault would
* silently corrupt caller bookkeeping.
*/
- multicallSettled(
+ async multicallSettled(
calls: Aria2MethodCall[]
): Promise<PromiseSettledResult<unknown>[]> {
+ const sequence = ++this.requestSequence
const withSecret = calls.map((c) => ({
method: c.method,
params: SECRET_EXEMPT_METHODS.has(c.method)
? c.params
: this.withSecret(c.params),
}))
- return this.protocol.multicallSettled(withSecret)
+ const results = await this.protocol.multicallSettled(withSecret)
+ return results.map((result, index) =>
+ result.status === 'fulfilled'
+ ? {
+ status: 'fulfilled',
+ value: this.pauseState.reconcile(
+ calls[index].method,
+ calls[index].params,
+ result.value,
+ sequence
+ ),
+ }
+ : result
+ )
}
// ─── SQLite3-Persistence RPCs (aria2_motrix fork) ────────────
diff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.ts
index efcf0e3e..fbb72e2d 100644
--- a/src/core/task/actions/finalize-task.test.ts
+++ b/src/core/task/actions/finalize-task.test.ts
@@ -112,6 +112,81 @@ function buildSingleFileTorrent(name: string): Uint8Array {
}
describe('finalizeTask HTTP/FTP branch', () => {
+ it.each([TaskType.Http, TaskType.Ftp])(
+ 'publishes %s Finalizing with idle transfer metrics before a slow artifact commit',
+ async (type) => {
+ const entered = Promise.withResolvers<void>()
+ const release = Promise.withResolvers<void>()
+ const snapshots: DownloadTask[] = []
+ const task = makeTask({
+ type,
+ totalBytes: 1000,
+ downloadedBytes: 998,
+ progress: 0.998,
+ downloadSpeed: 64000,
+ uploadSpeed: 1000,
+ etaSeconds: 200,
+ connections: 1,
+ instances: [makePrimaryInstance()],
+ })
+ const deps = makeDeps({
+ publishTaskUpdateNow: () => snapshots.push(structuredClone(task)),
+ commitFinalizedArtifact: async () => {
+ entered.resolve()
+ await release.promise
+ },
+ })
+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)
+ const finishing = finalizeTask(task.id, deps)
+ await entered.promise
+ try {
+ expect(snapshots).toHaveLength(1)
+ expect(snapshots[0]).toMatchObject({
+ status: TaskStatus.Finalizing,
+ transitionPhase: TransitionPhase.Renaming,
+ downloadSpeed: 0,
+ uploadSpeed: 0,
+ etaSeconds: 0,
+ connections: 0,
+ progress: 1,
+ downloadedBytes: 1000,
+ finishedAt: null,
+ diskPath: '/d/foo.mp4.motrix',
+ })
+ expect(snapshots[0].instances[0].status).toBe(TaskStatus.Finalizing)
+ expect(
+ deps.activityRecorder.recordDownloadCompleted
+ ).not.toHaveBeenCalled()
+ } finally {
+ release.resolve()
+ await finishing
+ }
+ expect(snapshots.map((value) => value.status)).toEqual([
+ TaskStatus.Finalizing,
+ TaskStatus.Completed,
+ ])
+ expect(task.diskPath).toBe('/d/foo.mp4')
+ expect(
+ deps.activityRecorder.recordDownloadCompleted
+ ).toHaveBeenCalledOnce()
+ }
+ )
+
+ it('does not publish Finalizing or touch files before its state is durable', async () => {
+ const deps = makeDeps()
+ const task = makeTask()
+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)
+ vi.mocked(deps.taskManager.persist).mockRejectedValue(
+ new Error('database busy')
+ )
+ await expect(finalizeTask(task.id, deps)).rejects.toThrow('database busy')
+ expect(task.status).toBe(TaskStatus.Downloading)
+ expect(task.transitionPhase).toBe(TransitionPhase.Idle)
+ expect(deps.eventBus.emit).not.toHaveBeenCalled()
+ expect(deps.adapter.removeDownloadResult).not.toHaveBeenCalled()
+ expect(deps.fs.renameAtomic).not.toHaveBeenCalled()
+ })
+
it('performs removeDownloadResult → rename → status=Completed', async () => {
const deps = makeDeps()
const task = makeTask()
@@ -180,7 +255,7 @@ describe('finalizeTask HTTP/FTP branch', () => {
await finalizeTask('t1', deps)
- expect(publishTaskUpdateNow).toHaveBeenCalledTimes(1)
+ expect(publishTaskUpdateNow).toHaveBeenCalledTimes(2)
expect(publishTaskUpdate).not.toHaveBeenCalled()
expect(deps.eventBus.emit).not.toHaveBeenCalledWith(
Events.TaskUpdated,
@@ -207,7 +282,7 @@ describe('finalizeTask HTTP/FTP branch', () => {
expect.objectContaining({
type: 'terminal',
taskId: 't1',
- fromStatus: TaskStatus.Downloading,
+ fromStatus: TaskStatus.Finalizing,
toStatus: TaskStatus.Completed,
cause: 'finalize',
})
@@ -232,17 +307,18 @@ describe('finalizeTask HTTP/FTP branch', () => {
expect(recordTransition).toHaveBeenCalledWith(
expect.objectContaining({
taskId: 't1',
- previousStatus: TaskStatus.Downloading,
+ previousStatus: TaskStatus.Finalizing,
nextStatus: TaskStatus.Completed,
accuracy: 'exact',
})
)
const completedPersistOrder = persist.mock.invocationCallOrder.at(-1)
expect(completedPersistOrder).toBeLessThan(
- recordTransition.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY
+ recordTransition.mock.invocationCallOrder.at(-1) ??
+ Number.POSITIVE_INFINITY
)
- expect(recordTransition.mock.invocationCallOrder[0]).toBeLessThan(
- emit.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY
+ expect(recordTransition.mock.invocationCallOrder.at(-1)).toBeLessThan(
+ emit.mock.invocationCallOrder.at(-1) ?? Number.POSITIVE_INFINITY
)
})
@@ -262,9 +338,14 @@ describe('finalizeTask HTTP/FTP branch', () => {
await expect(finalizeTask('t1', deps)).rejects.toThrow('database busy')
- expect(deps.recordTransition).not.toHaveBeenCalled()
- expect(deps.eventBus.emit).not.toHaveBeenCalled()
- expect(task.status).toBe(TaskStatus.Downloading)
+ expect(deps.recordTransition).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ nextStatus: TaskStatus.Finalizing })
+ )
+ expect(deps.eventBus.emit).toHaveBeenCalledExactlyOnceWith(
+ Events.TaskUpdated,
+ []
+ )
+ expect(task.status).toBe(TaskStatus.Finalizing)
expect(task.transitionPhase).toBe(TransitionPhase.Renaming)
expect(task.diskPath).toBe('/d/foo.mp4.motrix')
})
@@ -313,7 +394,7 @@ describe('finalizeTask HTTP/FTP branch', () => {
Number.POSITIVE_INFINITY
)
expect(recordDownloadCompleted.mock.invocationCallOrder[0]).toBeLessThan(
- emit.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY
+ emit.mock.invocationCallOrder.at(-1) ?? Number.POSITIVE_INFINITY
)
})
@@ -401,7 +482,7 @@ describe('finalizeTask failure-path publication routing', () => {
await expect(finalizeTask('t1', deps)).rejects.toThrow()
expect(task.status).toBe(TaskStatus.Error)
- expect(publishTaskUpdateNow).toHaveBeenCalledTimes(1)
+ expect(publishTaskUpdateNow).toHaveBeenCalledTimes(2)
expect(publishTaskUpdate).not.toHaveBeenCalled()
})
})
diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.ts
index 26dde58f..ee3a79c6 100644
--- a/src/core/task/actions/finalize-task.ts
+++ b/src/core/task/actions/finalize-task.ts
@@ -216,8 +216,13 @@ async function finalizeHttp(
task: DownloadTask,
deps: FinalizeTaskDeps
): Promise<void> {
+ const statusBeforeFinalize = task.status
+ Object.assign(task, applyTerminalTransition(task, TaskStatus.Finalizing))
setTaskTransitionPhase(task, TransitionPhase.Renaming)
- await persistTaskState(task, deps)
+ syncCompletionMetrics(task)
+ syncPrimaryInstanceIdentity(task)
+ await persistTaskTransition(task, statusBeforeFinalize, deps)
+ deps.publishTaskUpdateNow()
// Plan C plugin-hook chain: beforeFinalize. Eligible plugins can request
// a different final filePath (e.g. ffmpeg-transcode plugin) and stage
diff --git a/src/core/task/normalize-terminal-runtime-metrics.ts b/src/core/task/normalize-terminal-runtime-metrics.ts
index aa20cae0..6a7b5bc9 100644
--- a/src/core/task/normalize-terminal-runtime-metrics.ts
+++ b/src/core/task/normalize-terminal-runtime-metrics.ts
@@ -1,8 +1,8 @@
-import type { DownloadTask } from '@shared/types/task'
+import { type DownloadTask, TaskStatus } from '@shared/types/task'
import { isTerminalTaskStatus } from '@shared/types/task-actions'
/**
- * Clear engine-sampled metrics once a task can no longer transfer data.
+ * Clear engine-sampled metrics after transfer stops, including finalization.
*
* These values are process-local snapshots rather than durable task history.
* Keeping the final polling sample on Completed/Error makes a terminal task
@@ -11,7 +11,10 @@ import { isTerminalTaskStatus } from '@shared/types/task-actions'
* remain live and must continue to be refreshed by engine polling.
*/
export function normalizeTerminalRuntimeMetrics(task: DownloadTask): void {
- if (!isTerminalTaskStatus(task.status)) {
+ if (
+ !isTerminalTaskStatus(task.status) &&
+ task.status !== TaskStatus.Finalizing
+ ) {
return
}
diff --git a/src/core/task/task-manager.test.ts b/src/core/task/task-manager.test.ts
index b37e24d1..9f501f52 100644
--- a/src/core/task/task-manager.test.ts
+++ b/src/core/task/task-manager.test.ts
@@ -51,7 +51,7 @@ describe('TaskManager', () => {
expect(manager.getAll()).toHaveLength(1)
})
- it.each([TaskStatus.Completed, TaskStatus.Error])(
+ it.each([TaskStatus.Finalizing, TaskStatus.Completed, TaskStatus.Error])(
'set clears volatile runtime metrics for %s tasks',
(status) => {
const task = makeTask({
diff --git a/src/main/ipc/commands/reveal-in-folder.test.ts b/src/main/ipc/commands/reveal-in-folder.test.ts
index 45a7ba02..3d90dd97 100644
--- a/src/main/ipc/commands/reveal-in-folder.test.ts
+++ b/src/main/ipc/commands/reveal-in-folder.test.ts
@@ -1,9 +1,33 @@
-import { describe, expect, it, vi } from 'vitest'
+// @vitest-environment node
+
+import { mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createRevealInFolderHandler } from './reveal-in-folder'
+vi.mock('node:fs/promises', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('node:fs/promises')>()),
+ stat: vi.fn(),
+}))
+
+const statMock = vi.mocked(stat)
+const fileStat = { isDirectory: () => false } as Awaited<
+ ReturnType<typeof stat>
+>
+const directoryStat = { isDirectory: () => true } as Awaited<
+ ReturnType<typeof stat>
+>
+const missingPath = () =>
+ Object.assign(new Error('missing'), { code: 'ENOENT' })
+
+beforeEach(() => {
+ statMock.mockReset().mockResolvedValue(fileStat)
+})
+
describe('revealInFolder', () => {
it('reveals the current path owned by the requested task', async () => {
- const shell = { showItemInFolder: vi.fn() }
+ const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }
const handler = createRevealInFolderHandler({
shell,
getTask: (taskId) =>
@@ -23,7 +47,7 @@ describe('revealInFolder', () => {
})
it('hides an indexed BT workspace behind its stable final path', async () => {
- const shell = { showItemInFolder: vi.fn() }
+ const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }
const handler = createRevealInFolderHandler({
shell,
getTask: () => ({
@@ -39,8 +63,133 @@ describe('revealInFolder', () => {
)
})
+ it.each(['direct', 'indexed-bt', 'queued'])(
+ 'opens the destination folder while the %s output is still missing',
+ async (kind) => {
+ const fs =
+ await vi.importActual<typeof import('node:fs/promises')>(
+ 'node:fs/promises'
+ )
+ statMock.mockImplementation(fs.stat)
+ const saveDir = await mkdtemp(path.join(tmpdir(), 'motrix-reveal-'))
+ const finalPath = path.join(saveDir, 'download.iso')
+ const diskPath =
+ kind === 'indexed-bt'
+ ? path.join(saveDir, '.motrix', 'workspace', 'p')
+ : `${finalPath}.motrix`
+ const shell = {
+ showItemInFolder: vi.fn(),
+ openPath: vi.fn(async () => ''),
+ }
+ const handler = createRevealInFolderHandler({
+ shell,
+ getTask: () => ({ diskPath, finalPath }),
+ })
+
+ try {
+ if (kind === 'indexed-bt') await mkdir(diskPath, { recursive: true })
+ else if (kind === 'direct') await writeFile(diskPath, 'partial')
+
+ await handler({ taskId: 'downloading-task' })
+
+ expect(shell.openPath).toHaveBeenCalledExactlyOnceWith(saveDir)
+ expect(shell.showItemInFolder).not.toHaveBeenCalled()
+
+ await writeFile(finalPath, 'complete')
+ shell.openPath.mockClear()
+ await handler({ taskId: 'downloading-task' })
+
+ expect(shell.showItemInFolder).toHaveBeenCalledExactlyOnceWith(
+ finalPath
+ )
+ expect(shell.openPath).not.toHaveBeenCalled()
+ } finally {
+ await rm(saveDir, { recursive: true, force: true })
+ }
+ }
+ )
+
+ it('opens a Windows containing folder when the final output is missing', async () => {
+ statMock
+ .mockRejectedValueOnce(missingPath())
+ .mockResolvedValueOnce(directoryStat)
+ const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }
+ const handler = createRevealInFolderHandler({
+ shell,
+ getTask: () => ({
+ diskPath: 'C:\\Downloads\\file.iso.motrix',
+ finalPath: 'C:\\Downloads\\file.iso',
+ }),
+ })
+
+ await handler({ taskId: 'task-windows' })
+
+ expect(shell.openPath).toHaveBeenCalledExactlyOnceWith('C:\\Downloads')
+ expect(shell.showItemInFolder).not.toHaveBeenCalled()
+ })
+
+ it.each(['missing', 'file', 'denied'])(
+ 'rejects a %s containing folder without launching a file',
+ async (kind) => {
+ statMock.mockRejectedValueOnce(missingPath())
+ if (kind === 'file') statMock.mockResolvedValueOnce(fileStat)
+ else
+ statMock.mockRejectedValueOnce(
+ Object.assign(new Error('unavailable'), {
+ code: kind === 'missing' ? 'ENOENT' : 'EACCES',
+ })
+ )
+ const shell = {
+ showItemInFolder: vi.fn(),
+ openPath: vi.fn(async () => ''),
+ }
+ const handler = createRevealInFolderHandler({
+ shell,
+ getTask: () => ({ diskPath: '', finalPath: '/downloads/file.iso' }),
+ })
+
+ await expect(handler({ taskId: 'task-1' })).rejects.toThrow()
+ expect(shell.openPath).not.toHaveBeenCalled()
+ expect(shell.showItemInFolder).not.toHaveBeenCalled()
+ }
+ )
+
+ it('propagates file manager failures instead of reporting success', async () => {
+ statMock
+ .mockRejectedValueOnce(missingPath())
+ .mockResolvedValueOnce(directoryStat)
+ const shell = {
+ showItemInFolder: vi.fn(),
+ openPath: vi.fn(async () => 'OS failed to open /downloads'),
+ }
+ const handler = createRevealInFolderHandler({
+ shell,
+ getTask: () => ({ diskPath: '', finalPath: '/downloads/file.iso' }),
+ })
+
+ await expect(handler({ taskId: 'task-1' })).rejects.toThrow(
+ /cannot be revealed/
+ )
+ expect(shell.showItemInFolder).not.toHaveBeenCalled()
+ })
+
+ it('does not treat a permission error as a missing output', async () => {
+ statMock.mockRejectedValueOnce(
+ Object.assign(new Error('denied'), { code: 'EACCES' })
+ )
+ const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }
+ const handler = createRevealInFolderHandler({
+ shell,
+ getTask: () => ({ diskPath: '', finalPath: '/downloads/file.iso' }),
+ })
+
+ await expect(handler({ taskId: 'task-1' })).rejects.toThrow()
+ expect(shell.showItemInFolder).not.toHaveBeenCalled()
+ expect(shell.openPath).not.toHaveBeenCalled()
+ })
+
it('rejects an unknown task instead of accepting a renderer path', async () => {
- const shell = { showItemInFolder: vi.fn() }
+ const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }
const handler = createRevealInFolderHandler({
shell,
getTask: () => undefined,
@@ -54,7 +203,7 @@ describe('revealInFolder', () => {
'\\\\server\\share\\downloads\\file.iso',
'//server/share/downloads/file.iso',
])('allows a task-owned UNC path: %s', async (diskPath) => {
- const shell = { showItemInFolder: vi.fn() }
+ const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }
const handler = createRevealInFolderHandler({
shell,
getTask: () => ({ diskPath, finalPath: '' }),
@@ -71,7 +220,7 @@ describe('revealInFolder', () => {
'\\??\\C:\\downloads\\file.iso',
'//?/C:/downloads/file.iso',
])('rejects a Windows device namespace: %s', async (diskPath) => {
- const shell = { showItemInFolder: vi.fn() }
+ const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }
const handler = createRevealInFolderHandler({
shell,
getTask: () => ({ diskPath, finalPath: '' }),
@@ -84,7 +233,7 @@ describe('revealInFolder', () => {
})
it('rejects a relative task path', async () => {
- const shell = { showItemInFolder: vi.fn() }
+ const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }
const handler = createRevealInFolderHandler({
shell,
getTask: () => ({
diff --git a/src/main/ipc/commands/reveal-in-folder.ts b/src/main/ipc/commands/reveal-in-folder.ts
index ff35ca4f..091d325a 100644
--- a/src/main/ipc/commands/reveal-in-folder.ts
+++ b/src/main/ipc/commands/reveal-in-folder.ts
@@ -1,9 +1,13 @@
+import { stat } from 'node:fs/promises'
import path from 'node:path'
import { AppError, ErrorCode } from '@shared/errors'
import type { DownloadTask } from '@shared/types/task'
export interface RevealInFolderDeps {
- shell: { showItemInFolder: (path: string) => void }
+ shell: {
+ showItemInFolder: (path: string) => void
+ openPath: (path: string) => Promise<string>
+ }
getTask: (
taskId: string
) => Pick<DownloadTask, 'diskPath' | 'finalPath'> | undefined
@@ -57,6 +61,34 @@ export function createRevealInFolderHandler(deps: RevealInFolderDeps) {
)
}
- deps.shell.showItemInFolder(taskPath)
+ try {
+ const output = await stat(taskPath).catch(
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT') return null
+ throw error
+ }
+ )
+ if (output !== null) {
+ deps.shell.showItemInFolder(taskPath)
+ return
+ }
+
+ // Incomplete outputs can still have a .motrix suffix or live in a BT
+ // workspace. showItemInFolder silently fails for their absent final
+ // path, so open its containing directory until the output is published.
+ const pathApi = path.posix.isAbsolute(taskPath) ? path.posix : path.win32
+ const directory = pathApi.dirname(taskPath)
+ if (!(await stat(directory)).isDirectory()) {
+ throw new Error('task parent is not a directory')
+ }
+ const error = await deps.shell.openPath(directory)
+ if (error) throw new Error(error)
+ } catch (cause) {
+ throw new AppError(
+ ErrorCode.TaskRevealFailed,
+ 'revealInFolder: task output cannot be revealed',
+ cause
+ )
+ }
}
}
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 19a6025f..3527c551 100644
--- a/src/renderer/components/desktop-kit/hooks/use-selectable-list.ts
+++ b/src/renderer/components/desktop-kit/hooks/use-selectable-list.ts
@@ -3,6 +3,7 @@ import {
type MouseEvent as ReactMouseEvent,
useCallback,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
} from 'react'
@@ -38,6 +39,7 @@ interface UseSelectableListReturn<T> {
items: T[]
getId: (item: T) => string
rowHeight: number
+ headerHeight: number
scrollRef: React.RefObject<HTMLDivElement | null>
}
marqueeProps: {
@@ -67,24 +69,33 @@ export function useSelectableList<T>(
const fallbackStore = useMemo(() => createSelectionStore<T>(getId), [])
const store = options.store ?? fallbackStore
- useEffect(() => {
+ useLayoutEffect(() => {
store.getState().setItems(items)
}, [store, items])
- useEffect(() => {
- return store.subscribe((state, prev) => {
- if (
- state.focusedIndex !== null &&
- state.focusedIndex !== prev.focusedIndex
- ) {
- listRef.current?.scrollToIndex(state.focusedIndex)
- }
- })
- }, [store])
-
const selectedIds = store((s) => s.selectedIds)
const focusedIndex = store((s) => s.focusedIndex)
+ // 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])
+
+ 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.
+ // Observe after the virtualizer so its viewport measurement is current.
+ const observer = new ResizeObserver(() => {
+ const index = store.getState().focusedIndex
+ if (index !== null) listRef.current?.scrollToIndex(index)
+ })
+ observer.observe(container)
+ return () => observer.disconnect()
+ }, [hasItems, store])
+
const getRowProps = useCallback(
(index: number): RowProps => {
const item = items[index]
@@ -191,7 +202,13 @@ export function useSelectableList<T>(
return {
listRef,
- listProps: { items, getId, rowHeight, scrollRef: containerRef },
+ listProps: {
+ items,
+ getId,
+ rowHeight,
+ headerHeight,
+ scrollRef: containerRef,
+ },
marqueeProps,
selection: store,
getRowProps,
diff --git a/src/renderer/components/desktop-kit/virtual-list/types.ts b/src/renderer/components/desktop-kit/virtual-list/types.ts
index e8228bc6..2f75b940 100644
--- a/src/renderer/components/desktop-kit/virtual-list/types.ts
+++ b/src/renderer/components/desktop-kit/virtual-list/types.ts
@@ -4,6 +4,7 @@ export interface VirtualListProps<T> {
items: T[]
getId: (item: T) => string
rowHeight: number
+ headerHeight?: number
overscan?: number
scrollRef?: RefObject<HTMLDivElement | null>
renderRow: (props: RowRenderProps<T>) => 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 532697f3..512be6ee 100644
--- a/src/renderer/components/desktop-kit/virtual-list/virtual-list.tsx
+++ b/src/renderer/components/desktop-kit/virtual-list/virtual-list.tsx
@@ -3,6 +3,7 @@ import {
type ForwardedRef,
forwardRef,
type ReactElement,
+ useCallback,
useImperativeHandle,
useRef,
} from 'react'
@@ -16,6 +17,7 @@ function VirtualListInner<T>(
items,
getId,
rowHeight,
+ headerHeight = 0,
overscan = 5,
scrollRef,
renderRow,
@@ -28,8 +30,15 @@ function VirtualListInner<T>(
const internalRef = useRef<HTMLDivElement>(null)
const containerRef = scrollRef ?? internalRef
+ const getItemKey = useCallback(
+ (index: number) => getId(items[index]),
+ [getId, items]
+ )
const virtualizer = useVirtualizer({
count: items.length,
+ getItemKey,
+ scrollMargin: headerHeight,
+ scrollPaddingStart: headerHeight,
getScrollElement: () => containerRef.current,
estimateSize: () => rowHeight,
overscan,
@@ -96,7 +105,7 @@ function VirtualListInner<T>(
left: 0,
width: '100%',
height: rowHeight,
- transform: `translateY(${virtualRow.start}px)`,
+ transform: `translateY(${virtualRow.start - headerHeight}px)`,
}}
>
{renderRow({
diff --git a/src/renderer/lib/format.test.ts b/src/renderer/lib/format.test.ts
index 3ee454c7..d6d06680 100644
--- a/src/renderer/lib/format.test.ts
+++ b/src/renderer/lib/format.test.ts
@@ -1,6 +1,11 @@
import { SUPPORTED_LOCALE_CODES } from '@shared/constants/locales'
import { describe, expect, it } from 'vitest'
-import { formatByteParts, formatBytes, formatTime24Hour } from './format'
+import {
+ formatByteParts,
+ formatBytes,
+ formatProgressPercent,
+ formatTime24Hour,
+} from './format'
describe('formatBytes', () => {
it('preserves the existing number formatting contract', () => {
@@ -47,3 +52,18 @@ describe('formatTime24Hour', () => {
}
)
})
+
+describe('formatProgressPercent', () => {
+ it.each([0.9949, 0.995, 0.999, 1 - Number.EPSILON])(
+ 'does not report 100%% while progress is %s',
+ (progress) => expect(formatProgressPercent(progress)).toBe(99)
+ )
+ it('reports full byte completion and handles invalid snapshots', () => {
+ expect(formatProgressPercent(1)).toBe(100)
+ expect(formatProgressPercent(1.01)).toBe(100)
+ for (const value of [NaN, Infinity, -Infinity, -1, 0]) {
+ expect(formatProgressPercent(value)).toBe(0)
+ }
+ expect(formatProgressPercent(0.426)).toBe(43)
+ })
+})
diff --git a/src/renderer/lib/format.ts b/src/renderer/lib/format.ts
index cb2fd627..3dbdd263 100644
--- a/src/renderer/lib/format.ts
+++ b/src/renderer/lib/format.ts
@@ -100,3 +100,9 @@ export function formatDurationHMS(seconds: number): string {
const pad = (n: number) => n.toString().padStart(2, '0')
return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${pad(m)}:${pad(s)}`
}
+
+/** Round display percentages without claiming completion while bytes remain. */
+export function formatProgressPercent(progress: number): number {
+ if (!Number.isFinite(progress) || progress <= 0) return 0
+ return progress >= 1 ? 100 : Math.min(99, Math.round(progress * 100))
+}
diff --git a/src/renderer/routes/downloads/downloads-page.tsx b/src/renderer/routes/downloads/downloads-page.tsx
index be9884e2..db7c1247 100644
--- a/src/renderer/routes/downloads/downloads-page.tsx
+++ b/src/renderer/routes/downloads/downloads-page.tsx
@@ -274,6 +274,7 @@ export function DownloadsPage() {
<TaskListUnavailable onRetry={() => void retry()} />
) : (
<TaskListPanel
+ key={`${filter}:${serializeTypeParam(types)}`}
tasks={filtered}
hasAnyTasks={counts.all > 0}
selection={useDownloadsSelection}
@@ -284,33 +285,38 @@ export function DownloadsPage() {
)
return (
- <div ref={setContainer} className="relative flex h-full flex-col">
- <PanelShell
- title={
- <StatusTitleMenu
- tab={filter}
- onTabChange={onTabChange}
- counts={counts}
- />
- }
- actions={
- <FilterSearchCommand
- tasks={tasks}
- types={types}
- onTypesChange={onTypesChange}
- typeCounts={typeCounts}
- onOpenTask={onOpenTask}
- />
- }
- actionsPosition="end"
- footer={<GlobalStatsBar counts={counts} />}
- contentClassName="px-6"
- >
- {status === 'error' && hasReadySnapshot ? (
- <TaskListStaleBanner onRetry={() => void retry()} />
- ) : null}
- {taskList}
- </PanelShell>
+ <div
+ ref={setContainer}
+ className="relative flex h-full min-h-0 flex-col overflow-hidden"
+ >
+ <div className="min-h-0 flex-1">
+ <PanelShell
+ title={
+ <StatusTitleMenu
+ tab={filter}
+ onTabChange={onTabChange}
+ counts={counts}
+ />
+ }
+ actions={
+ <FilterSearchCommand
+ tasks={tasks}
+ types={types}
+ onTypesChange={onTypesChange}
+ typeCounts={typeCounts}
+ onOpenTask={onOpenTask}
+ />
+ }
+ actionsPosition="end"
+ footer={<GlobalStatsBar counts={counts} />}
+ contentClassName="px-6"
+ >
+ {status === 'error' && hasReadySnapshot ? (
+ <TaskListStaleBanner onRetry={() => void retry()} />
+ ) : null}
+ {taskList}
+ </PanelShell>
+ </div>
<TaskInspectorDrawer
selection={useDownloadsSelection}
tasks={tasks}
diff --git a/src/renderer/routes/downloads/filter-search-panel.tsx b/src/renderer/routes/downloads/filter-search-panel.tsx
index 5855170f..6c2cc93b 100644
--- a/src/renderer/routes/downloads/filter-search-panel.tsx
+++ b/src/renderer/routes/downloads/filter-search-panel.tsx
@@ -5,7 +5,7 @@ import {
CommandItem,
CommandList,
} from '@renderer/components/ui/command'
-import { formatBytes } from '@renderer/lib/format'
+import { formatBytes, 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'
@@ -153,7 +153,7 @@ export function FilterSearchPanel({
<span className="flex-1 truncate">{task.name}</span>
<span className="text-xs text-muted-foreground tabular-nums">
{task.status === TaskStatus.Downloading
- ? `${Math.round(task.progress * 100)}%`
+ ? `${formatProgressPercent(task.progress)}%`
: formatBytes(task.sizeWhenDone)}
</span>
</CommandItem>
diff --git a/src/renderer/routes/downloads/inspector/files-tab.tsx b/src/renderer/routes/downloads/inspector/files-tab.tsx
index a164c158..17427578 100644
--- a/src/renderer/routes/downloads/inspector/files-tab.tsx
+++ b/src/renderer/routes/downloads/inspector/files-tab.tsx
@@ -1,6 +1,7 @@
import { FileList } from '@renderer/components/file-list/file-list'
import { Button } from '@renderer/components/ui/button'
import { useTaskFiles } from '@renderer/hooks/use-task-files'
+import { formatProgressPercent } from '@renderer/lib/format'
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import type { DownloadTask, TaskFile } from '@shared/types/task'
@@ -15,6 +16,7 @@ const ACTIVE_DOWNLOAD = new Set<TaskStatus>([
])
const READ_ONLY_STATES = new Set<TaskStatus>([
+ TaskStatus.Finalizing,
TaskStatus.Completed,
TaskStatus.Removed,
])
@@ -62,8 +64,8 @@ export function FilesTab({ task }: { task: DownloadTask }) {
isActive ? (
<span className="shrink-0 text-xs tabular-nums text-muted-foreground">
{files.length === 1
- ? Math.round(task.progress * 100)
- : Math.floor((f.completedBytes / Math.max(f.size, 1)) * 100)}
+ ? formatProgressPercent(task.progress)
+ : formatProgressPercent(f.completedBytes / Math.max(f.size, 1))}
%
</span>
) : null
diff --git a/src/renderer/routes/downloads/inspector/multi-selection-summary.tsx b/src/renderer/routes/downloads/inspector/multi-selection-summary.tsx
index 448bf56b..265c6e88 100644
--- a/src/renderer/routes/downloads/inspector/multi-selection-summary.tsx
+++ b/src/renderer/routes/downloads/inspector/multi-selection-summary.tsx
@@ -1,4 +1,8 @@
-import { formatBytes, formatDurationHMS } from '@renderer/lib/format'
+import {
+ formatBytes,
+ formatDurationHMS,
+ formatProgressPercent,
+} from '@renderer/lib/format'
import type { DownloadTask, TaskStatus } from '@shared/types/task'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
@@ -71,7 +75,7 @@ export function MultiSelectionSummary({
/>
<Row
label={t('panel.downloads.inspector.multi.avgProgress')}
- value={`${Math.round(agg.avgProgress * 100)}%`}
+ value={`${formatProgressPercent(agg.avgProgress)}%`}
/>
</Card>
<Card title={t('panel.downloads.inspector.multi.liveSpeed')}>
diff --git a/src/renderer/routes/downloads/inspector/overview-tab.tsx b/src/renderer/routes/downloads/inspector/overview-tab.tsx
index 200741ea..09b06434 100644
--- a/src/renderer/routes/downloads/inspector/overview-tab.tsx
+++ b/src/renderer/routes/downloads/inspector/overview-tab.tsx
@@ -12,7 +12,12 @@ import {
TooltipTrigger,
} from '@renderer/components/ui/tooltip'
import { resolveFailureReason } from '@renderer/lib/failure-reason'
-import { formatBytes, formatDurationHMS } from '@renderer/lib/format'
+import {
+ formatBytes,
+ formatDateTime,
+ 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'
@@ -47,7 +52,7 @@ function Row({
value: string | number | React.ReactNode
}) {
return (
- <div className="flex justify-between">
+ <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-0.5">
<span className="text-muted-foreground">{label}</span>
{typeof value === 'string' || typeof value === 'number' ? (
<span className="tabular-nums">{value}</span>
@@ -58,6 +63,32 @@ 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])
@@ -106,7 +137,7 @@ function ErrorPanel({ task }: { task: DownloadTask }) {
}
export function OverviewTab({ task }: { task: DownloadTask }) {
- const { t } = useTranslation()
+ const { t, i18n } = useTranslation()
const isBt = task.type === TaskType.Bt || task.type === TaskType.Magnet
return (
<div className="flex flex-col gap-3">
@@ -137,7 +168,7 @@ export function OverviewTab({ task }: { task: DownloadTask }) {
/>
<Row
label={t('panel.downloads.inspector.overview.percent')}
- value={`${Math.round(task.progress * 100)}%`}
+ value={`${formatProgressPercent(task.progress)}%`}
/>
</Card>
<Card title={t('panel.downloads.inspector.overview.network')}>
@@ -163,7 +194,7 @@ export function OverviewTab({ task }: { task: DownloadTask }) {
/>
)}
</Card>
- <Card title={t('panel.downloads.inspector.overview.metadata')}>
+ <Card title={t('panel.downloads.inspector.overview.general')}>
<Row
label={t('panel.downloads.inspector.overview.type')}
value={task.type.toUpperCase()}
@@ -195,6 +226,26 @@ export function OverviewTab({ task }: { task: DownloadTask }) {
value={task.bt.isPrivate ? '✓' : '—'}
/>
)}
+ <Row
+ label={t('panel.downloads.inspector.overview.createdAt')}
+ value={
+ <TaskTimestamp
+ timestamp={task.createdAt}
+ locale={i18n.language}
+ />
+ }
+ />
+ {task.status === TaskStatus.Completed && (
+ <Row
+ label={t('panel.downloads.inspector.overview.finishedAt')}
+ value={
+ <TaskTimestamp
+ timestamp={task.finishedAt}
+ locale={i18n.language}
+ />
+ }
+ />
+ )}
</Card>
</div>
</div>
diff --git a/src/renderer/routes/downloads/task-column-header.tsx b/src/renderer/routes/downloads/task-column-header.tsx
index b617acc8..f32f2e50 100644
--- a/src/renderer/routes/downloads/task-column-header.tsx
+++ b/src/renderer/routes/downloads/task-column-header.tsx
@@ -21,7 +21,7 @@ export function TaskColumnHeader({ headerCheckbox }: TaskColumnHeaderProps) {
const { t } = useTranslation()
return (
<div
- className="sticky top-0 z-10 grid items-center gap-3 border-b border-border bg-muted/40 px-3 py-2 text-[10.5px] font-medium uppercase tracking-wide text-muted-foreground"
+ 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,
diff --git a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx b/src/renderer/routes/downloads/task-inspector-drawer.test.tsx
index 8aeea175..3755cb2a 100644
--- a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx
+++ b/src/renderer/routes/downloads/task-inspector-drawer.test.tsx
@@ -360,12 +360,12 @@ describe('TaskInspectorDrawer', () => {
render(<TestHarness selection={selection} tasks={tasks} />)
const drawer = screen.getByRole('dialog')
- expect(drawer).toHaveClass('max-h-[80%]')
- expect(drawer).not.toHaveClass('max-h-[85%]')
+ expect(drawer).toHaveClass('max-h-[min(80%,calc(100%-16rem))]')
+ expect(drawer).not.toHaveClass('max-h-[min(85%,calc(100%-16rem))]')
await user.click(screen.getByRole('tab', { name: /activity/i }))
- expect(drawer).toHaveClass('max-h-[85%]')
- expect(drawer).not.toHaveClass('max-h-[80%]')
+ expect(drawer).toHaveClass('max-h-[min(85%,calc(100%-16rem))]')
+ expect(drawer).not.toHaveClass('max-h-[min(80%,calc(100%-16rem))]')
})
})
diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsx
index 89ca554f..57f6d2cc 100644
--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx
+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx
@@ -49,7 +49,7 @@ type SubTab =
export interface TaskInspectorDrawerProps {
selection: SelectionStore<DownloadTask>
tasks: readonly DownloadTask[]
- /** Portal target. Must have `position: relative`. Drawer does not render when null. */
+ /** Bounded flex-column portal target. The inspector shares height with the list. */
container: HTMLElement | null
onDismiss?: () => void
}
@@ -107,8 +107,11 @@ export function TaskInspectorDrawer({
role="dialog"
aria-label={t('panel.downloads.title')}
className={cn(
- 'drawer-slide-in absolute inset-x-0 bottom-0 z-30 flex flex-col',
- subtab === 'activity' ? 'max-h-[85%]' : 'max-h-[80%]',
+ '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)]'
)}
diff --git a/src/renderer/routes/downloads/task-list-panel.tsx b/src/renderer/routes/downloads/task-list-panel.tsx
index 5c2dfed9..120cfd60 100644
--- a/src/renderer/routes/downloads/task-list-panel.tsx
+++ b/src/renderer/routes/downloads/task-list-panel.tsx
@@ -66,7 +66,7 @@ export function TaskListPanel({
<VirtualList
ref={listRef}
{...listProps}
- className="min-h-full"
+ className="min-h-0 flex-1"
renderHeader={() => (
<TaskColumnHeader headerCheckbox={headerCheckbox} />
)}
diff --git a/src/renderer/routes/downloads/task-row.test.tsx b/src/renderer/routes/downloads/task-row.test.tsx
index 5d0277d2..da23b381 100644
--- a/src/renderer/routes/downloads/task-row.test.tsx
+++ b/src/renderer/routes/downloads/task-row.test.tsx
@@ -60,6 +60,22 @@ function getEtaCell(container: HTMLElement): Element {
}
describe('TaskRow', () => {
+ it('keeps a slow unfinished tail below 100% until bytes finish', () => {
+ const task = fake({ progress: 0.995, downloadSpeed: 102400 })
+ const { rerender } = render(<TaskRow task={task} rowProps={rowProps} />)
+ expect(screen.getByText('99%')).toBeInTheDocument()
+ expect(screen.queryByText('100%')).not.toBeInTheDocument()
+ rerender(
+ <TaskRow
+ task={{ ...task, progress: 1, status: TaskStatus.Finalizing }}
+ rowProps={rowProps}
+ />
+ )
+ expect(screen.getByText('100%')).toBeInTheDocument()
+ expect(screen.getByText('Finalizing')).toBeInTheDocument()
+ expect(screen.queryByText('100 KB/s')).not.toBeInTheDocument()
+ })
+
it('renders task name and formatted size', () => {
render(<TaskRow task={fake()} rowProps={rowProps} />)
expect(screen.getByText('ubuntu.iso')).toBeInTheDocument()
@@ -77,7 +93,7 @@ describe('TaskRow', () => {
expect(screen.getAllByText('—').length).toBeGreaterThan(0)
})
- it.each([TaskStatus.Paused, TaskStatus.Completed])(
+ it.each([TaskStatus.Paused, TaskStatus.Completed, TaskStatus.Finalizing])(
'renders a dash for stale ETA when a memoized task becomes %s',
(status) => {
const downloading = fake({
diff --git a/src/renderer/routes/downloads/task-row.tsx b/src/renderer/routes/downloads/task-row.tsx
index 4c9fefae..e499ee4c 100644
--- a/src/renderer/routes/downloads/task-row.tsx
+++ b/src/renderer/routes/downloads/task-row.tsx
@@ -1,6 +1,10 @@
import { Checkbox } from '@renderer/components/ui/checkbox'
import { resolveFailureReason } from '@renderer/lib/failure-reason'
-import { formatBytes, formatDurationHMS } from '@renderer/lib/format'
+import {
+ formatBytes,
+ 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'
@@ -22,11 +26,15 @@ export interface TaskRowProps {
function TaskRowBase({ task, rowProps }: TaskRowProps) {
const { t, i18n } = useTranslation()
- const pct = Math.round(task.progress * 100)
+ const pct = formatProgressPercent(task.progress)
const showDash = (value: number) =>
- value <= 0 || task.status === TaskStatus.Completed
+ value <= 0 ||
+ task.status === TaskStatus.Completed ||
+ task.status === TaskStatus.Finalizing
const hideEta =
- task.status === TaskStatus.Paused || task.status === TaskStatus.Completed
+ 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}`
diff --git a/src/shared/errors.ts b/src/shared/errors.ts
index 11547fcc..4ed4d55c 100644
--- a/src/shared/errors.ts
+++ b/src/shared/errors.ts
@@ -6,6 +6,7 @@ export enum ErrorCode {
EngineProcessTerminationFailed = 'ENGINE_PROCESS_TERMINATION_FAILED',
TaskCreateFailed = 'TASK_CREATE_FAILED',
TaskNotFound = 'TASK_NOT_FOUND',
+ TaskRevealFailed = 'TASK_REVEAL_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 152960a2..fdae4512 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -550,7 +550,9 @@
"transfer": "Transfer",
"progress": "Progress",
"network": "Network",
- "metadata": "Metadata",
+ "general": "General",
+ "createdAt": "Created",
+ "finishedAt": "Completed",
"downSpeed": "↓ speed",
"upSpeed": "↑ speed",
"eta": "ETA",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 3c3242d7..4a213e2f 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -548,7 +548,9 @@
"transfer": "传输",
"progress": "进度",
"network": "网络",
- "metadata": "元数据",
+ "general": "常规",
+ "createdAt": "创建时间",
+ "finishedAt": "完成时间",
"downSpeed": "↓ 速度",
"upSpeed": "↑ 速度",
"eta": "ETA",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index bd6ca0b3..92442d93 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -548,7 +548,9 @@
"transfer": "傳輸",
"progress": "進度",
"network": "網路",
- "metadata": "中繼資料",
+ "general": "一般",
+ "createdAt": "建立時間",
+ "finishedAt": "完成時間",
"downSpeed": "↓ 速度",
"upSpeed": "↑ 速度",
"eta": "預估剩餘時間",