Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

Add download scheduling to network limits (#106)

Anmol Kapil7bfbe99396fb
diff --git a/README.md b/README.md
index 1887f79..8382fd2 100644
--- a/README.md
+++ b/README.md
@@ -88,6 +88,14 @@ Two buttons manage a network's limits, and both ask you to confirm:
- **Reset data usage…** sets the network's usage for the current period back to zero, so a network that hit its allowance can be used again
- **Remove limits…** clears the network's speed and data limits and keeps its recorded usage
+## Schedule overnight downloads
+
+Open **Networks → Speed & data limits… → All downloads** and find **Download schedule**. Enable the schedule, choose start and stop times in your computer’s local time, pick repeat days, and optionally set an end date. For a free-data window from midnight to 7 AM, use **00:00** and **07:00**.
+
+Outside those hours, new downloads and downloads you resume wait in the queue. At the stop time, active downloads and torrent uploads stop, keeping progress for the next window. Downloads you pause yourself stay paused. Scheduled work survives restarting Plexo; when the end date passes, it stays waiting until you change or disable the schedule. Disabling the schedule lets the queue start immediately.
+
+For a window crossing midnight, repeat days and the end date refer to the day it starts. Keep Plexo running and the computer awake for the scheduled start; Plexo keeps the computer awake while downloading, but does not wake a sleeping computer. Checking links and fetching magnet metadata when adding downloads can still use data outside the scheduled hours. The schedule controls Plexo’s transfers, not other apps or Plexo’s update check.
+
## How Plexo combines networks
Your operating system sends all of a computer's traffic through one default connection and leaves the others idle. Plexo opens its own connections on each network you select, and downloads different parts of the file on each.
diff --git a/e2e/downloadSchedule.spec.ts b/e2e/downloadSchedule.spec.ts
new file mode 100644
index 0000000..6f2ba3e
--- /dev/null
+++ b/e2e/downloadSchedule.spec.ts
@@ -0,0 +1,76 @@
+import { expect, test } from '@playwright/test'
+import {
+ DEFAULT_DOWNLOAD_SCHEDULE,
+ scheduleWindow,
+ validSchedule
+} from '../src/shared/downloadSchedule'
+import type { DownloadSchedule } from '../src/shared/types'
+
+const schedule: DownloadSchedule = { ...DEFAULT_DOWNLOAD_SCHEDULE, enabled: true }
+const at = (day: number, hour: number, minute = 0): number =>
+ new Date(2026, 9, day, hour, minute).getTime()
+
+test('the start is inclusive and the stop is exclusive', () => {
+ expect(scheduleWindow(schedule, at(10, 0)).allowed).toBe(true)
+ expect(scheduleWindow(schedule, at(10, 6, 59)).allowed).toBe(true)
+ expect(scheduleWindow(schedule, at(10, 7)).allowed).toBe(false)
+ expect(scheduleWindow(schedule, at(10, 7)).nextStart).toBe(at(11, 0))
+ expect(scheduleWindow(undefined, at(10, 12)).allowed).toBe(true)
+ expect(scheduleWindow({ ...schedule, enabled: false }, at(10, 12)).allowed).toBe(true)
+})
+
+test('overnight windows belong to their starting weekday', () => {
+ const friday = { ...schedule, startMinute: 22 * 60, days: [5] }
+ expect(scheduleWindow(friday, at(9, 22)).allowed).toBe(true)
+ expect(scheduleWindow(friday, at(10, 6)).allowed).toBe(true)
+ expect(scheduleWindow(friday, at(10, 7)).allowed).toBe(false)
+ expect(scheduleWindow(friday, at(10, 22)).nextStart).toBe(at(16, 22))
+})
+
+test('the final overnight window finishes, then expiration keeps downloads blocked', () => {
+ const final = { ...schedule, startMinute: 22 * 60, endDate: '2026-10-09' }
+ expect(scheduleWindow(final, at(10, 6)).allowed).toBe(true)
+ expect(scheduleWindow(final, at(10, 7))).toEqual({
+ allowed: false,
+ nextStart: undefined,
+ expired: true
+ })
+ expect(scheduleWindow(final, at(11, 22)).allowed).toBe(false)
+})
+
+test('invalid schedules fail closed', () => {
+ for (const patch of [
+ { days: [] },
+ { days: [7] },
+ { days: ['1'] },
+ { startMinute: -1 },
+ { endMinute: 1440 },
+ { endMinute: 0 },
+ { startMinute: 0.5 },
+ { endDate: '2026-02-30' },
+ { endDate: 'bad' }
+ ]) {
+ const invalid = { ...schedule, ...patch } as DownloadSchedule
+ expect(validSchedule(invalid)).toBe(false)
+ expect(scheduleWindow(invalid, at(10, 0)).allowed).toBe(false)
+ }
+})
+
+test('local wall-clock windows survive daylight saving changes', () => {
+ const previous = process.env.TZ
+ process.env.TZ = 'America/New_York'
+ try {
+ for (const date of [
+ [2026, 2, 8],
+ [2026, 10, 1]
+ ]) {
+ const [year, month, day] = date
+ const now = new Date(year, month, day, 6, 59).getTime()
+ expect(scheduleWindow(schedule, now).endsAt).toBe(new Date(year, month, day, 7).getTime())
+ expect(scheduleWindow(schedule, new Date(year, month, day, 7).getTime()).allowed).toBe(false)
+ }
+ } finally {
+ if (previous === undefined) delete process.env.TZ
+ else process.env.TZ = previous
+ }
+})
diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts
index 896d0ab..c1f3915 100644
--- a/e2e/fixtures.ts
+++ b/e2e/fixtures.ts
@@ -386,7 +386,7 @@ export class PlexoApp {
const ALLOWED_NEXT: Record<DownloadStatus, DownloadStatus[]> = {
queued: ['queued', 'downloading', 'paused', 'cancelled'],
- downloading: ['downloading', 'paused', 'completed', 'error', 'cancelled'],
+ downloading: ['downloading', 'queued', 'paused', 'completed', 'error', 'cancelled'],
// Resumed: at once, or into the queue when it's full.
paused: ['paused', 'downloading', 'queued', 'error', 'cancelled'],
completed: ['completed'],
diff --git a/e2e/scheduleQueue.spec.ts b/e2e/scheduleQueue.spec.ts
new file mode 100644
index 0000000..131a023
--- /dev/null
+++ b/e2e/scheduleQueue.spec.ts
@@ -0,0 +1,362 @@
+import { writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { DEFAULT_DOWNLOAD_SCHEDULE } from '../src/shared/downloadSchedule'
+import { BLOCK, expect, test, type PlexoApp } from './fixtures'
+import { named, Swarm, torrentFileOnDisk } from './torrentSwarm'
+import { seededBytes, sha256 } from './origin'
+
+const schedule = { ...DEFAULT_DOWNLOAD_SCHEDULE, enabled: true }
+const at = (day: number, hour: number): number => new Date(2000, 0, day, hour).getTime()
+
+async function clock(plexo: PlexoApp, now: number, wake = true): Promise<void> {
+ await plexo.evaluateMain(
+ ({ powerMonitor }, value) => {
+ Date.now = () => value.now
+ if (value.wake) powerMonitor.emit('resume')
+ },
+ { now, wake }
+ )
+}
+
+test('scheduled queue holds new downloads and manual resumes; manually paused downloads stay paused @smoke', async ({
+ plexo,
+ serve
+}) => {
+ await clock(plexo, at(1, 8))
+ await plexo.api.updateSettings({ downloadSchedule: schedule, downloadsAtOnce: 1 })
+ const origin = await serve({ size: 24 * BLOCK })
+ const first = await plexo.start(origin.url('/first'), origin.sha256)
+ const second = await plexo.start(origin.url('/second'), origin.sha256)
+ expect((await plexo.byId(first))?.status).toBe('queued')
+ expect((await plexo.byId(second))?.bytesDownloaded).toBe(0)
+ await plexo.api.pauseDownload(first)
+ await plexo.api.resumeDownload(first)
+ await expect.poll(async () => (await plexo.byId(first))?.status).toBe('queued')
+ await plexo.api.pauseDownload(first)
+ await clock(plexo, at(2, 0))
+ await expect.poll(async () => (await plexo.byId(second))?.status).toBe('completed')
+ expect((await plexo.byId(first))?.status).toBe('paused')
+ await plexo.api.resumeDownload(first)
+ await expect.poll(async () => (await plexo.byId(first))?.status).toBe('completed')
+})
+
+test('the clock cutoff stops active HTTP transfers, preserves progress, and blocks queue draining', async ({
+ plexo,
+ serve
+}) => {
+ await clock(plexo, at(1, 0))
+ await plexo.api.updateSettings({ downloadSchedule: schedule, downloadsAtOnce: 1 })
+ const origin = await serve({ size: 24 * BLOCK })
+ const held = origin.hold(4 * BLOCK)
+ const id = await plexo.start(origin.url(), origin.sha256)
+ await held
+ const next = await plexo.start(origin.url('/next'), origin.sha256)
+ // No wake event: the main-process timer must enforce the cutoff itself.
+ await clock(plexo, at(1, 7), false)
+ await expect.poll(async () => (await plexo.byId(id))?.status).toBe('queued')
+ const stopped = await plexo.byId(id)
+ expect(stopped?.bytesDownloaded).toBeGreaterThan(0)
+ expect(stopped?.speedBytesPerSec).toBe(0)
+ expect((await plexo.byId(next))?.bytesDownloaded).toBe(0)
+ origin.release()
+ await clock(plexo, at(2, 0))
+ await expect.poll(async () => (await plexo.byId(id))?.status).toBe('completed')
+ await expect.poll(async () => (await plexo.byId(next))?.status).toBe('completed')
+})
+
+test('scheduled intent survives restart, while expiration stays blocked until disabled', async ({
+ plexo,
+ serve
+}) => {
+ await clock(plexo, at(1, 8))
+ await plexo.api.updateSettings({ downloadSchedule: { ...schedule, endDate: '2000-01-02' } })
+ const origin = await serve({ size: 16 * BLOCK })
+ const id = await plexo.start(origin.url(), origin.sha256)
+ await plexo.relaunch()
+ expect((await plexo.byId(id))?.status).toBe('queued')
+ expect((await plexo.byId(id))?.bytesDownloaded).toBe(0)
+ await plexo.api.updateSettings({ downloadSchedule: { ...schedule, enabled: false } })
+ await expect.poll(async () => (await plexo.byId(id))?.status).toBe('completed')
+})
+
+test('a restart inside the window continues scheduled work', async ({ plexo, serve }) => {
+ const minute = new Date().getHours() * 60 + new Date().getMinutes()
+ const open = { ...schedule, startMinute: (minute + 1420) % 1440, endMinute: (minute + 20) % 1440 }
+ await plexo.api.updateSettings({ downloadSchedule: open })
+ const origin = await serve({ size: 24 * BLOCK })
+ const held = origin.hold(4 * BLOCK)
+ const id = await plexo.start(origin.url(), origin.sha256)
+ await held
+ await plexo.quit()
+ origin.release()
+ await plexo.launch()
+ await expect.poll(async () => (await plexo.byId(id))?.status).toBe('completed')
+})
+
+test('the cutoff stops torrent peers and uploads; reopening finishes the same file', async ({
+ plexo
+}) => {
+ const swarm = await new Swarm().start()
+ try {
+ await clock(plexo, at(1, 0))
+ await plexo.api.updateSettings({ downloadSchedule: schedule, speedLimit: 128 * 1024 })
+ const data = seededBytes(2 * 1024 * 1024, 32)
+ const torrent = await swarm.seed([named(data, 'scheduled.bin')], { pieceLength: 64 * 1024 })
+ const id = await plexo.start(await torrentFileOnDisk(torrent), sha256(data))
+ await plexo.waitUntil((state) => state.bytesDownloaded > 0)
+ await clock(plexo, at(1, 7))
+ await expect.poll(async () => (await plexo.byId(id))?.status).toBe('queued')
+ // Saving a closed window waits for the client to finish closing.
+ await plexo.api.updateSettings({ downloadSchedule: schedule })
+ const stopped = await plexo.byId(id)
+ expect(stopped?.speedBytesPerSec).toBe(0)
+ if (stopped?.kind === 'torrent') expect(stopped.uploadSpeedBytesPerSec).toBe(0)
+ await clock(plexo, at(2, 0))
+ await plexo.api.updateSettings({ speedLimit: undefined })
+ await expect
+ .poll(async () => (await plexo.byId(id))?.status, { timeout: 30_000 })
+ .toBe('completed')
+ } finally {
+ await swarm.stop()
+ }
+})
+
+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()
+ await plexo.page.getByRole('region', { name: 'Download schedule' }).scrollIntoViewIfNeeded()
+}
+
+async function chooseTime(plexo: PlexoApp, label: string, time: string): Promise<void> {
+ const [hour, minute] = time.split(':')
+ for (const [part, value] of [
+ ['hour', hour],
+ ['minute', minute]
+ ]) {
+ await plexo.page.getByRole('spinbutton', { name: `${label} ${part}`, exact: true }).fill(value)
+ }
+}
+
+test('schedule dialog saves, cancels edits, validates times, and restores settings', async ({
+ plexo
+}, testInfo) => {
+ const page = plexo.page
+ const indicator = page.getByRole('button', { name: 'Download schedule enabled', exact: true })
+ await expect(indicator).toBeHidden()
+ await openSchedule(plexo)
+ const dialog = page.getByRole('dialog', { name: 'Speed & data limits' })
+ await expect(dialog.getByRole('group', { name: 'Start at', exact: true })).toBeHidden()
+ await dialog.getByRole('switch', { name: 'Enable download schedule' }).check()
+ await chooseTime(plexo, 'Start at', '00:00')
+ await chooseTime(plexo, 'Stop at', '00:00')
+ await expect(dialog.getByRole('button', { name: 'Save', exact: true })).toBeDisabled()
+ await chooseTime(plexo, 'Stop at', '07:00')
+ await expect(dialog.locator('input[type="date"], input[type="time"]')).toHaveCount(0)
+ await dialog.getByRole('button', { name: 'Mon', exact: true }).click()
+ await expect(dialog.getByRole('button', { name: 'Mon', exact: true })).toHaveAttribute(
+ 'aria-pressed',
+ 'false'
+ )
+ await chooseTime(plexo, 'Stop at', '07:13')
+ await chooseTime(plexo, 'Stop at', '07:00')
+ await dialog.getByRole('button', { name: 'End date', exact: true }).click()
+ const calendar = page.getByRole('dialog', { name: 'Choose end date' })
+ await calendar.getByRole('button', { name: 'Go to the next month' }).click()
+ await page.screenshot({ path: '/tmp/plexo-schedule-calendar.png' })
+ // Choose a day in the displayed month, excluding the adjacent months' trailing dates.
+ await calendar
+ .locator('[data-slot="calendar"] td:not([data-outside]) button')
+ .filter({ hasText: /^15$/ })
+ .click()
+ const endDateLabel = await dialog
+ .getByRole('button', { name: 'End date', exact: true })
+ .innerText()
+ await testInfo.attach('schedule-dialog.png', {
+ body: await page.screenshot({ path: '/tmp/plexo-schedule-dialog.png' }),
+ contentType: 'image/png'
+ })
+ await dialog.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(dialog).toBeHidden()
+ await expect(indicator).toBeVisible()
+ await page.screenshot({ path: '/tmp/plexo-schedule-toolbar.png' })
+ await indicator.click()
+ await expect(dialog.getByRole('switch', { name: 'Enable download schedule' })).toBeFocused()
+ await expect(dialog.getByRole('region', { name: 'Download schedule' })).toBeInViewport()
+ await expect(dialog.getByRole('button', { name: 'End date', exact: true })).toBeInViewport({
+ ratio: 1
+ })
+ await chooseTime(plexo, 'Stop at', '09:00')
+ await dialog.getByRole('navigation').getByRole('button').nth(1).click()
+ await dialog.getByRole('button', { name: /^All downloads/ }).click()
+ await expect(dialog.getByRole('spinbutton', { name: 'Stop at hour', exact: true })).toHaveValue(
+ '09'
+ )
+ await dialog.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await plexo.relaunch()
+ await openSchedule(plexo)
+ const restored = plexo.page.getByRole('dialog', { name: 'Speed & data limits' })
+ await expect(restored.getByRole('switch', { name: 'Enable download schedule' })).toBeChecked()
+ await expect(restored.getByRole('spinbutton', { name: 'Stop at hour', exact: true })).toHaveValue(
+ '07'
+ )
+ await expect(restored.getByRole('button', { name: 'End date', exact: true })).toHaveText(
+ endDateLabel
+ )
+ await expect(restored.getByRole('button', { name: 'Mon', exact: true })).toHaveAttribute(
+ 'aria-pressed',
+ 'false'
+ )
+ await restored.getByRole('button', { name: 'End date', exact: true }).click()
+ await plexo.page.getByRole('button', { name: 'Clear', exact: true }).click()
+ await expect(restored.getByRole('button', { name: 'End date', exact: true })).toHaveText(
+ 'No end date'
+ )
+ await restored.getByRole('switch', { name: 'Enable download schedule' }).uncheck()
+ await restored.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(
+ plexo.page.getByRole('button', { name: 'Download schedule enabled', exact: true })
+ ).toBeHidden()
+})
+
+test('an overnight schedule remains usable at the minimum window size', async ({ plexo }) => {
+ await plexo.evaluateMain(({ BrowserWindow }) => {
+ const window = BrowserWindow.getAllWindows()[0]
+ window.setSize(720, 620)
+ }, null)
+ await plexo.page.emulateMedia({ colorScheme: 'dark' })
+ await openSchedule(plexo)
+ const dialog = plexo.page.getByRole('dialog', { name: 'Speed & data limits' })
+ await dialog.getByRole('switch', { name: 'Enable download schedule' }).check()
+ await chooseTime(plexo, 'Start at', '22:00')
+ const minute = dialog.getByRole('spinbutton', { name: 'Start at minute', exact: true })
+ const hour = dialog.getByRole('spinbutton', { name: 'Start at hour', exact: true })
+ await minute.focus()
+ await plexo.page.keyboard.press('ArrowDown')
+ await expect(minute).toHaveValue('59')
+ await expect(minute).toHaveAttribute('aria-valuenow', '59')
+ await plexo.page.keyboard.press('ArrowUp')
+ await expect(minute).toHaveValue('00')
+ await plexo.page.keyboard.press('ArrowLeft')
+ await expect(hour).toBeFocused()
+ await plexo.page.keyboard.press('End')
+ await expect(hour).toHaveValue('23')
+ await plexo.page.keyboard.press('ArrowUp')
+ await expect(hour).toHaveValue('00')
+ await hour.evaluate((input) => {
+ const clipboardData = new DataTransfer()
+ clipboardData.setData('text/plain', '21:37')
+ input.dispatchEvent(
+ new ClipboardEvent('paste', { clipboardData, bubbles: true, cancelable: true })
+ )
+ })
+ await expect(hour).toHaveValue('21')
+ await expect(minute).toHaveValue('37')
+ await hour.focus()
+ await plexo.page.keyboard.press('ControlOrMeta+A')
+ await hour.pressSequentially('22')
+ await expect(minute).toBeFocused()
+ await minute.fill('00')
+ await minute.fill('75')
+ await expect(minute).toHaveValue('00')
+ await plexo.page.screenshot({ path: '/tmp/plexo-schedule-time-dark.png' })
+ await expect(dialog.getByText('Next day', { exact: true })).toBeVisible()
+ await dialog.getByRole('button', { name: 'Save', exact: true }).scrollIntoViewIfNeeded()
+ await expect(dialog.getByRole('button', { name: 'Save', exact: true })).toBeInViewport({
+ ratio: 1
+ })
+ await dialog.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(dialog).toBeHidden()
+})
+
+test('main refuses invalid schedule changes without clearing the existing window', async ({
+ plexo,
+ serve
+}) => {
+ await clock(plexo, at(1, 8))
+ await plexo.api.updateSettings({ downloadSchedule: schedule })
+ await expect(
+ plexo.api.updateSettings({ downloadSchedule: { ...schedule, days: [] } })
+ ).rejects.toThrow()
+ const origin = await serve({ size: 8 * BLOCK })
+ const id = await plexo.start(origin.url(), origin.sha256)
+ expect((await plexo.byId(id))?.status).toBe('queued')
+ await plexo.api.updateSettings({ downloadSchedule: { ...schedule, enabled: false } })
+ await expect.poll(async () => (await plexo.byId(id))?.status).toBe('completed')
+})
+
+test('quitting during the cutoff saves progress and leaves the restored queue stopped', async ({
+ plexo,
+ serve
+}) => {
+ await clock(plexo, at(1, 0))
+ await plexo.api.updateSettings({ downloadSchedule: { ...schedule, endDate: '2000-01-02' } })
+ const origin = await serve({ size: 24 * BLOCK })
+ const held = origin.hold(4 * BLOCK)
+ const id = await plexo.start(origin.url(), origin.sha256)
+ await held
+ await clock(plexo, at(1, 7))
+ await plexo.quit()
+ origin.release()
+ await plexo.launch()
+ const restored = await plexo.byId(id)
+ expect(restored?.status).toBe('queued')
+ expect(restored?.bytesDownloaded).toBeGreaterThan(0)
+ await plexo.api.updateSettings({ downloadSchedule: { ...schedule, enabled: false } })
+ await expect.poll(async () => (await plexo.byId(id))?.status).toBe('completed')
+})
+
+test('enabling a closed window adopts active work; a manual pause survives its cutoff and restart', async ({
+ plexo,
+ serve
+}) => {
+ const origin = await serve({ size: 24 * BLOCK })
+ const held = origin.hold(4 * BLOCK)
+ await plexo.api.updateSettings({ downloadsAtOnce: 1 })
+ const active = await plexo.start(origin.url('/active'), origin.sha256)
+ await held
+ const waiting = await plexo.start(origin.url('/waiting'), origin.sha256)
+ await clock(plexo, at(1, 8))
+ await plexo.api.updateSettings({ downloadSchedule: schedule })
+ const stopped = await plexo.byId(active)
+ expect(stopped?.status).toBe('queued')
+ expect(stopped?.scheduled).toBe(true)
+ expect((await plexo.byId(waiting))?.scheduled).toBe(true)
+ await plexo.api.pauseDownload(active)
+ await plexo.quit()
+ origin.release()
+ await plexo.launch()
+ expect((await plexo.byId(active))?.status).toBe('paused')
+ // Whichever local time the app restarted in, the scheduled entry can run when disabled.
+ await plexo.api.updateSettings({ downloadSchedule: { ...schedule, enabled: false } })
+ await expect.poll(async () => (await plexo.byId(waiting))?.status).toBe('completed')
+ expect((await plexo.byId(active))?.status).toBe('paused')
+ await plexo.api.resumeDownload(active)
+ await expect.poll(async () => (await plexo.byId(active))?.status).toBe('completed')
+})
+
+test('a malformed saved schedule blocks transfers and can be disabled from settings', async ({
+ plexo,
+ serve,
+ dirs
+}) => {
+ await clock(plexo, at(1, 8))
+ await plexo.api.updateSettings({ downloadSchedule: schedule })
+ const origin = await serve({ size: 8 * BLOCK })
+ const id = await plexo.start(origin.url(), origin.sha256)
+ await plexo.quit()
+ await writeFile(
+ join(dirs.userData, 'app-settings.json'),
+ JSON.stringify({
+ downloadSchedule: { ...schedule, days: [] }
+ })
+ )
+ await plexo.launch()
+ expect((await plexo.byId(id))?.status).toBe('queued')
+ expect((await plexo.byId(id))?.bytesDownloaded).toBe(0)
+ await openSchedule(plexo)
+ const dialog = plexo.page.getByRole('dialog', { name: 'Speed & data limits' })
+ await expect(dialog.getByRole('button', { name: 'Save', exact: true })).toBeDisabled()
+ await dialog.getByRole('switch', { name: 'Enable download schedule' }).uncheck()
+ await dialog.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect.poll(async () => (await plexo.byId(id))?.status).toBe('completed')
+})
diff --git a/package-lock.json b/package-lock.json
index 2570363..2580a2b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -15,10 +15,12 @@
"bittorrent-peerid": "2.0.2",
"class-variance-authority": "^0.7.1",
"cn": "^0.3.0",
+ "date-fns": "^4.4.0",
"fs-chunk-store": "5.0.1",
"koffi": "^2.16.3",
"lucide-react": "^1.47.0",
"parse-torrent": "11.0.24",
+ "react-day-picker": "^10.0.2",
"webtorrent": "3.0.21",
"zustand": "^5.0.15"
},
@@ -417,6 +419,12 @@
}
}
},
+ "node_modules/@date-fns/tz": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.5.0.tgz",
+ "integrity": "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==",
+ "license": "MIT"
+ },
"node_modules/@electron-internal/extract-zip": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.5.tgz",
@@ -4873,6 +4881,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/date-fns": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz",
+ "integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/kossnocorp"
+ }
+ },
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -9829,6 +9847,32 @@
"node": ">=0.10.0"
}
},
+ "node_modules/react-day-picker": {
+ "version": "10.0.2",
+ "resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-10.0.2.tgz",
+ "integrity": "sha512-QetiKtZWE9Uaw/pM/SYNv6WPYOTRnSJ2puL0GgwkmUFMIwiY0dtjH1W4B7DOVXVNQM0ZOClGpH/heOfBSzWeiA==",
+ "license": "MIT",
+ "dependencies": {
+ "@date-fns/tz": "^1.4.1",
+ "date-fns": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://github.com/sponsors/gpbl"
+ },
+ "peerDependencies": {
+ "@types/react": ">=16.8.0",
+ "react": ">=16.8.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/react-dom": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz",
diff --git a/package.json b/package.json
index 0427257..ba40858 100644
--- a/package.json
+++ b/package.json
@@ -35,10 +35,12 @@
"bittorrent-peerid": "2.0.2",
"class-variance-authority": "^0.7.1",
"cn": "^0.3.0",
+ "date-fns": "^4.4.0",
"fs-chunk-store": "5.0.1",
"koffi": "^2.16.3",
"lucide-react": "^1.47.0",
"parse-torrent": "11.0.24",
+ "react-day-picker": "^10.0.2",
"webtorrent": "3.0.21",
"zustand": "^5.0.15"
},
diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.ts
index 4632ac7..2271c7f 100644
--- a/src/main/download/downloadManager.ts
+++ b/src/main/download/downloadManager.ts
@@ -5,12 +5,14 @@ import { lstat, readFile, readdir, rename, rm, stat, statfs, writeFile } from 'n
import { basename, dirname, isAbsolute, join, sep } from 'node:path'
import type { BrowserWindow } from 'electron'
import { app, Notification, powerSaveBlocker, safeStorage, shell } from 'electron'
+import { scheduleWindow } from '../../shared/downloadSchedule'
import { IpcChannels } from '../../shared/ipc-channels'
import {
DOWNLOADS_AT_ONCE,
SPEED_HISTORY_SECONDS,
type AppSettings,
type BrowserContext,
+ type DownloadSchedule,
type DownloadNetwork,
type DownloadState,
type DownloadStatus,
@@ -74,6 +76,7 @@ interface RuntimeFields {
publicationIdentity?: { dev: number; ino: number }
runPromise?: Promise<void>
cancelPromise?: Promise<void>
+ scheduleStopping?: boolean
publishing: boolean
pushScheduled: boolean
persistenceTimer?: NodeJS.Timeout
@@ -352,6 +355,9 @@ export class DownloadManager {
private relinking = new Set<string>()
private readonly initialization: Promise<void>
private suspending = false
+ private scheduleLoaded = false
+ private downloadSchedule?: DownloadSchedule
+ private scheduleTimer?: NodeJS.Timeout
/** Each network's addresses as last seen, by id: what tells a network that has changed. */
private seenAddresses = new Map<string, string[]>()
/** The powerSaveBlocker keeping the computer awake while a download runs (see keepAwake). */
@@ -365,20 +371,42 @@ export class DownloadManager {
private getWindow: () => BrowserWindow | null,
private networks: NetworkMonitor
) {
- this.initialization = Promise.all([
- this.restorePersistedDownloads(),
- this.limits.loaded,
- loadSettings().then((settings) => this.applySettings(settings))
- ]).then(() => {})
+ this.initialization = Promise.all([this.restorePersistedDownloads(), this.limits.loaded]).then(
+ async () => {
+ // Read after recovery, including any settings saved while the manifests were loading.
+ await this.configureSettings(await loadSettings())
+ }
+ )
}
/** Takes up what the user set: how many run at once, and the limits. One running past a
* lowered count is left to finish; a raised one starts the next ones in the queue. */
- applySettings(settings: AppSettings): void {
+ async applySettings(settings: AppSettings): Promise<void> {
+ await this.initialization
+ await this.configureSettings(settings)
+ }
+
+ private async configureSettings(settings: AppSettings): Promise<void> {
+ this.downloadSchedule = settings.downloadSchedule
+ this.scheduleLoaded = true
+ const enrollmentChanged: DownloadRuntime[] = []
+ const scheduled = this.downloadSchedule?.enabled || undefined
+ for (const runtime of this.runtimes.values()) {
+ if (
+ (runtime.state.status === 'queued' || runtime.state.status === 'downloading') &&
+ runtime.state.scheduled !== scheduled
+ ) {
+ runtime.state.scheduled = scheduled
+ enrollmentChanged.push(runtime)
+ this.pushUpdate(runtime)
+ }
+ }
this.downloadsAtOnce = settings.downloadsAtOnce ?? DOWNLOADS_AT_ONCE.default
this.limits.configure(settings)
+ await this.refreshSchedule()
this.limitsChanged()
- this.pump()
+ await Promise.all(enrollmentChanged.map((runtime) => this.persistNow(runtime)))
+ this.armScheduleTimer()
}
/** A network ran out of data, or a limit changed: each download's networks are looked at
@@ -397,6 +425,45 @@ export class DownloadManager {
}
}
+ private armScheduleTimer(): void {
+ clearTimeout(this.scheduleTimer)
+ if (this.suspending || !this.downloadSchedule?.enabled) return
+ // Check the clock as well as exact boundaries, including timezone changes while running.
+ const now = Date.now()
+ const window = scheduleWindow(this.downloadSchedule, now)
+ const boundary = window.allowed ? window.endsAt : window.nextStart
+ this.scheduleTimer = setTimeout(
+ () => {
+ void this.refreshSchedule()
+ .catch((error) => console.error('[plexo] schedule', error))
+ .finally(() => this.armScheduleTimer())
+ },
+ boundary ? Math.max(1, Math.min(1000, boundary - now)) : 1000
+ )
+ this.scheduleTimer.unref()
+ }
+
+ private scheduleAllowsDownloads(): boolean {
+ return this.scheduleLoaded && scheduleWindow(this.downloadSchedule).allowed
+ }
+
+ /** Close transfers before the queue can start anything else. The queued intent is persisted,
+ * so a scheduled download can continue next night after a relaunch. */
+ private async refreshSchedule(): Promise<void> {
+ if (this.suspending) return
+ if (!this.scheduleAllowsDownloads()) {
+ await Promise.all(
+ [...this.runtimes.values()].map((runtime) =>
+ runtime.state.status === 'downloading' || runtime.scheduleStopping
+ ? this.pause(runtime.state.id, true)
+ : undefined
+ )
+ )
+ } else {
+ this.pump()
+ }
+ }
+
/** Running downloads on Auto with `networkId` on: how many share its streams (see
* concurrency.ts). One that can't split runs a single stream, and a picked count is kept, so
* neither takes a share. */
@@ -428,9 +495,9 @@ export class DownloadManager {
/** Starts queued downloads, first queued first, while fewer than downloadsAtOnce run. Called
* whenever one might have room: a run ended, a queued one went, the count went up. */
private pump(): void {
- if (this.suspending) return
+ if (this.suspending || !this.scheduleAllowsDownloads()) return
const queued = [...this.runtimes.values()]
- .filter((runtime) => runtime.state.status === 'queued')
+ .filter((runtime) => runtime.state.status === 'queued' && !runtime.scheduleStopping)
.sort((a, b) => (a.state.queuedAt ?? 0) - (b.state.queuedAt ?? 0))
for (const runtime of queued) {
if (this.runningCount() >= this.downloadsAtOnce) return
@@ -444,6 +511,7 @@ export class DownloadManager {
.filter((other) => other !== runtime && other.state.status === 'queued')
.map((other) => other.state.queuedAt ?? 0)
runtime.state.status = 'queued'
+ runtime.state.scheduled = this.downloadSchedule?.enabled || undefined
// Time spent waiting isn't time spent downloading (begin adds it to totalPausedMs).
runtime.state.pausedAt ??= Date.now()
runtime.state.queuedAt = front
@@ -731,7 +799,7 @@ export class DownloadManager {
return null
}
const units = unitsOf(runtime)
- // Nothing starts by itself after a relaunch: running or waiting, it comes back paused.
+ // Restore paused first so the partial file can be checked before scheduled work is queued.
if (state.status === 'downloading' || state.status === 'queued') {
state.status = 'paused'
state.pausedAt = persisted.savedAt || Date.now()
@@ -786,6 +854,11 @@ export class DownloadManager {
}
}
+ if (state.status === 'paused' && state.scheduled === true) {
+ state.status = 'queued'
+ state.queuedAt = persisted.state.queuedAt ?? state.startedAt
+ }
+
runtime.publicationPath = persisted.publicationPath
runtime.publicationIdentity = persisted.publicationIdentity
// A resumed download's last minute starts when it does, not where it stopped before the
@@ -938,12 +1011,13 @@ export class DownloadManager {
)
}
// Decided only now: other starts may have taken the room while this one was set up.
- const room = this.runningCount() < this.downloadsAtOnce
+ const room = this.runningCount() < this.downloadsAtOnce && this.scheduleAllowsDownloads()
if (!room) this.enqueue(runtime, false)
+ runtime.state.scheduled = this.downloadSchedule?.enabled || undefined
this.runtimes.set(id, runtime)
await this.persistNow(runtime)
this.pushUpdate(runtime)
- if (room) this.launch(runtime)
+ if (room) this.begin(runtime)
return id
}
@@ -953,19 +1027,31 @@ export class DownloadManager {
runtime.runPromise = this.run(runtime).finally(() => this.pump())
}
- async pause(id: string): Promise<void> {
+ async pause(id: string, forSchedule = false): Promise<void> {
const runtime = this.runtimes.get(id)
if (runtime?.state.status === 'queued') {
+ if (forSchedule) {
+ await runtime.runPromise
+ return
+ }
+ runtime.state.scheduled = undefined
runtime.state.status = 'paused'
runtime.state.queuedAt = undefined
runtime.state.pausedAt ??= Date.now()
this.pushUpdate(runtime)
+ await runtime.runPromise
await this.persistNow(runtime)
return
}
if (!runtime || runtime.state.status !== 'downloading' || runtime.publishing) return
- runtime.state.status = 'paused'
+ if (forSchedule) {
+ runtime.scheduleStopping = true
+ this.enqueue(runtime, false)
+ } else {
+ runtime.state.status = 'paused'
+ runtime.state.scheduled = undefined
+ }
runtime.state.pausedAt = Date.now()
clearSpeeds(runtime.state)
if (runtime.kind === 'http') {
@@ -986,8 +1072,13 @@ export class DownloadManager {
runtime.transfer.reset()
this.stopRun(runtime)
this.pushUpdate(runtime)
- await runtime.runPromise
- await this.persistNow(runtime)
+ try {
+ await runtime.runPromise
+ await this.persistNow(runtime)
+ } finally {
+ runtime.scheduleStopping = false
+ this.pump()
+ }
}
/** Gives a download whose link stopped working (a signed link ran out, say) a fresh link to the
@@ -1142,13 +1233,14 @@ export class DownloadManager {
// Switched back on, then off again while the paused run wound down: it stays paused.
if (byNetwork && !networks.some((network) => network.enabled)) return
- if (this.runningCount() >= this.downloadsAtOnce) {
+ if (this.runningCount() >= this.downloadsAtOnce || !this.scheduleAllowsDownloads()) {
// Asked for by name, so it goes next.
this.enqueue(runtime, true)
runtime.state.error = undefined
runtime.state.resumable = undefined
runtime.pausedForNoNetwork = undefined
this.pushUpdate(runtime)
+ await this.persistNow(runtime)
return
}
this.begin(runtime)
@@ -1156,6 +1248,13 @@ export class DownloadManager {
/** Starts a run of a paused, failed or queued download, from where it stopped. */
private begin(runtime: DownloadRuntime): void {
+ if (this.suspending || !this.scheduleAllowsDownloads()) {
+ this.enqueue(runtime, false)
+ this.pushUpdate(runtime)
+ void this.persistNow(runtime)
+ return
+ }
+ runtime.state.scheduled = this.downloadSchedule?.enabled || undefined
const { networks } = runtime.state
runtime.state.status = 'downloading'
runtime.state.queuedAt = undefined
@@ -1280,6 +1379,9 @@ export class DownloadManager {
* a stall watchdog runs out, and every judgement made by the clock (a silent network, a
* crawling connection) spans the sleep. All of it starts over. */
systemResumed(): void {
+ void this.refreshSchedule().catch((error) =>
+ console.error('[plexo] schedule after wake', error)
+ )
const now = Date.now()
for (const runtime of this.runtimes.values()) {
if (runtime.state.status !== 'downloading') continue
@@ -1506,10 +1608,15 @@ export class DownloadManager {
async suspendAll(): Promise<void> {
await this.initialization
this.suspending = true
+ clearTimeout(this.scheduleTimer)
await Promise.all(
[...this.runtimes.values()].map(async (runtime) => {
- if (runtime.state.status === 'downloading') await this.pause(runtime.state.id)
- else await this.persistNow(runtime)
+ if (runtime.state.status === 'downloading')
+ await this.pause(runtime.state.id, runtime.state.scheduled === true)
+ else {
+ if (runtime.scheduleStopping) await runtime.runPromise
+ await this.persistNow(runtime)
+ }
})
)
await this.limits.save()
@@ -1733,6 +1840,12 @@ export class DownloadManager {
}
}
if (state.status !== 'downloading' || runtime.stop.signal.aborted) return
+ if (!this.scheduleAllowsDownloads()) {
+ void this.pause(state.id, true).catch((error) =>
+ console.error('[plexo] schedule cutoff', error)
+ )
+ return
+ }
const enabled = state.networks.filter((network) => network.enabled)
if (enabled.length > 0 && enabled.every((network) => network.status === 'failed')) {
@@ -1877,7 +1990,7 @@ export class DownloadManager {
publicationIdentity: runtime.publicationIdentity,
...savedRequest(runtime)
}
- if (runtime.state.status === 'downloading' || runtime.state.status === 'paused') {
+ if (['downloading', 'paused', 'queued'].includes(runtime.state.status)) {
await runtime.file.sync()
}
await ensureDirectory(dir)
diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.ts
index e9fef0a..1f07300 100644
--- a/src/main/ipc/handlers.ts
+++ b/src/main/ipc/handlers.ts
@@ -105,7 +105,7 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
}
await saveSettings(patch)
// Read back rather than taken from the patch: what was saved is what passed the checks.
- manager.applySettings(await loadSettings())
+ await manager.applySettings(await loadSettings())
})
// Answered via sendSync from the preload, which blocks the page until returnValue is set — so a
@@ -126,6 +126,7 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
new Promise<boolean>((resolve) => setTimeout(resolve, DESTINATION_CHECK_MS, false))
]))
event.returnValue = {
+ downloadSchedule: settings.downloadSchedule,
homeDir: getHomeDir(),
downloadsDir: getDefaultDownloadsDir(),
themeSource: currentThemeSource(),
diff --git a/src/main/settings.ts b/src/main/settings.ts
index 2964a47..69af7d3 100644
--- a/src/main/settings.ts
+++ b/src/main/settings.ts
@@ -9,6 +9,7 @@ import {
type ThemeSource
} from '../shared/types'
import { readJson, updateJson } from './jsonFile'
+import { DEFAULT_DOWNLOAD_SCHEDULE, validSchedule } from '../shared/downloadSchedule'
function settingsPath(): string {
return join(app.getPath('userData'), 'app-settings.json')
@@ -62,6 +63,11 @@ function sanitizeSettings(parsed: unknown): AppSettings {
const { themeSource, dismissedUpdateVersion, destinationDir, downloadsAtOnce } = parsed
const settings: AppSettings = {}
+ if (parsed.downloadSchedule !== undefined) {
+ settings.downloadSchedule = validSchedule(parsed.downloadSchedule)
+ ? parsed.downloadSchedule
+ : { ...DEFAULT_DOWNLOAD_SCHEDULE, enabled: true, days: [] }
+ }
// 'system' was once an option — dropping it falls back to the OS appearance (loadThemeSource).
if (themeSource === 'light' || themeSource === 'dark') settings.themeSource = themeSource
if (typeof dismissedUpdateVersion === 'string') {
@@ -100,6 +106,13 @@ export async function loadSettings(): Promise<AppSettings> {
/** Merges `patch` over what's saved. */
export function saveSettings(patch: unknown): Promise<void> {
+ if (
+ isRecord(patch) &&
+ patch.downloadSchedule !== undefined &&
+ !validSchedule(patch.downloadSchedule)
+ ) {
+ return Promise.reject(new Error('Choose different start and stop times and at least one day.'))
+ }
return updateJson(settingsPath(), (current) =>
sanitizeSettings({ ...sanitizeSettings(current), ...(isRecord(patch) ? patch : {}) })
)
diff --git a/src/renderer/src/components/LimitsDialog.tsx b/src/renderer/src/components/LimitsDialog.tsx
index 48f87fd..b53a337 100644
--- a/src/renderer/src/components/LimitsDialog.tsx
+++ b/src/renderer/src/components/LimitsDialog.tsx
@@ -1,12 +1,15 @@
+import { DEFAULT_DOWNLOAD_SCHEDULE, scheduleTime, validSchedule } from '@shared/downloadSchedule'
+import { ScheduleFields } from './ScheduleFields'
import { DATA_LIMIT_PERIODS, dataUsageLabel, nextDataReset } from '@shared/dataLimits'
import {
DEFAULT_SLOW_MODE_SPEED,
DOWNLOADS_AT_ONCE,
+ type AppSettings,
type DataLimitPeriod,
type NetworkPreference
} from '@shared/types'
import { Minus, Plus } from 'lucide-react'
-import { useEffect, useId, useState } from 'react'
+import { useEffect, useId, useRef, useState } from 'react'
import { useNetworkUsage } from '../hooks/useNetworks'
import { useNetworkVisuals } from '../hooks/useNetworkVisuals'
import { useAppStore } from '../store/useAppStore'
@@ -22,6 +25,7 @@ import {
AlertDialogCancel,
AlertDialogAction
} from './ui/alert-dialog'
+import { Alert, AlertDescription } from './ui/alert'
import { Button } from './ui/button'
import { Dialog, DialogContent, DialogTitle } from './ui/dialog'
import { Input } from './ui/input'
@@ -31,11 +35,17 @@ import { ToggleGroup, ToggleGroupItem } from './ui/toggle-group'
/** What the dialog edits: a copy taken when it opens, written back only on Save. */
type Draft = Pick<
ReturnType<typeof useAppStore.getState>,
- 'speedLimit' | 'slowMode' | 'slowModeSpeed' | 'downloadsAtOnce' | 'networkPreferences'
+ | 'speedLimit'
+ | 'slowMode'
+ | 'slowModeSpeed'
+ | 'downloadsAtOnce'
+ | 'networkPreferences'
+ | 'downloadSchedule'
>
/** All downloads as a fresh install has them. */
const GENERAL_DEFAULTS = {
+ downloadSchedule: undefined,
speedLimit: undefined,
slowMode: false,
slowModeSpeed: DEFAULT_SLOW_MODE_SPEED,
@@ -291,6 +301,10 @@ function GeneralPage({
at the same time
</div>
</section>
+ <ScheduleFields
+ schedule={draft.downloadSchedule ?? DEFAULT_DOWNLOAD_SCHEDULE}
+ onChange={(downloadSchedule) => change({ downloadSchedule })}
+ />
<div className="flex flex-wrap items-center gap-2 border-t-[0.5px] border-border pt-3">
<Button
variant="secondary"
@@ -306,8 +320,8 @@ function GeneralPage({
<AlertDialogHeader>
<AlertDialogTitle>Reset all downloads to defaults?</AlertDialogTitle>
<AlertDialogDescription>
- This resets total speed, slow mode and downloads at once. Network limits stay
- unchanged.
+ This resets total speed, slow mode, downloads at once and the download schedule.
+ Network limits stay unchanged.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
@@ -535,20 +549,38 @@ function describeLimits(
* Save; Cancel (or Escape) leaves everything as it was. Resetting data usage is the exception:
* it's an action, not a setting, so it happens once confirmed. */
export function LimitsDialog({
+ showSchedule = false,
open,
onOpenChange,
page,
onPageChange
}: {
+ showSchedule?: boolean
open: boolean
onOpenChange: (open: boolean) => void
/** The network shown, by interface id; null for General. */
page: string | null
onPageChange: (page: string | null) => void
}): React.JSX.Element {
+ const contentRef = useRef<HTMLDivElement>(null)
return (
<Dialog open={open} disablePointerDismissal onOpenChange={onOpenChange}>
<DialogContent
+ ref={contentRef}
+ initialFocus={
+ showSchedule
+ ? () => {
+ contentRef.current
+ ?.querySelector<HTMLElement>('[aria-label="Download schedule"]')
+ ?.scrollIntoView({ block: 'start' })
+ return (
+ contentRef.current?.querySelector<HTMLElement>(
+ '[aria-label="Enable download schedule"]'
+ ) ?? false
+ )
+ }
+ : undefined
+ }
showCloseButton={false}
className="flex h-[min(520px,calc(100%-2rem))] max-w-[680px] flex-col gap-0 p-0 sm:max-w-[680px]"
>
@@ -571,9 +603,22 @@ function LimitsEditor({
const formatSpeedLimit = useFormatSpeedLimit()
const interfaces = useAppStore((store) => store.interfaces)
const [draft, setDraft] = useState<Draft>(() => {
- const { speedLimit, slowMode, slowModeSpeed, downloadsAtOnce, networkPreferences } =
- useAppStore.getState()
- return { speedLimit, slowMode, slowModeSpeed, downloadsAtOnce, networkPreferences }
+ const {
+ speedLimit,
+ slowMode,
+ slowModeSpeed,
+ downloadsAtOnce,
+ networkPreferences,
+ downloadSchedule
+ } = useAppStore.getState()
+ return {
+ speedLimit,
+ slowMode,
+ slowModeSpeed,
+ downloadsAtOnce,
+ networkPreferences,
+ downloadSchedule
+ }
})
const change = (patch: Partial<Draft>): void =>
setDraft((previous) => ({ ...previous, ...patch }))
@@ -585,19 +630,36 @@ function LimitsEditor({
[id]: { ...previous.networkPreferences[id], ...patch }
}
}))
- // Only what changed is written, so a running download isn't re-limited for nothing.
- const save = (): void => {
+ const [saving, setSaving] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const valid = draft.downloadSchedule === undefined || validSchedule(draft.downloadSchedule)
+ // Save one patch so the schedule and limits take effect together. Failed saves keep the draft.
+ const save = async (): Promise<void> => {
+ setSaving(true)
+ setError(null)
const store = useAppStore.getState()
- if (draft.speedLimit !== store.speedLimit) store.setSpeedLimit(draft.speedLimit)
- if (draft.slowMode !== store.slowMode) store.setSlowMode(draft.slowMode)
- if (draft.slowModeSpeed !== store.slowModeSpeed) store.setSlowModeSpeed(draft.slowModeSpeed)
- if (draft.downloadsAtOnce !== store.downloadsAtOnce) {
- store.setDownloadsAtOnce(draft.downloadsAtOnce)
- }
+ const patch: AppSettings = {}
+ if (draft.speedLimit !== store.speedLimit) patch.speedLimit = draft.speedLimit
+ if (draft.slowMode !== store.slowMode) patch.slowMode = draft.slowMode
+ if (draft.slowModeSpeed !== store.slowModeSpeed) patch.slowModeSpeed = draft.slowModeSpeed
+ if (draft.downloadsAtOnce !== store.downloadsAtOnce)
+ patch.downloadsAtOnce = draft.downloadsAtOnce
+ if (draft.downloadSchedule !== store.downloadSchedule)
+ patch.downloadSchedule = draft.downloadSchedule
for (const [id, preference] of Object.entries(draft.networkPreferences)) {
- if (preference !== store.networkPreferences[id]) store.setNetworkPreference(id, preference)
+ if (preference !== store.networkPreferences[id]) {
+ patch.networkPreferences ??= { ...store.networkPreferences }
+ patch.networkPreferences[id] = preference
+ }
+ }
+ try {
+ await window.plexo.updateSettings(patch)
+ useAppStore.setState(patch)
+ onClose()
+ } catch (cause) {
+ setError(describeError(cause))
+ setSaving(false)
}
- onClose()
}
const { speedLimit, slowMode, networkPreferences: preferences } = draft
const running = useAppStore(
@@ -652,7 +714,12 @@ function LimitsEditor({
? 'Slow mode on'
: speedLimit
? `Limit ${formatSpeedLimit(speedLimit)}`
- : 'No limit'
+ : 'No limit',
+ ...(draft.downloadSchedule?.enabled
+ ? [
+ `${scheduleTime(draft.downloadSchedule.startMinute)}–${scheduleTime(draft.downloadSchedule.endMinute)}`
+ ]
+ : [])
])}
<div className={navLabelClass}>Networks</div>
{interfaces.map((iface) => {
@@ -671,7 +738,7 @@ function LimitsEditor({
)
})}
</nav>
- <div className="min-h-0 flex-1 overflow-y-auto px-4 py-3">
+ <fieldset disabled={saving} className="min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-3">
{shown ? (
<NetworkPage
key={shown.id}
@@ -685,14 +752,23 @@ function LimitsEditor({
) : (
<GeneralPage running={running} draft={draft} change={change} />
)}
- </div>
+ </fieldset>
</div>
+ {(!valid || error) && (
+ <div className="px-4 pb-2">
+ <Alert variant="destructive">
+ <AlertDescription>
+ {error ?? 'Check schedule times, repeat days and end date.'}
+ </AlertDescription>
+ </Alert>
+ </div>
+ )}
<div className="flex items-center justify-end gap-2 border-t-[0.5px] border-border px-4 py-2">
- <Button type="button" variant="secondary" onClick={onClose}>
+ <Button type="button" variant="secondary" onClick={onClose} disabled={saving}>
Cancel
</Button>
- <Button type="button" onClick={save}>
- Save
+ <Button type="button" disabled={!valid || saving} onClick={() => void save()}>
+ {saving ? 'Saving…' : 'Save'}
</Button>
</div>
</>
diff --git a/src/renderer/src/components/NewDownloadDialog.tsx b/src/renderer/src/components/NewDownloadDialog.tsx
index b8b7580..ac93ecc 100644
--- a/src/renderer/src/components/NewDownloadDialog.tsx
+++ b/src/renderer/src/components/NewDownloadDialog.tsx
@@ -5,6 +5,7 @@ import { useEffect, useRef, useState } from 'react'
import { useFormatSpeedLimit } from '../hooks/useFormatSpeed'
import { useNetworkUsage } from '../hooks/useNetworks'
import { useNetworkVisuals } from '../hooks/useNetworkVisuals'
+import { useDownloadSchedule } from '../hooks/useDownloadSchedule'
import { useAppStore } from '../store/useAppStore'
import {
acceptedLink,
@@ -57,6 +58,8 @@ export function NewDownloadDialog(): React.JSX.Element {
}
function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element {
+ const { schedule, window: scheduleWindow } = useDownloadSchedule()
+ const scheduledWait = schedule?.enabled && !scheduleWindow.allowed
const interfaces = useAppStore((store) => store.interfaces)
const homeDir = useAppStore((store) => store.homeDir)
const url = useAppStore((store) => store.draftUrl)
@@ -197,9 +200,11 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element
? 'Starting'
: probe.status === 'probing'
? 'Checking'
- : full
- ? 'Add to queue'
- : 'Download'
+ : scheduledWait
+ ? 'Add to scheduled queue'
+ : full
+ ? 'Add to queue'
+ : 'Download'
// Two networks on one subnet: the OS sends both down one route, so there's nothing to combine.
let subnetConflict: { subnet: string; names: string[] } | null = null
@@ -311,7 +316,7 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element
// screen opens, unless it was only added to the queue.
useAppStore.setState({
startedUrl: url.trim(),
- ...(full ? {} : { view: { name: 'download', id } as const })
+ ...(full || scheduledWait ? {} : { view: { name: 'download', id } as const })
})
if (linkId) {
finishLink(linkId, true)
diff --git a/src/renderer/src/components/ScheduleFields.tsx b/src/renderer/src/components/ScheduleFields.tsx
new file mode 100644
index 0000000..3422e94
--- /dev/null
+++ b/src/renderer/src/components/ScheduleFields.tsx
@@ -0,0 +1,300 @@
+import type { DownloadSchedule } from '@shared/types'
+import { useRef, useState } from 'react'
+import { CalendarDays, Clock3 } from 'lucide-react'
+import { DEFAULT_DOWNLOAD_SCHEDULE, localDate, validSchedule } from '@shared/downloadSchedule'
+import { Button } from './ui/button'
+import { Calendar } from './ui/calendar'
+import { Popover, PopoverContent, PopoverTrigger } from './ui/popover'
+import { InputGroup, InputGroupAddon, InputGroupInput, InputGroupText } from './ui/input-group'
+import { Switch } from './ui/switch'
+import { ToggleGroup, ToggleGroupItem } from './ui/toggle-group'
+
+const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
+const pad = (value: number): string => String(value).padStart(2, '0')
+
+function TimeSegment({
+ label,
+ value,
+ max,
+ invalid,
+ inputRef,
+ previous,
+ next,
+ onChange,
+ onPasteTime
+}: {
+ label: string
+ value: number
+ max: number
+ invalid: boolean
+ inputRef: React.RefObject<HTMLInputElement | null>
+ previous?: React.RefObject<HTMLInputElement | null>
+ next?: React.RefObject<HTMLInputElement | null>
+ onChange: (value: number) => void
+ onPasteTime: (time: string) => void
+}): React.JSX.Element {
+ const [draft, setDraft] = useState<string>()
+ return (
+ <InputGroupInput
+ ref={inputRef}
+ type="text"
+ inputMode="numeric"
+ role="spinbutton"
+ aria-label={label}
+ aria-valuemin={0}
+ aria-valuemax={max}
+ aria-valuenow={value}
+ aria-invalid={invalid}
+ autoComplete="off"
+ value={draft ?? pad(value)}
+ className="w-9 flex-none px-1 text-center font-mono tabular-nums"
+ onFocus={(event) => event.currentTarget.select()}
+ onBlur={() => setDraft(undefined)}
+ onChange={(event) => {
+ const text = event.target.value
+ if (!/^\d{0,2}$/.test(text) || Number(text) > max) return
+ setDraft(text)
+ if (text) onChange(Number(text))
+ if (text.length === 2) next?.current?.focus()
+ }}
+ onPaste={(event) => {
+ const text = event.clipboardData.getData('text').trim()
+ if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(text)) return
+ event.preventDefault()
+ onPasteTime(text)
+ setDraft(undefined)
+ event.currentTarget.blur()
+ }}
+ onKeyDown={(event) => {
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
+ const key = event.key
+ if (['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(key)) {
+ event.preventDefault()
+ const updated =
+ key === 'Home'
+ ? 0
+ : key === 'End'
+ ? max
+ : (value + (key === 'ArrowUp' ? 1 : max)) % (max + 1)
+ onChange(updated)
+ setDraft(undefined)
+ requestAnimationFrame(() => {
+ if (document.activeElement === inputRef.current) inputRef.current?.select()
+ })
+ } else if ((key === 'ArrowRight' || key === ':') && next?.current) {
+ event.preventDefault()
+ next.current.focus()
+ } else if (key === 'ArrowLeft' && previous?.current) {
+ event.preventDefault()
+ previous.current.focus()
+ }
+ }}
+ />
+ )
+}
+
+function TimePicker({
+ label,
+ value,
+ invalid,
+ onChange
+}: {
+ label: string
+ value: number
+ invalid: boolean
+ onChange: (minute: number) => void
+}): React.JSX.Element {
+ const hourRef = useRef<HTMLInputElement>(null)
+ const minuteRef = useRef<HTMLInputElement>(null)
+ const hour = Math.floor(value / 60)
+ const minute = value % 60
+ const pasteTime = (time: string): void => {
+ const [hours, minutes] = time.split(':').map(Number)
+ onChange(hours * 60 + minutes)
+ }
+ return (
+ <InputGroup aria-label={label} className="gap-0.5 pl-1.5">
+ <TimeSegment
+ label={`${label} hour`}
+ value={hour}
+ max={23}
+ invalid={invalid}
+ inputRef={hourRef}
+ next={minuteRef}
+ onChange={(next) => onChange(next * 60 + minute)}
+ onPasteTime={pasteTime}
+ />
+ <InputGroupText aria-hidden="true">:</InputGroupText>
+ <TimeSegment
+ label={`${label} minute`}
+ value={minute}
+ max={59}
+ invalid={invalid}
+ inputRef={minuteRef}
+ previous={hourRef}
+ onChange={(next) => onChange(hour * 60 + next)}
+ onPasteTime={pasteTime}
+ />
+ <InputGroupAddon align="inline-end" className="ml-auto" aria-hidden="true">
+ <InputGroupText>24h</InputGroupText>
+ <Clock3 />
+ </InputGroupAddon>
+ </InputGroup>
+ )
+}
+
+function EndDatePicker({
+ value,
+ onChange
+}: {
+ value?: string
+ onChange: (date?: string) => void
+}): React.JSX.Element {
+ const [open, setOpen] = useState(false)
+ const selected = value ? new Date(`${value}T12:00:00`) : undefined
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ render={
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-label="End date"
+ className="w-full justify-between"
+ >
+ {selected
+ ? selected.toLocaleDateString(undefined, {
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric'
+ })
+ : 'No end date'}
+ <CalendarDays data-icon="inline-end" />
+ </Button>
+ }
+ />
+ <PopoverContent align="start" aria-label="Choose end date" className="w-auto gap-0 p-0">
+ <Calendar
+ mode="single"
+ selected={selected}
+ defaultMonth={selected}
+ weekStartsOn={1}
+ autoFocus
+ onSelect={(date) => {
+ onChange(date ? localDate(date) : undefined)
+ setOpen(false)
+ }}
+ />
+ <div className="flex justify-end border-t border-border p-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() => {
+ onChange(undefined)
+ setOpen(false)
+ }}
+ >
+ Clear
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ )
+}
+
+/** Part of the limits dialog's draft; saving and cancellation belong to its shared footer. */
+export function ScheduleFields({
+ schedule,
+ onChange
+}: {
+ schedule: DownloadSchedule
+ onChange: (schedule: DownloadSchedule) => void
+}): React.JSX.Element {
+ const change = (patch: Partial<DownloadSchedule>): void => onChange({ ...schedule, ...patch })
+ return (
+ <section
+ className="flex flex-col gap-2.5 border-t-[0.5px] border-border py-3"
+ aria-label="Download schedule"
+ >
+ <div className="flex items-center justify-between gap-3">
+ <h4 className="font-sans text-[14px] leading-none font-semibold">Download schedule</h4>
+ <label className="flex items-center gap-2 text-[13px]">
+ Enabled
+ <Switch
+ aria-label="Enable download schedule"
+ checked={schedule.enabled}
+ onCheckedChange={(enabled) =>
+ onChange({
+ ...(validSchedule(schedule) ? schedule : DEFAULT_DOWNLOAD_SCHEDULE),
+ enabled
+ })
+ }
+ />
+ </label>
+ </div>
+ {schedule.enabled && (
+ <fieldset className="flex min-w-0 flex-col gap-3">
+ <legend className="sr-only">Schedule times and days</legend>
+ <div className="grid grid-cols-2 gap-3">
+ <div className="flex flex-col gap-2 text-[13px]">
+ Start at
+ <TimePicker
+ label="Start at"
+ value={schedule.startMinute}
+ invalid={schedule.startMinute === schedule.endMinute}
+ onChange={(startMinute) => change({ startMinute })}
+ />
+ </div>
+ <div className="flex flex-col gap-2 text-[13px]">
+ <span className="flex items-center justify-between gap-2">
+ Stop at
+ {schedule.endMinute < schedule.startMinute && (
+ <span className="text-[12px] text-muted-foreground">Next day</span>
+ )}
+ </span>
+ <TimePicker
+ label="Stop at"
+ value={schedule.endMinute}
+ invalid={schedule.startMinute === schedule.endMinute}
+ onChange={(endMinute) => change({ endMinute })}
+ />
+ </div>
+ </div>
+ <fieldset className="flex min-w-0 flex-col gap-2">
+ <legend className="mb-2 text-[13px]">Repeat on</legend>
+ <ToggleGroup
+ multiple
+ value={schedule.days.map(String)}
+ onValueChange={(values) => change({ days: values.map(Number) })}
+ variant="pill"
+ size="xs"
+ spacing={1}
+ aria-label="Schedule days"
+ className="flex-wrap"
+ >
+ {[1, 2, 3, 4, 5, 6, 0].map((day) => (
+ <ToggleGroupItem
+ key={day}
+ value={String(day)}
+ aria-label={DAYS[day]}
+ className="h-6 min-w-6 px-2"
+ >
+ {DAYS[day]}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ </fieldset>
+ <div className="flex flex-col gap-2 text-[13px]">
+ <span className="flex items-center justify-between gap-2">
+ End date
+ <span className="text-[12px] text-muted-foreground">Optional</span>
+ </span>
+ <EndDatePicker value={schedule.endDate} onChange={(endDate) => change({ endDate })} />
+ </div>
+ </fieldset>
+ )}
+ </section>
+ )
+}
diff --git a/src/renderer/src/components/ScheduleIndicator.tsx b/src/renderer/src/components/ScheduleIndicator.tsx
new file mode 100644
index 0000000..c575526
--- /dev/null
+++ b/src/renderer/src/components/ScheduleIndicator.tsx
@@ -0,0 +1,29 @@
+import { Clock3 } from 'lucide-react'
+import { useDownloadSchedule } from '../hooks/useDownloadSchedule'
+import { Button } from './ui/button'
+import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'
+
+export function ScheduleIndicator({ onClick }: { onClick: () => void }): React.JSX.Element | null {
+ const { schedule, message } = useDownloadSchedule()
+ if (!schedule?.enabled) return null
+
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="secondary"
+ size="icon"
+ aria-label="Download schedule enabled"
+ className="text-primary"
+ onClick={onClick}
+ >
+ <Clock3 />
+ </Button>
+ }
+ />
+ <TooltipContent>{message ?? 'Download schedule enabled'}</TooltipContent>
+ </Tooltip>
+ )
+}
diff --git a/src/renderer/src/components/StatusBar.tsx b/src/renderer/src/components/StatusBar.tsx
index 3c34616..0735cc6 100644
--- a/src/renderer/src/components/StatusBar.tsx
+++ b/src/renderer/src/components/StatusBar.tsx
@@ -3,6 +3,7 @@ import { useEffect, useState } from 'react'
import { useAppStore } from '../store/useAppStore'
import { formatBytes } from '../utils/format'
import { useFormatSpeedLimit } from '../hooks/useFormatSpeed'
+import { useDownloadSchedule } from '../hooks/useDownloadSchedule'
import { ScreenFooter } from './ScreenFooter'
import { ThemeToggle } from './ThemeToggle'
import { Switch } from './ui/switch'
@@ -53,6 +54,7 @@ function SpeedUnitToggle(): React.JSX.Element {
* show them — repeated down here they only doubled up, or read as a limit with no cause. */
export function StatusBar(): React.JSX.Element {
const formatSpeedLimit = useFormatSpeedLimit()
+ const { message } = useDownloadSchedule()
// A count, not the downloads: progress ticks don't re-render the footer.
const waiting = useAppStore(
(store) =>
@@ -89,6 +91,7 @@ export function StatusBar(): React.JSX.Element {
return (
<ScreenFooter className="gap-4 font-mono text-[11.5px] text-muted-foreground">
<span className="min-w-0 flex-1 truncate tabular-nums">{status.join(' · ')}</span>
+ {message && <span className="truncate">{message}</span>}
{/* Controls, most-flipped first: the edge holds the set-once view preferences. */}
<div className="flex shrink-0 items-center gap-3">
<UpdateIndicator />
diff --git a/src/renderer/src/components/ui/calendar.tsx b/src/renderer/src/components/ui/calendar.tsx
new file mode 100644
index 0000000..2b5d147
--- /dev/null
+++ b/src/renderer/src/components/ui/calendar.tsx
@@ -0,0 +1,192 @@
+'use client'
+
+import * as React from 'react'
+import { cn } from 'cn'
+import {
+ DayPicker,
+ getDefaultClassNames,
+ type DayButton,
+ type Locale,
+ type Root,
+ type Chevron
+} from 'react-day-picker'
+
+import { Button, buttonVariants } from '@renderer/components/ui/button'
+import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from 'lucide-react'
+
+function Calendar({
+ className,
+ classNames,
+ showOutsideDays = true,
+ captionLayout = 'label',
+ buttonVariant = 'ghost',
+ locale,
+ formatters,
+ components,
+ ...props
+}: React.ComponentProps<typeof DayPicker> & {
+ buttonVariant?: React.ComponentProps<typeof Button>['variant']
+}): React.JSX.Element {
+ const defaultClassNames = getDefaultClassNames()
+
+ return (
+ <DayPicker
+ showOutsideDays={showOutsideDays}
+ className={cn(
+ 'group/calendar bg-background p-2 [--cell-radius:var(--radius-md)] [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent',
+ String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
+ String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
+ className
+ )}
+ captionLayout={captionLayout}
+ locale={locale}
+ formatters={{
+ formatMonthDropdown: (date) => date.toLocaleString(locale?.code, { month: 'short' }),
+ ...formatters
+ }}
+ classNames={{
+ root: cn('w-fit', defaultClassNames.root),
+ months: cn('relative flex flex-col gap-4 md:flex-row', defaultClassNames.months),
+ month: cn('flex w-full flex-col gap-4', defaultClassNames.month),
+ nav: cn(
+ 'absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1',
+ defaultClassNames.nav
+ ),
+ button_previous: cn(
+ buttonVariants({ variant: buttonVariant }),
+ 'size-(--cell-size) p-0 select-none aria-disabled:opacity-50',
+ defaultClassNames.button_previous
+ ),
+ button_next: cn(
+ buttonVariants({ variant: buttonVariant }),
+ 'size-(--cell-size) p-0 select-none aria-disabled:opacity-50',
+ defaultClassNames.button_next
+ ),
+ month_caption: cn(
+ 'flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)',
+ defaultClassNames.month_caption
+ ),
+ dropdowns: cn(
+ 'flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium',
+ defaultClassNames.dropdowns
+ ),
+ dropdown_root: cn('relative rounded-(--cell-radius)', defaultClassNames.dropdown_root),
+ dropdown: cn('absolute inset-0 bg-popover opacity-0', defaultClassNames.dropdown),
+ caption_label: cn(
+ 'font-medium select-none',
+ captionLayout === 'label'
+ ? 'text-sm'
+ : 'flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground',
+ defaultClassNames.caption_label
+ ),
+ month_grid: cn('w-full border-collapse', defaultClassNames.month_grid),
+ weekdays: cn('flex', defaultClassNames.weekdays),
+ weekday: cn(
+ 'flex-1 rounded-(--cell-radius) text-[0.8rem] font-normal text-muted-foreground select-none',
+ defaultClassNames.weekday
+ ),
+ week: cn('mt-2 flex w-full', defaultClassNames.week),
+ week_number_header: cn('w-(--cell-size) select-none', defaultClassNames.week_number_header),
+ week_number: cn(
+ 'text-[0.8rem] text-muted-foreground select-none',
+ defaultClassNames.week_number
+ ),
+ day: cn(
+ 'group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)',
+ props.showWeekNumber
+ ? '[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)'
+ : '[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)',
+ defaultClassNames.day
+ ),
+ range_start: cn(
+ 'relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted',
+ defaultClassNames.range_start
+ ),
+ range_middle: cn('rounded-none', defaultClassNames.range_middle),
+ range_end: cn(
+ 'relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted',
+ defaultClassNames.range_end
+ ),
+ today: cn(
+ 'rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none',
+ defaultClassNames.today
+ ),
+ outside: cn(
+ 'text-muted-foreground aria-selected:text-muted-foreground',
+ defaultClassNames.outside
+ ),
+ disabled: cn('text-muted-foreground opacity-50', defaultClassNames.disabled),
+ hidden: cn('invisible', defaultClassNames.hidden),
+ ...classNames
+ }}
+ components={{
+ Root: ({ className, rootRef, ...props }: React.ComponentProps<typeof Root>) => {
+ return <div data-slot="calendar" ref={rootRef} className={cn(className)} {...props} />
+ },
+ Chevron: ({ className, orientation, ...props }: React.ComponentProps<typeof Chevron>) => {
+ if (orientation === 'left') {
+ return <ChevronLeftIcon className={cn('size-4', className)} {...props} />
+ }
+
+ if (orientation === 'right') {
+ return <ChevronRightIcon className={cn('size-4', className)} {...props} />
+ }
+
+ return <ChevronDownIcon className={cn('size-4', className)} {...props} />
+ },
+ DayButton: ({ ...props }) => <CalendarDayButton locale={locale} {...props} />,
+ WeekNumber: ({ children, ...props }) => {
+ return (
+ <td {...props}>
+ <div className="flex size-(--cell-size) items-center justify-center text-center">
+ {children}
+ </div>
+ </td>
+ )
+ },
+ ...components
+ }}
+ {...props}
+ />
+ )
+}
+
+function CalendarDayButton({
+ className,
+ day,
+ modifiers,
+ locale,
+ ...props
+}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }): React.JSX.Element {
+ const defaultClassNames = getDefaultClassNames()
+
+ const ref = React.useRef<HTMLButtonElement>(null)
+ React.useEffect(() => {
+ if (modifiers.focused) ref.current?.focus()
+ }, [modifiers.focused])
+
+ return (
+ <Button
+ variant="ghost"
+ size="icon"
+ data-day={day.date.toLocaleDateString(locale?.code)}
+ data-selected-single={
+ modifiers.selected &&
+ !modifiers.range_start &&
+ !modifiers.range_end &&
+ !modifiers.range_middle
+ }
+ data-range-start={modifiers.range_start}
+ data-range-end={modifiers.range_end}
+ data-range-middle={modifiers.range_middle}
+ className={cn(
+ 'relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70',
+ defaultClassNames.day,
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export { Calendar, CalendarDayButton }
diff --git a/src/renderer/src/components/ui/input-group.tsx b/src/renderer/src/components/ui/input-group.tsx
new file mode 100644
index 0000000..309638b
--- /dev/null
+++ b/src/renderer/src/components/ui/input-group.tsx
@@ -0,0 +1,150 @@
+import * as React from 'react'
+import { cva, type VariantProps } from 'class-variance-authority'
+import { cn } from 'cn'
+
+import { Button } from '@renderer/components/ui/button'
+import { Input } from '@renderer/components/ui/input'
+import { Textarea } from '@renderer/components/ui/textarea'
+
+function InputGroup({ className, ...props }: React.ComponentProps<'div'>): React.JSX.Element {
+ return (
+ <div
+ data-slot="input-group"
+ role="group"
+ className={cn(
+ 'group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5',
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+const inputGroupAddonVariants = cva(
+ "flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ align: {
+ 'inline-start': 'order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]',
+ 'inline-end': 'order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]',
+ 'block-start':
+ 'order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2',
+ 'block-end':
+ 'order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2'
+ }
+ },
+ defaultVariants: {
+ align: 'inline-start'
+ }
+ }
+)
+
+function InputGroupAddon({
+ className,
+ align = 'inline-start',
+ ...props
+}: React.ComponentProps<'div'> & VariantProps<typeof inputGroupAddonVariants>): React.JSX.Element {
+ return (
+ <div
+ role="group"
+ data-slot="input-group-addon"
+ data-align={align}
+ className={cn(inputGroupAddonVariants({ align }), className)}
+ onClick={(e) => {
+ if ((e.target as HTMLElement).closest('button')) {
+ return
+ }
+ e.currentTarget.parentElement?.querySelector('input')?.focus()
+ }}
+ {...props}
+ />
+ )
+}
+
+const inputGroupButtonVariants = cva('flex items-center gap-2 text-sm shadow-none', {
+ variants: {
+ size: {
+ xs: "h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5",
+ sm: '',
+ 'icon-xs': 'size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0',
+ 'icon-sm': 'size-8 p-0 has-[>svg]:p-0'
+ }
+ },
+ defaultVariants: {
+ size: 'xs'
+ }
+})
+
+function InputGroupButton({
+ className,
+ type = 'button',
+ variant = 'ghost',
+ size = 'xs',
+ ...props
+}: Omit<React.ComponentProps<typeof Button>, 'size' | 'type'> &
+ VariantProps<typeof inputGroupButtonVariants> & {
+ type?: 'button' | 'submit' | 'reset'
+ }): React.JSX.Element {
+ return (
+ <Button
+ type={type}
+ data-size={size}
+ variant={variant}
+ className={cn(inputGroupButtonVariants({ size }), className)}
+ {...props}
+ />
+ )
+}
+
+function InputGroupText({ className, ...props }: React.ComponentProps<'span'>): React.JSX.Element {
+ return (
+ <span
+ className={cn(
+ "flex items-center gap-2 text-sm text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function InputGroupInput({
+ className,
+ ...props
+}: React.ComponentProps<'input'>): React.JSX.Element {
+ return (
+ <Input
+ data-slot="input-group-control"
+ className={cn(
+ 'flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent',
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function InputGroupTextarea({
+ className,
+ ...props
+}: React.ComponentProps<'textarea'>): React.JSX.Element {
+ return (
+ <Textarea
+ data-slot="input-group-control"
+ className={cn(
+ 'flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent',
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ InputGroupText,
+ InputGroupInput,
+ InputGroupTextarea
+}
diff --git a/src/renderer/src/components/ui/textarea.tsx b/src/renderer/src/components/ui/textarea.tsx
new file mode 100644
index 0000000..3ab2750
--- /dev/null
+++ b/src/renderer/src/components/ui/textarea.tsx
@@ -0,0 +1,17 @@
+import * as React from 'react'
+import { cn } from 'cn'
+
+function Textarea({ className, ...props }: React.ComponentProps<'textarea'>): React.JSX.Element {
+ return (
+ <textarea
+ data-slot="textarea"
+ className={cn(
+ 'flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40',
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export { Textarea }
diff --git a/src/renderer/src/hooks/useDownloadSchedule.ts b/src/renderer/src/hooks/useDownloadSchedule.ts
new file mode 100644
index 0000000..5207c74
--- /dev/null
+++ b/src/renderer/src/hooks/useDownloadSchedule.ts
@@ -0,0 +1,22 @@
+import { scheduleMessage, scheduleWindow } from '@shared/downloadSchedule'
+import { useEffect, useState } from 'react'
+import { useAppStore } from '../store/useAppStore'
+
+export function useDownloadSchedule(): {
+ schedule: ReturnType<typeof useAppStore.getState>['downloadSchedule']
+ window: ReturnType<typeof scheduleWindow>
+ message: string | null
+} {
+ const schedule = useAppStore((store) => store.downloadSchedule)
+ const [now, setNow] = useState(() => Date.now())
+ useEffect(() => {
+ if (!schedule?.enabled) return
+ const timer = setInterval(() => setNow(Date.now()), 1000)
+ return () => clearInterval(timer)
+ }, [schedule?.enabled])
+ return {
+ schedule,
+ window: scheduleWindow(schedule, now),
+ message: scheduleMessage(schedule, now)
+ }
+}
diff --git a/src/renderer/src/screens/DownloadingScreen.tsx b/src/renderer/src/screens/DownloadingScreen.tsx
index 2e6138f..7768ea4 100644
--- a/src/renderer/src/screens/DownloadingScreen.tsx
+++ b/src/renderer/src/screens/DownloadingScreen.tsx
@@ -15,6 +15,7 @@ import { TruncatedText } from '../components/TruncatedText'
import { Button } from '../components/ui/button'
import { Tooltip, TooltipContent, TooltipTrigger } from '../components/ui/tooltip'
import { useNetworkVisuals } from '../hooks/useNetworkVisuals'
+import { useDownloadSchedule } from '../hooks/useDownloadSchedule'
import { useAppStore } from '../store/useAppStore'
import { KIND_PALETTE, NETWORK_ROW_GRID_COLUMNS } from '../theme'
import {
@@ -115,6 +116,7 @@ export const DownloadingScreen = memo(function DownloadingScreen({
const speedHistory = download.speedHistory ?? {}
const peakSpeedBytesPerSec = download.peakSpeedBytesPerSec
const networkVisual = useNetworkVisuals()
+ const { window: scheduleWindow, message: scheduleMessage } = useDownloadSchedule()
const isQueued = download.status === 'queued'
// Waiting in the queue looks like a pause: nothing moves.
const isPaused = download.status === 'paused' || isQueued
@@ -208,6 +210,11 @@ export const DownloadingScreen = memo(function DownloadingScreen({
return (
<div className="flex h-full flex-col bg-background">
<DetailHeader download={download} />
+ {isQueued && !scheduleWindow.allowed && (
+ <div className="border-b-[0.5px] border-border px-5 py-3 text-[12.5px] text-muted-foreground">
+ {scheduleMessage}
+ </div>
+ )}
{/* Hero band — always visible under the header */}
<HeroBand>
{/* At their designed size: a wider window opens a gap between the speed and the chart
diff --git a/src/renderer/src/screens/DownloadsScreen.tsx b/src/renderer/src/screens/DownloadsScreen.tsx
index 98f21ef..f396a81 100644
--- a/src/renderer/src/screens/DownloadsScreen.tsx
+++ b/src/renderer/src/screens/DownloadsScreen.tsx
@@ -10,7 +10,9 @@ import { MoreActionsMenu } from '../components/MoreActionsMenu'
import { DownloadFilterMenu } from '../components/DownloadFilterMenu'
import { CombineDiagram } from '../components/CombineDiagram'
import { LimitsDialog } from '../components/LimitsDialog'
+import { ScheduleIndicator } from '../components/ScheduleIndicator'
import { networkStatusText } from '../components/NetworkRow'
+import { scheduleMessage, scheduleWindow } from '@shared/downloadSchedule'
import { NetworksMenu } from '../components/NetworksMenu'
import { TorrentBadge } from '../components/TorrentBadge'
import { Button } from '../components/ui/button'
@@ -95,6 +97,7 @@ export function DownloadsScreen(): React.JSX.Element {
const { perform, askClearFinished } = useDownloadActions()
const { busy } = useDownloadActionsState()
const [limitsOpen, setLimitsOpen] = useState(false)
+ const [showSchedule, setShowSchedule] = useState(false)
const [limitsPage, setLimitsPage] = useState<string | null>(null)
const [now, setNow] = useState(() => Date.now())
@@ -173,6 +176,12 @@ export function DownloadsScreen(): React.JSX.Element {
// the rest of what the menu does for the selection behind More, so six never need more room.
const { buttons: toolbarButtons, more: moreActions } = splitToolbar(availableActions(chosen))
+ const openSchedule = (): void => {
+ setLimitsPage(null)
+ setShowSchedule(true)
+ setLimitsOpen(true)
+ }
+
return (
<div className="flex h-full flex-col bg-background">
{chosen.length === 0 ? (
@@ -192,8 +201,10 @@ export function DownloadsScreen(): React.JSX.Element {
</div>
)}
<div className="flex-1" />
+ <ScheduleIndicator onClick={openSchedule} />
<NetworksMenu
onOpenLimits={(page) => {
+ setShowSchedule(false)
setLimitsPage(page)
setLimitsOpen(true)
}}
@@ -255,6 +266,7 @@ export function DownloadsScreen(): React.JSX.Element {
))}
<MoreActionsMenu groups={moreActions} disabled={busy} />
</div>
+ <ScheduleIndicator onClick={openSchedule} />
</div>
)}
@@ -335,6 +347,7 @@ export function DownloadsScreen(): React.JSX.Element {
<LimitsDialog
open={limitsOpen}
+ showSchedule={showSchedule}
onOpenChange={setLimitsOpen}
page={limitsPage}
onPageChange={setLimitsPage}
@@ -429,6 +442,7 @@ const DownloadRow = memo(function DownloadRow({
onPerform: (id: ActionId, targets: Item[]) => Promise<boolean>
}): React.JSX.Element {
const formatSpeed = useFormatSpeed()
+ const schedule = useAppStore((store) => store.downloadSchedule)
const [working, setWorking] = useState(false)
const finished = isFinished(item) || item.status === 'completed'
const badge = isFolder(item) ? 'DIR' : fileExtensionBadge(item.fileName)
@@ -465,7 +479,7 @@ const DownloadRow = memo(function DownloadRow({
.join(' · ')
break
case 'queued':
- detail = `Waiting for a turn · ${sizes}`
+ detail = `${schedule?.enabled && !scheduleWindow(schedule, now).allowed ? (scheduleMessage(schedule, now) ?? 'Waiting for a turn') : 'Waiting for a turn'} · ${sizes}`
break
case 'paused':
detail = wanted > 0 ? `Paused at ${percent}% · ${sizes}` : `Paused · ${sizes}`
diff --git a/src/renderer/src/store/useAppStore.ts b/src/renderer/src/store/useAppStore.ts
index 2b5e4d4..5f29252 100644
--- a/src/renderer/src/store/useAppStore.ts
+++ b/src/renderer/src/store/useAppStore.ts
@@ -1,6 +1,7 @@
import { applyDownloadUpdate } from '@shared/downloadUpdate'
import type {
AppSettings,
+ DownloadSchedule,
DownloadState,
DownloadUpdate,
FinishedDownload,
@@ -45,6 +46,7 @@ interface AppStore {
view: View
downloadFilter: DownloadFilter
setDownloadFilter: (filter: DownloadFilter) => void
+ downloadSchedule: DownloadSchedule | undefined
/** The New download dialog, over whatever the window shows. */
newDownloadOpen: boolean
/** Persisted — how many downloads run at once; the rest wait in the queue. */
@@ -132,6 +134,7 @@ export const useAppStore = create<AppStore>((set, get) => ({
view: { name: 'list' },
downloadFilter: 'all',
setDownloadFilter: (downloadFilter) => set({ downloadFilter }),
+ downloadSchedule: initial.downloadSchedule,
newDownloadOpen: false,
downloadsAtOnce: initial.downloadsAtOnce,
speedLimit: initial.speedLimit,
diff --git a/src/shared/downloadSchedule.ts b/src/shared/downloadSchedule.ts
new file mode 100644
index 0000000..fad6dff
--- /dev/null
+++ b/src/shared/downloadSchedule.ts
@@ -0,0 +1,93 @@
+import type { DownloadSchedule } from './types'
+
+export const DEFAULT_DOWNLOAD_SCHEDULE: DownloadSchedule = {
+ enabled: false,
+ startMinute: 0,
+ endMinute: 7 * 60,
+ days: [0, 1, 2, 3, 4, 5, 6]
+}
+
+export function localDate(date: Date): string {
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
+}
+
+export function validSchedule(value: unknown): value is DownloadSchedule {
+ if (typeof value !== 'object' || value === null) return false
+ const schedule = value as DownloadSchedule
+ if (
+ typeof schedule.enabled !== 'boolean' ||
+ ![schedule.startMinute, schedule.endMinute].every(
+ (minute) => Number.isInteger(minute) && minute >= 0 && minute < 1440
+ ) ||
+ schedule.startMinute === schedule.endMinute ||
+ !Array.isArray(schedule.days) ||
+ schedule.days.length === 0 ||
+ !schedule.days.every((day) => Number.isInteger(day) && day >= 0 && day <= 6)
+ )
+ return false
+ if (schedule.endDate !== undefined) {
+ if (typeof schedule.endDate !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(schedule.endDate))
+ return false
+ const date = new Date(`${schedule.endDate}T12:00:00`)
+ if (!Number.isFinite(date.getTime()) || localDate(date) !== schedule.endDate) return false
+ }
+ return true
+}
+
+export interface ScheduleWindow {
+ allowed: boolean
+ nextStart?: number
+ endsAt?: number
+ expired?: boolean
+}
+
+/** Calendar arithmetic, rather than 24-hour offsets, keeps local times across DST changes.
+ * Overnight windows belong to the day they start; the end date includes that whole window. */
+export function scheduleWindow(
+ schedule: DownloadSchedule | undefined,
+ now = Date.now()
+): ScheduleWindow {
+ if (!schedule?.enabled) return { allowed: true }
+ if (!validSchedule(schedule)) return { allowed: false }
+ const today = new Date(now)
+ let nextStart: number | undefined
+ for (let offset = -1; offset <= 7; offset++) {
+ const start = new Date(today.getFullYear(), today.getMonth(), today.getDate() + offset)
+ if (!schedule.days.includes(start.getDay())) continue
+ if (schedule.endDate && localDate(start) > schedule.endDate) continue
+ start.setHours(Math.floor(schedule.startMinute / 60), schedule.startMinute % 60, 0, 0)
+ const end = new Date(start)
+ if (schedule.endMinute < schedule.startMinute) end.setDate(end.getDate() + 1)
+ end.setHours(Math.floor(schedule.endMinute / 60), schedule.endMinute % 60, 0, 0)
+ if (now >= start.getTime() && now < end.getTime()) {
+ return { allowed: true, endsAt: end.getTime() }
+ }
+ if (start.getTime() > now && nextStart === undefined) nextStart = start.getTime()
+ }
+ return { allowed: false, nextStart, expired: nextStart === undefined }
+}
+
+export function scheduleTime(minute: number): string {
+ const date = new Date(2000, 0, 1, Math.floor(minute / 60), minute % 60)
+ return date.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })
+}
+
+export function scheduleMessage(
+ schedule: DownloadSchedule | undefined,
+ now = Date.now()
+): string | null {
+ if (!schedule?.enabled) return null
+ const window = scheduleWindow(schedule, now)
+ if (window.allowed && window.endsAt) {
+ return `Downloads stop at ${new Date(window.endsAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}`
+ }
+ if (window.nextStart) {
+ const next = new Date(window.nextStart)
+ const day =
+ localDate(next) === localDate(new Date(now))
+ ? 'today'
+ : next.toLocaleDateString([], { weekday: 'short' })
+ return `Waiting until ${scheduleTime(schedule.startMinute)} ${day}`
+ }
+ return window.expired ? 'Schedule ended · downloads waiting' : 'Schedule needs attention'
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index c82a063..2dffee1 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -206,6 +206,8 @@ interface DownloadStateBase {
* thrown away, e.g. the file changed on the server. */
resumable?: boolean
startedAt: number
+ /** Enrolled in the scheduled queue; survives relaunches until manually paused. */
+ scheduled?: boolean
/** While queued: its place in the queue, lowest first. */
queuedAt?: number
pausedAt?: number
@@ -317,9 +319,22 @@ export interface UpdateInfo {
dismissed: boolean
}
+/** A repeating window for all transfers, interpreted in the computer's local timezone. */
+export interface DownloadSchedule {
+ enabled: boolean
+ /** Minutes since local midnight. Equal start/stop times are invalid. */
+ startMinute: number
+ endMinute: number
+ /** Days on which a window starts, Sunday = 0. */
+ days: number[]
+ /** Last local date on which a window may start (YYYY-MM-DD). */
+ endDate?: string
+}
+
/** What app-settings.json holds, and what the renderer sends to change it (merged over the saved
* values, `undefined` clearing one). A missing field was never set. */
export interface AppSettings {
+ downloadSchedule?: DownloadSchedule
themeSource?: ThemeSource
dismissedUpdateVersion?: string
/** The last destination folder picked. */
@@ -350,6 +365,7 @@ export const DEFAULT_SLOW_MODE_SPEED = 2 * 1024 ** 2
/** Everything the renderer needs for its first paint, read synchronously by the preload so no
* saved value flashes in over a default a moment after launch. */
export interface InitialState {
+ downloadSchedule?: DownloadSchedule
homeDir: string
downloadsDir: string
themeSource: ThemeSource