Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

Add block grid layout component

Anmol Kapilf882bb975c7a
diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.ts
index 00f2bca..4b7946b 100644
--- a/src/main/download/downloadManager.ts
+++ b/src/main/download/downloadManager.ts
@@ -6,8 +6,10 @@ import type { BrowserWindow } from 'electron'
import { app } from 'electron'
import { IpcChannels } from '../../shared/ipc-channels'
import type {
+ BlockState,
ChunkState,
DownloadState,
+ DownloadStatus,
NetworkInterfaceInfo,
StartDownloadRequest
} from '../../shared/types'
@@ -33,9 +35,8 @@ interface DownloadRuntime {
tempDir: string
speedSamplesByChunk: Map<number, SpeedSample[]>
pushScheduled: boolean
- /** Chunk ids whose in-flight request was just aborted by a range split, not a pause/cancel —
- * runChunk checks this to tell the two apart and restart instead of stopping. */
- resizingChunkIds: Set<number>
+ blocks: BlockState[]
+ totalBlocks: number
}
const PROGRESS_THROTTLE_MS = 200
@@ -67,13 +68,6 @@ const MAX_CHUNK_RETRIES = 5
const RETRY_BASE_DELAY_MS = 1000
const RETRY_MAX_DELAY_MS = 15_000
-// A connection that finishes its own range early shouldn't just sit idle
-// while a sibling connection is still crawling through a much bigger one —
-// steal half of whichever chunk has the most bytes left. Only worth it
-// above a minimum size, so a nearly-finished download doesn't spawn a
-// connection for the last few KB.
-const MIN_STEAL_BYTES = 1024 * 1024
-
function retryDelayMs(attempt: number): number {
return Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), RETRY_MAX_DELAY_MS)
}
@@ -189,43 +183,59 @@ export class DownloadManager {
Math.max(1, Math.round(requestPayload.chunkCount / interfaces.length))
)
)
- const canSplit =
- requestPayload.supportsRanges &&
- requestPayload.totalBytes > 0 &&
- (interfaces.length > 1 || connectionsPerNetwork > 1)
+ const canSplit = requestPayload.supportsRanges && requestPayload.totalBytes > 0
+
+ const TARGET_BLOCKS = 64
+ const MIN_BLOCK_BYTES = 4 * 1024 * 1024 // 4 MB minimum block size
+
+ let blockSizeBytes = 0
+ const blocks: BlockState[] = []
+
+ if (canSplit) {
+ blockSizeBytes = Math.max(
+ MIN_BLOCK_BYTES,
+ Math.ceil(requestPayload.totalBytes / TARGET_BLOCKS)
+ )
+ let offset = 0
+ let bIdx = 0
+ while (offset < requestPayload.totalBytes) {
+ const bEnd = Math.min(offset + blockSizeBytes - 1, requestPayload.totalBytes - 1)
+ blocks.push({
+ index: bIdx++,
+ rangeStart: offset,
+ rangeEnd: bEnd,
+ status: 'pending',
+ bytesDownloaded: 0
+ })
+ offset = bEnd + 1
+ }
+ } else {
+ blockSizeBytes = requestPayload.totalBytes > 0 ? requestPayload.totalBytes : 0
+ blocks.push({
+ index: 0,
+ rangeStart: 0,
+ rangeEnd: requestPayload.totalBytes > 0 ? requestPayload.totalBytes - 1 : null,
+ status: 'pending',
+ bytesDownloaded: 0
+ })
+ }
const chunks: ChunkState[] = []
const activeInterfaces: NetworkInterfaceInfo[] = []
+ let workerIdCounter = 0
if (canSplit) {
- const netCount = interfaces.length
- let chunkIdCounter = 0
-
- for (let netIdx = 0; netIdx < netCount; netIdx++) {
- const iface = interfaces[netIdx]
- const netStart = Math.floor((netIdx * requestPayload.totalBytes) / netCount)
- const netEnd =
- netIdx === netCount - 1
- ? requestPayload.totalBytes - 1
- : Math.floor(((netIdx + 1) * requestPayload.totalBytes) / netCount) - 1
- const netSize = netEnd - netStart + 1
-
+ for (const iface of interfaces) {
for (let connIdx = 0; connIdx < connectionsPerNetwork; connIdx++) {
if (chunks.length >= MAX_CHUNKS) break
- const chunkStart = netStart + Math.floor((connIdx * netSize) / connectionsPerNetwork)
- const chunkEnd =
- connIdx === connectionsPerNetwork - 1
- ? netEnd
- : netStart + Math.floor(((connIdx + 1) * netSize) / connectionsPerNetwork) - 1
-
activeInterfaces.push(iface)
chunks.push({
- id: chunkIdCounter++,
+ id: workerIdCounter++,
interfaceId: iface.id,
interfaceLabel: iface.displayName,
interfaceKind: iface.kind,
- rangeStart: chunkStart,
- rangeEnd: chunkEnd,
+ rangeStart: 0,
+ rangeEnd: null,
bytesDownloaded: 0,
speedBytesPerSec: 0,
status: 'pending',
@@ -259,6 +269,9 @@ export class DownloadManager {
speedBytesPerSec: 0,
status: 'downloading',
chunks,
+ blocks,
+ totalBlocks: blocks.length,
+ blockSizeBytes,
startedAt: Date.now()
}
@@ -270,7 +283,8 @@ export class DownloadManager {
tempDir,
speedSamplesByChunk: new Map(),
pushScheduled: false,
- resizingChunkIds: new Set()
+ blocks,
+ totalBlocks: blocks.length
}
this.runtimes.set(id, runtime)
this.pushUpdate(runtime)
@@ -293,6 +307,11 @@ export class DownloadManager {
}
chunk.speedBytesPerSec = 0
}
+ for (const block of runtime.blocks) {
+ if (block.status === 'downloading') {
+ block.status = 'pending'
+ }
+ }
for (const chunkRuntime of runtime.chunkRuntimes.values()) {
chunkRuntime.controller.abort()
}
@@ -331,14 +350,22 @@ export class DownloadManager {
(runtime.state.totalPausedMs || 0) + (Date.now() - runtime.state.pausedAt)
runtime.state.pausedAt = undefined
}
- const pending = runtime.state.chunks.filter((chunk) => chunk.status !== 'completed')
- for (const chunk of pending) {
+ for (const block of runtime.blocks) {
+ if (block.status !== 'completed') {
+ block.status = 'pending'
+ }
+ }
+ for (const chunk of runtime.state.chunks) {
+ if (chunk.status !== 'completed') {
+ chunk.status = 'pending'
+ }
runtime.speedSamplesByChunk.delete(chunk.id)
chunk.speedBytesPerSec = 0
}
this.pushUpdate(runtime)
- void this.runChunksToCompletion(runtime, pending)
+ const pending = runtime.state.chunks.filter((chunk) => chunk.status !== 'completed')
+ void this.runChunksToCompletion(runtime, pending.length > 0 ? pending : runtime.state.chunks)
}
cancel(id: string): void {
@@ -350,6 +377,7 @@ export class DownloadManager {
runtime.state.speedBytesPerSec = 0
for (const chunk of runtime.state.chunks) {
chunk.speedBytesPerSec = 0
+ chunk.status = 'cancelled'
}
for (const chunkRuntime of runtime.chunkRuntimes.values()) {
chunkRuntime.controller.abort()
@@ -372,41 +400,22 @@ export class DownloadManager {
}
}
- /** Runs (or resumes) a set of chunks in parallel, then reassembles once they're all done. */
+ /** Runs (or resumes) fixed worker streams in parallel, leasing blocks until all are completed. */
private async runChunksToCompletion(
runtime: DownloadRuntime,
chunks: ChunkState[]
): Promise<void> {
- // A plain Promise.all can't grow once started — but a chunk that finishes
- // early may hand off half of a slower sibling's remaining range to a
- // brand new chunk, so the wait set has to be able to pick up new tasks
- // as they're spawned. Track it as chunk id -> its run promise instead.
const active = new Map<number, Promise<number>>()
for (const chunk of chunks) {
active.set(
chunk.id,
- this.runChunk(runtime, chunk).then(() => chunk.id)
+ this.runWorker(runtime, chunk).then(() => chunk.id)
)
}
- // Each run promise catches its own errors below, so this never rejects.
while (active.size > 0) {
const finishedId = await Promise.race(active.values())
active.delete(finishedId)
-
- if (runtime.state.status === 'downloading') {
- const finishedChunk = runtime.state.chunks.find((entry) => entry.id === finishedId)
- const stolenChunk =
- finishedChunk?.status === 'completed'
- ? this.stealWorkForIdleConnection(runtime, finishedChunk)
- : null
- if (stolenChunk) {
- active.set(
- stolenChunk.id,
- this.runChunk(runtime, stolenChunk).then(() => stolenChunk.id)
- )
- }
- }
}
if (runtime.state.status !== 'downloading') {
@@ -432,119 +441,102 @@ export class DownloadManager {
await this.cleanupTempDir(runtime)
}
- /**
- * Called when `freedChunk` finishes while others are still running. Finds
- * whichever active chunk has the most bytes left, shrinks it in place, and
- * returns a new chunk covering the back half for the now-idle connection
- * to pick up — or null if nothing is worth splitting yet.
- */
- private stealWorkForIdleConnection(
- runtime: DownloadRuntime,
- freedChunk: ChunkState
- ): ChunkState | null {
- if (!runtime.requestPayload.supportsRanges) return null
-
- let victim: ChunkState | null = null
- let victimRemaining = 0
- for (const candidate of runtime.state.chunks) {
- if (candidate.status !== 'downloading' || candidate.rangeEnd === null) continue
- const remaining = candidate.rangeEnd - (candidate.rangeStart + candidate.bytesDownloaded) + 1
- if (remaining > victimRemaining) {
- victim = candidate
- victimRemaining = remaining
- }
- }
-
- // Only worth splitting if both halves clear the minimum — otherwise the
- // new connection would spend more time on setup than on actual transfer.
- if (!victim || victimRemaining < MIN_STEAL_BYTES * 2) return null
-
- const freedInterface = runtime.activeInterfaces[freedChunk.id]
- const victimRuntime = runtime.chunkRuntimes.get(victim.id)
- if (!freedInterface || !victimRuntime) return null
-
- const victimPosition = victim.rangeStart + victim.bytesDownloaded
- const splitPoint = victimPosition + Math.floor(victimRemaining / 2)
- const originalRangeEnd = victim.rangeEnd
-
- // Swap in a fresh controller before aborting the old one — runChunk reads
- // the controller fresh on every loop iteration, so once its in-flight
- // request rejects it picks the new one back up instead of stopping.
- runtime.resizingChunkIds.add(victim.id)
- runtime.chunkRuntimes.set(victim.id, {
- controller: new AbortController(),
- partPath: victimRuntime.partPath
- })
- victimRuntime.controller.abort()
- victim.rangeEnd = splitPoint - 1
-
- // Reuse the same activeInterfaces[chunk.id] lookup runChunk already does
- // for every other chunk, rather than introducing a second lookup path.
- runtime.activeInterfaces.push(freedInterface)
- const newChunk: ChunkState = {
- id: runtime.activeInterfaces.length - 1,
- interfaceId: freedInterface.id,
- interfaceLabel: freedInterface.displayName,
- interfaceKind: freedInterface.kind,
- rangeStart: splitPoint,
- rangeEnd: originalRangeEnd,
- bytesDownloaded: 0,
- speedBytesPerSec: 0,
- status: 'pending',
- retryCount: 0
- }
- runtime.state.chunks.push(newChunk)
- this.scheduleUpdate(runtime)
- return newChunk
- }
+ private async runWorker(runtime: DownloadRuntime, chunk: ChunkState): Promise<void> {
+ const iface =
+ runtime.activeInterfaces.find((i) => i.id === chunk.interfaceId) ??
+ runtime.activeInterfaces[chunk.id]
- private async runChunk(runtime: DownloadRuntime, chunk: ChunkState): Promise<void> {
- const iface = runtime.activeInterfaces[chunk.id]
const controller = new AbortController()
- const existing = runtime.chunkRuntimes.get(chunk.id)
- const partPath = existing?.partPath ?? join(runtime.tempDir, `part-${chunk.id}`)
- runtime.chunkRuntimes.set(chunk.id, { controller, partPath })
- chunk.status = 'downloading'
- this.scheduleUpdate(runtime)
+ runtime.chunkRuntimes.set(chunk.id, { controller, partPath: '' })
- // A dropped connection shouldn't fail the whole download outright — most
- // network blips are transient, so give the chunk a few tries with
- // backoff before giving up on it (and, by extension, the download).
let attempt = 0
- for (;;) {
- // Read fresh each pass — a sibling connection stealing half of this
- // chunk's range swaps in a new controller and a smaller rangeEnd.
- const activeController = runtime.chunkRuntimes.get(chunk.id)?.controller ?? controller
-
- const resumeOffset = await reconcilePartFileSize(partPath, chunk.bytesDownloaded)
- if (resumeOffset !== chunk.bytesDownloaded) {
- chunk.bytesDownloaded = resumeOffset
- runtime.speedSamplesByChunk.delete(chunk.id)
+
+ while (runtime.state.status === 'downloading') {
+ if (controller.signal.aborted) break
+
+ // Atomically lease the next pending block in this event tick
+ const block = runtime.blocks.find((b) => b.status === 'pending')
+ if (!block) {
+ // If other workers are still downloading, remain idle briefly in case a block fails and resets
+ const anyStillDownloading = runtime.blocks.some((b) => b.status === 'downloading')
+ if (anyStillDownloading) {
+ chunk.speedBytesPerSec = 0
+ this.scheduleUpdate(runtime)
+ await delay(250, controller.signal).catch(() => {})
+ continue
+ }
+ chunk.status = 'completed'
+ chunk.speedBytesPerSec = 0
+ this.scheduleUpdate(runtime)
+ break
+ }
+
+ block.status = 'downloading'
+ block.interfaceId = iface.id
+ chunk.status = 'downloading'
+ chunk.rangeStart = block.rangeStart
+ chunk.rangeEnd = block.rangeEnd
+ chunk.currentBlockIndex = block.index
+ this.scheduleUpdate(runtime)
+
+ const partPath = join(runtime.tempDir, `part-${block.index}`)
+ const chunkRuntime = runtime.chunkRuntimes.get(chunk.id)
+ if (chunkRuntime) {
+ chunkRuntime.partPath = partPath
+ }
+
+ const resumeOffset = await reconcilePartFileSize(partPath, block.bytesDownloaded)
+ if (resumeOffset !== block.bytesDownloaded) {
+ block.bytesDownloaded = resumeOffset
this.recomputeAggregates(runtime)
}
+ if (block.rangeEnd !== null && block.rangeStart + resumeOffset > block.rangeEnd) {
+ block.status = 'completed'
+ block.interfaceId = iface.id
+ this.recomputeAggregates(runtime)
+ this.scheduleUpdate(runtime)
+ continue
+ }
+
+ let lastReportedThisRun = 0
+
try {
await downloadChunk({
url: runtime.requestPayload.url,
- rangeStart: chunk.rangeStart + resumeOffset,
- rangeEnd: chunk.rangeEnd,
+ rangeStart: block.rangeStart + resumeOffset,
+ rangeEnd: block.rangeEnd,
localAddress: iface.address,
destinationPath: partPath,
append: resumeOffset > 0,
- signal: activeController.signal,
- onProgress: (bytesThisRun) =>
- this.onChunkProgress(runtime, chunk.id, resumeOffset + bytesThisRun)
+ signal: controller.signal,
+ onProgress: (bytesThisRun) => {
+ const delta = bytesThisRun - lastReportedThisRun
+ lastReportedThisRun = bytesThisRun
+ if (delta > 0) {
+ this.onWorkerProgress(runtime, chunk.id, block.index, delta)
+ }
+ }
})
- chunk.status = 'completed'
- break
+
+ // Block finished successfully
+ block.status = 'completed'
+ block.interfaceId = iface.id
+ if (block.rangeEnd !== null) {
+ block.bytesDownloaded = block.rangeEnd - block.rangeStart + 1
+ }
+ attempt = 0
+ this.recomputeAggregates(runtime)
+ this.scheduleUpdate(runtime)
} catch (error) {
- if (activeController.signal.aborted) {
- if (runtime.resizingChunkIds.delete(chunk.id)) {
- // Not a pause/cancel — a sibling just stole the back half of our
- // range. The fresh controller is already in place; keep going.
- continue
+ const currentStatus = runtime.state.status as DownloadStatus
+ if (controller.signal.aborted || currentStatus !== 'downloading') {
+ if (currentStatus === 'paused') {
+ block.status = 'pending'
+ chunk.status = 'paused'
+ } else {
+ chunk.status = 'cancelled'
}
- chunk.status = runtime.state.status === 'paused' ? 'paused' : 'cancelled'
chunk.speedBytesPerSec = 0
break
}
@@ -554,15 +546,18 @@ export class DownloadManager {
attempt += 1
chunk.retryCount += 1
+ // Return block back to queue so any available worker can pick it up
+ block.status = 'pending'
+
if (attempt > MAX_CHUNK_RETRIES) {
chunk.status = 'error'
- // Fail fast: one broken connection shouldn't leave the others
- // downloading a file we're about to discard anyway.
- if (runtime.state.status === 'downloading') {
+ chunk.speedBytesPerSec = 0
+ const allErrored = runtime.state.chunks.every((c) => c.status === 'error')
+ if (allErrored && (runtime.state.status as DownloadStatus) === 'downloading') {
runtime.state.status = 'error'
runtime.state.error = message
- for (const chunkRuntime of runtime.chunkRuntimes.values()) {
- chunkRuntime.controller.abort()
+ for (const cr of runtime.chunkRuntimes.values()) {
+ cr.controller.abort()
}
}
break
@@ -570,9 +565,10 @@ export class DownloadManager {
chunk.status = 'retrying'
this.scheduleUpdate(runtime)
- await delay(retryDelayMs(attempt), activeController.signal)
- if (activeController.signal.aborted) {
- chunk.status = runtime.state.status === 'paused' ? 'paused' : 'cancelled'
+ await delay(retryDelayMs(attempt), controller.signal).catch(() => {})
+ const statusAfterDelay = runtime.state.status as DownloadStatus
+ if (controller.signal.aborted || statusAfterDelay !== 'downloading') {
+ chunk.status = statusAfterDelay === 'paused' ? 'paused' : 'cancelled'
chunk.speedBytesPerSec = 0
break
}
@@ -583,13 +579,19 @@ export class DownloadManager {
this.scheduleUpdate(runtime)
}
- private onChunkProgress(
+ private onWorkerProgress(
runtime: DownloadRuntime,
chunkId: number,
- bytesDownloaded: number
+ blockIndex: number,
+ deltaBytes: number
): void {
const chunk = runtime.state.chunks.find((entry) => entry.id === chunkId)
- if (!chunk) return
+ const block = runtime.blocks[blockIndex]
+ if (!chunk || !block) return
+
+ chunk.bytesDownloaded += deltaBytes
+ block.bytesDownloaded += deltaBytes
+ chunk.currentBlockIndex = blockIndex
const now = Date.now()
let samples = runtime.speedSamplesByChunk.get(chunkId)
@@ -597,15 +599,14 @@ export class DownloadManager {
samples = []
runtime.speedSamplesByChunk.set(chunkId, samples)
}
- chunk.speedBytesPerSec = pushSpeedSample(samples, bytesDownloaded, now)
- chunk.bytesDownloaded = bytesDownloaded
+ chunk.speedBytesPerSec = pushSpeedSample(samples, chunk.bytesDownloaded, now)
this.recomputeAggregates(runtime)
this.scheduleUpdate(runtime)
}
private recomputeAggregates(runtime: DownloadRuntime): void {
- runtime.state.bytesDownloaded = runtime.state.chunks.reduce(
+ runtime.state.bytesDownloaded = runtime.blocks.reduce(
(sum, entry) => sum + entry.bytesDownloaded,
0
)
@@ -635,16 +636,11 @@ export class DownloadManager {
private async reassemble(runtime: DownloadRuntime): Promise<void> {
const output = createWriteStream(runtime.state.destinationPath)
- // Chunks created by splitting a sibling's range mid-download are appended to
- // the array, not inserted in byte order — sort by rangeStart or the file
- // comes out scrambled whenever a split happened anywhere but at the end.
- const orderedChunks = [...runtime.state.chunks].sort((a, b) => a.rangeStart - b.rangeStart)
try {
- for (const chunk of orderedChunks) {
- const chunkRuntime = runtime.chunkRuntimes.get(chunk.id)
- if (!chunkRuntime) throw new Error(`Missing part file for chunk ${chunk.id}`)
- await appendFileToStream(chunkRuntime.partPath, output)
+ for (let i = 0; i < runtime.totalBlocks; i++) {
+ const partPath = join(runtime.tempDir, `part-${i}`)
+ await appendFileToStream(partPath, output)
}
} catch (error) {
output.destroy()
diff --git a/src/renderer/src/components/BlockGrid.tsx b/src/renderer/src/components/BlockGrid.tsx
new file mode 100644
index 0000000..4ca5fa9
--- /dev/null
+++ b/src/renderer/src/components/BlockGrid.tsx
@@ -0,0 +1,177 @@
+import type { BlockState } from '@shared/types'
+import { FONT_MONO, type NetworkVisual } from '../theme'
+import { formatBytes, type NetworkGroup } from '../utils/format'
+
+interface BlockGridProps {
+ blocks?: BlockState[]
+ groups: NetworkGroup[]
+ visuals: NetworkVisual[]
+ knownSize: boolean
+ remainingBytes: number
+ isPaused?: boolean
+ blockSizeBytes?: number
+}
+
+export function BlockGrid({
+ blocks,
+ groups,
+ visuals,
+ knownSize,
+ remainingBytes,
+ isPaused = false,
+ blockSizeBytes
+}: BlockGridProps): React.JSX.Element {
+ // If we have 2D blocks from range splitting, render the rich 2D Block Matrix
+ if (blocks && blocks.length > 1) {
+ const visualByInterfaceId = new Map<string, NetworkVisual>()
+ groups.forEach((g, idx) => {
+ if (visuals[idx]) {
+ visualByInterfaceId.set(g.interfaceId, visuals[idx])
+ }
+ })
+
+ const effectiveBlockSize =
+ blockSizeBytes ||
+ (blocks[0]?.rangeEnd !== null ? blocks[0].rangeEnd - blocks[0].rangeStart + 1 : 0)
+
+ // 32 columns yields a clean 2-row grid for ~64 blocks
+ const cols = blocks.length <= 32 ? blocks.length : Math.ceil(blocks.length / 2)
+
+ return (
+ <div
+ style={{
+ background: 'var(--bg-secondary)',
+ border: '0.5px solid var(--border)',
+ borderRadius: 9,
+ padding: '10px 14px 11px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 9
+ }}
+ >
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 14,
+ flexWrap: 'wrap'
+ }}
+ >
+ {groups.map((group, idx) => {
+ const visual = visuals[idx]
+ return (
+ <div
+ key={group.interfaceId}
+ 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: visual.solid,
+ flexShrink: 0
+ }}
+ />
+ <span style={{ color: 'var(--text)', fontWeight: 600 }}>{visual.name}</span>
+ </div>
+ )
+ })}
+ </div>
+
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`,
+ gap: 3,
+ width: '100%'
+ }}
+ >
+ {blocks.map((block) => {
+ const visual = block.interfaceId
+ ? visualByInterfaceId.get(block.interfaceId)
+ : undefined
+ const blockSize =
+ block.rangeEnd !== null ? block.rangeEnd - block.rangeStart + 1 : effectiveBlockSize
+
+ let bg = 'rgba(255, 255, 255, 0.05)'
+ let border = '0.5px solid rgba(255, 255, 255, 0.08)'
+ let boxShadow = 'none'
+ let opacity = 1
+
+ if (block.status === 'completed') {
+ bg = visual?.solid || 'var(--color-wifi)'
+ border = 'none'
+ opacity = 0.92
+ } else if (block.status === 'downloading') {
+ bg = visual?.bg || 'var(--color-accent-bg)'
+ border = `1px solid ${visual?.solid || 'var(--color-accent)'}`
+ boxShadow = isPaused ? 'none' : `0 0 7px ${visual?.solid || 'var(--color-accent)'}`
+ opacity = isPaused ? 0.6 : 1
+ } else if (block.status === 'error') {
+ bg = 'var(--color-danger)'
+ border = 'none'
+ }
+
+ const networkName = visual?.name || (block.interfaceId ? 'Assigned' : 'Pending')
+ const title = `Block #${block.index + 1} (${formatBytes(blockSize)}) · ${networkName} · ${block.status}`
+
+ return (
+ <div
+ key={block.index}
+ title={title}
+ style={{
+ height: 13,
+ borderRadius: 2.5,
+ background: bg,
+ border,
+ boxShadow,
+ opacity,
+ transition: 'background 0.15s, opacity 0.15s, box-shadow 0.15s'
+ }}
+ />
+ )
+ })}
+ </div>
+ </div>
+ )
+ }
+
+ // Fallback for single stream / non-splittable download: clean horizontal bar
+ return (
+ <div
+ style={{
+ height: 10,
+ borderRadius: 5,
+ background: 'var(--track-bg)',
+ overflow: 'hidden',
+ display: 'flex',
+ gap: 2,
+ border: '0.5px solid var(--border-strong)'
+ }}
+ >
+ {knownSize ? (
+ <>
+ {groups.map((group, index) => (
+ <div
+ key={group.interfaceId}
+ style={{
+ flex: group.bytesDownloaded || 0.0001,
+ background: visuals[index].solid
+ }}
+ />
+ ))}
+ <div style={{ flex: remainingBytes || 0.0001 }} />
+ </>
+ ) : (
+ <div style={{ width: '100%', background: 'var(--color-accent)' }} />
+ )}
+ </div>
+ )
+}
diff --git a/src/renderer/src/components/NetworkRow.tsx b/src/renderer/src/components/NetworkRow.tsx
index 944d22b..ee97641 100644
--- a/src/renderer/src/components/NetworkRow.tsx
+++ b/src/renderer/src/components/NetworkRow.tsx
@@ -1,5 +1,6 @@
import { useRef, useState } from 'react'
import { useAppStore } from '../store/useAppStore'
+import type { BlockState } from '@shared/types'
import {
DANGER,
FONT_MONO,
@@ -12,15 +13,20 @@ import type { NetworkGroup } from '../utils/format'
import { formatBytes, formatSpeed } from '../utils/format'
import { NetworkEditorFields } from './NetworkEditorFields'
+interface NetworkRowProps {
+ group: NetworkGroup
+ sharePercent: number
+ totalBytes?: number | null
+ totalDownloaded?: number
+ blocks?: BlockState[]
+}
+
export function NetworkRow({
group,
+ sharePercent,
totalBytes,
- sharePercent
-}: {
- group: NetworkGroup
- totalBytes: number
- sharePercent: number
-}): React.JSX.Element {
+ blocks
+}: NetworkRowProps): React.JSX.Element {
const [editing, setEditing] = useState(false)
const [expanded, setExpanded] = useState(false)
const buttonRef = useRef<HTMLButtonElement>(null)
@@ -30,13 +36,20 @@ export function NetworkRow({
const hasError = group.chunks.some((chunk) => chunk.status === 'error')
const isActive = group.chunks.some((chunk) => chunk.status === 'downloading')
+ const groupShareDisplay =
+ group.bytesDownloaded === 0
+ ? '0%'
+ : Math.round(sharePercent) === 0 && sharePercent > 0
+ ? '<1%'
+ : `${Math.round(sharePercent)}%`
+
return (
<div>
<div
style={{
display: 'grid',
gridTemplateColumns: NETWORK_ROW_GRID_COLUMNS,
- gap: 14,
+ gap: 12,
alignItems: 'center',
padding: '11px 20px',
borderTop: '0.5px solid var(--border-subtle)'
@@ -106,57 +119,40 @@ export function NetworkRow({
⋯
</button>
</div>
- <div style={{ display: 'flex', gap: 4, height: 16 }}>
- {group.chunks.map((chunk, index) => {
- const chunkSize =
- chunk.rangeEnd !== null
- ? chunk.rangeEnd - chunk.rangeStart + 1
- : totalBytes - chunk.rangeStart
- const percent =
- chunkSize > 0 ? Math.min(100, (chunk.bytesDownloaded / chunkSize) * 100) : 0
- const isChunkDone = chunk.status === 'completed'
- const isChunkActive = chunk.status === 'downloading'
- const isChunkError = chunk.status === 'error'
- const title = `Stream #${index + 1}: ${Math.round(percent)}% · ${formatBytes(chunk.bytesDownloaded)} / ${formatBytes(chunkSize)}${chunk.speedBytesPerSec > 0 ? ` · ${formatSpeed(chunk.speedBytesPerSec)}` : chunk.status === 'paused' ? ' · Paused' : ''}`
-
- return (
- <div
- key={chunk.id}
- title={title}
- style={{
- flex: 1,
- borderRadius: 3,
- background: 'var(--track-bg)',
- border: '0.5px solid var(--border-strong)',
- overflow: 'hidden',
- position: 'relative',
- display: 'flex',
- alignItems: 'center'
- }}
- >
- <div
- style={{
- height: '100%',
- width: isChunkDone ? '100%' : `${percent}%`,
- background: isChunkError ? DANGER : visual.solid,
- opacity: isChunkDone ? 1 : isChunkActive ? 0.9 : 0.45,
- transition: 'width 0.2s ease-out',
- borderRadius: 2
- }}
- />
- </div>
- )
- })}
+ <div style={{ display: 'flex', alignItems: 'center', minWidth: 0 }}>
+ <div
+ style={{
+ flex: 1,
+ height: 6,
+ borderRadius: 999,
+ background: 'var(--track-bg)',
+ border: '0.5px solid var(--border-strong)',
+ overflow: 'hidden'
+ }}
+ >
+ <div
+ style={{
+ height: '100%',
+ width:
+ totalBytes && totalBytes > 0
+ ? `${Math.min(100, Math.max(0, (group.bytesDownloaded / totalBytes) * 100))}%`
+ : '0%',
+ background: visual.solid,
+ borderRadius: 999,
+ transition: 'width 0.25s ease-out'
+ }}
+ />
+ </div>
</div>
<div
style={{
textAlign: 'right',
- font: `500 12px/1 ${FONT_MONO}`,
- color: 'var(--text)',
+ font: `500 11.5px/1 ${FONT_MONO}`,
+ color: sharePercent > 0 ? 'var(--text)' : 'var(--text-tertiary)',
fontVariantNumeric: 'tabular-nums'
}}
>
- {Math.round(sharePercent)}%
+ {groupShareDisplay}
</div>
<div
style={{
@@ -182,7 +178,7 @@ export function NetworkRow({
{expanded && group.chunks.length > 0 && (
<div
style={{
- padding: '6px 20px 10px 42px',
+ padding: '6px 20px 10px',
display: 'flex',
flexDirection: 'column',
gap: 6,
@@ -192,34 +188,56 @@ export function NetworkRow({
}}
>
{group.chunks.map((chunk, index) => {
- const chunkSize =
- chunk.rangeEnd !== null
- ? chunk.rangeEnd - chunk.rangeStart + 1
- : totalBytes - chunk.rangeStart
- const percent =
- chunkSize > 0 ? Math.min(100, (chunk.bytesDownloaded / chunkSize) * 100) : 0
const isChunkActive = chunk.status === 'downloading'
const isChunkDone = chunk.status === 'completed'
const isChunkError = chunk.status === 'error'
- const rangeText =
- chunk.rangeEnd !== null
- ? `${formatBytes(chunk.rangeStart)} – ${formatBytes(chunk.rangeEnd)}`
- : `${formatBytes(chunk.rangeStart)}+`
+ const currentBlock =
+ blocks && blocks.length > 0
+ ? ((chunk.currentBlockIndex != null
+ ? blocks[chunk.currentBlockIndex]
+ : undefined) ?? blocks.find((b) => b.rangeStart === chunk.rangeStart))
+ : undefined
+
+ const chunkSize = currentBlock
+ ? currentBlock.rangeEnd !== null
+ ? currentBlock.rangeEnd - currentBlock.rangeStart + 1
+ : 0
+ : chunk.rangeEnd !== null
+ ? chunk.rangeEnd - chunk.rangeStart + 1
+ : totalBytes
+ ? totalBytes - chunk.rangeStart
+ : 0
+
+ const chunkBytesDownloaded = currentBlock
+ ? currentBlock.bytesDownloaded
+ : isChunkDone && chunkSize > 0
+ ? chunkSize
+ : chunk.bytesDownloaded
+
+ const chunkPercent =
+ chunkSize > 0
+ ? Math.min(100, Math.max(0, (chunkBytesDownloaded / chunkSize) * 100))
+ : 0
+
+ const isCurrentBlockDone =
+ currentBlock?.status === 'completed' ||
+ isChunkDone ||
+ (chunkSize > 0 && chunkPercent >= 100)
return (
<div
key={chunk.id}
style={{
display: 'grid',
- gridTemplateColumns: '110px 1fr 52px 82px 140px',
+ gridTemplateColumns: NETWORK_ROW_GRID_COLUMNS,
gap: 12,
alignItems: 'center',
padding: '3px 0',
font: `11px/1.2 ${FONT_MONO}`
}}
>
- <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
+ <div style={{ display: 'flex', justifyContent: 'center' }}>
<div
style={{
width: 5,
@@ -227,86 +245,167 @@ export function NetworkRow({
borderRadius: '50%',
background: isChunkError
? DANGER
- : isChunkDone
+ : isCurrentBlockDone
? visual.solid
: isChunkActive
? visual.solid
: 'var(--icon-muted)',
- opacity: isChunkActive || isChunkDone ? 1 : 0.4
+ opacity: isChunkActive || isCurrentBlockDone ? 1 : 0.4
}}
/>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
<span
style={{
color: 'var(--text)',
- fontWeight: 600,
+ fontWeight: 500,
whiteSpace: 'nowrap'
}}
>
Stream #{index + 1}
</span>
+ {currentBlock && (
+ <span
+ style={{
+ font: `500 9px/1 ${FONT_MONO}`,
+ color: 'var(--text-tertiary)',
+ background: 'var(--bg-tertiary)',
+ padding: '1.5px 4.5px',
+ borderRadius: 3,
+ border: '0.5px solid var(--border)',
+ whiteSpace: 'nowrap'
+ }}
+ title={`Range: ${currentBlock.rangeStart} – ${currentBlock.rangeEnd ?? 'end'}`}
+ >
+ Chunk #{currentBlock.index + 1}
+ </span>
+ )}
+ {isChunkActive ? (
+ <span
+ style={{
+ padding: '1px 5px',
+ borderRadius: 3,
+ background: visual.bg,
+ border: `0.5px solid ${visual.border}`,
+ color: visual.text,
+ fontSize: '9px',
+ fontWeight: 600,
+ letterSpacing: '0.04em'
+ }}
+ >
+ ACTIVE
+ </span>
+ ) : isCurrentBlockDone ? (
+ <span
+ style={{
+ color: 'var(--text-tertiary)',
+ fontSize: '9.5px'
+ }}
+ >
+ Done
+ </span>
+ ) : chunk.status === 'paused' ? (
+ <span
+ style={{
+ color: 'var(--text-tertiary)',
+ fontSize: '9.5px'
+ }}
+ >
+ Paused
+ </span>
+ ) : chunk.status === 'retrying' ? (
+ <span
+ style={{
+ color: DANGER,
+ fontSize: '9.5px'
+ }}
+ >
+ Retrying…
+ </span>
+ ) : (
+ <span
+ style={{
+ color: 'var(--text-tertiary)',
+ fontSize: '9.5px'
+ }}
+ >
+ Waiting
+ </span>
+ )}
</div>
- <div
- style={{
- height: 6,
- borderRadius: 999,
- background: 'var(--track-bg)',
- overflow: 'hidden',
- position: 'relative'
- }}
- >
+ <div style={{ display: 'flex', alignItems: 'center', minWidth: 0 }}>
<div
style={{
- height: '100%',
- width: isChunkDone ? '100%' : `${percent}%`,
- background: isChunkError ? DANGER : visual.solid,
+ flex: 1,
+ height: 5,
borderRadius: 999,
- transition: 'width 0.2s ease-out'
+ background: 'var(--track-bg)',
+ border: '0.5px solid var(--border-strong)',
+ overflow: 'hidden'
}}
- />
+ title={
+ chunkSize > 0
+ ? `Chunk progress: ${formatBytes(chunkBytesDownloaded)} of ${formatBytes(chunkSize)} (${Math.round(chunkPercent)}%)`
+ : undefined
+ }
+ >
+ <div
+ style={{
+ height: '100%',
+ width: isCurrentBlockDone ? '100%' : `${chunkPercent}%`,
+ background: isChunkError ? DANGER : visual.solid,
+ borderRadius: 999,
+ transition: 'width 0.2s ease-out'
+ }}
+ />
+ </div>
</div>
<div
style={{
textAlign: 'right',
- color: isChunkDone ? visual.text : 'var(--text)',
- fontVariantNumeric: 'tabular-nums',
- fontWeight: 500
+ font: `500 11px/1 ${FONT_MONO}`,
+ color: isCurrentBlockDone
+ ? visual.text
+ : isChunkActive
+ ? 'var(--text)'
+ : 'var(--text-tertiary)',
+ fontVariantNumeric: 'tabular-nums'
}}
>
- {Math.round(percent)}%
+ {Math.round(chunkPercent)}%
</div>
<div
style={{
textAlign: 'right',
+ font: `500 11px/1 ${FONT_MONO}`,
color: isChunkActive ? visual.text : 'var(--text-tertiary)',
- fontVariantNumeric: 'tabular-nums',
- fontWeight: 500
+ fontVariantNumeric: 'tabular-nums'
}}
>
- {isChunkActive
- ? formatSpeed(chunk.speedBytesPerSec)
- : isChunkDone
- ? 'Done'
- : chunk.status === 'retrying'
- ? 'Retrying…'
- : chunk.status === 'paused'
- ? 'Paused'
- : 'Waiting'}
+ {isChunkActive ? formatSpeed(chunk.speedBytesPerSec) : '—'}
</div>
<div
style={{
textAlign: 'right',
+ font: `11px/1 ${FONT_MONO}`,
color: 'var(--text-secondary)',
fontVariantNumeric: 'tabular-nums',
- fontSize: '10.5px',
whiteSpace: 'nowrap'
}}
- title={`Byte range: ${rangeText}`}
+ title={
+ chunkSize > 0
+ ? `${formatBytes(chunkBytesDownloaded)} of ${formatBytes(chunkSize)}`
+ : formatBytes(chunkBytesDownloaded)
+ }
>
- {formatBytes(chunk.bytesDownloaded)} / {formatBytes(chunkSize)}
+ {chunkSize > 0
+ ? `${formatBytes(chunkBytesDownloaded)} / ${formatBytes(chunkSize)}`
+ : formatBytes(chunkBytesDownloaded)}
</div>
</div>
)
diff --git a/src/renderer/src/screens/DownloadingScreen.tsx b/src/renderer/src/screens/DownloadingScreen.tsx
index 0fb302b..dcbac95 100644
--- a/src/renderer/src/screens/DownloadingScreen.tsx
+++ b/src/renderer/src/screens/DownloadingScreen.tsx
@@ -1,5 +1,6 @@
import type { DownloadState } from '@shared/types'
import { useEffect, useState } from 'react'
+import { BlockGrid } from '../components/BlockGrid'
import { MergeDiagram } from '../components/MergeDiagram'
import { NetworkRow } from '../components/NetworkRow'
import { ThroughputChart } from '../components/ThroughputChart'
@@ -86,6 +87,7 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
const effectiveSpeed = isPaused ? 0 : download.speedBytesPerSec
const speed = splitFormattedBytes(effectiveSpeed)
const groups = groupChunksByInterface(download.chunks)
+ const totalDownloadedByNetworks = groups.reduce((sum, g) => sum + g.bytesDownloaded, 0)
const visuals = groups.map((group) =>
resolveNetworkVisual(
group.interfaceKind,
@@ -96,10 +98,6 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
const activeGroups = groups.filter((group) =>
group.chunks.some((chunk) => chunk.status === 'downloading')
)
- const weights = groups.map((group) =>
- effectiveSpeed > 0 ? group.speedBytesPerSec : group.bytesDownloaded
- )
- const totalWeight = weights.reduce((sum, weight) => sum + weight, 0) || 1
const [chipModeIndex, setChipModeIndex] = useState(0)
@@ -412,33 +410,16 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
</div>
</div>
</div>
- <div
- style={{
- height: 9,
- borderRadius: 999,
- background: 'var(--track-bg)',
- overflow: 'hidden',
- display: 'flex',
- gap: 2
- }}
- >
- {knownSize ? (
- <>
- {groups.map((group, index) => (
- <div
- key={group.interfaceId}
- style={{
- flex: group.bytesDownloaded || 0.0001,
- background: visuals[index].solid
- }}
- />
- ))}
- <div style={{ flex: remainingBytes || 0.0001 }} />
- </>
- ) : (
- <div style={{ width: '100%', background: 'var(--color-accent)' }} />
- )}
- </div>
+
+ <BlockGrid
+ blocks={download.blocks}
+ groups={groups}
+ visuals={visuals}
+ knownSize={knownSize}
+ remainingBytes={remainingBytes}
+ isPaused={isPaused}
+ blockSizeBytes={download.blockSizeBytes}
+ />
</div>
<div style={{ flex: 1, overflowY: 'auto' }}>
@@ -452,26 +433,34 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
>
<div style={sectionHeaderLabelStyle}>Networks</div>
<div style={sectionHeaderMetaStyle}>
- {groups.length} merged · {download.chunks.length} chunks ·{' '}
+ {groups.length} merged · {download.chunks.length} streams ·{' '}
{isPaused ? 'paused' : `${activeGroups.length} active`}
</div>
</div>
<div style={networkTableHeaderStyle}>
<div />
<div>Network</div>
- <div>Chunks</div>
+ <div>Progress</div>
<div style={{ textAlign: 'right' }}>Share</div>
<div style={{ textAlign: 'right' }}>Speed</div>
<div style={{ textAlign: 'right' }}>Downloaded</div>
</div>
- {groups.map((group, index) => (
- <NetworkRow
- key={group.interfaceId}
- group={group}
- totalBytes={download.totalBytes}
- sharePercent={(weights[index] / totalWeight) * 100}
- />
- ))}
+ {groups.map((group) => {
+ const sharePercent =
+ totalDownloadedByNetworks > 0
+ ? (group.bytesDownloaded / totalDownloadedByNetworks) * 100
+ : 0
+ return (
+ <NetworkRow
+ key={group.interfaceId}
+ group={group}
+ sharePercent={sharePercent}
+ totalBytes={download.totalBytes}
+ totalDownloaded={totalDownloadedByNetworks}
+ blocks={download.blocks}
+ />
+ )
+ })}
</div>
<div style={footerStyle}>
diff --git a/src/renderer/src/theme.ts b/src/renderer/src/theme.ts
index c77c467..b213abf 100644
--- a/src/renderer/src/theme.ts
+++ b/src/renderer/src/theme.ts
@@ -192,7 +192,7 @@ export const statValueStyle: React.CSSProperties = {
fontVariantNumeric: 'tabular-nums'
}
-export const NETWORK_ROW_GRID_COLUMNS = '10px 190px 1fr 44px 82px 82px'
+export const NETWORK_ROW_GRID_COLUMNS = '10px 175px 1fr 48px 82px 125px'
export const networkTableHeaderStyle: React.CSSProperties = {
display: 'grid',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 8c8d0f4..58b0a9b 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -43,6 +43,19 @@ export interface ChunkState {
error?: string
/** Number of times this chunk's connection has been retried after a dropped/failed attempt. */
retryCount: number
+ /** Index of the block currently being downloaded by this worker chunk. */
+ currentBlockIndex?: number
+}
+
+export type BlockStatus = 'pending' | 'downloading' | 'completed' | 'error'
+
+export interface BlockState {
+ index: number
+ rangeStart: number
+ rangeEnd: number | null
+ status: BlockStatus
+ interfaceId?: string
+ bytesDownloaded: number
}
export interface DownloadState {
@@ -56,6 +69,9 @@ export interface DownloadState {
speedBytesPerSec: number
status: DownloadStatus
chunks: ChunkState[]
+ blocks?: BlockState[]
+ totalBlocks?: number
+ blockSizeBytes?: number
error?: string
startedAt: number
pausedAt?: number