Speed up downloads by combining multiple network connections in parallel
TypeScript bandwidth-aggregationcross-platformdesktop-appdownloaderdownloadmanagerlinuxmacosmulticonnectionparallel-downloadswindows
chore: remove the simulated-download dev tool
Anmol Kapile20c5e919c4c
diff --git a/e2e/download.spec.ts b/e2e/download.spec.tsindex 634d288..665fe20 100644--- a/e2e/download.spec.ts+++ b/e2e/download.spec.ts@@ -1,3 +1,4 @@+import { existsSync } from 'node:fs'import { BLOCK, expect, LAN_ADDRESS, test } from './fixtures'// A. Downloads that should simply work. Every test also runs the automatic checks in@@ -73,6 +74,41 @@ test.describe('happy paths @smoke', () => {expect(attributed).toEqual(served)})+ test('a file with fewer blocks than streams still gives every network work', async ({+ plexo,+ serve+ }) => {+ test.skip(!LAN_ADDRESS, 'needs a LAN address to act as the second network')+ // 7 blocks against 8 streams a network: the first network's streams used to claim every+ // block before the second network's had started, leaving it idle for the whole download.+ const origin = await serve({ size: 7 * BLOCK })+ await plexo.start(origin.url(), origin.sha256, { networks: ['a', 'b'], connections: 8 })+ const state = await plexo.waitForStatus('completed')+ expect(new Set(origin.chunkRequests().map((request) => request.from)).size).toBe(2)+ // A stream with no block to claim would only idle: each network gets its share of the 7.+ for (const network of ['a', 'b']) {+ expect(state.chunks.filter((chunk) => chunk.interfaceId === network)).toHaveLength(4)+ }+ })++ test('a slow download fills a staging file beside the destination, reporting as it goes', async ({+ plexo,+ serve+ }) => {+ const origin = await serve({ size: 16 * BLOCK, bytesPerSecond: 200_000 })+ const id = await plexo.start(origin.url(), origin.sha256)+ const running = await plexo.waitUntil((state) => state.bytesDownloaded > 0)+ expect(existsSync(`${running.destinationPath}.plexo`)).toBe(true)+ expect(existsSync(running.destinationPath)).toBe(false)+ await plexo.waitForStatus('completed')+ const updates = plexo.sessions+ .at(-1)!+ .filter(+ (state) => state.id === id && state.status === 'downloading' && state.bytesDownloaded > 0+ )+ expect(updates.length, 'progress kept coming while it downloaded').toBeGreaterThan(5)+ })+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)diff --git a/e2e/fixtures.ts b/e2e/fixtures.tsindex 20c8778..b6e26e6 100644--- a/e2e/fixtures.ts+++ b/e2e/fixtures.ts@@ -212,19 +212,6 @@ export class PlexoApp {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,- options: Pick<StartOptions, 'connections'> = {}- ): Promise<string> {- await this.pinStreams(options.connections)- 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()}diff --git a/e2e/lifecycle.spec.ts b/e2e/lifecycle.spec.tsindex 04a5358..865213b 100644--- a/e2e/lifecycle.spec.ts+++ b/e2e/lifecycle.spec.ts@@ -235,10 +235,13 @@ test.describe('cancel and remove @smoke', () => {const id = await plexo.start(origin.url(), origin.sha256)await reachedawait plexo.api.pauseDownload(id)- await plexo.waitForStatus('paused')+ const paused = await plexo.waitForStatus('paused')+ const staging = `${paused.destinationPath}.plexo`+ expect(existsSync(staging), 'pausing keeps the staging file').toBe(true)origin.release()await plexo.api.cancelDownload(id)await plexo.waitForStatus('cancelled')+ await expect.poll(() => existsSync(staging), { message: 'cancelling removes it' }).toBe(false)})test('remove after completion keeps the file', async ({ plexo, serve, dirs }) => {diff --git a/e2e/sim.spec.ts b/e2e/sim.spec.tsdeleted file mode 100644index 92fe477..0000000--- a/e2e/sim.spec.ts+++ /dev/null@@ -1,151 +0,0 @@-import { existsSync } from 'node:fs'-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 and retry-// 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)]- },- source.sha- )- const state = await plexo.waitForStatus('completed', 30_000)- expect(state.chunks.reduce((sum, chunk) => sum + chunk.retryCount, 0)).toBeGreaterThan(0)- })-- test('a file with fewer blocks than streams still gives every network work', async ({- plexo,- dirs- }) => {- // 7 blocks against 16 requested streams: the first network's streams used to claim every- // block before the second network's had started, leaving it idle for the whole download.- const bytes = seededBytes(7 * BLOCK, 3)- const path = join(dirs.userData, '..', 'source-small.bin')- await writeFile(path, bytes)- await plexo.startSimulated(- {- sourceFilePath: path,- networks: [network('one'), network('two')]- },- sha256(bytes),- { connections: 8 }- )- const state = await plexo.waitForStatus('completed')-- const delivered = new Map<string, number>()- for (const chunk of state.chunks) delivered.set(chunk.interfaceId, 0)- for (const block of state.blocks ?? []) {- for (const [id, size] of Object.entries(block.bytesByInterface)) {- delivered.set(id, (delivered.get(id) ?? 0) + size)- }- }- expect(delivered.size, 'both networks are listed').toBe(2)- for (const [id, size] of delivered) expect(size, `${id} delivered bytes`).toBeGreaterThan(0)- // 16 streams were asked for, but a stream with no block to claim would only idle: each- // network gets as many as its share of the 7 blocks (4).- for (const id of delivered.keys()) {- expect(state.chunks.filter((chunk) => chunk.interfaceId === id)).toHaveLength(4)- }- })-- test('writes one staging file beside the final destination and publishes it', async ({- plexo,- dirs- }) => {- const source = await sourceFile(dirs.userData, 5)- const id = await plexo.startSimulated(- {- sourceFilePath: source.path,- networks: [{ ...network('one'), speedBytesPerSec: 200_000 }]- },- source.sha- )- await plexo.waitUntil((state) => state.bytesDownloaded > 0)- const staging = join(dirs.dest, 'source-5.bin.plexo')- expect(existsSync(staging)).toBe(true)- expect(existsSync(join(dirs.dest, 'source-5.bin'))).toBe(false)- expect(existsSync(join(dirs.userData, 'downloads', id, 'parts'))).toBe(false)- await plexo.waitForStatus('completed', 30_000)- expect(existsSync(staging)).toBe(false)- const progressUpdates = plexo.sessions- .at(-1)!- .filter(- (state) => state.id === id && state.status === 'downloading' && state.bytesDownloaded > 0- )- expect(- progressUpdates.length,- 'progress remains responsive during a slow download'- ).toBeGreaterThan(5)- })-- test('pausing keeps the staging file; cancellation removes it', async ({ plexo, dirs }) => {- const source = await sourceFile(dirs.userData, 2)- const id = await plexo.startSimulated(- {- sourceFilePath: source.path,- networks: [{ ...network('one'), speedBytesPerSec: 200_000 }]- },- source.sha- )- await plexo.waitUntil((state) => state.bytesDownloaded > 0)- const staging = join(dirs.dest, 'source-2.bin.plexo')- await plexo.api.pauseDownload(id)- expect((await plexo.current())?.status).toBe('paused')- expect(existsSync(staging)).toBe(true)- await plexo.api.cancelDownload(id)- expect(existsSync(staging)).toBe(false)- })-})--test.describe('a slow simulated network', () => {- test.use({ appEnv: { PLEXO_E2E_HEDGE_MS: '300' } })-- test('does not hold the download back: the fast one takes over its blocks', async ({- plexo,- dirs- }) => {- // The slow network needs 6.4 s for each 64 KB block it is given, and gets two of them.- const source = await sourceFile(dirs.userData, 4)- const started = Date.now()- await plexo.startSimulated(- {- sourceFilePath: source.path,- networks: [- { kind: 'usb', label: 'slow', speedBytesPerSec: 10_000, faultRatePercent: 0 },- network('fast')- ]- },- source.sha- )- await plexo.waitForStatus('completed', 15_000)- expect(Date.now() - started).toBeLessThan(5000)- })-})diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.tsindex f92ef96..9a6c85b 100644--- a/src/main/download/downloadManager.ts+++ b/src/main/download/downloadManager.ts@@ -10,8 +10,7 @@ import type {DownloadState,DownloadStatus,NetworkInterfaceInfo,- StartDownloadRequest,- StartSimulatedDownloadRequest+ StartDownloadRequest} from '../../shared/types'import { testKnobs, testStreamsPerNetwork } from '../testKnobs'import { advanceBlock, retractBlock } from './blockProgress'@@ -29,12 +28,6 @@ import {StreamConnection,targetHost} from '../network/routes'-import {- createSimSession,- downloadChunkSimulated,- isSimulatedUrl,- unregisterSimSession-} from './simDownload'/** Why an attempt was called off by the manager rather than by a pause or a failure. */type AbortReason = 'refresh' | 'lost'@@ -530,47 +523,6 @@ export class DownloadManager {return this.startWithInterfaces(requestPayload, interfaces)}- /**- * Dev-tool entry point: "downloads" a file that's already on disk through the exact same- * pipeline a real download uses — chunking, the block grid, pause/resume and retries — so- * every feature can be exercised on demand instead of needing- * a real multi-network setup and a slow, flaky remote server to provoke retries and errors.- * Only `chunkDownloader`'s HTTP transfer is swapped out (see simDownload.ts); everything else- * in DownloadManager is unaware this isn't a real network transfer.- */- async startSimulated(payload: StartSimulatedDownloadRequest): Promise<string> {- await this.initialization- if (this.hasActiveDownload()) {- throw new Error('A download is already in progress — finish or remove it first.')- }- if (payload.networks.length === 0) {- throw new Error('Select at least one simulated network')- }-- const { url, interfaces, totalBytes } = await createSimSession(- payload.sourceFilePath,- payload.networks- )-- const requestPayload: StartDownloadRequest = {- url,- destinationDir: payload.destinationDir,- suggestedFileName: basename(payload.sourceFilePath),- totalBytes,- supportsRanges: true,- interfaceIds: interfaces.map((iface) => iface.id),- etag: null,- lastModified: null- }-- try {- return await this.startWithInterfaces(requestPayload, interfaces)- } catch (error) {- unregisterSimSession(url)- throw error- }- }-private async startWithInterfaces(requestPayload: StartDownloadRequest,interfaces: NetworkInterfaceInfo[]@@ -722,35 +674,27 @@ export class DownloadManager {const { url } = runtime.requestPayloadlet availableInterfaces: NetworkInterfaceInfo[]- if (isSimulatedUrl(url)) {- // Synthetic sim interfaces aren't real NICs the OS enumerates — they never "disconnect",- // so the ones already on the runtime are still exactly right.- availableInterfaces = runtime.activeInterfaces- } else {- try {- availableInterfaces = await this.refreshInterfaces()- } catch {- runtime.state.error = 'Could not refresh network interfaces. Try resuming again.'- this.pushUpdate(runtime)- return- }+ try {+ availableInterfaces = await this.refreshInterfaces()+ } catch {+ runtime.state.error = 'Could not refresh network interfaces. Try resuming again.'+ this.pushUpdate(runtime)+ return}if (runtime.state.status !== 'paused' && runtime.state.status !== 'error') returnconst selectedIds = new Set(runtime.requestPayload.interfaceIds)runtime.activeInterfaces = availableInterfaces.filter((iface) => selectedIds.has(iface.id))const selectedAvailable = runtime.activeInterfaces.length > 0- if (!isSimulatedUrl(url)) {- try {- runtime.activeInterfaces = compatibleInterfaces(- runtime.activeInterfaces,- await resolveTargetWithin(targetHost(new URL(url)), testKnobs.stallTimeoutMs)- )- } catch {- runtime.state.error = 'Could not resolve the download host. Try resuming again.'- this.pushUpdate(runtime)- return- }+ try {+ runtime.activeInterfaces = compatibleInterfaces(+ runtime.activeInterfaces,+ await resolveTargetWithin(targetHost(new URL(url)), testKnobs.stallTimeoutMs)+ )+ } catch {+ runtime.state.error = 'Could not resolve the download host. Try resuming again.'+ this.pushUpdate(runtime)+ return}if (runtime.activeInterfaces.length === 0) {runtime.state.error = selectedAvailable@@ -833,7 +777,6 @@ export class DownloadManager {this.pushUpdate(runtime, false)await runtime.runPromiseawait runtime.file.discard()- unregisterSimSession(runtime.requestPayload.url)await this.removePersistedDownload(runtime)}@@ -939,7 +882,6 @@ export class DownloadManager {if (runtime.state.status === 'error' || runtime.state.status === 'cancelled') {this.pushUpdate(runtime)await runtime.file.discard()- unregisterSimSession(runtime.requestPayload.url)}return}@@ -976,8 +918,6 @@ export class DownloadManager {runtime.publishing = falsethis.pushUpdate(runtime)- // Publication failures keep the complete partial file so Resume can try again.- if (runtime.state.status === 'completed') unregisterSimSession(runtime.requestPayload.url)}/**@@ -1194,10 +1134,7 @@ export class DownloadManager {}attempt.startedAt = Date.now()- const runDownload = isSimulatedUrl(runtime.requestPayload.url)- ? downloadChunkSimulated- : downloadChunk- await runDownload({+ await downloadChunk({url: runtime.requestPayload.url,rangeStart: block.rangeStart + attempt.startOffset,rangeEnd: block.rangeEnd,diff --git a/src/main/download/simDownload.ts b/src/main/download/simDownload.tsdeleted file mode 100644index 2dc7a3b..0000000--- a/src/main/download/simDownload.ts+++ /dev/null@@ -1,173 +0,0 @@-import { createReadStream } from 'node:fs'-import { stat } from 'node:fs/promises'-import { randomUUID } from 'node:crypto'-import type { NetworkInterfaceInfo, SimulatedNetworkConfig } from '../../shared/types'-import type { ChunkDownloadOptions } from './chunkDownloader'--/** Marks a download as sourced from a local file rather than the network — the rest of- * `DownloadManager` treats `requestPayload.url` as opaque, so this prefix is the only thing- * that has to recognize a simulated download and route it to `downloadChunkSimulated` instead- * of the real HTTP `downloadChunk`. */-const SIM_URL_PREFIX = 'plexo-sim://'--export function isSimulatedUrl(url: string): boolean {- return url.startsWith(SIM_URL_PREFIX)-}--interface SimSession {- sourcePath: string- /** Keyed by the synthetic NetworkInterfaceInfo.id assigned to each simulated network. */- networks: Map<string, SimulatedNetworkConfig>- /** When each network is next free to deliver, by the same id. A network's speed is shared by- * all of its streams, as a real link's is: a stream more doesn't make it any faster. */- busyUntil: Map<string, number>-}--const sessions = new Map<string, SimSession>()--/** Registers one dev-tool "virtual download" run and returns the `plexo-sim://<token>` url to- * use as its `StartDownloadRequest.url` — everything downstream (blocks, chunks, persistence,- * storage) is unaware this isn't a real network transfer. */-function registerSimSession(- sourcePath: string,- networks: Map<string, SimulatedNetworkConfig>-): string {- const token = randomUUID()- sessions.set(token, { sourcePath, networks, busyUntil: new Map() })- return token-}--export function unregisterSimSession(url: string): void {- if (!isSimulatedUrl(url)) return- sessions.delete(url.slice(SIM_URL_PREFIX.length))-}--/** Builds the synthetic interfaces + registers the sim session a `StartDownloadRequest` needs- * to drive a simulated download through the normal `DownloadManager.start()` path. */-export async function createSimSession(- sourceFilePath: string,- networkConfigs: SimulatedNetworkConfig[]-): Promise<{ url: string; interfaces: NetworkInterfaceInfo[]; totalBytes: number }> {- const fileStat = await stat(sourceFilePath)- const networks = new Map<string, SimulatedNetworkConfig>()- const interfaces: NetworkInterfaceInfo[] = networkConfigs.map((config, index) => {- const id = `sim-${index}-${randomUUID().slice(0, 8)}`- networks.set(id, config)- return {- id,- device: id,- displayName: config.label,- addresses: [],- kind: config.kind- }- })-- const token = registerSimSession(sourceFilePath, networks)- return { url: `${SIM_URL_PREFIX}${token}`, interfaces, totalBytes: fileStat.size }-}--const DEFAULT_SPEED_BYTES_PER_SEC = 3 * 1024 * 1024--/** Local-file stand-in for `downloadChunk()` — same contract (resolves only once the exact- * byte range is written to the supplied writer, honors `signal`, calls `onProgress` with- * cumulative bytes) so `DownloadManager` can swap one for the other without knowing which one- * it's running. Reads the requested range off disk instead of over HTTP, throttled to the- * simulated network's configured speed so the UI has something real to show — a chunk grid or- * speed readout that jumped from 0 to 100% instantly would defeat the point of simulating it. */-export function downloadChunkSimulated(options: ChunkDownloadOptions): Promise<void> {- const {- url,- rangeStart,- rangeEnd,- connection,- createDestination,- onNetworkProgress,- onProgress,- signal- } = options-- return new Promise((resolve, reject) => {- if (signal.aborted) {- reject(new DOMException('Aborted', 'AbortError'))- return- }-- const session = sessions.get(url.slice(SIM_URL_PREFIX.length))- if (!session) {- reject(new Error('Simulated download session no longer exists (was the dev tool closed?)'))- return- }-- const network = session.networks.get(connection.iface.id)- if (network && Math.random() * 100 < network.faultRatePercent) {- reject(new Error(`Simulated drop on ${network.label}`))- return- }- const speedBytesPerSec = network?.speedBytesPerSec ?? DEFAULT_SPEED_BYTES_PER_SEC-- const expectedBytes = rangeEnd === null ? null : rangeEnd - rangeStart + 1- const input = createReadStream(session.sourcePath, {- start: rangeStart,- end: rangeEnd ?? undefined- })- const output = createDestination()-- let bytesWritten = 0- let settled = false-- const settle = (fn: () => void): void => {- if (settled) return- settled = true- signal.removeEventListener('abort', onAbort)- fn()- }- const fail = (error: Error): void =>- settle(() => {- input.destroy()- output.destroy()- reject(error)- })- const onAbort = (): void => fail(new DOMException('Aborted', 'AbortError'))- signal.addEventListener('abort', onAbort)-- input.on('error', fail)- output.on('error', fail)-- input.on('data', (chunk: string | Buffer) => {- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)- // Pausing the source for a delay proportional to this chunk's size — rather than writing- // everything Node hands us as fast as disk I/O allows — is what makes the simulated speed- // real: a real download is limited by the network, so the block grid and speed readout- // should move at a rate this slow, not spike and then sit idle.- input.pause()- const now = Date.now()- const deliveredAt =- Math.max(now, session.busyUntil.get(connection.iface.id) ?? 0) +- (buffer.length / speedBytesPerSec) * 1000- session.busyUntil.set(connection.iface.id, deliveredAt)- const delayMs = Math.max(1, deliveredAt - now)- setTimeout(() => {- if (settled) return- bytesWritten += buffer.length- const progress = bytesWritten- onNetworkProgress(progress)- output.write(buffer, (error) => {- if (error) fail(error)- else if (!settled) {- onProgress(progress)- input.resume()- }- })- }, delayMs)- })-- input.on('end', () => output.end())- output.on('finish', () => {- if (expectedBytes !== null && bytesWritten !== expectedBytes) {- fail(new Error(`Simulated chunk wrote ${bytesWritten} bytes but expected ${expectedBytes}`))- return- }- settle(resolve)- })- })-}diff --git a/src/main/index.ts b/src/main/index.tsindex cf5847b..0d1fd8e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,11 +1,10 @@import { electronApp, is, optimizer } from '@electron-toolkit/utils'-import { app, BrowserWindow, Menu, nativeTheme, shell } from 'electron'+import { app, BrowserWindow, nativeTheme, shell } from 'electron'import { join } from 'path'import icon from '../../resources/icon-dark.png?asset'import { registerIpcHandlers } from './ipc/handlers'import { loadThemeSource, migrateLegacyNetworkPreferences } from './settings'import { testKnobs } from './testKnobs'-import { IpcChannels } from '../shared/ipc-channels'import type { DownloadManager } from './download/downloadManager'// In dev mode the app runs as the raw `electron` binary, which otherwise shows "Electron" in@@ -20,29 +19,6 @@ let mainWindow: BrowserWindow | null = nulllet downloadManager: DownloadManager | null = nulllet quitAfterSuspending = false-// Only wired in dev — mirrors the default Electron menu (app/edit/view/window) plus one item to-// toggle the renderer's floating simulate-download panel, which itself only renders in dev.-function installDevMenu(): void {- Menu.setApplicationMenu(- Menu.buildFromTemplate([- ...(process.platform === 'darwin' ? [{ role: 'appMenu' as const }] : []),- { role: 'editMenu' },- { role: 'viewMenu' },- { role: 'windowMenu' },- {- label: 'Developer',- submenu: [- {- label: 'Toggle Dev Tools Panel',- accelerator: 'CmdOrCtrl+Shift+D',- click: () => mainWindow?.webContents.send(IpcChannels.toggleDevToolsPanel)- }- ]- }- ])- )-}-function createWindow(): void {mainWindow = new BrowserWindow({width: 760,@@ -114,8 +90,6 @@ app.whenReady().then(async () => {mainWindow?.setBackgroundColor(nativeTheme.shouldUseDarkColors ? '#1c1c1e' : '#ffffff')})- if (is.dev) installDevMenu()-createWindow()if (testKnobs.hideWindow) app.dock?.hide()diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.tsindex 8f0b9df..4143c4b 100644--- a/src/main/ipc/handlers.ts+++ b/src/main/ipc/handlers.ts@@ -1,5 +1,4 @@import { stat } from 'node:fs/promises'-import { is } from '@electron-toolkit/utils'import {app,clipboard,@@ -113,7 +112,6 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Downevent.returnValue = {homeDir: getHomeDir(),downloadsDir: getDefaultDownloadsDir(),- isDev: is.dev,themeSource: currentThemeSource(),networkPreferences: settings.networkPreferences ?? {},destinationDir: destinationExists ? destinationDir : undefined@@ -124,7 +122,6 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Downevent.returnValue = {homeDir: '',downloadsDir: '',- isDev: is.dev,themeSource: currentThemeSource(),networkPreferences: {}} satisfies InitialState@@ -164,8 +161,6 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Downhandle('startDownload', async (_event, request) => manager.start(request))- handle('startSimulatedDownload', async (_event, request) => manager.startSimulated(request))-handle('getCurrentDownload', async () => manager.getCurrentDownload())handle('pauseDownload', async (_event, id) => {diff --git a/src/preload/index.ts b/src/preload/index.tsindex 1b95972..e17d440 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -30,8 +30,6 @@ const plexoApi = {revealInFolder: (filePath: string) => invoke('revealInFolder', filePath),startDownload: (request: IpcContract['startDownload']['args'][0]) =>invoke('startDownload', request),- startSimulatedDownload: (request: IpcContract['startSimulatedDownload']['args'][0]) =>- invoke('startSimulatedDownload', request),getCurrentDownload: () => invoke('getCurrentDownload'),pauseDownload: (downloadId: string) => invoke('pauseDownload', downloadId),resumeDownload: (downloadId: string) => invoke('resumeDownload', downloadId),@@ -43,12 +41,6 @@ const plexoApi = {const listener = (_event: IpcRendererEvent, state: DownloadState): void => callback(state)ipcRenderer.on(IpcChannels.downloadUpdated, listener)return () => ipcRenderer.removeListener(IpcChannels.downloadUpdated, listener)- },-- onToggleDevToolsPanel: (callback: () => void): (() => void) => {- const listener = (): void => callback()- ipcRenderer.on(IpcChannels.toggleDevToolsPanel, listener)- return () => ipcRenderer.removeListener(IpcChannels.toggleDevToolsPanel, listener)}}diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex b9098a4..97ff416 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -1,6 +1,5 @@import type { DownloadState } from '@shared/types'import { useEffect } from 'react'-import { DevToolsPanel } from './components/DevToolsPanel'import { TitleBar, type TitleBarStatus } from './components/TitleBar'import { NetworkBindingDialog } from './components/NetworkBindingDialog'import { UpdateDialog } from './components/UpdateDialog'@@ -112,7 +111,6 @@ function App(): React.JSX.Element {<div className="flex h-full flex-col"><TitleBar status={titleBarStatus} /><div className="min-h-0 flex-1">{screen}</div>- <DevToolsPanel /><UpdateDialog /><NetworkBindingDialog /></div>diff --git a/src/renderer/src/components/DevToolsPanel.tsx b/src/renderer/src/components/DevToolsPanel.tsxdeleted file mode 100644index 31a7802..0000000--- a/src/renderer/src/components/DevToolsPanel.tsx+++ /dev/null@@ -1,315 +0,0 @@-import type { NetworkInterfaceKind, SimulatedNetworkConfig } from '@shared/types'-import { useEffect, useState } from 'react'-import { useAppStore } from '../store/useAppStore'-import { describeError, toDisplayPath } from '../utils/format'-import { TruncatedText } from './TruncatedText'-import { Button } from './ui/button'-import { Dialog, DialogClose, DialogContent, DialogTitle } from './ui/dialog'-import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'--const KIND_OPTIONS: NetworkInterfaceKind[] = ['wifi', 'usb', 'ethernet', 'bridge', 'other']-const MAX_SIM_NETWORKS = 4-const MBPS_TO_BYTES_PER_SEC = (1024 * 1024) / 8--interface SimNetworkDraft {- key: number- kind: NetworkInterfaceKind- label: string- speedMbps: number- faultRatePercent: number-}--let nextKey = 0-function makeDraft(kind: NetworkInterfaceKind, label: string, speedMbps: number): SimNetworkDraft {- return { key: nextKey++, kind, label, speedMbps, faultRatePercent: 0 }-}--const DEFAULT_NETWORKS: SimNetworkDraft[] = [- makeDraft('wifi', 'Simulated Wi-Fi', 30),- makeDraft('usb', 'Simulated USB', 12)-]--const fieldLabelClass =- 'font-mono text-[9.5px] leading-none font-medium tracking-[0.12em] text-muted-foreground'--const rowInputClass =- 'rounded-[6px] border-[0.5px] border-[var(--border-strong)] bg-[var(--input-bg)] px-[7px] py-[5px] font-mono text-[12px] leading-[1.3] text-foreground'--const draftBoxClass =- 'flex flex-col gap-1.5 rounded-lg border-[0.5px] border-border bg-background p-2'--/**- * Dev-only panel that exercises the whole download pipeline against a file already on disk —- * chunking across fake networks, the block grid, retries/errors and pause/resume,- * completion — without needing a real multi-network setup or a slow, flaky server to provoke- * the states that are otherwise hard to reproduce on demand. Only rendered when- * `useAppStore.isDev` is true (see App.tsx), so it never reaches a packaged build's UI.- */-export function DevToolsPanel(): React.JSX.Element | null {- const isDev = useAppStore((store) => store.isDev)- const downloadsDir = useAppStore((store) => store.downloadsDir)- const homeDir = useAppStore((store) => store.homeDir)-- const [open, setOpen] = useState(false)- const [sourceFilePath, setSourceFilePath] = useState<string | null>(null)- const [destinationDir, setDestinationDir] = useState('')- const [networks, setNetworks] = useState<SimNetworkDraft[]>(DEFAULT_NETWORKS)- const [starting, setStarting] = useState(false)- const [error, setError] = useState<string | null>(null)-- // Menu item lives in the main process (see installDevMenu in src/main/index.ts) — it can't- // reach this component's state directly, so it round-trips through IPC instead.- useEffect(() => {- if (!isDev) return- return window.plexo.onToggleDevToolsPanel(() => setOpen((v) => !v))- }, [isDev])-- if (!isDev) return null-- const effectiveDestinationDir = destinationDir || downloadsDir-- const handleChooseFile = async (): Promise<void> => {- const chosen = await window.plexo.chooseSourceFile()- if (chosen) setSourceFilePath(chosen)- }-- const handleChooseDestination = async (): Promise<void> => {- const chosen = await window.plexo.chooseDestinationFolder(effectiveDestinationDir)- if (chosen) setDestinationDir(chosen)- }-- const updateNetwork = (key: number, patch: Partial<SimNetworkDraft>): void => {- setNetworks((prev) => prev.map((n) => (n.key === key ? { ...n, ...patch } : n)))- }-- const addNetwork = (): void => {- if (networks.length >= MAX_SIM_NETWORKS) return- setNetworks((prev) => [- ...prev,- makeDraft('ethernet', `Simulated Network ${prev.length + 1}`, 20)- ])- }-- const removeNetwork = (key: number): void => {- setNetworks((prev) => (prev.length > 1 ? prev.filter((n) => n.key !== key) : prev))- }-- const canStart = Boolean(sourceFilePath) && Boolean(effectiveDestinationDir) && !starting-- const handleStart = async (): Promise<void> => {- if (!sourceFilePath || !effectiveDestinationDir) return- setStarting(true)- setError(null)- try {- const simulatedNetworks: SimulatedNetworkConfig[] = networks.map((n) => ({- kind: n.kind,- label: n.label.trim() || 'Simulated Network',- speedBytesPerSec: Math.max(1, Math.round(n.speedMbps * MBPS_TO_BYTES_PER_SEC)),- faultRatePercent: Math.min(100, Math.max(0, n.faultRatePercent))- }))- await window.plexo.startSimulatedDownload({- sourceFilePath,- destinationDir: effectiveDestinationDir,- networks: simulatedNetworks- })- setOpen(false)- } catch (err) {- setError(describeError(err))- } finally {- setStarting(false)- }- }-- return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogContent- // showCloseButton={false}: this panel keeps its own close button inline in the header- // row below, not the default absolute-positioned one.- showCloseButton={false}- className="flex max-h-[calc(100%-4rem)] w-[380px] max-w-[380px] flex-col gap-3 overflow-y-auto rounded-[12px] border-[0.5px] border-[var(--border-strong)] bg-card p-4 [overscroll-behavior:contain] sm:max-w-[380px]"- >- <div className="flex items-center justify-between">- <DialogTitle className="font-sans text-[13px] leading-[1.2] font-bold text-foreground">- Simulate a download- </DialogTitle>- <DialogClose- render={- <Button- type="button"- variant="ghost"- size="icon-xs"- aria-label="Close"- className="font-sans text-sm leading-none font-semibold text-muted-foreground"- >- ×- </Button>- }- />- </div>- <div className="font-sans text-[11.5px] leading-[1.4] text-muted-foreground">- Pick a file already on disk to “download” it through the real pipeline — chunking, the- block grid, pause/resume and retries — against fake networks you control.- </div>-- <div className="flex flex-col gap-[5px]">- <div className={fieldLabelClass}>SOURCE FILE</div>- <div className="flex gap-1.5">- <div- className={`${rowInputClass} min-w-0 flex-1 ${- sourceFilePath ? 'text-foreground' : 'text-muted-foreground'- }`}- >- <TruncatedText- text={sourceFilePath ? toDisplayPath(sourceFilePath, homeDir) : 'No file chosen'}- tooltipText={sourceFilePath ?? 'No file chosen'}- />- </div>- <Button type="button" variant="secondary" onClick={handleChooseFile}>- Choose…- </Button>- </div>- </div>-- <div className="flex flex-col gap-[5px]">- <div className={fieldLabelClass}>DESTINATION</div>- <div className="flex gap-1.5">- <div className={`${rowInputClass} min-w-0 flex-1`}>- <TruncatedText- text={toDisplayPath(effectiveDestinationDir, homeDir)}- tooltipText={effectiveDestinationDir}- />- </div>- <Button type="button" variant="secondary" onClick={handleChooseDestination}>- Browse…- </Button>- </div>- </div>-- <div className="flex flex-col gap-[7px]">- <div className="flex items-center justify-between">- <div className={fieldLabelClass}>SIMULATED NETWORKS</div>- <Button- type="button"- variant="link"- size="xs"- onClick={addNetwork}- disabled={networks.length >= MAX_SIM_NETWORKS}- >- + Add network- </Button>- </div>-- {networks.map((network) => (- <div key={network.key} className={draftBoxClass}>- <div className="flex items-center gap-1.5">- <select- value={network.kind}- onChange={(event) =>- updateNetwork(network.key, {- kind: event.target.value as NetworkInterfaceKind- })- }- aria-label="Network kind"- className={`${rowInputClass} shrink-0`}- >- {KIND_OPTIONS.map((kind) => (- <option key={kind} value={kind}>- {kind}- </option>- ))}- </select>- <input- type="text"- value={network.label}- onChange={(event) => updateNetwork(network.key, { label: event.target.value })}- aria-label="Network name"- className={`${rowInputClass} min-w-0 flex-1`}- />- <Tooltip>- <TooltipTrigger- render={- <Button- type="button"- variant="ghost"- size="icon-xs"- onClick={() => removeNetwork(network.key)}- disabled={networks.length <= 1}- focusableWhenDisabled- aria-label="Remove network"- className="text-destructive hover:text-destructive"- >- ×- </Button>- }- />- <TooltipContent>Remove network</TooltipContent>- </Tooltip>- </div>- <div className="flex gap-2.5">- <label className="flex flex-1 items-center gap-[5px] font-mono text-[10.5px] leading-none text-muted-foreground">- Speed- <input- type="number"- min={1}- max={1000}- value={network.speedMbps}- onChange={(event) =>- updateNetwork(network.key, {- speedMbps: Number(event.target.value) || 1- })- }- className={`${rowInputClass} w-14`}- />- Mbps- </label>- <Tooltip>- <TooltipTrigger- render={- <label className="flex flex-1 items-center gap-[5px] font-mono text-[10.5px] leading-none text-muted-foreground">- Faults- <input- type="number"- min={0}- max={100}- value={network.faultRatePercent}- onChange={(event) =>- updateNetwork(network.key, {- faultRatePercent: Number(event.target.value) || 0- })- }- className={`${rowInputClass} w-12`}- />- %- </label>- }- />- <TooltipContent>- Chance a chunk attempt on this network fails outright, to exercise retry/error- handling- </TooltipContent>- </Tooltip>- </div>- </div>- ))}- </div>-- {error && (- <div className="font-sans text-[11.5px] leading-[1.4] text-destructive">⚠ {error}</div>- )}-- <div className="flex justify-end gap-2">- <DialogClose- render={- <Button type="button" variant="destructive">- Cancel- </Button>- }- />- <Button type="button" onClick={handleStart} disabled={!canStart}>- {starting ? 'Starting…' : 'Start simulated download'}- </Button>- </div>- </DialogContent>- </Dialog>- )-}diff --git a/src/renderer/src/store/useAppStore.ts b/src/renderer/src/store/useAppStore.tsindex 5abc928..d501c55 100644--- a/src/renderer/src/store/useAppStore.ts+++ b/src/renderer/src/store/useAppStore.ts@@ -36,8 +36,6 @@ interface AppStore {homeDir: stringdownloadsDir: string- /** True in electron-vite's dev server, false in a packaged build — gates the dev tools panel. */- isDev: boolean/** Plexo focuses on one download at a time — this is it. */currentDownload: DownloadState | null@@ -87,7 +85,6 @@ export const useAppStore = create<AppStore>((set, get) => ({homeDir: initial.homeDir,downloadsDir: initial.downloadsDir,- isDev: initial.isDev,currentDownload: null,speedHistory: [],diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.tsindex 94ec2db..1390ad9 100644--- a/src/shared/ipc-channels.ts+++ b/src/shared/ipc-channels.ts@@ -11,13 +11,11 @@ export const IpcChannels = {readClipboardText: 'clipboard:read-text',revealInFolder: 'shell:reveal-in-folder',startDownload: 'download:start',- startSimulatedDownload: 'download:start-simulated',getCurrentDownload: 'download:get-current',pauseDownload: 'download:pause',resumeDownload: 'download:resume',cancelDownload: 'download:cancel',removeDownload: 'download:remove',downloadUpdated: 'download:updated',- toggleDevToolsPanel: 'dev:toggle-panel',checkForUpdate: 'update:check'} as constdiff --git a/src/shared/ipc-contract.ts b/src/shared/ipc-contract.tsindex 2041e51..dc2fc4e 100644--- a/src/shared/ipc-contract.ts+++ b/src/shared/ipc-contract.ts@@ -4,12 +4,11 @@ import type {NetworkInterfaceInfo,ProbeResult,StartDownloadRequest,- StartSimulatedDownloadRequest,UpdateInfo} from './types'-/** The request/response half of the IPC surface (every IpcChannels entry except the two- * main->renderer push events, downloadUpdated and toggleDevToolsPanel) — one source of truth for+/** The request/response half of the IPC surface (every IpcChannels entry except the+ * main->renderer push event, downloadUpdated) — one source of truth for* both plexoApi (preload) and registerIpcHandlers (main), so a signature drift between the two* is a compile error instead of a runtime one. */export interface IpcContract {@@ -24,7 +23,6 @@ export interface IpcContract {readClipboardText: { args: []; result: string }revealInFolder: { args: [filePath: string]; result: void }startDownload: { args: [request: StartDownloadRequest]; result: string }- startSimulatedDownload: { args: [request: StartSimulatedDownloadRequest]; result: string }getCurrentDownload: { args: []; result: DownloadState | null }pauseDownload: { args: [id: string]; result: void }resumeDownload: { args: [id: string]; result: void }diff --git a/src/shared/types.ts b/src/shared/types.tsindex b60dbf5..f3853c5 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -116,27 +116,6 @@ export interface NetworkPreference {export type NetworkPreferences = Record<string, NetworkPreference>-/** One fake network in a dev-tool "virtual download" — see SimulatedNetworkConfig callers in- * main/download/simDownload.ts. Lets a developer exercise the multi-network UI (the block grid,- * per-network speed/throughput, retries and errors) against a file already on disk,- * without needing a real flaky connection or a slow remote server to test against. */-export interface SimulatedNetworkConfig {- kind: NetworkInterfaceKind- label: string- /** Target sustained throughput for this simulated network, in bytes/sec. */- speedBytesPerSec: number- /** 0-100 chance a chunk attempt on this network fails outright, simulating a dropped- * connection — set above 0 to exercise the retry/error UI on demand. */- faultRatePercent: number-}--export interface StartSimulatedDownloadRequest {- /** Absolute path to a file already on disk — this is what gets "downloaded". */- sourceFilePath: string- destinationDir: string- networks: SimulatedNetworkConfig[]-}-export interface UpdateInfo {version: string/** Where clicking the notification should take the user — the landing page's downloads. */@@ -162,8 +141,6 @@ export interface AppSettings {export interface InitialState {homeDir: stringdownloadsDir: string- /** True in electron-vite's dev server, false in a packaged build — gates the dev tools panel. */- isDev: booleanthemeSource: ThemeSourcenetworkPreferences: NetworkPreferences/** The last folder picked, if it still exists — otherwise the renderer uses downloadsDir. */