Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

feat(ui): display destination free space and warn on insufficient disk space (#227)

Dhruvil Patelb9eabeabd69c
diff --git a/e2e/disk.spec.ts b/e2e/disk.spec.ts
index fc88fa3..266a472 100644
--- a/e2e/disk.spec.ts
+++ b/e2e/disk.spec.ts
@@ -1,6 +1,6 @@
import { execFileSync } from 'node:child_process'
import { existsSync } from 'node:fs'
-import { chmod, mkdir, mkdtemp, readdir, rm } from 'node:fs/promises'
+import { chmod, mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { BLOCK, expect, PlexoApp, test } from './fixtures'
@@ -80,6 +80,35 @@ test.describe('disk space @disk', () => {
}
})
+ test('New download dialog warns and disables start when file exceeds free space', async ({
+ serve
+ }) => {
+ const volume = await smallVolume(10)
+ test.skip(!volume, 'cannot create a small volume on this machine')
+ const app = new PlexoApp({
+ userData: join(volume!.path, 'userData'),
+ dest: join(volume!.path, 'dest')
+ })
+ try {
+ await mkdir(app.dirs.userData)
+ await mkdir(app.dirs.dest)
+ await writeFile(
+ join(app.dirs.userData, 'app-settings.json'),
+ JSON.stringify({ destinationDir: app.dirs.dest })
+ )
+ await app.launch()
+ const origin = await serve({ size: 256 * BLOCK }) // 16 MB > 10 MB free
+ const link = await app.newDownload()
+ await link.fill(origin.url())
+ const dialog = app.page.getByRole('dialog', { name: 'New download' })
+ await expect(dialog.getByRole('alert')).toContainText(/Not enough disk space/)
+ await expect(dialog.locator('button[type="submit"]')).toBeDisabled()
+ } finally {
+ if (app.alive) await app.kill()
+ await volume!.dispose()
+ }
+ })
+
test('a file that fits once but not twice completes on the destination volume', async ({
serve
}) => {
diff --git a/e2e/ui.spec.ts b/e2e/ui.spec.ts
index aba168f..8381df4 100644
--- a/e2e/ui.spec.ts
+++ b/e2e/ui.spec.ts
@@ -272,6 +272,12 @@ test.describe('UI journeys @smoke', () => {
await expect(page.getByRole('button', { name: 'Download' })).toBeDisabled()
})
+ test('New download dialog shows free space on destination folder', async ({ plexo }) => {
+ await plexo.newDownload()
+ const dialog = plexo.page.getByRole('dialog', { name: 'New download' })
+ await expect(dialog.getByText(/\(\d+(\.\d+)?\s*(B|KB|MB|GB|TB)\s*free\)/)).toBeVisible()
+ })
+
test('a completed download is shown again after a restart', async ({ plexo, serve }) => {
const origin = await serve({ size: SIZE })
await plexo.start(origin.url(), origin.sha256)
@@ -301,7 +307,9 @@ test.describe('settings @smoke', () => {
await plexo.newDownload()
await page().getByRole('button', { name: 'Change' }).click()
const destinationRow = (): Locator => page().getByText('Save to', { exact: true }).locator('..')
- const chosenDestination = await destinationRow().innerText()
+ const destination = async (): Promise<string> =>
+ (await destinationRow().innerText()).replace(/\s*\([^)]*free\)/, '')
+ const chosenDestination = await destination()
await page().keyboard.press('Escape')
// A function: the window, and so the page, is a new one after a relaunch.
const networksMenu = (): Locator =>
@@ -322,7 +330,7 @@ test.describe('settings @smoke', () => {
const expectAllKept = async (): Promise<void> => {
await expect(page().getByRole('button', { name: labelAfterSwitch })).toBeVisible()
await plexo.newDownload()
- await expect(destinationRow()).toHaveText(chosenDestination, { useInnerText: true })
+ await expect.poll(destination).toBe(chosenDestination)
// Presentation may abbreviate home; persistence must retain the usable absolute path.
const saved = JSON.parse(await readFile(join(dirs.userData, 'app-settings.json'), 'utf8'))
expect(saved.destinationDir).toBe(dirs.dest)
@@ -356,7 +364,8 @@ test.describe('settings @smoke', () => {
await plexo.newDownload()
const row = await plexo.page.getByText('Save to', { exact: true }).locator('..').innerText()
await plexo.page.keyboard.press('Escape')
- return row
+ // Free space shows up when it's ready; only the folder is compared.
+ return row.replace(/\s*\([^)]*free\)/, '')
}
const fresh = await choices()
diff --git a/src/renderer/src/components/NewDownloadDialog.tsx b/src/renderer/src/components/NewDownloadDialog.tsx
index fc56baf..d9999b3 100644
--- a/src/renderer/src/components/NewDownloadDialog.tsx
+++ b/src/renderer/src/components/NewDownloadDialog.tsx
@@ -12,6 +12,7 @@ import {
} from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { useFormatSpeedLimit } from '../hooks/useFormatSpeed'
+import { useFreeSpace } from '../hooks/useFreeSpace'
import { useNetworkUsage } from '../hooks/useNetworks'
import { useNetworkVisuals } from '../hooks/useNetworkVisuals'
import { useDownloadSchedule } from '../hooks/useDownloadSchedule'
@@ -145,6 +146,7 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element
// The news server, for an NZB: undefined until it has been asked for, null when there's none.
const [server, setServer] = useState<UsenetServer | null | undefined>(undefined)
const [serverOpen, setServerOpen] = useState(false)
+ const freeSpace = useFreeSpace(destinationDir)
// Opened with nothing in it: a link on the clipboard is most likely what it's for, as download
// managers have long assumed. Anything else on the clipboard is left alone.
@@ -230,6 +232,12 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element
const sizeToFetch = torrent
? chosenFiles.reduce((sum, index) => sum + torrent.files[index].length, 0)
: (ready?.totalBytes ?? null)
+ const availableFreeSpace = destinationDir ? freeSpace : null
+ const hasInsufficientSpace =
+ availableFreeSpace !== null &&
+ sizeToFetch !== null &&
+ sizeToFetch > 0 &&
+ sizeToFetch > availableFreeSpace
const multiChunkAllowed = ready !== null && ready.supportsRanges && ready.totalBytes !== null
const isSingleStreamOnly = ready !== null && !multiChunkAllowed
@@ -259,6 +267,7 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element
(!nzb || !!server) &&
selectedInterfaceIds.length > 0 &&
Boolean(destinationDir) &&
+ !hasInsufficientSpace &&
!starting
const startLabel = starting
? 'Starting'
@@ -609,8 +618,20 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element
<div className="flex items-center gap-3">
<div className={labelClass}>Save to</div>
- <div className="min-w-0 flex-1 truncate font-mono text-[12.5px]">
- {toDisplayPath(destinationDir, homeDir)}
+ <div className="flex min-w-0 flex-1 items-baseline gap-2 truncate font-mono text-[12.5px]">
+ <span className="truncate">{toDisplayPath(destinationDir, homeDir)}</span>
+ {availableFreeSpace !== null && (
+ <span
+ className={cn(
+ 'shrink-0 text-[11.5px] tabular-nums',
+ hasInsufficientSpace
+ ? 'font-medium text-[var(--color-danger)]'
+ : 'text-muted-foreground'
+ )}
+ >
+ ({formatBytes(availableFreeSpace)} free)
+ </span>
+ )}
</div>
<Button type="button" variant="secondary" size="sm" onClick={handleBrowse}>
Change
@@ -774,6 +795,18 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element
computer sends both down one route and they can’t be combined.
</div>
)}
+ {hasInsufficientSpace && (
+ <div
+ role="alert"
+ className="flex items-start gap-2 text-[12px] leading-snug text-[var(--color-danger)]"
+ >
+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
+ <span>
+ Not enough disk space: this download needs {formatBytes(sizeToFetch)}, but only{' '}
+ {formatBytes(availableFreeSpace)} is free on this drive.
+ </span>
+ </div>
+ )}
{usedUpPick.length > 0 && (
<div className="flex items-start gap-2 text-[12px] leading-snug text-[var(--color-usb-text)]">
<AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
diff --git a/src/renderer/src/components/StatusBar.tsx b/src/renderer/src/components/StatusBar.tsx
index 0735cc6..05383d1 100644
--- a/src/renderer/src/components/StatusBar.tsx
+++ b/src/renderer/src/components/StatusBar.tsx
@@ -1,5 +1,5 @@
import type { SpeedUnit } from '@shared/types'
-import { useEffect, useState } from 'react'
+import { useFreeSpace } from '../hooks/useFreeSpace'
import { useAppStore } from '../store/useAppStore'
import { formatBytes } from '../utils/format'
import { useFormatSpeedLimit } from '../hooks/useFormatSpeed'
@@ -11,8 +11,6 @@ import { ToggleGroup, ToggleGroupItem } from './ui/toggle-group'
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'
import { UpdateIndicator } from './UpdateIndicator'
-const FREE_SPACE_POLL_MS = 30_000
-
/** MB/s or Mbps for every speed in the app; sits with the theme toggle as a view preference. */
function SpeedUnitToggle(): React.JSX.Element {
const speedUnit = useAppStore((store) => store.speedUnit)
@@ -64,23 +62,7 @@ export function StatusBar(): React.JSX.Element {
const slowModeSpeed = useAppStore((store) => store.slowModeSpeed)
const setSlowMode = useAppStore((store) => store.setSlowMode)
const destinationDir = useAppStore((store) => store.destinationDir)
- const [free, setFree] = useState<number | null>(null)
-
- useEffect(() => {
- let disposed = false
- const load = (): void => {
- void window.plexo
- .freeSpace(destinationDir)
- .then((bytes) => !disposed && setFree(bytes))
- .catch(() => {})
- }
- load()
- const interval = setInterval(load, FREE_SPACE_POLL_MS)
- return () => {
- disposed = true
- clearInterval(interval)
- }
- }, [destinationDir])
+ const free = useFreeSpace(destinationDir)
// Limits show by the speeds they cap (the Downloading screen, the networks menu), not here.
const status = [
diff --git a/src/renderer/src/hooks/useFreeSpace.ts b/src/renderer/src/hooks/useFreeSpace.ts
new file mode 100644
index 0000000..fdbeb66
--- /dev/null
+++ b/src/renderer/src/hooks/useFreeSpace.ts
@@ -0,0 +1,43 @@
+import { useEffect, useState } from 'react'
+
+export const FREE_SPACE_POLL_MS = 30_000
+
+/**
+ * Polls the available free space on the drive hosting `dir`.
+ * Returns null while loading or when `dir` is empty/unavailable.
+ * Resets to null whenever `dir` changes to prevent showing stale values.
+ */
+export function useFreeSpace(dir: string | null | undefined): number | null {
+ const [prevDir, setPrevDir] = useState(dir)
+ const [free, setFree] = useState<number | null>(null)
+
+ if (dir !== prevDir) {
+ setPrevDir(dir)
+ setFree(null)
+ }
+
+ useEffect(() => {
+ if (!dir) return
+
+ let disposed = false
+ const check = (): void => {
+ void window.plexo
+ .freeSpace(dir)
+ .then((bytes) => {
+ if (!disposed) setFree(bytes)
+ })
+ .catch(() => {
+ if (!disposed) setFree(null)
+ })
+ }
+
+ check()
+ const timer = setInterval(check, FREE_SPACE_POLL_MS)
+ return () => {
+ disposed = true
+ clearInterval(timer)
+ }
+ }, [dir])
+
+ return free
+}