Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions e2e/downloadActions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,12 @@ test.describe('what each state offers', () => {
])
})

test('queued: it can also go first in line', () => {
test('queued: it can also go first in line, or move up or down it', () => {
expect(ids([download({ status: 'queued' })])).toEqual([
'pause',
'next',
'earlier',
'later',
'reveal',
'copy',
'cancel'
Expand All @@ -68,6 +70,23 @@ test.describe('what each state offers', () => {
for (const item of others) expect(ids([item])).not.toContain('next')
})

test('only a queued download can move in the queue, and one at a time', () => {
const others = [
download({ status: 'downloading' }),
download({ status: 'paused' }),
download({ status: 'error', error: 'reset' }),
download({ status: 'completed' }),
finished()
]
for (const item of others) {
expect(ids([item])).not.toContain('earlier')
expect(ids([item])).not.toContain('later')
}
const two = [download({ status: 'queued' }), download({ status: 'queued' })]
expect(ids(two)).not.toContain('earlier')
expect(ids(two)).not.toContain('later')
})

test('paused', () => {
expect(ids([download({ status: 'paused' })])).toEqual(['resume', 'reveal', 'copy', 'cancel'])
})
Expand Down Expand Up @@ -219,10 +238,10 @@ test.describe('the selection toolbar', () => {
buttons: ['pause', 'cancel'],
more: ['reveal', 'copy']
})
// Start next goes under More: Pause and Cancel stay the buttons.
// Start next, Move up and Move down go under More: Pause and Cancel stay the buttons.
expect(shown([download({ status: 'queued' })])).toEqual({
buttons: ['pause', 'cancel'],
more: ['next', 'reveal', 'copy']
more: ['next', 'earlier', 'later', 'reveal', 'copy']
})
expect(shown([download({ status: 'paused' })])).toEqual({
buttons: ['resume', 'cancel'],
Expand Down
51 changes: 51 additions & 0 deletions e2e/moveInQueue.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { BLOCK, expect, test } from './fixtures'
import type { Origin } from './origin'

/** Which of these downloads gets its first bytes first: each origin stops just past its start. */
function firstToStart(origins: Record<string, Origin>): Promise<string> {
return Promise.race(
Object.entries(origins).map(([name, origin]) => origin.hold(4 * BLOCK).then(() => name))
)
}

test('Move up and Move down change which queued download starts next', async ({ plexo, serve }) => {
await plexo.api.updateSettings({ downloadsAtOnce: 1 })
const [first, second, third] = await Promise.all([0, 1, 2].map(() => serve({ size: 24 * BLOCK })))
const running = first.hold(4 * BLOCK)
const firstId = await plexo.start(first.url(), first.sha256, { fileName: 'first.bin' })
await running
const secondId = await plexo.start(second.url(), second.sha256, { fileName: 'second.bin' })
const thirdId = await plexo.start(third.url(), third.sha256, { fileName: 'third.bin' })

const page = plexo.page
const queued = page.getByRole('checkbox', { name: /^Select (second|third)\.bin$/ })
await expect(queued.first()).toHaveAccessibleName('Select second.bin')
const menu = async (name: string, item: string): Promise<void> => {
await page.getByRole('button', { name: `Open ${name}`, exact: true }).click({ button: 'right' })
await page.getByRole('menuitem', { name: item, exact: true }).click()
}

// Up, then down again: back where they were.
await menu('third.bin', 'Move up')
await expect(queued.first()).toHaveAccessibleName('Select third.bin')
await menu('third.bin', 'Move down')
await expect(queued.first()).toHaveAccessibleName('Select second.bin')
// At the end of the queue there's nowhere to go: the order holds.
await menu('third.bin', 'Move down')
await menu('second.bin', 'Move up')
await expect(queued.first()).toHaveAccessibleName('Select second.bin')

// Move the second down: the third starts when the first is done. Nothing running is paused.
await menu('second.bin', 'Move down')
await expect(queued.first()).toHaveAccessibleName('Select third.bin')
expect((await plexo.byId(firstId))?.status).toBe('downloading')

const started = firstToStart({ second, third })
first.release()
expect(await started).toBe('third')
expect((await plexo.byId(secondId))?.status).toBe('queued')
third.release()
second.release()
for (const id of [firstId, secondId, thirdId])
await expect.poll(async () => (await plexo.byId(id))?.status).toBe('completed')
})
40 changes: 33 additions & 7 deletions e2e/scheduleQueue.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,18 +121,19 @@ test('the cutoff stops torrent peers and uploads; reopening finishes the same fi
}
})

/** Three downloads waiting for the schedule, one at a time, with the last moved up by Start next;
* each origin stops just past its start, so the one started first is the one that gets there. */
async function startNextWhileClosed(
/** Three downloads waiting for the schedule, one at a time, reordered by `reorder`; each origin
* stops just past its start, so the one started first is the one that gets there. */
async function queueWhileClosed(
plexo: PlexoApp,
serve: (options: { size: number }) => Promise<Origin>
serve: (options: { size: number }) => Promise<Origin>,
reorder: (ids: string[]) => Promise<void>
): Promise<{ origins: Origin[]; ids: string[]; firstToStart: () => Promise<number> }> {
await plexo.api.updateSettings({ downloadsAtOnce: 1 })
const origins = await Promise.all([0, 1, 2].map(() => serve({ size: 16 * BLOCK })))
const ids: string[] = []
for (const origin of origins) ids.push(await plexo.start(origin.url(), origin.sha256))
for (const id of ids) expect((await plexo.byId(id))?.status).toBe('queued')
await plexo.api.startNext(ids[2])
await reorder(ids)
const firstToStart = (): Promise<number> =>
Promise.race(origins.map((origin, index) => origin.hold(4 * BLOCK).then(() => index)))
return { origins, ids, firstToStart }
Expand All @@ -144,7 +145,9 @@ test('Start next while the schedule is closed starts that download first when it
}) => {
await clock(plexo, at(1, 8))
await plexo.api.updateSettings({ downloadSchedule: schedule })
const { origins, ids, firstToStart } = await startNextWhileClosed(plexo, serve)
const { origins, ids, firstToStart } = await queueWhileClosed(plexo, serve, (ids) =>
plexo.api.startNext(ids[2])
)
const started = firstToStart()
await clock(plexo, at(2, 0))
expect(await started).toBe(2)
Expand All @@ -159,7 +162,9 @@ test('the order Start next gives a scheduled queue survives a crash and restart'
}) => {
await clock(plexo, at(1, 8))
await plexo.api.updateSettings({ downloadSchedule: { ...schedule, endDate: '2000-01-02' } })
const { origins, ids, firstToStart } = await startNextWhileClosed(plexo, serve)
const { origins, ids, firstToStart } = await queueWhileClosed(plexo, serve, (ids) =>
plexo.api.startNext(ids[2])
)
// Killed, not quit: the new order is saved when it's given, not only when Plexo quits.
await plexo.kill()
await plexo.launch()
Expand All @@ -172,6 +177,27 @@ test('the order Start next gives a scheduled queue survives a crash and restart'
await expect.poll(async () => (await plexo.byId(id))?.status).toBe('completed')
})

test('the order Move down gives a scheduled queue survives a crash and restart', async ({
plexo,
serve
}) => {
await clock(plexo, at(1, 8))
await plexo.api.updateSettings({ downloadSchedule: { ...schedule, endDate: '2000-01-02' } })
// The first moves down a place, so the second starts first.
const { origins, ids, firstToStart } = await queueWhileClosed(plexo, serve, (ids) =>
plexo.api.moveInQueue(ids[0], 1)
)
await plexo.kill()
await plexo.launch()
for (const id of ids) expect((await plexo.byId(id))?.status).toBe('queued')
const started = firstToStart()
await plexo.api.updateSettings({ downloadSchedule: { ...schedule, enabled: false } })
expect(await started).toBe(1)
for (const origin of origins) origin.release()
for (const id of ids)
await expect.poll(async () => (await plexo.byId(id))?.status).toBe('completed')
})

async function openSchedule(plexo: PlexoApp): Promise<void> {
await plexo.page.getByRole('button', { name: /^\d+ networks?/ }).click()
await plexo.page.getByRole('button', { name: 'Speed & data limits', exact: true }).click()
Expand Down
30 changes: 27 additions & 3 deletions src/main/download/downloadManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -626,9 +626,7 @@ export class DownloadManager {
* whenever one might have room: a run ended, a queued one went, the count went up. */
private pump(): void {
if (this.suspending || !this.scheduleAllowsDownloads()) return
const queued = [...this.runtimes.values()]
.filter((runtime) => runtime.state.status === 'queued' && !runtime.scheduleStopping)
.sort((a, b) => (a.state.queuedAt ?? 0) - (b.state.queuedAt ?? 0))
const queued = this.queuedInOrder().filter((runtime) => !runtime.scheduleStopping)
for (const runtime of queued) {
if (this.runningCount() >= this.downloadsAtOnce) return
// Each would only fail on the switch, making room for the next to fail too.
Expand All @@ -637,6 +635,13 @@ export class DownloadManager {
}
}

/** The queued downloads, in the order they'll start. */
private queuedInOrder(): DownloadRuntime[] {
return [...this.runtimes.values()]
.filter((runtime) => runtime.state.status === 'queued')
.sort((a, b) => (a.state.queuedAt ?? 0) - (b.state.queuedAt ?? 0))
}

/** Puts a download in the queue: at its end, or at its front when the user asked for it. */
private enqueue(runtime: DownloadRuntime, front: boolean): void {
const places = [...this.runtimes.values()]
Expand Down Expand Up @@ -1662,6 +1667,25 @@ export class DownloadManager {
await this.persistNow(runtime)
}

/** Moves a queued download one place earlier (`-1`) or later (`1`) in the queue, by swapping
* its place with its neighbour's. Like Start next, it only reorders the waiting: nothing
* running is touched. At either end of the queue there's nowhere to go. */
async moveInQueue(id: string, by: -1 | 1): Promise<void> {
const runtime = this.runtimes.get(id)
// It arrives over IPC: one place either way, nothing else.
if (by !== -1 && by !== 1) return
if (!runtime || runtime.cancelPromise || runtime.state.status !== 'queued') return
const queue = this.queuedInOrder()
const neighbour = queue[queue.indexOf(runtime) + by]
if (!neighbour) return
const place = runtime.state.queuedAt
runtime.state.queuedAt = neighbour.state.queuedAt
neighbour.state.queuedAt = place
this.pushUpdate(runtime)
this.pushUpdate(neighbour)
await Promise.all([this.persistNow(runtime), this.persistNow(neighbour)])
}

// A file that changed on the server while this download was paused is caught by the first
// chunk request after resuming: its response is checked against the version the download
// started on (see runWorker), which can tell a real change from a relabelled server. Whether a
Expand Down
2 changes: 2 additions & 0 deletions src/main/ipc/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,8 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down

handle('startNext', async (_event, id) => manager.startNext(id))

handle('moveInQueue', async (_event, id, by) => manager.moveInQueue(id, by))

handle('relinkDownload', async (_event, id, url) => manager.relink(id, url))

handle('setDownloadNetwork', async (_event, id, networkId, enabled) => {
Expand Down
1 change: 1 addition & 0 deletions src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ const plexoApi = {
pauseDownload: (downloadId: string) => invoke('pauseDownload', downloadId),
resumeDownload: (downloadId: string) => invoke('resumeDownload', downloadId),
startNext: (downloadId: string) => invoke('startNext', downloadId),
moveInQueue: (downloadId: string, by: -1 | 1) => invoke('moveInQueue', downloadId, by),
relinkDownload: (downloadId: string, url: string) => invoke('relinkDownload', downloadId, url),
setDownloadNetwork: (downloadId: string, networkId: string, enabled: boolean) =>
invoke('setDownloadNetwork', downloadId, networkId, enabled),
Expand Down
8 changes: 8 additions & 0 deletions src/renderer/src/components/DownloadActionsProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ export function DownloadActionsProvider({
} catch (cause) {
return fail(cause)
}
case 'earlier':
case 'later':
try {
await window.plexo.moveInQueue(targets[0].id, id === 'earlier' ? -1 : 1)
return true
} catch (cause) {
return fail(cause)
}
case 'fix':
setFixing(targets[0] as DownloadState)
return true
Expand Down
16 changes: 16 additions & 0 deletions src/renderer/src/components/downloadActionMeta.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {
ChevronDown,
ChevronUp,
ChevronsUp,
Copy,
Download,
Expand Down Expand Up @@ -63,6 +65,20 @@ export const ACTION_META: Record<ActionId, ActionMeta> = {
failure: SOMETHING_WRONG,
icon: ChevronsUp
},
earlier: {
label: 'Move up',
toolbar: 'Move up',
single: true,
failure: SOMETHING_WRONG,
icon: ChevronUp
},
later: {
label: 'Move down',
toolbar: 'Move down',
single: true,
failure: SOMETHING_WRONG,
icon: ChevronDown
},
retry: {
label: 'Retry',
many: (n) => `Retry ${n} downloads`,
Expand Down
30 changes: 28 additions & 2 deletions src/renderer/src/utils/downloadActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export type ActionId =
| 'pause'
| 'resume'
| 'next'
| 'earlier'
| 'later'
| 'retry'
| 'fix'
| 'again'
Expand Down Expand Up @@ -58,6 +60,8 @@ const appliesTo: Record<ActionId, (item: DownloadItem) => boolean> = {
resume: (item) => !isFinished(item) && item.status === 'paused',
// Waiting its turn, it can go first in line.
next: (item) => !isFinished(item) && item.status === 'queued',
earlier: (item) => !isFinished(item) && item.status === 'queued',
later: (item) => !isFinished(item) && item.status === 'queued',
retry: (item) => isFailed(item) && failureAction(item) === 'retry',
fix: (item) => isFailed(item) && failureAction(item) === 'fix',
again: (item) => isFailed(item) && failureAction(item) === 'again',
Expand All @@ -71,12 +75,32 @@ const appliesTo: Record<ActionId, (item: DownloadItem) => boolean> = {
}

/** These make sense for one download at a time: with several selected, they aren't offered. */
const SINGLE_ONLY: ReadonlySet<ActionId> = new Set(['fix', 'again', 'open', 'reveal', 'trackers'])
const SINGLE_ONLY: ReadonlySet<ActionId> = new Set([
'earlier',
'later',
'fix',
'again',
'open',
'reveal',
'trackers'
])

/** The order they're shown in, in groups: what to do with it, its link, getting rid of it.
* Menus put a separator between groups. */
export const ACTION_GROUPS: readonly (readonly ActionId[])[] = [
['pause', 'resume', 'next', 'retry', 'fix', 'again', 'open', 'reveal', 'trackers'],
[
'pause',
'resume',
'next',
'earlier',
'later',
'retry',
'fix',
'again',
'open',
'reveal',
'trackers'
],
['copy'],
['cancel', 'remove', 'trash']
]
Expand Down Expand Up @@ -113,6 +137,8 @@ export const TOOLBAR_PRIORITY: readonly ActionId[] = [
'open',
'cancel',
'next',
'earlier',
'later',
'reveal',
'remove',
'trash',
Expand Down
1 change: 1 addition & 0 deletions src/shared/ipc-channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const IpcChannels = {
pauseDownload: 'download:pause',
resumeDownload: 'download:resume',
startNext: 'download:start-next',
moveInQueue: 'download:move-in-queue',
relinkDownload: 'download:relink',
setDownloadNetwork: 'download:set-network',
cancelDownload: 'download:cancel',
Expand Down
2 changes: 2 additions & 0 deletions src/shared/ipc-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ export interface IpcContract {
resumeDownload: { args: [id: string]; result: void }
/** Moves a queued download to the front of the queue, to start when a place is free. */
startNext: { args: [id: string]; result: void }
/** Moves a queued download one place earlier (-1) or later (1) in the queue. */
moveInQueue: { args: [id: string, by: -1 | 1]; result: void }
/** A fresh link to the same file, for a download whose link stopped working; it resumes. */
relinkDownload: { args: [id: string, url: string]; result: void }
setDownloadNetwork: { args: [id: string, networkId: string, enabled: boolean]; result: void }
Expand Down