Speed up downloads by combining multiple network connections in parallel
TypeScript bandwidth-aggregationcross-platformdesktop-appdownloaderdownloadmanagerlinuxmacosmulticonnectionparallel-downloadswindows
Add end-to-end test suite for the download pipeline
Anmol Kapil15311a68442b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4f0727a..fb0071a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -40,6 +40,33 @@ jobs:- name: Check formattingrun: npm run format:check+ e2e:+ name: E2E (smoke)+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: npm++ # Unlike the ci job, this one runs the app, so Electron's binary is needed.+ - name: Install dependencies+ run: npm ci++ # Electron needs a display even with its window hidden.+ - name: Run smoke tests+ run: xvfb-run --auto-servernum npm run test:e2e:smoke++ - name: Upload report+ if: failure()+ uses: actions/upload-artifact@v4+ with:+ name: playwright-report+ path: playwright-report+ retention-days: 14+windows:name: Windows buildruns-on: windows-latestdiff --git a/.github/workflows/e2e-nightly.yml b/.github/workflows/e2e-nightly.ymlnew file mode 100644index 0000000..aeb8275--- /dev/null+++ b/.github/workflows/e2e-nightly.yml@@ -0,0 +1,65 @@+name: E2E nightly++# The whole e2e suite — including the @disk and @chaos tiers the PR job skips — on both+# platforms, with the race-prone tests repeated so an intermittent failure shows up here+# rather than in someone's download.+on:+ schedule:+ - cron: '0 3 * * *'+ workflow_dispatch:+ inputs:+ chaos_runs:+ description: Random chaos sequences to try+ default: '50'++jobs:+ e2e:+ name: E2E (${{ matrix.os }})+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, windows-latest]+ runs-on: ${{ matrix.os }}+ timeout-minutes: 60+ env:+ PLEXO_CHAOS_RUNS: ${{ github.event.inputs.chaos_runs || '50' }}+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: npm++ - name: Install dependencies+ run: npm ci++ - name: Build+ run: npx electron-vite build++ # The @disk tests mount small tmpfs volumes, which needs passwordless sudo (GitHub's+ # Linux runners have it); elsewhere they skip themselves.+ - name: Full suite (Linux)+ if: runner.os == 'Linux'+ run: xvfb-run --auto-servernum npx playwright test+ env:+ PLEXO_E2E_SKIP_BUILD: '1'++ - name: Full suite (Windows)+ if: runner.os == 'Windows'+ run: npx playwright test+ env:+ PLEXO_E2E_SKIP_BUILD: '1'++ - name: Race-prone tests, repeated+ run: ${{ runner.os == 'Linux' && 'xvfb-run --auto-servernum ' || '' }}npx playwright test e2e/lifecycle.spec.ts e2e/recovery.spec.ts --repeat-each=10+ env:+ PLEXO_E2E_SKIP_BUILD: '1'++ - name: Upload report+ if: failure()+ uses: actions/upload-artifact@v4+ with:+ name: playwright-report-${{ matrix.os }}+ path: playwright-report+ retention-days: 14diff --git a/.gitignore b/.gitignoreindex 75ef73c..9f8da0c 100644--- a/.gitignore+++ b/.gitignore@@ -4,3 +4,5 @@ out.DS_Store.eslintcache*.log*+test-results+playwright-reportdiff --git a/.prettierignore b/.prettierignoreindex 9c6b791..934000e 100644--- a/.prettierignore+++ b/.prettierignore@@ -4,3 +4,5 @@ pnpm-lock.yamlLICENSE.mdtsconfig.jsontsconfig.*.json+test-results+playwright-reportdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex caca03d..fa56fde 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -19,6 +19,7 @@ Requires Windows 10/11 or macOS and Node.js 22.12+. See [requirements](README.mdnpm run lintnpm run typechecknpm run format+npm run test:e2e:smoke```CI runs these checks on every pull request, with formatting checked rather than applied — if it flags something, `npm run format` fixes it.@@ -27,6 +28,19 @@ CI runs these checks on every pull request, with formatting checked rather thanCI also builds the Windows installer. Please describe how you checked your change manually (which URL/file size/interfaces you tried) in the PR description.+## End-to-end tests++`e2e/` drives the real built app through the same `window.plexo` API the renderer uses, against a local test server that can drop, stall, corrupt or hold any response at an exact byte. Every test also runs automatic checks: a `completed` download must match the source byte for byte, and anything else must leave no file, part files or open handles behind. The app's window stays hidden while tests run.++```bash+npm run test:e2e:smoke # what CI runs on every PR (~1 min)+npm run test:e2e # everything, including @disk and @chaos+PLEXO_CHAOS_RUNS=50 npx playwright test e2e/chaos.spec.ts # more random sequences+PLEXO_CHAOS_SEED=<seed> npx playwright test e2e/chaos.spec.ts # replay a chaos failure+```++Tests build the app first; set `PLEXO_E2E_SKIP_BUILD=1` when `out/` is already fresh. Known bugs are written as `test.fail(...)` — when a fix lands, Playwright reports the test as unexpectedly passing, and the marker comes off. Retries are deliberately off: a download test that passes only on a retry has found a race.+## Making changes- Keep PRs focused — one fix or feature per PR is easier to review than a bundle of unrelated changes.diff --git a/e2e/chaos.spec.ts b/e2e/chaos.spec.tsnew file mode 100644index 0000000..97f8667--- /dev/null+++ b/e2e/chaos.spec.ts@@ -0,0 +1,179 @@+import fc from 'fast-check'+import type { DownloadStatus } from '../src/shared/types'+import {+ BLOCK,+ checkEvents,+ checkFinalState,+ expect,+ LAN_ADDRESS,+ makeDirs,+ PlexoApp,+ test+} from './fixtures'+import { Origin, type Fault } from './origin'++// H. Model-based chaos. fast-check generates random sequences of user actions and failures —+// pause, resume, crash, quit, flaky server, waiting — and runs each against a real app and a+// throttled server. The property: whatever the sequence, once the faults stop and the download+// is resumed it completes with the exact bytes, and every event along the way obeyed the+// invariants. When a sequence fails, fast-check shrinks it to the shortest one that still+// fails and prints its seed; rerun that exact case with PLEXO_CHAOS_SEED=<seed>.+//+// PLEXO_CHAOS_RUNS sets how many sequences to try (default 5; nightly runs more).++const RUNS = Number(process.env.PLEXO_CHAOS_RUNS ?? 5)+const SEED = process.env.PLEXO_CHAOS_SEED ? Number(process.env.PLEXO_CHAOS_SEED) : undefined+const SIZE = 48 * BLOCK++interface Model {+ /** What the app should be doing, as far as the commands so far can tell. */+ phase: 'running' | 'paused' | 'done'+}++interface Real {+ app: PlexoApp+ origin: Origin+ id: string+ /** Faults still to hand out, one per chunk request. */+ faults: Fault[]+}++async function status(real: Real): Promise<DownloadStatus | undefined> {+ return (await real.app.current())?.status+}++/** Re-reads the app, since a running download may have finished on its own since last looked. */+async function sync(model: Model, real: Real): Promise<void> {+ const current = await status(real)+ if (current === 'completed' || current === 'assembling') model.phase = 'done'+ if (current === 'error' || current === 'cancelled') {+ throw new Error(`download ended ${current}: ${(await real.app.current())?.error}`)+ }+}++class Wait implements fc.AsyncCommand<Model, Real> {+ constructor(readonly ms: number) {}+ check = (): boolean => true+ async run(model: Model, real: Real): Promise<void> {+ await new Promise((resolve) => setTimeout(resolve, this.ms))+ await sync(model, real)+ }+ toString = (): string => `Wait(${this.ms})`+}++class Pause implements fc.AsyncCommand<Model, Real> {+ check = (model: Readonly<Model>): boolean => model.phase === 'running'+ async run(model: Model, real: Real): Promise<void> {+ await real.app.api.pauseDownload(real.id)+ // Either it paused, or it had already finished downloading before the pause arrived.+ const state = await real.app.waitForStatus(['paused', 'assembling', 'completed'], 15_000)+ model.phase = state.status === 'paused' ? 'paused' : 'done'+ }+ toString = (): string => 'Pause'+}++class Resume implements fc.AsyncCommand<Model, Real> {+ check = (model: Readonly<Model>): boolean => model.phase === 'paused'+ async run(model: Model, real: Real): Promise<void> {+ await real.app.api.resumeDownload(real.id)+ await real.app.waitForStatus(['downloading', 'assembling', 'completed'], 15_000)+ model.phase = 'running'+ await sync(model, real)+ }+ toString = (): string => 'Resume'+}++class Restart implements fc.AsyncCommand<Model, Real> {+ constructor(readonly how: 'crash' | 'quit') {}+ check = (): boolean => true+ async run(model: Model, real: Real): Promise<void> {+ await sync(model, real)+ if (this.how === 'crash') await real.app.kill()+ else await real.app.quit()+ await real.app.launch()++ const state = await real.app.current()+ expect(state?.id, 'the download survives the restart').toBe(real.id)+ // Anything unfinished comes back paused; one that finished (possibly in the instant between+ // the last look and the kill) stays completed — the final byte check covers that case.+ expect(['paused', 'completed'], `status after ${this.how}`).toContain(state?.status)+ model.phase = state?.status === 'completed' ? 'done' : 'paused'+ }+ toString = (): string => (this.how === 'crash' ? 'Crash' : 'Quit')+}++class Flaky implements fc.AsyncCommand<Model, Real> {+ constructor(readonly faults: Fault[]) {}+ check = (): boolean => true+ async run(_model: Model, real: Real): Promise<void> {+ // Replaces rather than adds, so faults never pile up past what the retry budget absorbs.+ real.faults = [...this.faults]+ }+ toString = (): string => `Flaky(${JSON.stringify(this.faults)})`+}++const faultArb: fc.Arbitrary<Fault> = fc.oneof(+ fc.integer({ min: 0, max: BLOCK - 1 }).map((cutAfter): Fault => ({ cutAfter })),+ fc.constant<Fault>({ status: 500 }),+ fc.constant<Fault>({ status: 503 }),+ fc.constant<Fault>('wrongStart'),+ fc.constant<Fault>('overlong'),+ fc.integer({ min: 0, max: BLOCK - 1 }).map((endAfter): Fault => ({ endAfter }))+)++const commands = fc.commands(+ [+ fc.integer({ min: 20, max: 700 }).map((ms) => new Wait(ms)),+ fc.constant(new Pause()),+ fc.constant(new Resume()),+ fc.constantFrom('crash' as const, 'quit' as const).map((how) => new Restart(how)),+ fc.array(faultArb, { minLength: 1, maxLength: 3 }).map((faults) => new Flaky(faults))+ ],+ { maxCommands: 12 }+)++test('any sequence of pauses, crashes and faults still ends in the exact file @chaos', async () => {+ test.setTimeout(RUNS * 90_000 + 60_000)++ await fc.assert(+ fc.asyncProperty(+ fc.integer({ min: 1, max: 2 ** 31 - 1 }),+ fc.integer({ min: 1, max: 4 }),+ commands,+ async (fileSeed, connections, cmds) => {+ const { dirs, dispose } = await makeDirs()+ const origin = await new Origin({+ size: SIZE,+ seed: fileSeed,+ bytesPerSecond: 512 * 1024+ }).start()+ const app = new PlexoApp(dirs)+ const real: Real = { app, origin, id: '', faults: [] }+ origin.setRule(({ range }) =>+ range && !(range.start === 0 && range.end === 0) ? real.faults.shift() : undefined+ )++ try {+ await app.launch()+ real.id = await app.start(origin.url(), origin.sha256, {+ networks: LAN_ADDRESS ? ['a', 'b'] : ['a'],+ connections+ })+ await fc.asyncModelRun(() => ({ model: { phase: 'running' } as Model, real }), cmds)++ // Faults off, let it finish, then hold it to every rule.+ real.faults = []+ if ((await status(real)) === 'paused') await app.api.resumeDownload(real.id)+ await app.waitForStatus('completed', 60_000)+ checkEvents(app.sessions)+ await checkFinalState(app)+ } finally {+ if (app.alive) await app.kill().catch(() => {})+ await origin.stop()+ await dispose()+ }+ }+ ),+ { numRuns: RUNS, seed: SEED, verbose: 1, interruptAfterTimeLimit: RUNS * 90_000 }+ )+})diff --git a/e2e/disk.spec.ts b/e2e/disk.spec.tsnew file mode 100644index 0000000..1649f45--- /dev/null+++ b/e2e/disk.spec.ts@@ -0,0 +1,162 @@+import { execFileSync } from 'node:child_process'+import { existsSync } from 'node:fs'+import { chmod, mkdir, mkdtemp, readdir, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { BLOCK, expect, PlexoApp, test } from './fixtures'++// E. The disk: out of space, folders vanishing, no permission. The small volumes are real+// filesystems (a RAM disk on macOS, tmpfs on Linux), so ENOSPC comes from the OS, not a mock.++interface Volume {+ path: string+ dispose: () => Promise<void>+}++/** A real filesystem of `megabytes` size, or null where one can't be made without a password. */+async function smallVolume(megabytes: number): Promise<Volume | null> {+ try {+ if (process.platform === 'darwin') {+ const name = `plexoe2e${process.pid}${Date.now() % 100000}`+ const device = execFileSync('hdiutil', ['attach', '-nomount', `ram://${megabytes * 2048}`])+ .toString()+ .trim()+ execFileSync('diskutil', ['erasevolume', 'HFS+', name, device], { stdio: 'ignore' })+ return {+ path: `/Volumes/${name}`,+ dispose: async () => {+ execFileSync('hdiutil', ['detach', device, '-force'], { stdio: 'ignore' })+ }+ }+ }+ if (process.platform === 'linux') {+ const path = await mkdtemp(join(tmpdir(), 'plexo-vol-'))+ execFileSync('sudo', [+ '-n',+ 'mount',+ '-t',+ 'tmpfs',+ '-o',+ `size=${megabytes}m`,+ 'tmpfs',+ path+ ])+ execFileSync('sudo', ['-n', 'chown', String(process.getuid?.()), path])+ return {+ path,+ dispose: async () => {+ execFileSync('sudo', ['-n', 'umount', path])+ await rm(path, { recursive: true, force: true })+ }+ }+ }+ } catch {+ // No RAM disk tools, or no passwordless sudo — the test skips itself.+ }+ return null+}++test.describe('disk space @disk', () => {+ test('a file bigger than the free space is refused before anything is written', async ({+ plexo,+ serve,+ dirs+ }) => {+ const volume = await smallVolume(10)+ test.skip(!volume, 'cannot create a small volume on this machine')+ try {+ const dest = join(volume!.path, 'dest')+ await mkdir(dest)+ const origin = await serve({ size: 256 * BLOCK }) // 16 MB+ await expect(+ plexo.start(origin.url(), origin.sha256, { destinationDir: dest })+ ).rejects.toThrow(/Not enough disk space/)+ expect(await readdir(dest)).toEqual([])+ const downloads = join(dirs.userData, 'downloads')+ expect(existsSync(downloads) ? await readdir(downloads) : []).toEqual([])+ } finally {+ await plexo.quit()+ await volume!.dispose()+ }+ })++ test('a disk that fills up while assembling ends in an error, not a hang', async ({ serve }) => {+ test.fail(+ true,+ 'known bugs: the space check ignores the part files (needs ~2× the size), and appendFileToStream hangs forever on a write error'+ )+ const volume = await smallVolume(12)+ test.skip(!volume, 'cannot create a small volume on this machine')+ // userData on the same small volume, so the part files and the final file compete for it.+ 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 app.launch()+ const origin = await serve({ size: 112 * BLOCK }) // 7 MB: fits once, not twice+ let refusedUpfront = false+ try {+ await app.start(origin.url(), origin.sha256)+ } catch (error) {+ refusedUpfront = /disk space/.test(String(error))+ if (!refusedUpfront) throw error+ }+ if (!refusedUpfront) {+ const state = await app.waitForStatus(['completed', 'error'], 20_000)+ expect(state.status).toBe('error')+ expect(existsSync(state.destinationPath)).toBe(false)+ }+ } finally {+ if (app.alive) await app.kill()+ await volume!.dispose()+ }+ })+})++test.describe('destination folder problems @smoke', () => {+ test('destination folder deleted mid-download → error, nothing left', async ({+ plexo,+ serve,+ dirs+ }) => {+ test.fail(+ true,+ 'known bug: appendFileToStream never settles once the output stream errors — stuck in assembling'+ )+ const origin = await serve({ size: 24 * BLOCK })+ const reached = origin.hold(10 * BLOCK)+ await plexo.start(origin.url(), origin.sha256)+ await reached+ await rm(dirs.dest, { recursive: true, force: true })+ origin.release()+ const state = await plexo.waitForStatus(['completed', 'error'])+ expect(state.status).toBe('error')+ })++ test('read-only destination folder → refused, and nothing left in userData', async ({+ plexo,+ serve,+ dirs+ }) => {+ test.skip(process.platform === 'win32', 'chmod does not make a folder read-only on Windows')+ test.fail(+ true,+ 'known bug: parts/ is created before the destination name is reserved, and never removed when that fails'+ )+ const origin = await serve({ size: 4 * BLOCK })+ await chmod(dirs.dest, 0o555)+ try {+ await expect(plexo.start(origin.url(), origin.sha256)).rejects.toThrow(/EACCES|permission/i)+ const downloads = join(dirs.userData, 'downloads')+ expect(+ existsSync(downloads) ? await readdir(downloads) : [],+ 'no orphaned parts folder from the refused start'+ ).toEqual([])+ } finally {+ await chmod(dirs.dest, 0o755)+ }+ })+})diff --git a/e2e/download.spec.ts b/e2e/download.spec.tsnew file mode 100644index 0000000..cd7fcc0--- /dev/null+++ b/e2e/download.spec.ts@@ -0,0 +1,159 @@+import { BLOCK, expect, LAN_ADDRESS, test } from './fixtures'++// A. Downloads that should simply work. Every test also runs the automatic checks in+// fixtures.ts: completed ⇒ the file's SHA-256 matches the source, nothing stray left behind.++test.describe('happy paths @smoke', () => {+ for (const [label, size] of [+ ['1 byte', 1],+ ['exactly one block', BLOCK],+ ['one block plus one byte', BLOCK + 1],+ ['37.5 blocks', Math.floor(BLOCK * 37.5)]+ ] as const) {+ test(`ranged download: ${label}`, async ({ plexo, serve }) => {+ const origin = await serve({ size })+ await plexo.start(origin.url(), origin.sha256, { connections: 4 })+ const state = await plexo.waitForStatus('completed')+ expect(state.bytesDownloaded).toBe(size)+ expect(state.totalBlocks).toBe(Math.ceil(size / BLOCK))+ })+ }++ for (const connections of [1, 8]) {+ test(`${connections} connection(s) per network`, async ({ plexo, serve }) => {+ const origin = await serve({ size: 20 * BLOCK + 123 })+ await plexo.start(origin.url(), origin.sha256, { connections })+ const state = await plexo.waitForStatus('completed')+ expect(state.chunks).toHaveLength(connections)+ })+ }++ test('two networks share the work, and attribution matches what the server saw', async ({+ plexo,+ serve+ }) => {+ test.skip(!LAN_ADDRESS, 'needs a LAN address to act as the second network')+ const origin = await serve({ size: 40 * BLOCK })+ await plexo.start(origin.url(), origin.sha256, { networks: ['a', 'b'], connections: 2 })+ const state = await plexo.waitForStatus('completed')++ const served = { a: 0, b: 0 }+ for (const entry of origin.chunkRequests()) {+ served[entry.from === '127.0.0.1' ? 'a' : 'b'] += entry.bytesSent+ }+ const attributed = { a: 0, b: 0 }+ for (const block of state.blocks ?? []) {+ attributed.a += block.bytesByInterface['a'] ?? 0+ attributed.b += block.bytesByInterface['b'] ?? 0+ }+ expect(served.a, 'network a carried some of the file').toBeGreaterThan(0)+ expect(served.b, 'network b carried some of the file').toBeGreaterThan(0)+ expect(attributed).toEqual(served)+ })++ test('server without range support: one stream, whole file', async ({ plexo, serve }) => {+ const origin = await serve({ size: 10 * BLOCK, ranges: false })+ await plexo.start(origin.url(), origin.sha256)+ const state = await plexo.waitForStatus('completed')+ expect(state.chunks).toHaveLength(1)+ })++ test('unknown size (no Content-Length)', async ({ plexo, serve }) => {+ const origin = await serve({ size: 10 * BLOCK, ranges: false, contentLength: false })+ await plexo.start(origin.url(), origin.sha256)+ const state = await plexo.waitForStatus('completed')+ expect(state.totalBytes).toBe(0)+ })++ test('redirect during probe and on chunk requests', async ({ plexo, serve }) => {+ const origin = await serve({ size: 12 * BLOCK })+ origin.setRule(({ path }) => (path === '/start' ? { redirect: '/files/test.bin' } : 'ok'))+ await plexo.start(origin.url('/start'), origin.sha256)+ await plexo.waitForStatus('completed')++ // The chunk requests follow redirects too (a signed CDN URL rotating mid-download).+ const next = await serve({ size: 12 * BLOCK, seed: 7 })+ let redirected = 0+ next.setRule(({ path, range }) => {+ if (path === '/files/test.bin' && range && range.start > 0 && redirected++ < 3) {+ return { redirect: '/files/moved.bin' }+ }+ return 'ok'+ })+ await plexo.start(next.url(), next.sha256)+ await plexo.waitForStatus('completed')+ expect(redirected).toBeGreaterThan(0)+ })+})++test.describe('file names @smoke', () => {+ const cases: [string, string, RegExp][] = [+ ['Content-Disposition name', 'attachment; filename="report.pdf"', /^report\.pdf$/],+ ['RFC 5987 filename*', "attachment; filename*=UTF-8''r%C3%A9sum%C3%A9.txt", /^résumé\.txt$/],+ ['path traversal is flattened', 'attachment; filename="../../evil.sh"', /^\.\._\.\._evil\.sh$/],+ ['control characters are replaced', 'attachment; filename="a%0Ab.txt"', /^a_b\.txt$/]+ ]+ for (const [label, disposition, expected] of cases) {+ test(label, async ({ plexo, serve, dirs }) => {+ const origin = await serve({ size: 3 * BLOCK, contentDisposition: disposition })+ await plexo.start(origin.url(), origin.sha256)+ const state = await plexo.waitForStatus('completed')+ expect(state.fileName).toMatch(expected)+ expect(state.destinationPath.startsWith(dirs.dest)).toBe(true)+ })+ }++ test('the same name twice gets "(1)" and leaves the first file alone', async ({+ plexo,+ serve+ }) => {+ const first = await serve({ size: 3 * BLOCK, seed: 1 })+ await plexo.start(first.url(), first.sha256)+ const one = await plexo.waitForStatus('completed')++ const second = await serve({ size: 5 * BLOCK, seed: 2 })+ await plexo.start(second.url(), second.sha256)+ const two = await plexo.waitForStatus('completed')++ expect(one.fileName).toBe('test.bin')+ expect(two.fileName).toBe('test (1).bin')+ const { readFile } = await import('node:fs/promises')+ const { sha256 } = await import('./origin')+ expect(sha256(await readFile(one.destinationPath))).toBe(first.sha256)+ })++ test('a malformed %-escape in the URL path still downloads', async ({ plexo, serve }) => {+ test.fail(true, 'known bug: probe.ts decodeURIComponent(url.pathname) throws a URIError')+ const origin = await serve({ size: 2 * BLOCK })+ await plexo.start(origin.url('/files/100%25%E0%A4%A.bin'), origin.sha256)+ await plexo.waitForStatus('completed')+ })+})++test.describe('edge cases', () => {+ test('a 0-byte file @smoke', async ({ plexo, serve }) => {+ test.fail(+ true,+ 'known bug: the probe asks for bytes=0-0, an empty file answers 416, probe throws'+ )+ const origin = await serve({ size: 0 })+ await plexo.start(origin.url(), origin.sha256)+ await plexo.waitForStatus('completed', 5000)+ })++ test('starting a second download while one is active is refused @smoke', async ({+ plexo,+ serve+ }) => {+ const origin = await serve({ size: 10 * BLOCK })+ const reached = origin.hold(BLOCK)+ await plexo.start(origin.url(), origin.sha256)+ await reached++ const other = await serve({ size: BLOCK, seed: 3 })+ await expect(plexo.start(other.url(), other.sha256)).rejects.toThrow(/already in progress/)++ origin.release()+ await plexo.waitForStatus('completed')+ })+})diff --git a/e2e/fixtures.ts b/e2e/fixtures.tsnew file mode 100644index 0000000..8d07130--- /dev/null+++ b/e2e/fixtures.ts@@ -0,0 +1,415 @@+import { execFile } from 'node:child_process'+import { existsSync } from 'node:fs'+import { mkdir, mkdtemp, readdir, readFile, realpath, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import { promisify } from 'node:util'+import {+ _electron as electron,+ expect,+ test as base,+ type ElectronApplication,+ type Page+} from '@playwright/test'+import type { IpcContract } from '../src/shared/ipc-contract'+import type { DownloadState, DownloadStatus } from '../src/shared/types'+import { Origin, sha256, type OriginOptions } from './origin'++export { expect }++const PROJECT_ROOT = resolve(__dirname, '..')++/** Small blocks so a ~1 MB test file still splits into many of them. */+export const BLOCK = 64 * 1024++/**+ * The second test "network": this machine's LAN address. A request bound to it still reaches+ * the loopback test server, but arrives from a different source address — which is how the+ * server tells the two networks apart. Found (and checked to work) by global-setup.ts; null+ * where there's no usable one, and the multi-network tests skip.+ */+export const LAN_ADDRESS = process.env.PLEXO_E2E_LAN || null++export const NETWORKS = LAN_ADDRESS+ ? { a: '127.0.0.1', b: LAN_ADDRESS }+ : ({ a: '127.0.0.1' } as Record<string, string>)++export function interfacesEnv(networks: Record<string, string>): string {+ return Object.entries(networks)+ .map(([id, address]) => `${id}=${address}`)+ .join(',')+}++type Api = {+ [K in keyof IpcContract]: (...args: IpcContract[K]['args']) => Promise<IpcContract[K]['result']>+}++interface StartOptions {+ networks?: string[]+ connections?: number+ fileName?: string+ destinationDir?: string+}++interface Tracked {+ expectedSha: string+ /** Files already in the destination folder before this download started. */+ destBefore: string[]+ destinationDir: string+}++/**+ * Drives one Plexo instance through the same `window.plexo` API the renderer uses — nothing+ * below this reaches into the main process's internals, so refactoring them can't break a test+ * that still describes correct behavior.+ */+export class PlexoApp {+ electronApp!: ElectronApplication+ page!: Page+ /** Every downloadUpdated state, one array per app launch (a relaunch starts a new one). */+ readonly sessions: DownloadState[][] = []+ readonly tracked = new Map<string, Tracked>()+ readonly output: string[] = []+ alive = false++ constructor(+ readonly dirs: { userData: string; dest: string },+ private extraEnv: Record<string, string> = {}+ ) {}++ async launch(extraEnv: Record<string, string> = {}): Promise<this> {+ Object.assign(this.extraEnv, extraEnv)+ this.electronApp = await electron.launch({+ args: [PROJECT_ROOT, ...(process.platform === 'linux' ? ['--no-sandbox'] : [])],+ env: {+ ...(process.env as Record<string, string>),+ PLEXO_USER_DATA: this.dirs.userData,+ PLEXO_E2E_HIDE_WINDOW: '1',+ PLEXO_E2E_BLOCK_BYTES: String(BLOCK),+ PLEXO_E2E_RETRY_BASE_MS: '20',+ PLEXO_E2E_STALL_MS: '1500',+ PLEXO_E2E_INTERFACES: interfacesEnv(NETWORKS),+ ...this.extraEnv+ }+ })+ const child = this.electronApp.process()+ child.stdout?.on('data', (data) => this.output.push(String(data)))+ child.stderr?.on('data', (data) => this.output.push(String(data)))+ this.alive = true++ this.page = await this.electronApp.firstWindow()+ await this.page.waitForLoadState('domcontentloaded')+ const session: DownloadState[] = []+ this.sessions.push(session)+ await this.page.exposeFunction('__plexoRecord', (state: DownloadState) => session.push(state))+ await this.page.evaluate(() => {+ const w = window as unknown as { __plexoRecord: (s: unknown) => void }+ window.plexo.onDownloadUpdated((state) => w.__plexoRecord(state))+ })+ return this+ }++ /** Kills the main process outright — no before-quit, no suspend: a crash or power cut. */+ async kill(): Promise<void> {+ const child = this.electronApp.process()+ const exited = new Promise((resolve) => child.once('exit', resolve))+ child.kill('SIGKILL')+ await exited+ this.alive = false+ }++ /** Normal quit — runs before-quit, which suspends (pauses and persists) the download. */+ async quit(): Promise<void> {+ await this.electronApp.close()+ this.alive = false+ }++ async relaunch(extraEnv: Record<string, string> = {}): Promise<this> {+ if (this.alive) await this.quit()+ return this.launch(extraEnv)+ }++ api: Api = new Proxy({} as Api, {+ get:+ (_target, name: string) =>+ (...args: unknown[]) =>+ this.page.evaluate(+ ([method, params]) =>+ (window.plexo as unknown as Record<string, (...a: unknown[]) => unknown>)[method](+ ...params+ ),+ [name, args] as const+ )+ })++ /** Main-process code, e.g. to replace a dialog or make a network disappear. */+ evaluateMain<R, A>(fn: (electron: typeof import('electron'), arg: A) => R, arg: A): Promise<R> {+ return this.electronApp.evaluate(fn as never, arg) as Promise<R>+ }++ /** Probes and starts `url` exactly the way IdleScreen's Start button does. */+ async start(url: string, expectedSha: string, options: StartOptions = {}): Promise<string> {+ await this.api.listInterfaces()+ const probe = await this.api.probeUrl(url)+ const multiChunk = probe.supportsRanges && probe.totalBytes !== null+ const networks = options.networks ?? ['a']+ const destinationDir = options.destinationDir ?? this.dirs.dest+ const destBefore = existsSync(destinationDir) ? await readdir(destinationDir) : []++ const id = await this.api.startDownload({+ url: probe.finalUrl,+ destinationDir,+ suggestedFileName: options.fileName ?? probe.suggestedFileName,+ totalBytes: probe.totalBytes ?? 0,+ supportsRanges: multiChunk,+ interfaceIds: multiChunk ? networks : networks.slice(0, 1),+ chunkCount: multiChunk ? networks.length * (options.connections ?? 2) : 1,+ connectionsPerNetwork: multiChunk ? (options.connections ?? 2) : 1,+ etag: probe.etag,+ lastModified: probe.lastModified+ })+ this.tracked.set(id, { expectedSha, destBefore, destinationDir })+ return id+ }++ /** For downloads started through the UI rather than start(): declares what the next one+ * should produce, so the automatic checks can verify it. Call before clicking Start. */+ async expectNextDownload(expectedSha: string): Promise<void> {+ this.nextDownload = {+ expectedSha,+ destBefore: await readdir(this.dirs.dest),+ destinationDir: this.dirs.dest+ }+ }++ nextDownload: Tracked | null = null++ /** Starts a dev-tool simulated download of a local file (see simDownload.ts). */+ async startSimulated(+ request: Omit<IpcContract['startSimulatedDownload']['args'][0], 'destinationDir'>,+ expectedSha: string+ ): Promise<string> {+ const destBefore = await readdir(this.dirs.dest)+ const id = await this.api.startSimulatedDownload({ ...request, destinationDir: this.dirs.dest })+ this.tracked.set(id, { expectedSha, destBefore, destinationDir: this.dirs.dest })+ return id+ }++ async current(): Promise<DownloadState | null> {+ return this.api.getCurrentDownload()+ }++ async waitForStatus(+ status: DownloadStatus | DownloadStatus[],+ timeout = 20_000+ ): Promise<DownloadState> {+ const wanted = Array.isArray(status) ? status : [status]+ return this.waitUntil((state) => wanted.includes(state.status), timeout)+ }++ /** Waits until the download state matches `predicate`. A timeout says what the state was+ * instead, so a hang reads as "stuck in assembling", not as a bare assertion mismatch. */+ async waitUntil(+ predicate: (state: DownloadState) => boolean,+ timeout = 20_000+ ): Promise<DownloadState> {+ const deadline = Date.now() + timeout+ let state: DownloadState | null = null+ while (Date.now() < deadline) {+ state = await this.current()+ if (state && predicate(state)) return state+ await new Promise((resolve) => setTimeout(resolve, 50))+ }+ const chunks = state?.chunks.map(+ (chunk) => `${chunk.status}${chunk.error ? ` (${chunk.error})` : ''}`+ )+ throw new Error(+ `Timed out after ${timeout} ms waiting on the download. Last seen: ${+ state+ ? `status=${state.status}${state.error ? `, error="${state.error}"` : ''}, bytes=${state.bytesDownloaded}/${state.totalBytes}, chunks=[${chunks?.join(', ')}]`+ : 'no current download'+ }`+ )+ }+}++// --- invariants --------------------------------------------------------------------------------++const ALLOWED_NEXT: Record<DownloadStatus, DownloadStatus[]> = {+ downloading: ['downloading', 'paused', 'assembling', 'error', 'cancelled'],+ paused: ['paused', 'downloading', 'error', 'cancelled'],+ assembling: ['assembling', 'completed', 'error'],+ completed: ['completed'],+ error: ['error'],+ cancelled: ['cancelled']+}++/** Rules every download event must satisfy, whatever the scenario. */+export function checkEvents(sessions: DownloadState[][]): void {+ for (const events of sessions) {+ const lastStatus = new Map<string, DownloadStatus>()+ for (const state of events) {+ const label = `${state.id} @ ${state.status}`+ if (state.totalBytes > 0) {+ expect(state.bytesDownloaded, `${label}: bytesDownloaded ≤ totalBytes`).toBeLessThanOrEqual(+ state.totalBytes+ )+ }+ for (const block of state.blocks ?? []) {+ const attributed = Object.values(block.bytesByInterface).reduce((a, b) => a + b, 0)+ expect(attributed, `${label}: block ${block.index} attribution sums to its bytes`).toBe(+ block.bytesDownloaded+ )+ if (block.rangeEnd !== null) {+ const size = block.rangeEnd - block.rangeStart + 1+ expect(+ block.bytesDownloaded,+ `${label}: block ${block.index} within its size`+ ).toBeLessThanOrEqual(size)+ if (block.status === 'completed') {+ expect(block.bytesDownloaded, `${label}: completed block ${block.index} is full`).toBe(+ size+ )+ }+ }+ }+ const previous = lastStatus.get(state.id)+ if (previous) {+ expect(ALLOWED_NEXT[previous], `${state.id}: ${previous} → ${state.status}`).toContain(+ state.status+ )+ }+ lastStatus.set(state.id, state.status)+ }+ }+}++async function openFilesUnder(pid: number, roots: string[]): Promise<string[]> {+ try {+ const { stdout } = await promisify(execFile)('lsof', ['-Fn', '-p', String(pid)])+ return stdout+ .split('\n')+ .filter((line) => line.startsWith('n'))+ .map((line) => line.slice(1))+ .filter((path) => roots.some((root) => path.startsWith(root)))+ } catch {+ return [] // lsof missing — skip this check rather than fail on it+ }+}++/**+ * The end-of-test rules: once a download has finished (either way), what's on disk must be+ * exactly right. The one that matters most: `completed` never means wrong bytes.+ */+export async function checkFinalState(app: PlexoApp): Promise<void> {+ const state = await app.current()+ if (!state) return+ const tracked = app.tracked.get(state.id) ?? app.nextDownload+ const terminal = ['completed', 'error', 'cancelled'].includes(state.status)+ if (!tracked || !terminal) return++ if (state.status === 'completed') {+ const bytes = await readFile(state.destinationPath)+ expect(sha256(bytes), 'completed file matches the source byte for byte').toBe(+ tracked.expectedSha+ )+ } else {+ expect(existsSync(state.destinationPath), 'no file left at the destination').toBe(false)+ }++ const destAfter = existsSync(tracked.destinationDir) ? await readdir(tracked.destinationDir) : []+ const added = destAfter.filter((name) => !tracked.destBefore.includes(name))+ const expectedAdded =+ state.status === 'completed' ? [state.destinationPath.split(/[\\/]/).pop()] : []+ expect(added, 'no stray files (placeholders, partials) in the destination folder').toEqual(+ expectedAdded+ )++ const partsDir = join(app.dirs.userData, 'downloads', state.id, 'parts')+ await expect+ .poll(() => existsSync(partsDir), { message: 'part files cleaned up', timeout: 5000 })+ .toBe(false)++ const pid = app.electronApp.process().pid+ if (pid) {+ await expect+ .poll(() => openFilesUnder(pid, [app.dirs.dest, join(app.dirs.userData, 'downloads')]), {+ message: 'no file handles left open on download files',+ timeout: 5000+ })+ .toEqual([])+ }+}++// --- fixtures ----------------------------------------------------------------------------------++/** A fresh userData + destination folder pair under the OS temp directory. */+export async function makeDirs(): Promise<{+ dirs: { userData: string; dest: string }+ dispose: () => Promise<void>+}> {+ const root = await realpath(await mkdtemp(join(tmpdir(), 'plexo-e2e-')))+ const dirs = { userData: join(root, 'userData'), dest: join(root, 'dest') }+ await Promise.all([mkdir(dirs.userData), mkdir(dirs.dest)])+ return { dirs, dispose: () => rm(root, { recursive: true, force: true, maxRetries: 5 }) }+}++interface Fixtures {+ /** Extra environment for the app, e.g. `test.use({ appEnv: { PLEXO_E2E_RETRY_BASE_MS: '2000' } })`. */+ appEnv: Record<string, string>+ dirs: { userData: string; dest: string }+ /** Starts a test server; every one started is stopped after the test. */+ serve: (options: OriginOptions) => Promise<Origin>+ plexo: PlexoApp+ checks: void+}++export const test = base.extend<Fixtures>({+ appEnv: [{}, { option: true }],++ // eslint-disable-next-line no-empty-pattern+ dirs: async ({}, use) => {+ const { dirs, dispose } = await makeDirs()+ await use(dirs)+ await dispose()+ },++ // eslint-disable-next-line no-empty-pattern+ serve: async ({}, use, testInfo) => {+ const origins: Origin[] = []+ await use(async (options) => {+ const origin = await new Origin(options).start()+ origins.push(origin)+ return origin+ })+ if (testInfo.status !== testInfo.expectedStatus) {+ const log = origins.map((origin) => origin.log)+ await testInfo.attach('server-requests.json', { body: JSON.stringify(log, null, 2) })+ }+ await Promise.all(origins.map((origin) => origin.stop()))+ },++ plexo: async ({ dirs, appEnv }, use, testInfo) => {+ const app = new PlexoApp(dirs, { ...appEnv })+ await app.launch()+ await use(app)+ if (testInfo.status !== testInfo.expectedStatus) {+ await testInfo.attach('download-events.json', {+ body: JSON.stringify(app.sessions, null, 2)+ })+ await testInfo.attach('app-output.txt', { body: app.output.join('') })+ }+ if (app.alive) await app.electronApp.close().catch(() => {})+ },++ checks: [+ async ({ plexo }, use, testInfo) => {+ await use()+ // A test already failing (or expected to fail) has said what it needed to.+ if (testInfo.status !== 'passed' || testInfo.expectedStatus !== 'passed') return+ checkEvents(plexo.sessions)+ if (plexo.alive) await checkFinalState(plexo)+ },+ { auto: true }+ ]+})diff --git a/e2e/global-setup.ts b/e2e/global-setup.tsnew file mode 100644index 0000000..a79e1f6--- /dev/null+++ b/e2e/global-setup.ts@@ -0,0 +1,39 @@+import { execSync } from 'node:child_process'+import { createServer, request } from 'node:http'+import type { AddressInfo } from 'node:net'+import { networkInterfaces } from 'node:os'++/** The second test "network" is this machine's LAN address, bound as the source of requests to+ * the loopback test server. Most systems route that fine; check once rather than assume, and+ * leave PLEXO_E2E_LAN empty (multi-network tests skip) where it doesn't work. */+async function findLanAddress(): Promise<string> {+ const candidate = Object.values(networkInterfaces())+ .flat()+ .find(+ (addr) => addr?.family === 'IPv4' && !addr.internal && !addr.address.startsWith('169.254.')+ )?.address+ if (!candidate) return ''++ const server = createServer((_req, res) => res.end('ok'))+ await new Promise<void>((resolve) => server.listen(0, '0.0.0.0', resolve))+ const { port } = server.address() as AddressInfo+ const works = await new Promise<boolean>((resolve) => {+ const req = request({ host: '127.0.0.1', port, localAddress: candidate, family: 4 }, (res) => {+ res.resume()+ resolve(res.statusCode === 200)+ })+ req.setTimeout(2000, () => req.destroy())+ req.on('error', () => resolve(false))+ req.end()+ })+ server.close()+ return works ? candidate : ''+}++/** Tests launch the built app (out/), so build it first — a stale build tests stale code.+ * PLEXO_E2E_SKIP_BUILD=1 skips it when the build is known to be fresh (e.g. a CI step). */+export default async function globalSetup(): Promise<void> {+ process.env.PLEXO_E2E_LAN ??= await findLanAddress()+ if (process.env.PLEXO_E2E_SKIP_BUILD === '1') return+ execSync('npx electron-vite build', { stdio: 'inherit' })+}diff --git a/e2e/integrity.spec.ts b/e2e/integrity.spec.tsnew file mode 100644index 0000000..cfae7db--- /dev/null+++ b/e2e/integrity.spec.ts@@ -0,0 +1,96 @@+import { readFile } from 'node:fs/promises'+import { BLOCK, expect, test } from './fixtures'+import { seededBytes, sha256, type Fault } from './origin'++// B. A misbehaving server or network. The rule every case here must satisfy — enforced by the+// automatic checks in fixtures.ts — is that a download never ends `completed` with wrong bytes:+// it either retries its way to the exact file, or it errors and leaves nothing behind.++const SIZE = 16 * BLOCK++/** Faults a real server or network produces, applied to the first few chunk requests only. */+const TRANSIENT: [string, Fault][] = [+ ['Content-Range starts at the wrong byte', 'wrongStart'],+ ['body runs past the requested range', 'overlong'],+ ['206 without a Content-Range header', 'noContentRange'],+ ['200 (whole file) for a range that does not start at 0', 'ignoreRange'],+ ['416 Range Not Satisfiable', { status: 416 }],+ ['500 Internal Server Error', { status: 500 }],+ ['503 Service Unavailable', { status: 503 }],+ ['short body, then a clean end', { endAfter: 1000 }],+ ['connection reset partway through the body', { cutAfter: 5000 }],+ ['connection reset before any body', { cutAfter: 0 }],+ ['stall after the headers', 'stallBody'],+ ['stall before the headers', 'stallHeaders']+]++test.describe('transient server faults are retried to a correct file @smoke', () => {+ for (const [label, fault] of TRANSIENT) {+ test(label, async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE })+ let faulted = 0+ origin.setRule(({ range }) => (range && range.start > 0 && faulted++ < 3 ? fault : 'ok'))++ await plexo.start(origin.url(), origin.sha256, { connections: 2 })+ const state = await plexo.waitForStatus('completed')+ expect(faulted, 'the fault was actually injected').toBeGreaterThanOrEqual(3)+ expect(state.chunks.reduce((sum, chunk) => sum + chunk.retryCount, 0)).toBeGreaterThan(0)+ })+ }++ test('random connection resets across the whole file', async ({ plexo, serve }) => {+ const origin = await serve({ size: 48 * BLOCK, seed: 11 })+ let n = 0+ // Every third chunk request dies somewhere inside its block.+ origin.setRule(({ range }) =>+ range && range.start > 0 && n++ % 3 === 0 ? { cutAfter: (n * 7919) % BLOCK } : 'ok'+ )+ await plexo.start(origin.url(), origin.sha256, { connections: 4 })+ await plexo.waitForStatus('completed')+ })+})++test.describe('permanent faults end in a clean error @smoke', () => {+ const PERMANENT: [string, Fault][] = [+ ['every chunk request fails with 500', { status: 500 }],+ ['every chunk request redirects to itself', { redirect: '/files/test.bin' }],+ ['every chunk request gets the wrong range', 'wrongStart']+ ]+ for (const [label, fault] of PERMANENT) {+ test(label, async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE })+ origin.setRule(({ range }) =>+ range && !(range.start === 0 && range.end === 0) ? fault : 'ok'+ )+ await plexo.start(origin.url(), origin.sha256, { connections: 2 })+ const state = await plexo.waitForStatus('error')+ expect(state.error).toBeTruthy()+ })+ }+})++test('file changes on the server mid-download (same size, new ETag) @smoke', async ({+ plexo,+ serve+}) => {+ test.fail(+ true,+ 'known gap: chunk responses are not checked against the probed ETag, so old and new bytes get stitched together'+ )+ const origin = await serve({ size: SIZE, seed: 1 })+ const original = origin.sha256+ const replacement = seededBytes(SIZE, 2)++ const reached = origin.hold(3 * BLOCK + 100)+ await plexo.start(origin.url(), original, { connections: 2 })+ await reached+ origin.setContent(replacement, '"v2"')+ origin.release()++ const state = await plexo.waitForStatus(['completed', 'error'])+ // Acceptable outcomes: an error, or a file that is entirely one version. Never a mix.+ if (state.status === 'completed') {+ const got = sha256(await readFile(state.destinationPath))+ expect([original, sha256(replacement)]).toContain(got)+ }+})diff --git a/e2e/lifecycle.spec.ts b/e2e/lifecycle.spec.tsnew file mode 100644index 0000000..17956e8--- /dev/null+++ b/e2e/lifecycle.spec.ts@@ -0,0 +1,249 @@+import { existsSync } from 'node:fs'+import { readFile } from 'node:fs/promises'+import { join } from 'node:path'+import { BLOCK, expect, interfacesEnv, LAN_ADDRESS, NETWORKS, test } from './fixtures'+import { seededBytes, sha256 } from './origin'++// C. Pause, resume, cancel, remove. Pause points are set with origin.hold(offset), so each one+// lands at the same byte every run instead of wherever a timer happened to fire.++const SIZE = 24 * BLOCK++test.describe('pause and resume @smoke', () => {+ const points: [string, number][] = [+ ['right at the start', 1],+ ['partway through a block', 5 * BLOCK + 1234],+ ['exactly on a block boundary', 8 * BLOCK],+ ['in the last block', SIZE - 100]+ ]+ for (const [label, offset] of points) {+ test(`pause ${label}, then resume`, async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE })+ const reached = origin.hold(offset)+ const id = await plexo.start(origin.url(), origin.sha256, { connections: 2 })+ await reached++ await plexo.api.pauseDownload(id)+ const paused = await plexo.waitForStatus('paused')+ expect(paused.speedBytesPerSec).toBe(0)+ origin.release()++ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('completed')+ })+ }++ test('rapid pause/resume, 20 times', async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE })+ const reached = origin.hold(6 * BLOCK + 10)+ const id = await plexo.start(origin.url(), origin.sha256, { connections: 4 })+ await reached+ for (let i = 0; i < 20; i++) {+ await plexo.api.pauseDownload(id)+ await plexo.api.resumeDownload(id)+ }+ origin.release()+ await plexo.waitForStatus('completed')+ })++ test('pause and resume several times over the whole file', async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE, seed: 5 })+ let reached = origin.hold(2 * BLOCK + 5)+ const id = await plexo.start(origin.url(), origin.sha256, { connections: 2 })+ for (let round = 0; round < 3; round++) {+ await reached+ await plexo.api.pauseDownload(id)+ const paused = await plexo.waitForStatus('paused')+ origin.release()+ // Hold next at a byte the app hasn't fetched yet — a fixed offset could already be done+ // by another connection, and a hold that's never reached would hang the test.+ const next = paused.blocks?.find((block) => block.status !== 'completed')+ if (!next) break+ reached = origin.hold(next.rangeStart + next.bytesDownloaded)+ await plexo.api.resumeDownload(id)+ }+ origin.release()+ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('completed')+ })+})++test.describe('pause during a retry backoff', () => {+ test.use({ appEnv: { PLEXO_E2E_RETRY_BASE_MS: '5000' } })++ test('pausing does not wait out the backoff @smoke', async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE })+ let failing = true+ origin.setRule(({ range }) =>+ failing && range && range.start === 4 * BLOCK ? { status: 500 } : 'ok'+ )+ const id = await plexo.start(origin.url(), origin.sha256, { connections: 2 })+ await plexo.waitUntil((state) => state.chunks.some((chunk) => chunk.status === 'retrying'))++ const before = Date.now()+ await plexo.api.pauseDownload(id)+ await plexo.waitForStatus('paused', 2000)+ expect(Date.now() - before).toBeLessThan(2000)++ failing = false+ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('completed')+ })+})++test.describe('resume safety checks @smoke', () => {+ test('ETag changed while paused → error, nothing kept', async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE })+ const reached = origin.hold(5 * BLOCK)+ const id = await plexo.start(origin.url(), origin.sha256)+ await reached+ await plexo.api.pauseDownload(id)+ await plexo.waitForStatus('paused')+ origin.setContent(seededBytes(SIZE, 9), '"v2"')+ origin.release()++ await plexo.api.resumeDownload(id)+ const state = await plexo.waitForStatus('error')+ expect(state.error).toMatch(/changed/)+ })++ test('Last-Modified changed while paused → error', async ({ plexo, serve }) => {+ const origin = await serve({+ size: SIZE,+ etag: null,+ lastModified: 'Wed, 01 Jan 2025 00:00:00 GMT'+ })+ const reached = origin.hold(5 * BLOCK)+ const id = await plexo.start(origin.url(), origin.sha256)+ await reached+ await plexo.api.pauseDownload(id)+ await plexo.waitForStatus('paused')+ origin.lastModified = 'Thu, 02 Jan 2025 00:00:00 GMT'+ origin.release()++ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('error')+ })++ test('no validators at all → resumes', async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE, etag: null, lastModified: null })+ const reached = origin.hold(5 * BLOCK)+ const id = await plexo.start(origin.url(), origin.sha256)+ await reached+ await plexo.api.pauseDownload(id)+ await plexo.waitForStatus('paused')+ origin.release()+ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('completed')+ })++ test('network gone while paused → stays paused with a message, resumes once it is back', async ({+ plexo,+ serve+ }) => {+ test.skip(!LAN_ADDRESS, 'needs a LAN address to act as the second network')+ const origin = await serve({ size: SIZE })+ const reached = origin.hold(5 * BLOCK)+ const id = await plexo.start(origin.url(), origin.sha256, { networks: ['a'] })+ await reached+ await plexo.api.pauseDownload(id)+ await plexo.waitForStatus('paused')+ origin.release()++ const setInterfaces = (value: string): Promise<void> =>+ plexo.evaluateMain((_electron, v) => {+ process.env['PLEXO_E2E_INTERFACES'] = v+ }, value)++ await setInterfaces(interfacesEnv({ b: NETWORKS['b'] }))+ await plexo.api.resumeDownload(id)+ const stuck = await plexo.waitUntil((state) => Boolean(state.error))+ expect(stuck.status).toBe('paused')+ expect(stuck.error).toMatch(/not currently available|None of the networks/)++ await setInterfaces(interfacesEnv(NETWORKS))+ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('completed')+ })++ test('resume against a server without range support', async ({ plexo, serve }) => {+ test.fail(+ true,+ 'known bug: resumes with Range: bytes=N-, the server answers 200, every retry fails'+ )+ const origin = await serve({ size: SIZE, ranges: false })+ const reached = origin.hold(5 * BLOCK)+ const id = await plexo.start(origin.url(), origin.sha256)+ await reached+ await plexo.api.pauseDownload(id)+ await plexo.waitForStatus('paused')+ origin.release()+ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('completed', 10_000)+ })++ test('resume while the server hangs on the check request', async ({ plexo, serve }) => {+ test.fail(true, 'known bug: probe.ts has no timeout, so resume waits forever')+ const origin = await serve({ size: SIZE })+ const reached = origin.hold(5 * BLOCK)+ const id = await plexo.start(origin.url(), origin.sha256)+ await reached+ await plexo.api.pauseDownload(id)+ await plexo.waitForStatus('paused')+ origin.release()+ origin.setRule(({ range }) => (range?.start === 0 && range.end === 0 ? 'stallHeaders' : 'ok'))++ await plexo.api.resumeDownload(id)+ // Either outcome is fine — resuming, or a clear error. Sitting silently paused is not.+ await plexo.waitUntil((state) => state.status !== 'paused' || Boolean(state.error), 15_000)+ })+})++test.describe('cancel and remove @smoke', () => {+ test('cancel while downloading', async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE })+ const reached = origin.hold(7 * BLOCK)+ const id = await plexo.start(origin.url(), origin.sha256, { connections: 4 })+ await reached+ await plexo.api.cancelDownload(id)+ origin.release()+ await plexo.waitForStatus('cancelled')+ })++ test('cancel while paused', async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE })+ const reached = origin.hold(7 * BLOCK)+ const id = await plexo.start(origin.url(), origin.sha256)+ await reached+ await plexo.api.pauseDownload(id)+ await plexo.waitForStatus('paused')+ origin.release()+ await plexo.api.cancelDownload(id)+ await plexo.waitForStatus('cancelled')+ })++ test('remove after completion keeps the file', async ({ plexo, serve, dirs }) => {+ const origin = await serve({ size: SIZE })+ const id = await plexo.start(origin.url(), origin.sha256)+ const state = await plexo.waitForStatus('completed')+ await plexo.api.removeDownload(id)++ expect(await plexo.current()).toBeNull()+ expect(sha256(await readFile(state.destinationPath))).toBe(origin.sha256)+ await expect.poll(() => existsSync(join(dirs.userData, 'downloads', id))).toBe(false)+ })++ test('remove while downloading deletes everything', async ({ plexo, serve, dirs }) => {+ const origin = await serve({ size: SIZE })+ const reached = origin.hold(7 * BLOCK)+ const id = await plexo.start(origin.url(), origin.sha256)+ await reached+ const { destinationPath } = (await plexo.current())!+ await plexo.api.removeDownload(id)+ origin.release()++ expect(await plexo.current()).toBeNull()+ await expect.poll(() => existsSync(destinationPath)).toBe(false)+ await expect.poll(() => existsSync(join(dirs.userData, 'downloads', id))).toBe(false)+ })+})diff --git a/e2e/origin.ts b/e2e/origin.tsnew file mode 100644index 0000000..4769ffe--- /dev/null+++ b/e2e/origin.ts@@ -0,0 +1,295 @@+import { createHash } from 'node:crypto'+import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'+import type { AddressInfo, Socket } from 'node:net'++/**+ * The download server every e2e test talks to. It serves one file and can be told, per+ * request, to misbehave in exactly the ways a real server or network does — and to *hold* a+ * response at a byte offset, so a test can pause, kill or race the app at a precise point in+ * the transfer instead of guessing with timeouts.+ */++/** What the server does with one request. Anything other than 'ok' is a fault. */+export type Fault =+ | 'ok'+ /** Replies 200 with the whole file, as a server without range support does. */+ | 'ignoreRange'+ /** 206 whose Content-Range starts one byte later than asked. */+ | 'wrongStart'+ /** 206 with a correct header but one byte more body than the range. */+ | 'overlong'+ /** 206 with no Content-Range header. */+ | 'noContentRange'+ /** Sends headers, then nothing, forever. */+ | 'stallBody'+ /** Never answers at all. */+ | 'stallHeaders'+ | { status: number }+ /** Sends this many body bytes, then drops the connection. */+ | { cutAfter: number }+ /** Sends this many body bytes, then ends the response cleanly (a short body). */+ | { endAfter: number }+ | { redirect: string }++export interface OriginRequest {+ /** 1-based count of requests this server has seen. */+ n: number+ path: string+ /** Source address — which "network" the request came in on. */+ from: string+ range: { start: number; end: number | null } | null+}++export interface LoggedRequest extends OriginRequest {+ fault: Fault+ status: number+ bytesSent: number+}++export interface OriginOptions {+ size: number+ seed?: number+ /** false: ignore Range headers and never advertise Accept-Ranges. */+ ranges?: boolean+ /** false: omit Content-Length (chunked transfer), so the size is unknown. */+ contentLength?: boolean+ etag?: string | null+ lastModified?: string | null+ contentDisposition?: string+ /** Per-response speed limit, so a download lasts long enough to be interrupted. */+ bytesPerSecond?: number+}++/** Deterministic bytes, so a failing seed reproduces the exact same file. */+export function seededBytes(size: number, seed: number): Buffer {+ const buffer = Buffer.alloc(size)+ let state = seed >>> 0 || 1+ for (let i = 0; i < size; i++) {+ // xorshift32+ state ^= state << 13+ state ^= state >>> 17+ state ^= state << 5+ buffer[i] = state & 0xff+ }+ return buffer+}++export function sha256(data: Buffer): string {+ return createHash('sha256').update(data).digest('hex')+}++const PIECE_BYTES = 16 * 1024++function parseRange(header: string | undefined): OriginRequest['range'] {+ const match = header && /^bytes=(\d+)-(\d*)$/.exec(header)+ if (!match) return null+ return { start: Number(match[1]), end: match[2] === '' ? null : Number(match[2]) }+}++export class Origin {+ content: Buffer+ etag: string | null+ lastModified: string | null+ readonly log: LoggedRequest[] = []+ private rule: (request: OriginRequest) => Fault | undefined = () => 'ok'+ private holdAt: number | null = null+ private holdReached: (() => void) | null = null+ private holdRelease: (() => void) | null = null+ private releasePromise: Promise<void> = Promise.resolve()+ private reachedPromise: Promise<void> = Promise.resolve()+ private sockets = new Set<Socket>()+ private server = createServer((req, res) => void this.handle(req, res))+ private port = 0++ constructor(private options: OriginOptions) {+ this.content = seededBytes(options.size, options.seed ?? 1)+ this.etag = options.etag === undefined ? '"v1"' : options.etag+ this.lastModified = options.lastModified ?? null+ this.server.on('connection', (socket) => {+ this.sockets.add(socket)+ socket.on('close', () => this.sockets.delete(socket))+ })+ }++ async start(): Promise<this> {+ // 0.0.0.0 so requests bound to a LAN address (the second test "network") still arrive.+ await new Promise<void>((resolve) => this.server.listen(0, '0.0.0.0', resolve))+ this.port = (this.server.address() as AddressInfo).port+ return this+ }++ async stop(): Promise<void> {+ this.release()+ for (const socket of this.sockets) socket.destroy()+ await new Promise<void>((resolve) => this.server.close(() => resolve()))+ }++ url(path = '/files/test.bin'): string {+ return `http://127.0.0.1:${this.port}${path}`+ }++ get sha256(): string {+ return sha256(this.content)+ }++ /** Decides each request's fault. Returning undefined means 'ok'. */+ setRule(rule: (request: OriginRequest) => Fault | undefined): void {+ this.rule = rule+ }++ /** Swaps the served file, as a server publishing a new version would. */+ setContent(content: Buffer, etag: string | null): void {+ this.content = content+ this.etag = etag+ }++ /**+ * Stops every response just before it sends the byte at `offset`, until release(). Resolves+ * once the first response reaches it — i.e. the app has received exactly the bytes before it.+ */+ hold(offset: number): Promise<void> {+ this.release()+ this.holdAt = offset+ this.reachedPromise = new Promise((resolve) => (this.holdReached = resolve))+ this.releasePromise = new Promise((resolve) => (this.holdRelease = resolve))+ return this.reachedPromise+ }++ release(): void {+ this.holdAt = null+ this.holdRelease?.()+ this.holdRelease = null+ }++ /** Requests that asked for byte ranges, i.e. the app's chunk requests (not the 1-byte probe). */+ chunkRequests(): LoggedRequest[] {+ return this.log.filter((entry) => !(entry.range?.start === 0 && entry.range.end === 0))+ }++ private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {+ const request: OriginRequest = {+ n: this.log.length + 1,+ path: req.url ?? '/',+ from: (req.socket.remoteAddress ?? '').replace(/^::ffff:/, ''),+ range: parseRange(req.headers.range)+ }+ const fault = this.rule(request) ?? 'ok'+ const entry: LoggedRequest = { ...request, fault, status: 0, bytesSent: 0 }+ this.log.push(entry)++ if (fault === 'stallHeaders') return+ if (typeof fault === 'object' && 'status' in fault) {+ entry.status = fault.status+ res.writeHead(fault.status).end()+ return+ }+ if (typeof fault === 'object' && 'redirect' in fault) {+ entry.status = 302+ res.writeHead(302, { Location: fault.redirect }).end()+ return+ }++ // Snapshot, so a setContent() mid-response doesn't splice two versions into one reply.+ const content = this.content+ const total = content.length+ const headers: Record<string, string | number> = {}+ if (this.etag) headers['ETag'] = this.etag+ if (this.lastModified) headers['Last-Modified'] = this.lastModified+ if (this.options.contentDisposition) {+ headers['Content-Disposition'] = this.options.contentDisposition+ }++ const rangesOn = this.options.ranges !== false && fault !== 'ignoreRange'+ if (this.options.ranges !== false) headers['Accept-Ranges'] = 'bytes'++ let start = 0+ let end = total - 1+ let status = 200+ if (rangesOn && request.range) {+ start = request.range.start+ end = Math.min(request.range.end ?? total - 1, total - 1)+ if (start >= total) {+ entry.status = 416+ res.writeHead(416, { 'Content-Range': `bytes */${total}` }).end()+ return+ }+ status = 206+ if (fault !== 'noContentRange') {+ const shownStart = fault === 'wrongStart' ? start + 1 : start+ headers['Content-Range'] = `bytes ${shownStart}-${end}/${total}`+ }+ }++ let bodyEnd = end + 1 // exclusive+ if (fault === 'overlong') bodyEnd = Math.min(bodyEnd + 1, total)+ if (typeof fault === 'object' && 'endAfter' in fault) {+ bodyEnd = Math.min(bodyEnd, start + fault.endAfter)+ }+ const cutAfter = typeof fault === 'object' && 'cutAfter' in fault ? fault.cutAfter : null++ if (this.options.contentLength !== false && cutAfter === null) {+ headers['Content-Length'] = bodyEnd - start+ }+ entry.status = status+ res.writeHead(status, headers)+ if (req.method === 'HEAD') {+ res.end()+ return+ }+ if (fault === 'stallBody') {+ res.flushHeaders()+ return+ }++ // The app's 1-byte probes (bytes=0-0) are never held — only real transfers are.+ const holdable = !(request.range?.start === 0 && request.range.end === 0)+ let position = start+ while (position < bodyEnd) {+ if (res.destroyed) return+ if (cutAfter !== null && position - start >= cutAfter) {+ req.socket.destroy()+ return+ }++ let next = Math.min(bodyEnd, position + PIECE_BYTES)+ if (cutAfter !== null) next = Math.min(next, start + cutAfter)+ if (holdable && this.holdAt !== null) {+ if (position === this.holdAt) {+ this.holdReached?.()+ await this.releasePromise+ continue+ }+ if (this.holdAt > position && this.holdAt < next) next = this.holdAt+ }++ const piece = content.subarray(position, next)+ entry.bytesSent += piece.length+ position = next+ if (!res.write(piece)) {+ await new Promise<void>((resolve) => {+ const done = (): void => {+ res.off('drain', done)+ res.off('close', done)+ resolve()+ }+ res.on('drain', done)+ res.on('close', done)+ })+ } else {+ // Yield so other connections — and the app's pause/cancel — interleave with this one.+ await new Promise((resolve) => setImmediate(resolve))+ }+ if (this.options.bytesPerSecond) {+ await new Promise((resolve) =>+ setTimeout(resolve, (piece.length / this.options.bytesPerSecond!) * 1000)+ )+ }+ }++ if (cutAfter !== null) {+ req.socket.destroy()+ return+ }+ res.end()+ }+}diff --git a/e2e/recovery.spec.ts b/e2e/recovery.spec.tsnew file mode 100644index 0000000..088d47d--- /dev/null+++ b/e2e/recovery.spec.ts@@ -0,0 +1,184 @@+import { cp, readFile, rm, writeFile } from 'node:fs/promises'+import { existsSync } from 'node:fs'+import { join } from 'node:path'+import { BLOCK, expect, test } from './fixtures'+import { seededBytes, sha256 } from './origin'++// D. Quitting, crashing and restarting. kill() is SIGKILL: no before-quit, no final save —+// what's on disk is whatever the app had managed to persist, exactly as after a crash or a+// power cut.++const SIZE = 32 * BLOCK++test.describe('restart @smoke', () => {+ test('normal quit mid-download → relaunch paused → resume', async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE })+ const reached = origin.hold(10 * BLOCK + 500)+ const id = await plexo.start(origin.url(), origin.sha256, { connections: 2 })+ await reached++ await plexo.quit()+ origin.release()+ await plexo.launch()++ const restored = await plexo.current()+ expect(restored?.id).toBe(id)+ expect(restored?.status).toBe('paused')+ expect(restored?.bytesDownloaded).toBeGreaterThan(0)++ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('completed')+ })++ test('a completed download is still there after a restart', async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE })+ await plexo.start(origin.url(), origin.sha256)+ const done = await plexo.waitForStatus('completed')++ await plexo.relaunch()+ const restored = await plexo.current()+ expect(restored?.status).toBe('completed')+ expect(sha256(await readFile(done.destinationPath))).toBe(origin.sha256)+ })+})++test.describe('crash (SIGKILL) and recover @smoke', () => {+ // Offsets chosen to land in different places: first block, mid-block, a block boundary,+ // and the tail — each one leaves different part-file and manifest states behind.+ for (const offset of [100, 3 * BLOCK + 777, 12 * BLOCK, 20 * BLOCK + 1, SIZE - 10]) {+ test(`killed with a response held at byte ${offset}`, async ({ plexo, serve }) => {+ const origin = await serve({ size: SIZE, seed: offset })+ const reached = origin.hold(offset)+ const id = await plexo.start(origin.url(), origin.sha256, { connections: 4 })+ await reached+ // Give progress events and the throttled manifest save a chance to (partly) happen.+ await plexo.waitUntil((state) => state.bytesDownloaded > 0)++ await plexo.kill()+ origin.release()+ await plexo.launch()++ const restored = await plexo.current()+ expect(restored?.id).toBe(id)+ expect(restored?.status).toBe('paused')++ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('completed')+ })+ }++ test('killed while assembling → relaunch paused → resume re-assembles', async ({+ plexo,+ dirs+ }) => {+ // A simulated download can throttle the assemble step, which keeps it in 'assembling'+ // long enough to kill it there.+ const source = join(dirs.userData, '..', 'source.bin')+ const bytes = seededBytes(SIZE, 21)+ await writeFile(source, bytes)+ const id = await plexo.startSimulated(+ {+ sourceFilePath: source,+ networks: [{ kind: 'ethernet', label: 'sim', speedBytesPerSec: 50e6, faultRatePercent: 0 }],+ chunkCount: 2,+ connectionsPerNetwork: 2,+ assembleSpeedBytesPerSec: SIZE / 4+ },+ sha256(bytes)+ )+ await plexo.waitUntil(+ (state) => state.status === 'assembling' && (state.assembledBytes ?? 0) > 0+ )++ await plexo.kill()+ await plexo.launch()+ expect((await plexo.current())?.status).toBe('paused')++ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('completed')+ })+})++test.describe('persisted state on disk @smoke', () => {+ async function pausedDownload(+ plexo: import('./fixtures').PlexoApp,+ serve: (o: { size: number; seed?: number }) => Promise<import('./origin').Origin>,+ seed = 1+ ): Promise<{ id: string; origin: import('./origin').Origin }> {+ const origin = await serve({ size: SIZE, seed })+ const reached = origin.hold(8 * BLOCK)+ const id = await plexo.start(origin.url(), origin.sha256)+ await reached+ await plexo.api.pauseDownload(id)+ await plexo.waitForStatus('paused')+ origin.release()+ return { id, origin }+ }++ test('a leftover manifest.json.tmp is ignored', async ({ plexo, serve, dirs }) => {+ const { id } = await pausedDownload(plexo, serve)+ await plexo.quit()+ await writeFile(join(dirs.userData, 'downloads', id, 'manifest.json.tmp'), '{"half":')+ await plexo.launch()+ expect((await plexo.current())?.id).toBe(id)+ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('completed')+ })++ test('a corrupt manifest does not stop the app from starting', async ({ plexo, serve, dirs }) => {+ const { id } = await pausedDownload(plexo, serve)+ await plexo.quit()+ await writeFile(join(dirs.userData, 'downloads', id, 'manifest.json'), 'not json {')+ await plexo.launch()+ expect(await plexo.current()).toBeNull()++ // And a new download still works.+ const origin = await serve({ size: 4 * BLOCK, seed: 99 })+ await plexo.start(origin.url(), origin.sha256)+ await plexo.waitForStatus('completed')+ })++ test('two saved downloads: only the newest is restored, the other is removed', async ({+ plexo,+ serve,+ dirs+ }) => {+ const { id } = await pausedDownload(plexo, serve)+ await plexo.quit()++ // Clone the saved download under another id, dated an hour earlier.+ const root = join(dirs.userData, 'downloads')+ const olderId = '00000000-0000-4000-8000-000000000000'+ await cp(join(root, id), join(root, olderId), { recursive: true })+ const manifestPath = join(root, olderId, 'manifest.json')+ const manifest = JSON.parse(await readFile(manifestPath, 'utf-8'))+ manifest.state.id = olderId+ manifest.state.startedAt -= 3_600_000+ await writeFile(manifestPath, JSON.stringify(manifest))++ await plexo.launch()+ expect((await plexo.current())?.id).toBe(id)+ await expect.poll(() => existsSync(join(root, olderId))).toBe(false)++ await plexo.api.resumeDownload(id)+ await plexo.waitForStatus('completed')+ })++ test('part files deleted while the app was closed → re-downloads them', async ({+ plexo,+ serve,+ dirs+ }) => {+ test.fail(+ true,+ 'known gap: resume trusts the manifest, never recreates parts/, and fails with ENOENT instead of re-fetching the missing blocks'+ )+ const { id } = await pausedDownload(plexo, serve)+ await plexo.quit()+ await rm(join(dirs.userData, 'downloads', id, 'parts'), { recursive: true, force: true })+ await plexo.launch()+ await plexo.api.resumeDownload(id)+ const state = await plexo.waitForStatus(['completed', 'error'])+ expect(state.error).toBeUndefined()+ })+})diff --git a/e2e/sim.spec.ts b/e2e/sim.spec.tsnew file mode 100644index 0000000..f037f85--- /dev/null+++ b/e2e/sim.spec.ts@@ -0,0 +1,63 @@+import { writeFile } from 'node:fs/promises'+import { join } from 'node:path'+import type { SimulatedNetworkConfig } from '../src/shared/types'+import { BLOCK, expect, test } from './fixtures'+import { seededBytes, sha256 } from './origin'++// F. The dev-tool simulated download: a local file pushed through the real chunking, retry and+// assembly pipeline, with only the HTTP transfer swapped out (see simDownload.ts).++const SIZE = 40 * BLOCK++async function sourceFile(dir: string, seed: number): Promise<{ path: string; sha: string }> {+ const bytes = seededBytes(SIZE, seed)+ const path = join(dir, '..', `source-${seed}.bin`)+ await writeFile(path, bytes)+ return { path, sha: sha256(bytes) }+}++const network = (label: string, faultRatePercent = 0): SimulatedNetworkConfig => ({+ kind: 'wifi',+ label,+ speedBytesPerSec: 40e6,+ faultRatePercent+})++test.describe('simulated downloads @smoke', () => {+ test('three flaky networks (30% of attempts dropped) still produce the exact file', async ({+ plexo,+ dirs+ }) => {+ const source = await sourceFile(dirs.userData, 1)+ await plexo.startSimulated(+ {+ sourceFilePath: source.path,+ networks: [network('one', 30), network('two', 30), network('three', 30)],+ chunkCount: 6,+ connectionsPerNetwork: 2+ },+ source.sha+ )+ const state = await plexo.waitForStatus('completed', 30_000)+ expect(state.chunks.reduce((sum, chunk) => sum + chunk.retryCount, 0)).toBeGreaterThan(0)+ })++ test('pause and cancel are ignored while assembling', async ({ plexo, dirs }) => {+ const source = await sourceFile(dirs.userData, 2)+ const id = await plexo.startSimulated(+ {+ sourceFilePath: source.path,+ networks: [network('one')],+ chunkCount: 2,+ connectionsPerNetwork: 2,+ assembleSpeedBytesPerSec: SIZE / 2+ },+ source.sha+ )+ await plexo.waitForStatus('assembling')+ await plexo.api.pauseDownload(id)+ await plexo.api.cancelDownload(id)+ expect((await plexo.current())?.status).toBe('assembling')+ await plexo.waitForStatus('completed')+ })+})diff --git a/e2e/ui.spec.ts b/e2e/ui.spec.tsnew file mode 100644index 0000000..6391c68--- /dev/null+++ b/e2e/ui.spec.ts@@ -0,0 +1,169 @@+import { writeFile } from 'node:fs/promises'+import { join } from 'node:path'+import { BLOCK, expect, test } from './fixtures'++// G. A handful of journeys through the real UI, to prove the screens are wired to the main+// process. Download correctness is covered far more thoroughly by the API-level specs; these+// only need to show that clicking the buttons drives it.++const SIZE = 24 * BLOCK++/** The destination picker and "Reveal in Finder" go through native OS UI — replace both. */+async function stubNativeUi(+ plexo: import('./fixtures').PlexoApp,+ destination: string+): Promise<void> {+ await plexo.evaluateMain(({ dialog, shell }, dest) => {+ dialog.showOpenDialog = (async () => ({ canceled: false, filePaths: [dest] })) as never+ const revealed: string[] = []+ ;(globalThis as Record<string, unknown>).__revealed = revealed+ shell.showItemInFolder = (path: string) => void revealed.push(path)+ }, destination)+}++test.describe('UI journeys @smoke', () => {+ test('paste a link, start, pause, resume, finish, reveal the file', async ({+ plexo,+ serve,+ dirs+ }) => {+ const origin = await serve({ size: SIZE })+ await stubNativeUi(plexo, dirs.dest)+ const page = plexo.page++ await page.getByRole('button', { name: 'Browse…' }).click()+ await page.getByRole('textbox', { name: 'LINK' }).fill(origin.url())+ const start = page.getByRole('button', { name: 'Start' })+ await expect(start).toBeEnabled()++ const reached = origin.hold(6 * BLOCK)+ await plexo.expectNextDownload(origin.sha256)+ await start.click()+ await reached++ await page.getByRole('button', { name: 'Pause' }).click()+ await expect(page.getByRole('button', { name: 'Resume' })).toBeVisible()+ origin.release()+ await page.getByRole('button', { name: 'Resume' }).click()++ const reveal = page.getByRole('button', { name: /Reveal in Finder|Show in folder/ })+ await expect(reveal).toBeVisible()+ await reveal.click()+ const { destinationPath } = (await plexo.current())!+ await expect+ .poll(() =>+ plexo.evaluateMain(() => (globalThis as Record<string, unknown>).__revealed, null)+ )+ .toEqual([destinationPath])+ })++ test('cancel through the confirmation dialog, then "Download Again"', async ({+ plexo,+ serve,+ dirs+ }) => {+ test.fail(+ true,+ 'known bug: remove() does not stop the cancelled run from pushing more updates, so a late "cancelled" event brings the removed download back on screen'+ )+ const origin = await serve({ size: SIZE })+ await stubNativeUi(plexo, dirs.dest)+ const page = plexo.page+ await page.getByRole('button', { name: 'Browse…' }).click()+ await page.getByRole('textbox', { name: 'LINK' }).fill(origin.url())++ const reached = origin.hold(6 * BLOCK)+ await page.getByRole('button', { name: 'Start' }).click()+ await reached+ await page.getByRole('button', { name: 'Cancel', exact: true }).click()+ await page.getByRole('button', { name: 'Cancel download' }).click()+ origin.release()++ await page.getByRole('button', { name: 'Download Again' }).click()+ await plexo.expectNextDownload(origin.sha256)+ await page.getByRole('button', { name: 'Start' }).click({ timeout: 5000 })+ await expect(+ page.getByRole('button', { name: /Reveal in Finder|Show in folder/ })+ ).toBeVisible()+ })++ test('a link the server rejects shows the error and keeps Start disabled', async ({+ plexo,+ serve+ }) => {+ const origin = await serve({ size: SIZE })+ origin.setRule(() => ({ status: 404 }))+ const page = plexo.page+ await page.getByRole('textbox', { name: 'LINK' }).fill(origin.url())+ await expect(page.getByText(/could not be found/)).toBeVisible()+ await expect(page.getByRole('button', { name: 'Start' })).toBeDisabled()+ })++ 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)+ await plexo.waitForStatus('completed')+ await plexo.relaunch()+ await expect(+ plexo.page.getByRole('button', { name: /Reveal in Finder|Show in folder/ })+ ).toBeVisible()+ })++ test('theme choice survives a restart', async ({ plexo }) => {+ const before = await plexo.api.getThemeSource()+ const next = before === 'light' ? 'dark' : 'light'+ await plexo.page.getByRole('button', { name: `Switch to ${next} theme` }).click()+ await expect.poll(() => plexo.api.getThemeSource()).toBe(next)+ await plexo.relaunch()+ expect(await plexo.api.getThemeSource()).toBe(next)+ })++ test('renaming a network survives a restart', async ({ plexo }) => {+ const page = plexo.page+ await page.getByRole('button', { name: 'Edit network' }).first().click()+ await page.getByRole('textbox', { name: 'Name' }).fill('Office fibre')+ await page.getByRole('button', { name: 'Done' }).click()+ await expect(page.getByText('Office fibre')).toBeVisible()++ await plexo.relaunch()+ await expect(plexo.page.getByText('Office fibre')).toBeVisible()+ })++ test('a corrupt network-preferences.json does not break the network list', async ({+ plexo,+ dirs+ }) => {+ await plexo.quit()+ await writeFile(join(dirs.userData, 'network-preferences.json'), '{"a": 42, "b": [')+ await plexo.launch()+ await expect(plexo.page.getByRole('button', { name: 'Edit network' }).first()).toBeVisible()+ })+})++test.describe('no networks', () => {+ test.use({ appEnv: { PLEXO_E2E_INTERFACES: '' } })++ test('shows the no-connections screen, and settles on it @smoke', async ({ plexo }) => {+ test.fail(+ true,+ 'known bug: Idle and NoConnections screens each re-scan on mount, the scan flips interfacesStatus to "loading", which swaps the screen back — an endless loop (~4000 scans/s) that freezes the renderer'+ )+ await plexo.evaluateMain(({ ipcMain }) => {+ const g = globalThis as unknown as Record<string, number>+ g.__scans = 0+ ipcMain.removeHandler('network:list-interfaces')+ ipcMain.handle('network:list-interfaces', () => {+ g.__scans+++ return []+ })+ }, null)+ await new Promise((resolve) => setTimeout(resolve, 2000))+ const scans = await plexo.evaluateMain(+ () => (globalThis as unknown as Record<string, number>).__scans,+ null+ )+ // The screen polls every 5 s; a couple of scans in 2 s is normal, thousands is the loop.+ expect(scans).toBeLessThan(10)+ await expect(plexo.page.getByText('No networks to combine')).toBeVisible({ timeout: 5000 })+ })+})diff --git a/eslint.config.mjs b/eslint.config.mjsindex aff5d3f..a5a55e4 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -28,5 +28,11 @@ export default defineConfig(...eslintPluginReactRefresh.configs.vite.rules}},+ {+ // Playwright fixtures call a parameter named `use`, which the React hooks rule mistakes for+ // React's use() hook.+ files: ['e2e/**'],+ rules: { 'react-hooks/rules-of-hooks': 'off' }+ },eslintConfigPrettier)diff --git a/package-lock.json b/package-lock.jsonindex ecfa9a9..cbcd966 100644--- a/package-lock.json+++ b/package-lock.json@@ -21,6 +21,7 @@"@electron-toolkit/eslint-config-prettier": "^3.0.0","@electron-toolkit/eslint-config-ts": "^3.1.0","@electron-toolkit/tsconfig": "^2.0.0",+ "@playwright/test": "^1.63.0","@tailwindcss/vite": "^4.3.3","@types/node": "^22.19.1","@types/react": "^19.2.7",@@ -33,6 +34,7 @@"eslint-plugin-react": "^7.37.5","eslint-plugin-react-hooks": "^7.0.1","eslint-plugin-react-refresh": "^0.4.24",+ "fast-check": "^4.10.1","prettier": "^3.7.4","react": "^19.2.1","react-dom": "^19.2.1",@@ -1928,6 +1930,22 @@"url": "https://opencollective.com/pkgr"}},+ "node_modules/@playwright/test": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",+ "integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright": "1.63.0"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/@rolldown/pluginutils": {"version": "1.0.0-rc.3","resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz",@@ -5365,6 +5383,29 @@"@types/yauzl": "^2.9.1"}},+ "node_modules/fast-check": {+ "version": "4.10.1",+ "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.10.1.tgz",+ "integrity": "sha512-sB5Vghiu8MyCyToHoBVGsT0baZg3sZWNIY+a6Ct2EDrQJlT4YdH6MC1BSLNe3kX1k5i5g0q1O52XFgcKK/rGHg==",+ "dev": true,+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/dubzzz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fast-check"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "pure-rand": "^8.0.0"+ },+ "engines": {+ "node": ">=12.17.0"+ }+ },"node_modules/fast-deep-equal": {"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",@@ -7809,6 +7850,35 @@"url": "https://paulmillr.com/funding/"}},+ "node_modules/playwright": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",+ "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.63.0"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/plist": {"version": "3.1.0","resolved": "https://registry.npmjs.org/plist/-/plist-3.1.0.tgz",@@ -8016,6 +8086,23 @@"node": ">=6"}},+ "node_modules/pure-rand": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-8.4.2.tgz",+ "integrity": "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng==",+ "dev": true,+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/dubzzz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fast-check"+ }+ ],+ "license": "MIT"+ },"node_modules/pvtsutils": {"version": "1.3.6","resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",diff --git a/package.json b/package.jsonindex f4666ba..36e5e76 100644--- a/package.json+++ b/package.json@@ -10,7 +10,8 @@"lint": "eslint --cache .","typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false","typecheck:web": "tsc --noEmit -p tsconfig.web.json --composite false",- "typecheck": "npm run typecheck:node && npm run typecheck:web",+ "typecheck:e2e": "tsc -p tsconfig.e2e.json",+ "typecheck": "npm run typecheck:node && npm run typecheck:web && npm run typecheck:e2e","start": "electron-vite preview","dev": "electron-vite dev","build": "npm run typecheck && electron-vite build",@@ -18,7 +19,9 @@"build:unpack": "npm run build && electron-builder --dir","build:win": "npm run build && electron-builder --win","build:mac": "electron-vite build && electron-builder --mac",- "build:linux": "electron-vite build && electron-builder --linux"+ "build:linux": "electron-vite build && electron-builder --linux",+ "test:e2e": "playwright test",+ "test:e2e:smoke": "playwright test --grep @smoke"},"dependencies": {"@base-ui/react": "^1.8.0",@@ -33,6 +36,7 @@"@electron-toolkit/eslint-config-prettier": "^3.0.0","@electron-toolkit/eslint-config-ts": "^3.1.0","@electron-toolkit/tsconfig": "^2.0.0",+ "@playwright/test": "^1.63.0","@tailwindcss/vite": "^4.3.3","@types/node": "^22.19.1","@types/react": "^19.2.7",@@ -45,6 +49,7 @@"eslint-plugin-react": "^7.37.5","eslint-plugin-react-hooks": "^7.0.1","eslint-plugin-react-refresh": "^0.4.24",+ "fast-check": "^4.10.1","prettier": "^3.7.4","react": "^19.2.1","react-dom": "^19.2.1",diff --git a/playwright.config.ts b/playwright.config.tsnew file mode 100644index 0000000..7ef363c--- /dev/null+++ b/playwright.config.ts@@ -0,0 +1,14 @@+import { defineConfig } from '@playwright/test'++export default defineConfig({+ testDir: './e2e',+ globalSetup: './e2e/global-setup.ts',+ timeout: 60_000,+ // Deliberately 0, including on CI: a download test that only passes on a retry has found a+ // race, and retrying would hide exactly what this suite exists to catch.+ retries: 0,+ fullyParallel: true,+ workers: process.env.CI ? 2 : 4,+ forbidOnly: !!process.env.CI,+ reporter: process.env.CI ? [['list'], ['html', { open: 'never' }]] : 'list'+})diff --git a/src/main/download/chunkDownloader.ts b/src/main/download/chunkDownloader.tsindex f2fe29a..3e92dc0 100644--- a/src/main/download/chunkDownloader.ts+++ b/src/main/download/chunkDownloader.ts@@ -2,6 +2,7 @@ import { createWriteStream, type WriteStream } from 'node:fs'import { request as httpRequest, type ClientRequest, type IncomingMessage } from 'node:http'import { request as httpsRequest } from 'node:https'import { URL } from 'node:url'+import { testKnobs } from '../testKnobs'export interface ChunkDownloadOptions {url: string@@ -20,7 +21,7 @@ export interface ChunkDownloadOptions {// A server that accepts the connection and then goes silent (no data, no// error, no close) would otherwise hang the chunk forever with no way to// detect or retry it.-const STALL_TIMEOUT_MS = 20_000+const STALL_TIMEOUT_MS = testKnobs.stallTimeoutMs// Only the initial probe resolves redirects today — if a CDN reissues a// redirect mid-download (e.g. a signed URL rotates), a chunk needs to bediff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.tsindex 8f01930..4e56b15 100644--- a/src/main/download/downloadManager.ts+++ b/src/main/download/downloadManager.ts@@ -26,6 +26,7 @@ import type {StartSimulatedDownloadRequest} from '../../shared/types'import { downloadChunk } from './chunkDownloader'+import { testKnobs } from '../testKnobs'import { reserveDestinationPath } from './paths'import { isResourceUnchanged } from './probe'import {@@ -95,7 +96,7 @@ function pushSpeedSample(samples: SpeedSample[], bytes: number, time: number): nconst MAX_CHUNKS = 32const MAX_CHUNK_RETRIES = 5-const RETRY_BASE_DELAY_MS = 1000+const RETRY_BASE_DELAY_MS = testKnobs.retryBaseDelayMsconst RETRY_MAX_DELAY_MS = 15_000function retryDelayMs(attempt: number): number {@@ -445,7 +446,7 @@ export class DownloadManager {// block size instead of the count once a file is big enough to hit it.// The UI caps how many cells it renders separately (see BlockGrid), by// bucketing these blocks rather than by shrinking their count here.- const BASE_BLOCK_BYTES = 8 * 1024 * 1024 // 8 MB+ const BASE_BLOCK_BYTES = testKnobs.blockBytes // 8 MB outside testsconst MAX_REAL_BLOCKS = 4096let blockSizeBytes = 0diff --git a/src/main/index.ts b/src/main/index.tsindex 111f4fb..35fb592 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -5,6 +5,7 @@ import iconDark from '../../resources/icon-dark.png?asset'import iconLight from '../../resources/icon-light.png?asset'import { registerIpcHandlers } from './ipc/handlers'import { loadThemeSource } from './settings'+import { testKnobs } from './testKnobs'import { IpcChannels } from '../shared/ipc-channels'import type { DownloadManager } from './download/downloadManager'@@ -13,6 +14,9 @@ import type { DownloadManager } from './download/downloadManager'// this from electron-builder's productName, but setting it here keeps dev and packaged in sync.app.setName('Plexo')+// Each e2e test runs against its own throwaway userData folder (downloads, manifests, settings).+if (testKnobs.userDataDir) app.setPath('userData', testKnobs.userDataDir)+let mainWindow: BrowserWindow | null = nulllet downloadManager: DownloadManager | null = nulllet quitAfterSuspending = false@@ -75,12 +79,14 @@ function createWindow(): void {? { titleBarStyle: 'hiddenInset', trafficLightPosition: { x: 16, y: 16 } }: {}),webPreferences: {- preload: join(__dirname, '../preload/index.js')+ preload: join(__dirname, '../preload/index.js'),+ // A hidden e2e window would otherwise have its timers throttled.+ backgroundThrottling: !testKnobs.hideWindow}})mainWindow.on('ready-to-show', () => {- mainWindow?.show()+ if (!testKnobs.hideWindow) mainWindow?.show()})mainWindow.on('closed', () => {@@ -123,7 +129,8 @@ app.whenReady().then(async () => {if (is.dev) installDevMenu()createWindow()- applyThemedIcon()+ if (testKnobs.hideWindow) app.dock?.hide()+ else applyThemedIcon()app.on('activate', function () {if (BrowserWindow.getAllWindows().length === 0) createWindow()diff --git a/src/main/network/interfaces.ts b/src/main/network/interfaces.tsindex 9d4c4b9..5f829da 100644--- a/src/main/network/interfaces.ts+++ b/src/main/network/interfaces.ts@@ -2,6 +2,7 @@ import { execFile } from 'node:child_process'import { networkInterfaces } from 'node:os'import { promisify } from 'node:util'import type { NetworkInterfaceInfo, NetworkInterfaceKind } from '../../shared/types'+import { testInterfaces } from '../testKnobs'const execFileAsync = promisify(execFile)const DISCOVERY_TIMEOUT_MS = 5000@@ -83,6 +84,9 @@ async function getWindowsAdapters(): Promise<Map<string, WindowsAdapter>> {* to a specific interface (see chunkDownloader's `localAddress` option).*/export async function listActiveInterfaces(): Promise<NetworkInterfaceInfo[]> {+ const overridden = testInterfaces()+ if (overridden) return overridden+const hardwarePorts = await getMacHardwarePortNames()const windowsAdapters = await getWindowsAdapters()const all = networkInterfaces()diff --git a/src/main/testKnobs.ts b/src/main/testKnobs.tsnew file mode 100644index 0000000..5f858cd--- /dev/null+++ b/src/main/testKnobs.ts@@ -0,0 +1,36 @@+import { app } from 'electron'+import type { NetworkInterfaceInfo } from '../shared/types'++// Overrides for the end-to-end suite (e2e/), read from the environment. A packaged build ignores+// all of them, so a shipped app can't be steered through its environment variables.+const env: NodeJS.ProcessEnv = app.isPackaged ? {} : process.env++function positiveNumber(name: string, fallback: number): number {+ const value = Number(env[name])+ return value > 0 ? value : fallback+}++export const testKnobs = {+ userDataDir: env['PLEXO_USER_DATA'],+ /** Keeps the window off-screen so a test run doesn't pop windows up over the desktop. */+ hideWindow: env['PLEXO_E2E_HIDE_WINDOW'] === '1',+ blockBytes: positiveNumber('PLEXO_E2E_BLOCK_BYTES', 8 * 1024 * 1024),+ retryBaseDelayMs: positiveNumber('PLEXO_E2E_RETRY_BASE_MS', 1000),+ stallTimeoutMs: positiveNumber('PLEXO_E2E_STALL_MS', 20_000)+}++/** `PLEXO_E2E_INTERFACES=a=127.0.0.1,b=192.168.1.5` replaces the real interface list. Read on+ * every call rather than once, so a test can make a network "disappear" mid-download by+ * rewriting process.env in the main process. */+export function testInterfaces(): NetworkInterfaceInfo[] | null {+ if (app.isPackaged) return null+ const raw = process.env['PLEXO_E2E_INTERFACES']+ if (raw === undefined) return null+ return raw+ .split(',')+ .filter(Boolean)+ .map((entry) => {+ const [id, address] = entry.split('=')+ return { id, device: id, displayName: id, address, kind: 'ethernet' as const }+ })+}diff --git a/tsconfig.e2e.json b/tsconfig.e2e.jsonnew file mode 100644index 0000000..bb9e502--- /dev/null+++ b/tsconfig.e2e.json@@ -0,0 +1,8 @@+{+ "extends": "@electron-toolkit/tsconfig/tsconfig.node.json",+ "include": ["e2e/**/*", "playwright.config.ts", "src/preload/index.d.ts"],+ "compilerOptions": {+ "noEmit": true,+ "lib": ["ESNext", "DOM"]+ }+}