Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

Add a visible merging phase and a dev tool to simulate downloads

prashantgeek669d7805d3ce
diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.ts
index 597c0a4..401b9d1 100644
--- a/src/main/download/downloadManager.ts
+++ b/src/main/download/downloadManager.ts
@@ -22,11 +22,19 @@ import type {
DownloadState,
DownloadStatus,
NetworkInterfaceInfo,
- StartDownloadRequest
+ StartDownloadRequest,
+ StartSimulatedDownloadRequest
} from '../../shared/types'
import { downloadChunk } from './chunkDownloader'
import { reserveDestinationPath } from './paths'
import { isResourceUnchanged } from './probe'
+import {
+ createSimSession,
+ downloadChunkSimulated,
+ getSimMergeSpeed,
+ isSimulatedUrl,
+ unregisterSimSession
+} from './simDownload'
interface ChunkRuntime {
controller: AbortController
@@ -155,6 +163,12 @@ function delay(ms: number, signal: AbortSignal): Promise<void> {
})
}
+/** Plain, unabortable wait — used only to throttle a simulated download's merge step to a
+ * configured speed (see reassemble()). Merging isn't cancellable, so there's nothing to race. */
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
// A part file's on-disk size is the only thing we can actually trust across
// a retry or resume — appending opens the file with flag 'a', which always
// writes at the real end-of-file regardless of what byte count we think
@@ -257,9 +271,14 @@ export class DownloadManager {
const state = persisted.state
const blocks = state.blocks
if (!blocks) return
- if (state.status === 'downloading') {
+ // 'merging' means every block was already 'completed' and only the reassembly step
+ // was interrupted — resuming re-enters runChunksToCompletion with nothing left to
+ // download, so it goes straight back into reassemble() rather than needing its own
+ // restart path.
+ if (state.status === 'downloading' || state.status === 'merging') {
state.status = 'paused'
state.pausedAt = persisted.savedAt || Date.now()
+ state.mergedBytes = 0
}
state.speedBytesPerSec = 0
for (const chunk of state.chunks) {
@@ -316,6 +335,49 @@ export class DownloadManager {
throw new Error('Select at least one network interface')
}
+ 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, retries, the
+ * merging phase, reassembly — 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 (payload.networks.length === 0) {
+ throw new Error('Select at least one simulated network')
+ }
+
+ const { url, interfaces, totalBytes } = await createSimSession(
+ payload.sourceFilePath,
+ payload.networks,
+ payload.mergeSpeedBytesPerSec || null
+ )
+
+ const requestPayload: StartDownloadRequest = {
+ url,
+ destinationDir: payload.destinationDir,
+ suggestedFileName: basename(payload.sourceFilePath),
+ totalBytes,
+ supportsRanges: true,
+ interfaceIds: interfaces.map((iface) => iface.id),
+ chunkCount: payload.chunkCount,
+ connectionsPerNetwork: payload.connectionsPerNetwork,
+ etag: null,
+ lastModified: null
+ }
+
+ return this.startWithInterfaces(requestPayload, interfaces)
+ }
+
+ private async startWithInterfaces(
+ requestPayload: StartDownloadRequest,
+ interfaces: NetworkInterfaceInfo[]
+ ): Promise<string> {
await ensureDiskSpace(requestPayload.destinationDir, requestPayload.totalBytes)
const id = randomUUID()
@@ -499,7 +561,9 @@ export class DownloadManager {
// output (the user can always start the download over from scratch).
private async resumeAfterVerifying(runtime: DownloadRuntime): Promise<void> {
const { url, etag, lastModified } = runtime.requestPayload
- const unchanged = await isResourceUnchanged(url, etag, lastModified)
+ // A simulated download has no server to re-probe — the source file sitting on disk is
+ // exactly what it was when the sim session was created, so there's nothing to verify.
+ const unchanged = isSimulatedUrl(url) || (await isResourceUnchanged(url, etag, lastModified))
if (runtime.state.status !== 'paused') return // cancelled while we were checking
@@ -635,6 +699,11 @@ export class DownloadManager {
return
}
+ runtime.state.status = 'merging'
+ runtime.state.mergedBytes = 0
+ runtime.state.speedBytesPerSec = 0
+ this.pushUpdate(runtime)
+
try {
await this.reassemble(runtime)
runtime.state.status = 'completed'
@@ -715,7 +784,10 @@ export class DownloadManager {
let lastReportedThisRun = 0
try {
- await downloadChunk({
+ const runDownload = isSimulatedUrl(runtime.requestPayload.url)
+ ? downloadChunkSimulated
+ : downloadChunk
+ await runDownload({
url: runtime.requestPayload.url,
rangeStart: block.rangeStart + resumeOffset,
rangeEnd: block.rangeEnd,
@@ -875,6 +947,11 @@ export class DownloadManager {
const output = createWriteStream(runtime.state.destinationPath)
let bytesWritten = 0
+ // Set only for a dev-tool simulated download that asked for a slowed-down merge — real
+ // downloads always reassemble at full disk speed. Throttling here (rather than faking it in
+ // the renderer) exercises the exact same mergedBytes/IPC path a real merge uses.
+ const mergeSpeedBytesPerSec = getSimMergeSpeed(runtime.requestPayload.url)
+
// Attached before the first write, and kept for the stream's whole life:
// destroying the output after a failed check can surface an in-flight
// write as an 'error' event, and an unhandled 'error' on a stream takes
@@ -898,6 +975,15 @@ export class DownloadManager {
await appendFileToStream(partPath, output)
if (outputErrors.length > 0) throw outputErrors[0]
bytesWritten += actualBytes
+
+ if (mergeSpeedBytesPerSec) {
+ await sleep(Math.max(1, (actualBytes / mergeSpeedBytesPerSec) * 1000))
+ }
+
+ // Reported per part rather than per underlying write so the merge visualization advances
+ // in the same units the block grid already shows — one step per chunk, not a byte stream.
+ runtime.state.mergedBytes = bytesWritten
+ this.scheduleUpdate(runtime)
}
output.end()
@@ -935,6 +1021,7 @@ export class DownloadManager {
}
private async cleanupTempDir(runtime: DownloadRuntime): Promise<void> {
+ unregisterSimSession(runtime.requestPayload.url)
try {
await rm(runtime.tempDir, { recursive: true, force: true })
} catch {
diff --git a/src/main/download/simDownload.ts b/src/main/download/simDownload.ts
new file mode 100644
index 0000000..32630bd
--- /dev/null
+++ b/src/main/download/simDownload.ts
@@ -0,0 +1,163 @@
+import { createReadStream, createWriteStream } 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>
+ /** bytes/sec to throttle reassembly to, or null to merge at full disk speed. */
+ mergeSpeedBytesPerSec: number | null
+}
+
+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,
+ * the merging phase) is unaware this isn't a real network transfer. */
+function registerSimSession(
+ sourcePath: string,
+ networks: Map<string, SimulatedNetworkConfig>,
+ mergeSpeedBytesPerSec: number | null
+): string {
+ const token = randomUUID()
+ sessions.set(token, { sourcePath, networks, mergeSpeedBytesPerSec })
+ return token
+}
+
+export function unregisterSimSession(url: string): void {
+ if (!isSimulatedUrl(url)) return
+ sessions.delete(url.slice(SIM_URL_PREFIX.length))
+}
+
+/** How slowly `DownloadManager.reassemble()` should stitch this simulated download's part
+ * files together, or null when it isn't simulated (or wasn't given a merge speed) and should
+ * run at full disk speed as usual. */
+export function getSimMergeSpeed(url: string): number | null {
+ if (!isSimulatedUrl(url)) return null
+ return sessions.get(url.slice(SIM_URL_PREFIX.length))?.mergeSpeedBytesPerSec ?? null
+}
+
+/** 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[],
+ mergeSpeedBytesPerSec: number | null
+): 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,
+ address: id,
+ kind: config.kind
+ }
+ })
+
+ const token = registerSimSession(sourceFilePath, networks, mergeSpeedBytesPerSec)
+ 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 `destinationPath`, 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, localAddress, destinationPath, append, 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(localAddress)
+ 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 = createWriteStream(destinationPath, { flags: append ? 'a' : 'w' })
+
+ 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 delayMs = Math.max(1, (buffer.length / speedBytesPerSec) * 1000)
+ setTimeout(() => {
+ if (settled) return
+ output.write(buffer)
+ bytesWritten += buffer.length
+ onProgress(bytesWritten)
+ 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/ipc/handlers.ts b/src/main/ipc/handlers.ts
index 060d4e0..44f3256 100644
--- a/src/main/ipc/handlers.ts
+++ b/src/main/ipc/handlers.ts
@@ -1,9 +1,11 @@
+import { is } from '@electron-toolkit/utils'
import { clipboard, dialog, ipcMain, nativeTheme, shell, type BrowserWindow } from 'electron'
import { IpcChannels } from '../../shared/ipc-channels'
import type {
NetworkInterfaceInfo,
NetworkPreference,
StartDownloadRequest,
+ StartSimulatedDownloadRequest,
ThemeSource
} from '../../shared/types'
import { DownloadManager } from '../download/downloadManager'
@@ -60,7 +62,8 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
ipcMain.handle(IpcChannels.getInitialPaths, async () => ({
homeDir: getHomeDir(),
- downloadsDir: getDefaultDownloadsDir()
+ downloadsDir: getDefaultDownloadsDir(),
+ isDev: is.dev
}))
ipcMain.handle(IpcChannels.chooseDestinationFolder, async (_event, defaultPath: string) => {
@@ -74,6 +77,14 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
return result.filePaths[0]
})
+ ipcMain.handle(IpcChannels.chooseSourceFile, async () => {
+ const window = getWindow()
+ if (!window) return null
+ const result = await dialog.showOpenDialog(window, { properties: ['openFile'] })
+ if (result.canceled || result.filePaths.length === 0) return null
+ return result.filePaths[0]
+ })
+
ipcMain.handle(IpcChannels.readClipboardText, async () => clipboard.readText())
ipcMain.handle(IpcChannels.revealInFolder, async (_event, filePath: string) => {
@@ -84,6 +95,11 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
manager.start(request)
)
+ ipcMain.handle(
+ IpcChannels.startSimulatedDownload,
+ async (_event, request: StartSimulatedDownloadRequest) => manager.startSimulated(request)
+ )
+
ipcMain.handle(IpcChannels.getCurrentDownload, async () => manager.getCurrentDownload())
ipcMain.handle(IpcChannels.pauseDownload, async (_event, id: string) => {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 4d1053a..8d5e72b 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -8,12 +8,15 @@ import type {
NetworkPreferences,
ProbeResult,
StartDownloadRequest,
+ StartSimulatedDownloadRequest,
ThemeSource
} from '../shared/types'
export interface InitialPaths {
homeDir: string
downloadsDir: string
+ /** True in electron-vite's dev server, false in a packaged build — gates the dev tools panel. */
+ isDev: boolean
}
const plexoApi = {
@@ -45,6 +48,8 @@ const plexoApi = {
chooseDestinationFolder: (defaultPath: string): Promise<string | null> =>
ipcRenderer.invoke(IpcChannels.chooseDestinationFolder, defaultPath),
+ chooseSourceFile: (): Promise<string | null> => ipcRenderer.invoke(IpcChannels.chooseSourceFile),
+
readClipboardText: (): Promise<string> => ipcRenderer.invoke(IpcChannels.readClipboardText),
revealInFolder: (filePath: string): Promise<void> =>
@@ -53,6 +58,9 @@ const plexoApi = {
startDownload: (request: StartDownloadRequest): Promise<string> =>
ipcRenderer.invoke(IpcChannels.startDownload, request),
+ startSimulatedDownload: (request: StartSimulatedDownloadRequest): Promise<string> =>
+ ipcRenderer.invoke(IpcChannels.startSimulatedDownload, request),
+
getCurrentDownload: (): Promise<DownloadState | null> =>
ipcRenderer.invoke(IpcChannels.getCurrentDownload),
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index b94651a..58d685b 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -1,4 +1,5 @@
import { useEffect } from 'react'
+import { DevToolsPanel } from './components/DevToolsPanel'
import { TitleBar, type TitleBarStatus } from './components/TitleBar'
import { useDownloadEvents } from './hooks/useDownloadEvents'
import { CompleteScreen } from './screens/CompleteScreen'
@@ -18,11 +19,13 @@ function App(): React.JSX.Element {
const clearCurrentDownload = useAppStore((store) => store.clearCurrentDownload)
const loadNetworkPreferences = useAppStore((store) => store.loadNetworkPreferences)
const loadThemeSource = useAppStore((store) => store.loadThemeSource)
+ const loadInitialPaths = useAppStore((store) => store.loadInitialPaths)
useEffect(() => {
loadNetworkPreferences()
loadThemeSource()
- }, [loadNetworkPreferences, loadThemeSource])
+ loadInitialPaths()
+ }, [loadNetworkPreferences, loadThemeSource, loadInitialPaths])
const handleNewDownload = (): void => {
if (currentDownload) void window.plexo.removeDownload(currentDownload.id)
@@ -56,6 +59,9 @@ function App(): React.JSX.Element {
kind: 'paused',
networkCount: groupChunksByInterface(currentDownload.chunks).length
}
+ } else if (currentDownload.status === 'merging') {
+ screen = <DownloadingScreen download={currentDownload} />
+ titleBarStatus = { kind: 'merging' }
} else if (currentDownload.status === 'completed') {
screen = <CompleteScreen download={currentDownload} onNewDownload={handleNewDownload} />
} else {
@@ -78,6 +84,7 @@ function App(): React.JSX.Element {
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
<TitleBar status={titleBarStatus} />
<div style={{ flex: 1, minHeight: 0 }}>{screen}</div>
+ <DevToolsPanel />
</div>
)
}
diff --git a/src/renderer/src/components/BlockGrid.tsx b/src/renderer/src/components/BlockGrid.tsx
index 58c9226..e19e18e 100644
--- a/src/renderer/src/components/BlockGrid.tsx
+++ b/src/renderer/src/components/BlockGrid.tsx
@@ -35,6 +35,12 @@ const GRID_INSET_PX = 3
const UNATTRIBUTED_SOLID = 'var(--text-tertiary)'
const UNATTRIBUTED_BG = 'var(--track-bg)'
+// Merged bytes are deliberately not painted in any network's color: once a chunk is stitched
+// onto disk it isn't "that network's work" anymore so much as "already part of the file", and a
+// dedicated neutral tone is what makes the sweep across the grid read as progress rather than as
+// chunks quietly losing their color for no reason.
+const MERGED_SOLID = 'var(--text)'
+
/** One network's share of a cell's downloaded bytes. */
interface CellSegment {
interfaceId: string
@@ -144,6 +150,14 @@ interface BlockGridProps {
knownSize: boolean
remainingBytes: number
isPaused?: boolean
+ /** All blocks are 'completed' by the time this is true — the grid switches from showing which
+ * network fetched each chunk to showing reassembly progress instead: a wipe, in the same
+ * part-file order `reassemble()` actually writes in, that fades a square once its bytes are
+ * safely on disk and pulses whichever one is being appended right now. Without this the grid
+ * would freeze solid the moment the last byte downloads, and a merge on a large file can take
+ * long enough that a frozen grid reads as hung rather than finishing up. */
+ merging?: boolean
+ mergedBytes?: number
}
export function BlockGrid({
@@ -152,7 +166,9 @@ export function BlockGrid({
visuals,
knownSize,
remainingBytes,
- isPaused = false
+ isPaused = false,
+ merging = false,
+ mergedBytes = 0
}: BlockGridProps): React.JSX.Element {
const [gridWidth, setGridWidth] = useState(0)
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)
@@ -198,7 +214,10 @@ export function BlockGrid({
// appears on an active block — and a tooltip advertises nothing to hover in the first place.
const hoveredCell = hoveredIndex !== null ? cells[hoveredIndex] : undefined
let readout: string
- if (hoveredCell) {
+ if (merging) {
+ const totalBytes = cells.reduce((sum, cell) => sum + cell.totalBytes, 0)
+ readout = `Merging into file · ${formatBytes(mergedBytes)} / ${formatBytes(totalBytes)}`
+ } else if (hoveredCell) {
const where =
describeContributors(hoveredCell, visualByInterfaceId) ??
(hoveredCell.status === 'pending' ? 'queued' : '—')
@@ -208,6 +227,18 @@ export function BlockGrid({
readout = `${blocks.length} chunks · ${formatBytes(chunkBytes)} each${scrollHint}`
}
+ // Cumulative byte offset per cell, in the exact order reassemble() appends part files —
+ // computed once here rather than per-cell so each square's merge state is a simple
+ // range comparison against `mergedBytes` below.
+ const mergeOffsets = cells.reduce<{ offsets: number[]; total: number }>(
+ (acc, cell) => {
+ acc.offsets.push(acc.total)
+ acc.total += cell.totalBytes
+ return acc
+ },
+ { offsets: [], total: 0 }
+ ).offsets
+
return (
<div
style={{
@@ -254,6 +285,28 @@ export function BlockGrid({
</div>
)
})}
+ {merging && (
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 5.5,
+ font: `500 10.5px/1 ${FONT_MONO}`,
+ color: 'var(--text-secondary)'
+ }}
+ >
+ <span
+ style={{
+ width: 7,
+ height: 7,
+ borderRadius: '50%',
+ background: MERGED_SOLID,
+ flexShrink: 0
+ }}
+ />
+ <span style={{ color: 'var(--text)', fontWeight: 600 }}>Merged</span>
+ </div>
+ )}
{cells.length > 0 && chunkBytes > 0 && (
<div
style={{
@@ -321,12 +374,49 @@ export function BlockGrid({
opacity = 0.92
}
+ let animation: string | undefined
+ if (merging) {
+ const start = mergeOffsets[index]
+ const end = start + cell.totalBytes
+ if (end <= mergedBytes) {
+ // Already appended to the destination file — turns neutral rather than just
+ // fading, so "merged" is a distinct state you can read at a glance, not a
+ // guess at how dim is dim enough.
+ fillColor = MERGED_SOLID
+ border = 'none'
+ boxShadow = 'none'
+ opacity = 0.85
+ } else if (start < mergedBytes) {
+ // The one part file being streamed onto disk right now — turning neutral too,
+ // with a pulse so the "write head" position is obvious.
+ fillColor = MERGED_SOLID
+ border = `1px solid ${MERGED_SOLID}`
+ boxShadow = `0 0 7px ${MERGED_SOLID}`
+ opacity = 1
+ animation = 'plexo-glow 0.9s ease-in-out infinite'
+ } else {
+ // Completed but not yet its turn to be appended — stays in its network's color
+ // a little dimmed, to signal "waiting its turn" rather than "already merged".
+ border = 'none'
+ boxShadow = 'none'
+ opacity = 0.75
+ }
+ }
+
const networkName =
describeContributors(cell, visualByInterfaceId) ||
(cell.interfaceId ? 'Assigned' : 'Pending')
// Numbered to match the "Chunk #N" badges the streams table shows for each active
// connection, so a hovered square maps onto a specific stream's work.
- const title = `Chunk #${cell.chunkNumber} · ${formatBytes(cell.bytesDownloaded)} / ${formatBytes(cell.totalBytes)} · ${networkName} · ${cell.status}`
+ const title = merging
+ ? `Chunk #${cell.chunkNumber} · ${
+ mergeOffsets[index] + cell.totalBytes <= mergedBytes
+ ? 'written to file'
+ : mergeOffsets[index] < mergedBytes
+ ? 'writing to file…'
+ : 'queued to write'
+ }`
+ : `Chunk #${cell.chunkNumber} · ${formatBytes(cell.bytesDownloaded)} / ${formatBytes(cell.totalBytes)} · ${networkName} · ${cell.status}`
const rawFillPercent = Math.min(1, Math.max(0, cell.fillRatio)) * 100
// A square is only ~12px wide, so the first bytes of a chunk round to nothing —
// floor a started chunk to a visible sliver rather than 0 width.
@@ -345,10 +435,11 @@ export function BlockGrid({
border,
boxShadow,
opacity,
+ animation,
outline: hoveredIndex === index ? '1.5px solid var(--text-secondary)' : 'none',
outlineOffset: 1,
overflow: 'hidden',
- transition: 'opacity 0.15s, box-shadow 0.15s'
+ transition: 'opacity 0.3s, box-shadow 0.15s'
}}
>
{/* One square, one color: the network that actually delivered most of this
diff --git a/src/renderer/src/components/DevToolsPanel.tsx b/src/renderer/src/components/DevToolsPanel.tsx
new file mode 100644
index 0000000..50f3e32
--- /dev/null
+++ b/src/renderer/src/components/DevToolsPanel.tsx
@@ -0,0 +1,514 @@
+import type { NetworkInterfaceKind, SimulatedNetworkConfig } from '@shared/types'
+import { useState } from 'react'
+import { useAppStore } from '../store/useAppStore'
+import {
+ DANGER,
+ FONT_MONO,
+ FONT_UI,
+ dangerButtonStyle,
+ disabledPrimaryButtonStyle,
+ primaryButtonStyle,
+ secondaryButtonStyle
+} from '../theme'
+import { describeError, toDisplayPath } from '../utils/format'
+
+const KIND_OPTIONS: NetworkInterfaceKind[] = ['wifi', 'usb', 'ethernet', 'bridge', 'other']
+const PRESET_CONNECTIONS = [1, 2, 4, 8] as const
+const MAX_SIM_NETWORKS = 4
+const MBPS_TO_BYTES_PER_SEC = (1024 * 1024) / 8
+const MB_TO_BYTES_PER_SEC = 1024 * 1024
+const DEFAULT_MERGE_SPEED_MBPS = 6
+
+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 fieldLabelStyle: React.CSSProperties = {
+ font: `500 9.5px/1 ${FONT_MONO}`,
+ letterSpacing: '0.12em',
+ color: 'var(--text-tertiary)'
+}
+
+const rowInputStyle: React.CSSProperties = {
+ border: '0.5px solid var(--border-strong)',
+ borderRadius: 6,
+ background: 'var(--input-bg)',
+ color: 'var(--text)',
+ font: `12px/1.3 ${FONT_MONO}`,
+ padding: '5px 7px'
+}
+
+/**
+ * Dev-only panel that exercises the whole download pipeline against a file already on disk —
+ * chunking across fake networks, the block grid, retries/errors, pause/resume, merging,
+ * 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 [connectionsPerNetwork, setConnectionsPerNetwork] = useState(2)
+ const [slowMerge, setSlowMerge] = useState(true)
+ const [mergeSpeedMBps, setMergeSpeedMBps] = useState(DEFAULT_MERGE_SPEED_MBPS)
+ const [starting, setStarting] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+
+ 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,
+ chunkCount: networks.length * connectionsPerNetwork,
+ connectionsPerNetwork,
+ mergeSpeedBytesPerSec: slowMerge
+ ? Math.max(1, Math.round(mergeSpeedMBps * MB_TO_BYTES_PER_SEC))
+ : undefined
+ })
+ setOpen(false)
+ } catch (err) {
+ setError(describeError(err))
+ } finally {
+ setStarting(false)
+ }
+ }
+
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ title="Dev tools — simulate a download"
+ style={{
+ position: 'fixed',
+ bottom: 14,
+ left: 14,
+ zIndex: 1000,
+ border: '0.5px solid var(--color-ethernet-border)',
+ borderRadius: 999,
+ background: 'var(--color-ethernet-bg)',
+ color: 'var(--color-ethernet-text)',
+ font: `700 10px/1 ${FONT_MONO}`,
+ letterSpacing: '0.08em',
+ padding: '6px 11px',
+ cursor: 'pointer',
+ boxShadow: '0 2px 10px rgba(0,0,0,0.25)'
+ }}
+ >
+ DEV
+ </button>
+
+ {open && (
+ <div
+ style={{
+ position: 'fixed',
+ inset: 0,
+ zIndex: 999,
+ background: 'rgba(0,0,0,0.35)',
+ display: 'flex',
+ alignItems: 'flex-end',
+ justifyContent: 'flex-start',
+ padding: 14
+ }}
+ onClick={(event) => {
+ if (event.target === event.currentTarget) setOpen(false)
+ }}
+ >
+ <div
+ style={{
+ width: 380,
+ maxHeight: 'calc(100% - 60px)',
+ overflowY: 'auto',
+ background: 'var(--bg-secondary)',
+ border: '0.5px solid var(--border-strong)',
+ borderRadius: 12,
+ padding: 16,
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 12,
+ boxShadow: '0 8px 30px rgba(0,0,0,0.4)'
+ }}
+ >
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}
+ >
+ <div style={{ font: `700 13px/1.2 ${FONT_UI}`, color: 'var(--text)' }}>
+ Simulate a download
+ </div>
+ <button
+ type="button"
+ onClick={() => setOpen(false)}
+ style={{
+ border: 'none',
+ background: 'none',
+ color: 'var(--text-tertiary)',
+ cursor: 'pointer',
+ font: `600 14px/1 ${FONT_UI}`
+ }}
+ >
+ ×
+ </button>
+ </div>
+ <div style={{ font: `11.5px/1.4 ${FONT_UI}`, color: 'var(--text-tertiary)' }}>
+ Pick a file already on disk to &quot;download&quot; it through the real pipeline —
+ chunking, the block grid, pause/resume, retries, merging — against fake networks you
+ control.
+ </div>
+
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
+ <div style={fieldLabelStyle}>SOURCE FILE</div>
+ <div style={{ display: 'flex', gap: 6 }}>
+ <div
+ style={{
+ ...rowInputStyle,
+ flex: 1,
+ minWidth: 0,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ color: sourceFilePath ? 'var(--text)' : 'var(--text-tertiary)'
+ }}
+ title={sourceFilePath ?? undefined}
+ >
+ {sourceFilePath ? toDisplayPath(sourceFilePath, homeDir) : 'No file chosen'}
+ </div>
+ <button type="button" onClick={handleChooseFile} style={secondaryButtonStyle}>
+ Choose…
+ </button>
+ </div>
+ </div>
+
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
+ <div style={fieldLabelStyle}>DESTINATION</div>
+ <div style={{ display: 'flex', gap: 6 }}>
+ <div
+ style={{
+ ...rowInputStyle,
+ flex: 1,
+ minWidth: 0,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap'
+ }}
+ title={effectiveDestinationDir}
+ >
+ {toDisplayPath(effectiveDestinationDir, homeDir)}
+ </div>
+ <button
+ type="button"
+ onClick={handleChooseDestination}
+ style={secondaryButtonStyle}
+ >
+ Browse…
+ </button>
+ </div>
+ </div>
+
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
+ <div
+ style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
+ >
+ <div style={fieldLabelStyle}>SIMULATED NETWORKS</div>
+ <button
+ type="button"
+ onClick={addNetwork}
+ disabled={networks.length >= MAX_SIM_NETWORKS}
+ style={{
+ border: 'none',
+ background: 'none',
+ color:
+ networks.length >= MAX_SIM_NETWORKS
+ ? 'var(--text-tertiary)'
+ : 'var(--color-accent)',
+ font: `600 10.5px/1 ${FONT_MONO}`,
+ cursor: networks.length >= MAX_SIM_NETWORKS ? 'not-allowed' : 'pointer'
+ }}
+ >
+ + Add network
+ </button>
+ </div>
+
+ {networks.map((network) => (
+ <div
+ key={network.key}
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 6,
+ padding: 8,
+ borderRadius: 8,
+ border: '0.5px solid var(--border)',
+ background: 'var(--bg)'
+ }}
+ >
+ <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
+ <select
+ value={network.kind}
+ onChange={(event) =>
+ updateNetwork(network.key, {
+ kind: event.target.value as NetworkInterfaceKind
+ })
+ }
+ style={{ ...rowInputStyle, flexShrink: 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 })
+ }
+ style={{ ...rowInputStyle, flex: 1, minWidth: 0 }}
+ />
+ <button
+ type="button"
+ onClick={() => removeNetwork(network.key)}
+ disabled={networks.length <= 1}
+ title="Remove network"
+ style={{
+ border: 'none',
+ background: 'none',
+ color: networks.length <= 1 ? 'var(--text-tertiary)' : DANGER,
+ cursor: networks.length <= 1 ? 'not-allowed' : 'pointer',
+ font: `600 13px/1 ${FONT_UI}`,
+ flexShrink: 0
+ }}
+ >
+ ×
+ </button>
+ </div>
+ <div style={{ display: 'flex', gap: 10 }}>
+ <label
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 5,
+ flex: 1,
+ font: `10.5px/1 ${FONT_MONO}`,
+ color: 'var(--text-tertiary)'
+ }}
+ >
+ Speed
+ <input
+ type="number"
+ min={1}
+ max={1000}
+ value={network.speedMbps}
+ onChange={(event) =>
+ updateNetwork(network.key, {
+ speedMbps: Number(event.target.value) || 1
+ })
+ }
+ style={{ ...rowInputStyle, width: 56 }}
+ />
+ Mbps
+ </label>
+ <label
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 5,
+ flex: 1,
+ font: `10.5px/1 ${FONT_MONO}`,
+ color: 'var(--text-tertiary)'
+ }}
+ title="Chance a chunk attempt on this network fails outright, to exercise retry/error handling"
+ >
+ Faults
+ <input
+ type="number"
+ min={0}
+ max={100}
+ value={network.faultRatePercent}
+ onChange={(event) =>
+ updateNetwork(network.key, {
+ faultRatePercent: Number(event.target.value) || 0
+ })
+ }
+ style={{ ...rowInputStyle, width: 48 }}
+ />
+ %
+ </label>
+ </div>
+ </div>
+ ))}
+ </div>
+
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
+ <div style={fieldLabelStyle}>CONNECTIONS PER NETWORK</div>
+ <div style={{ display: 'flex', gap: 4 }}>
+ {PRESET_CONNECTIONS.map((preset) => {
+ const isSelected = connectionsPerNetwork === preset
+ return (
+ <button
+ key={preset}
+ type="button"
+ onClick={() => setConnectionsPerNetwork(preset)}
+ style={{
+ border: isSelected
+ ? '0.5px solid var(--color-accent)'
+ : '0.5px solid var(--border)',
+ borderRadius: 5,
+ background: isSelected ? 'var(--color-usb-bg)' : 'var(--track-bg)',
+ color: isSelected ? 'var(--color-usb-text)' : 'var(--text-secondary)',
+ font: `600 10.5px/1 ${FONT_MONO}`,
+ padding: '4px 8px',
+ cursor: 'pointer'
+ }}
+ >
+ {preset}×
+ </button>
+ )
+ })}
+ </div>
+ </div>
+
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 6,
+ padding: 8,
+ borderRadius: 8,
+ border: '0.5px solid var(--border)',
+ background: 'var(--bg)'
+ }}
+ >
+ <label
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 7,
+ font: `11px/1.3 ${FONT_UI}`,
+ color: 'var(--text)',
+ cursor: 'pointer'
+ }}
+ >
+ <input
+ type="checkbox"
+ checked={slowMerge}
+ onChange={(event) => setSlowMerge(event.target.checked)}
+ />
+ Simulate the merging step
+ </label>
+ <div style={{ font: `10.5px/1.4 ${FONT_UI}`, color: 'var(--text-tertiary)' }}>
+ Reassembly normally finishes in a blink — this throttles it so the
+ &quot;merging&quot; screen (the block grid sweep, the pulsing merge line) stays on
+ screen long enough to actually watch.
+ </div>
+ {slowMerge && (
+ <label
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 5,
+ font: `10.5px/1 ${FONT_MONO}`,
+ color: 'var(--text-tertiary)'
+ }}
+ >
+ Merge speed
+ <input
+ type="number"
+ min={1}
+ max={500}
+ value={mergeSpeedMBps}
+ onChange={(event) => setMergeSpeedMBps(Number(event.target.value) || 1)}
+ style={{ ...rowInputStyle, width: 56 }}
+ />
+ MB/s
+ </label>
+ )}
+ </div>
+
+ {error && <div style={{ font: `11.5px/1.4 ${FONT_UI}`, color: DANGER }}>⚠ {error}</div>}
+
+ <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
+ <button type="button" onClick={() => setOpen(false)} style={dangerButtonStyle}>
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={handleStart}
+ disabled={!canStart}
+ style={canStart ? primaryButtonStyle : disabledPrimaryButtonStyle}
+ >
+ {starting ? 'Starting…' : 'Start simulated download'}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </>
+ )
+}
diff --git a/src/renderer/src/components/MergeDiagram.tsx b/src/renderer/src/components/MergeDiagram.tsx
index f0358e0..9b3c0a5 100644
--- a/src/renderer/src/components/MergeDiagram.tsx
+++ b/src/renderer/src/components/MergeDiagram.tsx
@@ -21,11 +21,16 @@ export interface MergeDiagramNetwork {
export function MergeDiagram({
networks,
muted = false,
- paused = false
+ paused = false,
+ merging = false
}: {
networks: MergeDiagramNetwork[]
muted?: boolean
paused?: boolean
+ /** The part files are all complete and being stitched into the destination — the individual
+ * network feeds have nothing left to send, so their dashed lines stop while the merged stream
+ * pulses to show the reassembly step is still actively running rather than stalled. */
+ merging?: boolean
}): React.JSX.Element {
const height = Math.max(78, networks.length * ROW_HEIGHT + 10)
const midY = height / 2
@@ -45,9 +50,12 @@ export function MergeDiagram({
d={`M${CURVE_START_X},${y.toFixed(1)} C${CURVE_START_X + 36},${y.toFixed(1)} ${MERGE_X - 26},${midY.toFixed(1)} ${MERGE_X},${midY.toFixed(1)}`}
stroke={color}
strokeDasharray="6 8"
- opacity={paused ? 0.55 : 1}
+ // Merging means the network feeds themselves are done — nothing left in flight on
+ // these lines — so they go still like a paused download rather than pretending to
+ // still be streaming.
+ opacity={paused || merging ? 0.55 : 1}
style={
- muted || paused
+ muted || paused || merging
? undefined
: { animation: `plexo-dash ${1.1 + index * 0.2}s linear infinite` }
}
@@ -61,6 +69,7 @@ export function MergeDiagram({
}
strokeWidth={6.5}
opacity={paused ? 0.6 : 1}
+ style={merging ? { animation: 'plexo-glow 1s ease-in-out infinite' } : undefined}
/>
</g>
<polygon
@@ -132,13 +141,15 @@ export function MergeDiagram({
x={STREAM_END_X + 2}
y={midY - 11}
textAnchor="end"
- fill={paused ? 'var(--color-usb)' : 'var(--text-tertiary)'}
+ fill={
+ paused ? 'var(--color-usb)' : merging ? 'var(--color-ethernet)' : 'var(--text-tertiary)'
+ }
style={{
- font: `${paused ? '600' : '500'} 8.5px ${FONT_MONO}`,
+ font: `${paused || merging ? '600' : '500'} 8.5px ${FONT_MONO}`,
letterSpacing: '0.12em'
}}
>
- {paused ? 'PAUSED' : 'MERGED'}
+ {paused ? 'PAUSED' : merging ? 'WRITING…' : 'MERGED'}
</text>
)}
</svg>
diff --git a/src/renderer/src/components/TitleBar.tsx b/src/renderer/src/components/TitleBar.tsx
index cdd6672..cd7bf1b 100644
--- a/src/renderer/src/components/TitleBar.tsx
+++ b/src/renderer/src/components/TitleBar.tsx
@@ -4,6 +4,7 @@ import { ThemeToggle } from './ThemeToggle'
export type TitleBarStatus =
| { kind: 'none' }
| { kind: 'merged'; networkCount: number }
+ | { kind: 'merging' }
| { kind: 'paused'; networkCount: number }
| { kind: 'offline' }
@@ -53,6 +54,20 @@ export function TitleBar({ status }: { status: TitleBarStatus }): React.JSX.Elem
{status.networkCount} {status.networkCount === 1 ? 'network' : 'networks'} merged
</div>
)}
+ {status.kind === 'merging' && (
+ <div style={pillStyle('merging')}>
+ <div
+ style={{
+ width: 6,
+ height: 6,
+ borderRadius: '50%',
+ background: 'var(--color-ethernet)',
+ animation: 'plexo-glow 1s ease-in-out infinite'
+ }}
+ />
+ Merging chunks…
+ </div>
+ )}
{status.kind === 'paused' && (
<div style={pillStyle('paused')}>
<div
diff --git a/src/renderer/src/screens/DownloadingScreen.tsx b/src/renderer/src/screens/DownloadingScreen.tsx
index c919ebf..2ce6d84 100644
--- a/src/renderer/src/screens/DownloadingScreen.tsx
+++ b/src/renderer/src/screens/DownloadingScreen.tsx
@@ -52,7 +52,9 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
const peakSpeedBytesPerSec = useAppStore((store) => store.peakSpeedBytesPerSec)
const networkPreferences = useAppStore((store) => store.networkPreferences)
const isPaused = download.status === 'paused'
+ const isMerging = download.status === 'merging'
const percent = formatPercent(download.bytesDownloaded, download.totalBytes)
+ const mergePercent = formatPercent(download.mergedBytes ?? 0, download.totalBytes)
const knownSize = download.totalBytes > 0
const [now, setNow] = useState(() => Date.now())
@@ -63,7 +65,9 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
}, [isPaused])
useEffect(() => {
- if (isPaused) {
+ if (isMerging) {
+ document.title = `Plexo — Merging (${mergePercent}%)`
+ } else if (isPaused) {
document.title = knownSize ? `Plexo — Paused (${percent}%)` : 'Plexo — Paused'
} else {
document.title = knownSize ? `Plexo — ${percent}%` : 'Plexo — downloading'
@@ -71,7 +75,7 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
return () => {
document.title = 'Plexo'
}
- }, [percent, knownSize, isPaused])
+ }, [percent, mergePercent, knownSize, isPaused, isMerging])
const totalPausedMs =
(download.totalPausedMs || 0) +
@@ -174,9 +178,10 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
networks={groups.map((group, index) => ({
solid: visuals[index].solid,
label: visuals[index].name,
- speedBytesPerSec: isPaused ? 0 : group.speedBytesPerSec
+ speedBytesPerSec: isPaused || isMerging ? 0 : group.speedBytesPerSec
}))}
paused={isPaused}
+ merging={isMerging}
/>
<div
@@ -188,109 +193,149 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
flexShrink: 0
}}
>
- <div
- style={{
- font: `500 10px/1 ${FONT_MONO}`,
- letterSpacing: '0.2em',
- color: 'var(--text-tertiary)',
- display: 'flex',
- alignItems: 'center',
- gap: 6
- }}
- >
- <span>TOTAL SPEED</span>
- {isPaused && (
- <span
+ {isMerging ? (
+ <>
+ <div
style={{
- font: `600 9px/1 ${FONT_MONO}`,
- letterSpacing: '0.08em',
- color: 'var(--color-usb)',
- background: 'var(--color-usb-bg)',
- border: '0.5px solid var(--color-usb-border)',
- padding: '2px 5px',
- borderRadius: 3
+ font: `500 10px/1 ${FONT_MONO}`,
+ letterSpacing: '0.2em',
+ color: 'var(--text-tertiary)'
}}
>
- PAUSED
- </span>
- )}
- </div>
- <div style={{ display: 'flex', alignItems: 'baseline', gap: 7 }}>
- <div
- style={{
- font: `600 38px/0.88 ${FONT_MONO}`,
- letterSpacing: '-0.03em',
- color: isPaused ? 'var(--text-tertiary)' : 'var(--text)',
- fontVariantNumeric: 'tabular-nums'
- }}
- >
- {isPaused ? '—' : speed.value}
- </div>
- {!isPaused && (
- <div style={{ font: `500 12px/1 ${FONT_MONO}`, color: 'var(--text-tertiary)' }}>
- {speed.unit}/s
+ MERGING
</div>
- )}
- </div>
- <div
- style={{
- display: 'flex',
- alignItems: 'center',
- gap: 8,
- font: `500 10px/1 ${FONT_MONO}`,
- color: 'var(--text-tertiary)',
- fontVariantNumeric: 'tabular-nums'
- }}
- >
- <span>
- AVG{' '}
- <span style={{ color: 'var(--text)', fontWeight: 600 }}>
- {formatSpeed(avgSpeedBytesPerSec)}
- </span>
- </span>
- <span style={{ opacity: 0.35 }}>·</span>
- <span>
- PEAK{' '}
- <span style={{ color: 'var(--text)', fontWeight: 600 }}>
- {formatSpeed(peakSpeedBytesPerSec)}
- </span>
- </span>
- </div>
- {isPaused ? (
- <div
- style={{
- font: `500 11px/1.2 ${FONT_UI}`,
- color: 'var(--text-tertiary)',
- marginTop: 2
- }}
- >
- Download paused
- </div>
+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 7 }}>
+ <div
+ style={{
+ font: `600 38px/0.88 ${FONT_MONO}`,
+ letterSpacing: '-0.03em',
+ color: 'var(--color-ethernet)',
+ fontVariantNumeric: 'tabular-nums'
+ }}
+ >
+ {mergePercent}
+ </div>
+ <div style={{ font: `500 12px/1 ${FONT_MONO}`, color: 'var(--text-tertiary)' }}>
+ %
+ </div>
+ </div>
+ <div
+ style={{
+ font: `500 11px/1.2 ${FONT_UI}`,
+ color: 'var(--text-tertiary)',
+ marginTop: 2
+ }}
+ >
+ Writing chunks to disk — almost done
+ </div>
+ </>
) : (
- activeChipOption && (
- <button
- type="button"
- onClick={() => setChipModeIndex((i) => (i + 1) % chipOptions.length)}
- title={`${activeChipOption.tooltip}${chipOptions.length > 1 ? ' (click to toggle)' : ''}`}
+ <>
+ <div
style={{
- ...accentChipStyle,
- display: 'inline-flex',
+ font: `500 10px/1 ${FONT_MONO}`,
+ letterSpacing: '0.2em',
+ color: 'var(--text-tertiary)',
+ display: 'flex',
alignItems: 'center',
- gap: 5,
- cursor: chipOptions.length > 1 ? 'pointer' : 'default',
- userSelect: 'none',
- border: `0.5px solid ${activeChipOption.border}`,
- background: activeChipOption.bg,
- color: activeChipOption.color,
- width: 'fit-content'
+ gap: 6
}}
>
- <span>{activeChipOption.label}</span>
- {chipOptions.length > 1 && (
- <span style={{ opacity: 0.55, fontSize: 8.5 }}>⇄</span>
+ <span>TOTAL SPEED</span>
+ {isPaused && (
+ <span
+ style={{
+ font: `600 9px/1 ${FONT_MONO}`,
+ letterSpacing: '0.08em',
+ color: 'var(--color-usb)',
+ background: 'var(--color-usb-bg)',
+ border: '0.5px solid var(--color-usb-border)',
+ padding: '2px 5px',
+ borderRadius: 3
+ }}
+ >
+ PAUSED
+ </span>
)}
- </button>
- )
+ </div>
+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 7 }}>
+ <div
+ style={{
+ font: `600 38px/0.88 ${FONT_MONO}`,
+ letterSpacing: '-0.03em',
+ color: isPaused ? 'var(--text-tertiary)' : 'var(--text)',
+ fontVariantNumeric: 'tabular-nums'
+ }}
+ >
+ {isPaused ? '—' : speed.value}
+ </div>
+ {!isPaused && (
+ <div style={{ font: `500 12px/1 ${FONT_MONO}`, color: 'var(--text-tertiary)' }}>
+ {speed.unit}/s
+ </div>
+ )}
+ </div>
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 8,
+ font: `500 10px/1 ${FONT_MONO}`,
+ color: 'var(--text-tertiary)',
+ fontVariantNumeric: 'tabular-nums'
+ }}
+ >
+ <span>
+ AVG{' '}
+ <span style={{ color: 'var(--text)', fontWeight: 600 }}>
+ {formatSpeed(avgSpeedBytesPerSec)}
+ </span>
+ </span>
+ <span style={{ opacity: 0.35 }}>·</span>
+ <span>
+ PEAK{' '}
+ <span style={{ color: 'var(--text)', fontWeight: 600 }}>
+ {formatSpeed(peakSpeedBytesPerSec)}
+ </span>
+ </span>
+ </div>
+ {isPaused ? (
+ <div
+ style={{
+ font: `500 11px/1.2 ${FONT_UI}`,
+ color: 'var(--text-tertiary)',
+ marginTop: 2
+ }}
+ >
+ Download paused
+ </div>
+ ) : (
+ activeChipOption && (
+ <button
+ type="button"
+ onClick={() => setChipModeIndex((i) => (i + 1) % chipOptions.length)}
+ title={`${activeChipOption.tooltip}${chipOptions.length > 1 ? ' (click to toggle)' : ''}`}
+ style={{
+ ...accentChipStyle,
+ display: 'inline-flex',
+ alignItems: 'center',
+ gap: 5,
+ cursor: chipOptions.length > 1 ? 'pointer' : 'default',
+ userSelect: 'none',
+ border: `0.5px solid ${activeChipOption.border}`,
+ background: activeChipOption.bg,
+ color: activeChipOption.color,
+ width: 'fit-content'
+ }}
+ >
+ <span>{activeChipOption.label}</span>
+ {chipOptions.length > 1 && (
+ <span style={{ opacity: 0.55, fontSize: 8.5 }}>⇄</span>
+ )}
+ </button>
+ )
+ )}
+ </>
)}
</div>
@@ -298,7 +343,7 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
style={{
flex: 1,
minWidth: 0,
- opacity: isPaused ? 0.45 : 1,
+ opacity: isPaused || isMerging ? 0.45 : 1,
transition: 'opacity 0.2s'
}}
>
@@ -309,7 +354,8 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
color: 'var(--text-tertiary)'
}}
>
- THROUGHPUT · {isPaused ? 'PAUSED' : `LAST ${speedHistory.length}S`}
+ THROUGHPUT ·{' '}
+ {isMerging ? 'MERGING' : isPaused ? 'PAUSED' : `LAST ${speedHistory.length}S`}
</div>
<ThroughputChart
order={groups.map((g, i) => ({
@@ -384,7 +430,7 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
<span style={{ color: 'var(--text)', fontWeight: 600 }}>{percent}%</span>
</>
)}
- {!isPaused && knownSize && effectiveSpeed > 0 && (
+ {!isPaused && !isMerging && knownSize && effectiveSpeed > 0 && (
<>
<span style={{ opacity: 0.35 }}>·</span>
<span style={{ color: 'var(--text-secondary)' }}>
@@ -407,6 +453,21 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
PAUSED
</span>
)}
+ {isMerging && (
+ <span
+ style={{
+ font: `600 9.5px/1 ${FONT_MONO}`,
+ letterSpacing: '0.08em',
+ color: 'var(--color-ethernet-text)',
+ background: 'var(--color-ethernet-bg)',
+ border: '0.5px solid var(--color-ethernet-border)',
+ padding: '2px 7px',
+ borderRadius: 3.5
+ }}
+ >
+ MERGING
+ </span>
+ )}
</div>
</div>
</div>
@@ -418,6 +479,8 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
knownSize={knownSize}
remainingBytes={remainingBytes}
isPaused={isPaused}
+ merging={isMerging}
+ mergedBytes={download.mergedBytes ?? 0}
/>
</div>
@@ -433,7 +496,7 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
<div style={sectionHeaderLabelStyle}>Networks</div>
<div style={sectionHeaderMetaStyle}>
{groups.length} merged · {download.chunks.length} streams ·{' '}
- {isPaused ? 'paused' : `${activeGroups.length} active`}
+ {isMerging ? 'writing to disk' : isPaused ? 'paused' : `${activeGroups.length} active`}
</div>
</div>
<div style={networkTableHeaderStyle}>
@@ -494,11 +557,23 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
<button
type="button"
onClick={handlePauseResume}
- style={isPaused ? primaryButtonStyle : secondaryButtonStyle}
+ disabled={isMerging}
+ style={{
+ ...(isPaused ? primaryButtonStyle : secondaryButtonStyle),
+ ...(isMerging && { opacity: 0.5, cursor: 'not-allowed' })
+ }}
>
{isPaused ? 'Resume' : 'Pause'}
</button>
- <button type="button" onClick={handleCancel} style={dangerButtonStyle}>
+ <button
+ type="button"
+ onClick={handleCancel}
+ disabled={isMerging}
+ style={{
+ ...dangerButtonStyle,
+ ...(isMerging && { opacity: 0.5, cursor: 'not-allowed' })
+ }}
+ >
Cancel
</button>
</div>
diff --git a/src/renderer/src/screens/IdleScreen.tsx b/src/renderer/src/screens/IdleScreen.tsx
index c6768fc..01f3deb 100644
--- a/src/renderer/src/screens/IdleScreen.tsx
+++ b/src/renderer/src/screens/IdleScreen.tsx
@@ -37,7 +37,6 @@ export function IdleScreen(): React.JSX.Element {
const homeDir = useAppStore((store) => store.homeDir)
const downloadsDir = useAppStore((store) => store.downloadsDir)
const latencies = useAppStore((store) => store.latencies)
- const loadInitialPaths = useAppStore((store) => store.loadInitialPaths)
const url = useAppStore((store) => store.draftUrl)
const setUrl = useAppStore((store) => store.setDraftUrl)
const destinationDir = useAppStore((store) => store.draftDestinationDir)
@@ -52,10 +51,6 @@ export function IdleScreen(): React.JSX.Element {
const probeRequestId = useRef(0)
- useEffect(() => {
- loadInitialPaths()
- }, [loadInitialPaths])
-
useEffect(() => {
if (!destinationDir && downloadsDir) setDestinationDir(downloadsDir)
}, [destinationDir, downloadsDir, setDestinationDir])
diff --git a/src/renderer/src/store/useAppStore.ts b/src/renderer/src/store/useAppStore.ts
index cdcad28..c08713e 100644
--- a/src/renderer/src/store/useAppStore.ts
+++ b/src/renderer/src/store/useAppStore.ts
@@ -31,6 +31,8 @@ interface AppStore {
homeDir: string
downloadsDir: string
pathsStatus: LoadStatus
+ /** 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
@@ -70,6 +72,7 @@ export const useAppStore = create<AppStore>((set, get) => ({
homeDir: '',
downloadsDir: '',
pathsStatus: 'idle',
+ isDev: false,
currentDownload: null,
speedHistory: [],
@@ -104,8 +107,8 @@ export const useAppStore = create<AppStore>((set, get) => ({
loadInitialPaths: async () => {
set({ pathsStatus: 'loading' })
try {
- const { homeDir, downloadsDir } = await window.plexo.getInitialPaths()
- set({ homeDir, downloadsDir, pathsStatus: 'ready' })
+ const { homeDir, downloadsDir, isDev } = await window.plexo.getInitialPaths()
+ set({ homeDir, downloadsDir, isDev, pathsStatus: 'ready' })
} catch {
set({ pathsStatus: 'error' })
}
diff --git a/src/renderer/src/theme.ts b/src/renderer/src/theme.ts
index b213abf..f28ac7e 100644
--- a/src/renderer/src/theme.ts
+++ b/src/renderer/src/theme.ts
@@ -54,7 +54,7 @@ export const accentChipStyle: React.CSSProperties = {
}
const PILL_TOKENS: Record<
- 'positive' | 'negative' | 'paused',
+ 'positive' | 'negative' | 'paused' | 'merging',
{ bg: string; border: string; text: string }
> = {
positive: {
@@ -71,10 +71,17 @@ const PILL_TOKENS: Record<
bg: 'var(--color-usb-bg)',
border: 'var(--color-usb-border)',
text: 'var(--color-usb-text)'
+ },
+ merging: {
+ bg: 'var(--color-ethernet-bg)',
+ border: 'var(--color-ethernet-border)',
+ text: 'var(--color-ethernet-text)'
}
}
-export function pillStyle(kind: 'positive' | 'negative' | 'paused'): React.CSSProperties {
+export function pillStyle(
+ kind: 'positive' | 'negative' | 'paused' | 'merging'
+): React.CSSProperties {
const tokens = PILL_TOKENS[kind]
return {
display: 'flex',
diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.ts
index d9735ca..66f0ef2 100644
--- a/src/shared/ipc-channels.ts
+++ b/src/shared/ipc-channels.ts
@@ -9,9 +9,11 @@ export const IpcChannels = {
probeUrl: 'download:probe',
getInitialPaths: 'paths:get-initial',
chooseDestinationFolder: 'dialog:choose-destination-folder',
+ chooseSourceFile: 'dialog:choose-source-file',
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',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 445ad92..9cbdc43 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -27,7 +27,8 @@ export interface ProbeResult {
lastModified: string | null
}
-export type DownloadStatus = 'downloading' | 'paused' | 'completed' | 'error' | 'cancelled'
+export type DownloadStatus =
+ 'downloading' | 'merging' | 'paused' | 'completed' | 'error' | 'cancelled'
export type ChunkStatus =
'pending' | 'downloading' | 'retrying' | 'paused' | 'completed' | 'error' | 'cancelled'
@@ -88,6 +89,10 @@ export interface DownloadState {
pausedAt?: number
totalPausedMs?: number
completedAt?: number
+ /** Bytes written to the destination file so far while `status` is 'merging' — the part files
+ * are already all complete at that point, so this tracks the sequential reassembly step
+ * rather than the network transfer. */
+ mergedBytes?: number
}
/** User customization for one physical network, keyed by NetworkInterfaceInfo.id — lets a
@@ -102,6 +107,34 @@ 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, errors, merging) 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[]
+ chunkCount: number
+ connectionsPerNetwork?: number
+ /** Throttles the reassembly step to this many bytes/sec, so the 'merging' phase's UI (the
+ * block grid sweep, the merge diagram) stays visible long enough to watch even on a small
+ * file that would otherwise reassemble in a single tick. Omitted or 0 merges at full disk
+ * speed, same as a real download. */
+ mergeSpeedBytesPerSec?: number
+}
+
export interface StartDownloadRequest {
url: string
destinationDir: string