Speed up downloads by combining multiple network connections in parallel
TypeScript bandwidth-aggregationcross-platformdesktop-appdownloaderdownloadmanagerlinuxmacosmulticonnectionparallel-downloadswindows
Speed units, limits beside what they cap, networks menu rework, readable throughput chart (#84)
Anmol Kapil21ad8c0c7887
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ee52abf..4e924fb 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -11,7 +11,15 @@ npm installnpm run dev```-Requires Windows 10/11 or macOS and Node.js 22.12+. See [requirements](README.md#requirements).+Requires Node.js 22.12+ and npm 9+, on Windows, macOS, or Linux.++## Packaging++- **macOS**: `npm run build:mac` writes `dist/mac/Plexo.app`. A build made on your own Mac isn't quarantined, so it opens without the first-launch step.+- **Windows**: `npm run build:win`, from PowerShell, writes the installer to `dist/`. For an app you run without installing, use `npm run build:unpack` and open `dist/win-unpacked/plexo.exe`.+- **Linux**: `npm run build:linux` writes the AppImage and `.deb` packages to `dist/`++Local builds are unsigned.## Before opening a PRdiff --git a/docs/index.html b/docs/index.htmlindex d33fff3..461a99a 100644--- a/docs/index.html+++ b/docs/index.html@@ -2464,7 +2464,8 @@phone by USB, then turn on <strong>USB tethering</strong> in your phone's hotspotand tethering settings. Once macOS shows it as a network connection, Plexo can useit. Follow the- <a href="https://github.com/anmolkapil/plexo#using-a-usb-tethered-android-phone"+ <a+ href="https://github.com/anmolkapil/plexo#use-an-android-phone-over-usb-on-macos">full Android USB tethering tutorial</a>.</p>diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.tsindex 43d3ca6..3b8a390 100644--- a/src/main/download/downloadManager.ts+++ b/src/main/download/downloadManager.ts@@ -8,6 +8,7 @@ import { app, Notification, powerSaveBlocker, shell } from 'electron'import { IpcChannels } from '../../shared/ipc-channels'import {DOWNLOADS_AT_ONCE,+ SPEED_HISTORY_SECONDS,type AppSettings,type DownloadNetwork,type DownloadState,@@ -87,8 +88,9 @@ interface RuntimeFields {pausedForNoNetwork?: boolean/** When the speeds last went into the history (see sampleSpeeds). */speedSampledAt: number- /** The best combined speed this run has shown: the peak of one done before it held one. */- bestSpeedSeen: number+ /** The byte count, read once a second while downloading and carried over pauses: back to the+ * newest reading PEAK_SECONDS old (see samplePeak). */+ peakReadings: { time: number; bytes: number }[]/** Changes asked of a torrent's choice of files, counted: only the latest applies. */fileChoices: number}@@ -128,14 +130,13 @@ const TICK_MS = 500// checkpoints independent of UI updates; pause and publication still force an immediate sync.const CHECKPOINT_INTERVAL_MS = 15_000-const SPEED_HISTORY_LENGTH = 60-// The peak is the best speed held this many samples (seconds): longer than a start's burst (an-// ISP's burst allowance, every connection ramping up at once), which isn't the line's speed.-const PEAK_SAMPLES = 5+// The peak is the best speed held this many seconds: longer than a start's burst (an ISP's burst+// allowance, every connection ramping up at once), which isn't the line's speed.+const PEAK_SECONDS = 5/** Adds each network's speed to the download's history, and 0 for one no longer listed. A* network seen for the first time starts at 0 too, so every series is as long as the others and- * lines up with them. Then raises the peak, once the last PEAK_SAMPLES are in. */+ * lines up with them. */function sampleSpeeds(state: DownloadState): void {const history = (state.speedHistory ??= {})const length = Object.values(history)[0]?.length ?? 0@@ -144,13 +145,32 @@ function sampleSpeeds(state: DownloadState): void {}for (const [id, series] of Object.entries(history)) {series.push(state.networks.find((network) => network.id === id)?.speedBytesPerSec ?? 0)- if (series.length > SPEED_HISTORY_LENGTH) series.shift()+ if (series.length > SPEED_HISTORY_SECONDS) series.shift()}- const series = Object.values(history)- if (series[0].length < PEAK_SAMPLES) return- let held = 0- for (const values of series) for (const value of values.slice(-PEAK_SAMPLES)) held += value- state.peakSpeedBytesPerSec = Math.max(state.peakSpeedBytesPerSec ?? 0, held / PEAK_SAMPLES)+}++/** Raises the peak to the last PEAK_SECONDS of downloading, read from the bytes themselves: what+ * AVG is made of, so the peak can't read below it (an average is never above its best stretch).+ * Read off the speed meters instead, it missed the opening burst AVG counts, and early on read+ * lower. The first stretch starts with the download, so a burst is in it, spread over the seconds,+ * not a speed. Readings run on across a pause (see run), so short runs between pauses count too. */+function samplePeak(runtime: DownloadRuntime, now: number): void {+ const { state } = runtime+ const readings = runtime.peakReadings+ readings.push({ time: now, bytes: state.bytesDownloaded })+ // Back to the newest reading at least PEAK_SECONDS old, by time rather than by count: a run that+ // stops between ticks adds a reading, and counted, a short stretch passed for a full one.+ while (readings.length > 1 && readings[1].time <= now - PEAK_SECONDS * 1000) readings.shift()+ const first = readings[0]+ if (now - first.time < PEAK_SECONDS * 1000) return+ const held = (state.bytesDownloaded - first.bytes) / ((now - first.time) / 1000)+ // Stretches are only read where a reading falls, so the download's first or last few seconds+ // can go unread as one — and when those were its fastest, every stretch read is slower than the+ // average. Its best 5 seconds can't be, though: past PEAK_SECONDS of downloading, the average+ // (as AVG works it out) is a floor the peak truly clears.+ const downloading = (now - state.startedAt - (state.totalPausedMs ?? 0)) / 1000+ const average = downloading >= PEAK_SECONDS ? state.bytesDownloaded / downloading : 0+ state.peakSpeedBytesPerSec = Math.max(state.peakSpeedBytesPerSec ?? 0, held, average)}function newHttpNetwork(iface: NetworkInterfaceInfo, enabled: boolean): HttpDownloadNetwork {@@ -386,7 +406,7 @@ export class DownloadManager {sentUpdates: 0,sentUnits: [],speedSampledAt: 0,- bestSpeedSeen: 0,+ peakReadings: [],fileChoices: 0}}@@ -1324,6 +1344,18 @@ export class DownloadManager {const watched = new WeakSet<Promise<void>>()let wake: { resolve: () => void; reject: (error: unknown) => void } | null = nulllet tickedAt = Date.now()+ // Readings carry over a pause, moved up to now: time paused isn't time downloading, so a+ // stretch can run across one, and runs too short for a stretch of their own still count — as+ // they do in AVG, which a reset here let read above PEAK.+ const lastReading = runtime.peakReadings.at(-1)+ const paused = lastReading ? tickedAt - lastReading.time : 0+ runtime.peakReadings = runtime.peakReadings.map((reading) => ({+ time: reading.time + paused,+ bytes: reading.bytes+ }))+ if (runtime.peakReadings.at(-1)?.bytes !== runtime.state.bytesDownloaded) {+ runtime.peakReadings.push({ time: tickedAt, bytes: runtime.state.bytesDownloaded })+ }while (runtime.state.status === 'downloading' &&@@ -1348,15 +1380,17 @@ export class DownloadManager {const timeLeftChanged = updateTimeLeft(runtime.state, (now - tickedAt) / 1000)tickedAt = nowif (speedsChanged || timeLeftChanged) this.scheduleUpdate(runtime)- runtime.bestSpeedSeen = Math.max(runtime.bestSpeedSeen, runtime.state.speedBytesPerSec)if (now - runtime.speedSampledAt >= 1000) {runtime.speedSampledAt = nowsampleSpeeds(runtime.state)+ samplePeak(runtime, now)this.scheduleUpdate(runtime)}runtime.transfer.tick(now)}- // The last blocks are in, or the run was stopped: its streams wind down.+ // The last blocks are in, or the run was stopped: its streams wind down. Its last part reads+ // too, up to the moment it stopped (and where the next run picks up).+ samplePeak(runtime, Date.now())runtime.stop.abort()await Promise.all(runtime.transfer.running())// However it ended — paused, failed, cancelled, done — nothing is moving now.@@ -1392,8 +1426,14 @@ export class DownloadManager {runtime.state.fileName = basename(publishedPath)runtime.state.status = 'completed'runtime.state.completedAt = Date.now()- // Done before it held a speed for long: the best it showed.- if (runtime.bestSpeedSeen > 0) runtime.state.peakSpeedBytesPerSec ??= runtime.bestSpeedSeen+ // Done before it downloaded for PEAK_SECONDS: its speed start to finish, pauses left out (the+ // readings close them up), is the best it held.+ const [start] = runtime.peakReadings+ const end = runtime.peakReadings.at(-1)+ const ranFor = start && end ? (end.time - start.time) / 1000 : 0+ if (ranFor > 0) {+ runtime.state.peakSpeedBytesPerSec ??= (end!.bytes - start.bytes) / ranFor+ }runtime.state.bytesDownloaded =runtime.state.totalBytes -(runtime.state.kind === 'torrent' ? runtime.state.skippedBytes : 0) ||diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.tsindex 6e0f0e6..c07b74a 100644--- a/src/main/ipc/handlers.ts+++ b/src/main/ipc/handlers.ts@@ -24,7 +24,6 @@ import { listHistory } from '../download/history'import { probeUrl } from '../download/probe'import { deviceBindingSupported } from '../network/deviceBinding'import { takePendingLink } from '../openLinks'-import { measureLatencies } from '../network/latency'import { NetworkMonitor } from '../network/interfaces'import { loadSettings, saveSettings } from '../settings'import { testKnobs } from '../testKnobs'@@ -88,9 +87,7 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Downhandle('listInterfaces', () => networks.refresh())- handle('pingInterfaces', async () => measureLatencies(networks.current ?? []))-- // Started now so it has settled before the first ping or download needs it.+ // Started now so it has settled before the first download needs it.const bindingSupport = deviceBindingSupported()handle('deviceBindingSupported', async () => bindingSupport)@@ -137,6 +134,7 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): DownspeedLimit: settings.speedLimit,slowMode: settings.slowMode ?? false,slowModeSpeed: settings.slowModeSpeed ?? DEFAULT_SLOW_MODE_SPEED,+ speedUnit: settings.speedUnit ?? 'bytes',destinationDir: destinationExists ? destinationDir : undefined} satisfies InitialState} catch (error) {@@ -149,7 +147,8 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): DownnetworkPreferences: {},downloadsAtOnce: DOWNLOADS_AT_ONCE.default,slowMode: false,- slowModeSpeed: DEFAULT_SLOW_MODE_SPEED+ slowModeSpeed: DEFAULT_SLOW_MODE_SPEED,+ speedUnit: 'bytes'} satisfies InitialState}})diff --git a/src/main/network/interfaces.ts b/src/main/network/interfaces.tsindex 9e20456..d57360e 100644--- a/src/main/network/interfaces.ts+++ b/src/main/network/interfaces.ts@@ -26,13 +26,16 @@ async function getMacHardwarePortNames(): Promise<Map<string, string>> {const { stdout } = await execFileAsync('networksetup', ['-listallhardwareports'], {timeout: DISCOVERY_TIMEOUT_MS})- const blocks = stdout.split(/\n\s*\n/)- for (const block of blocks) {- const portMatch = /Hardware Port:\s*(.+)/.exec(block)- const deviceMatch = /Device:\s*(.+)/.exec(block)- if (portMatch && deviceMatch) {- deviceToName.set(deviceMatch[1].trim(), portMatch[1].trim())- }+ // Each block is "Hardware Port: Wi-Fi", "Device: en0", "Ethernet Address: …", always in that+ // order. Read by position, not by label: a Mac in another language translates the labels+ // ("Matériel") as well as the names ("WLAN"), and matching English found nothing there.+ for (const block of stdout.split(/\n\s*\n/)) {+ const [port, device] = block+ .split('\n')+ .filter((line) => line.includes(':'))+ .map((line) => line.slice(line.indexOf(':') + 1).trim())+ // A BSD device name (en0, bridge0) is how a real block is told from the trailing VLAN list.+ if (port && device && /^[a-z]+\d+$/.test(device)) deviceToName.set(device, port)}} catch {// networksetup missing or failed — callers fall back to raw device names.@@ -40,6 +43,18 @@ async function getMacHardwarePortNames(): Promise<Map<string, string>> {return deviceToName}+/** Linux names a device by what it is, in systemd's predictable names (wlp2s0, enp3s0,+ * enp0s20f0u1, enx3a5b0c1d2e4f) or the older ones (wlan0, eth0, usb0): wl is Wi-Fi; a USB port in+ * the path (…u1), a MAC-based name (enx) or usb is a USB adapter, which a tethered phone is; en and+ * eth are Ethernet. There's no name lookup to read instead, as macOS and Windows have. */+function classifyLinuxDevice(device: string): NetworkInterfaceKind {+ if (/^wl/.test(device)) return 'wifi'+ if (/^usb|^enx|^en\w*u\d/.test(device)) return 'usb'+ if (/^(en|eth)/.test(device)) return 'ethernet'+ if (/^(br|virbr)/.test(device)) return 'bridge'+ return 'other'+}+function classifyInterface(hardwarePortName: string): NetworkInterfaceKind {const name = hardwarePortName.toLowerCase()if (/wi-?fi|wireless|wlan|802\.11|airport/.test(name)) return 'wifi'@@ -50,7 +65,9 @@ function classifyInterface(hardwarePortName: string): NetworkInterfaceKind {return 'other'}-/** Adapter aliases match Node's interface names; metadata identifies renamed or localized adapters. */+/** Adapter aliases ("Wi-Fi", "Ethernet 2") match Node's interface names, and are what Windows shows+ * people; the description ("Intel(R) Wi-Fi 6 AX201 160MHz") and physical medium only tell what kind+ * of network a renamed or localized adapter is. */async function getWindowsAdapters(): Promise<Map<string, WindowsAdapter>> {if (process.platform !== 'win32') return new Map()try {@@ -143,14 +160,19 @@ export async function listActiveInterfaces(): Promise<NetworkInterfaceInfo[]> {const hardwareName = hardwarePorts.get(device)const adapter = windowsAdapters.get(device)- let kind = classifyInterface(adapter?.InterfaceDescription ?? hardwareName ?? device)+ let kind =+ process.platform === 'linux'+ ? classifyLinuxDevice(device)+ : classifyInterface(adapter?.InterfaceDescription ?? hardwareName ?? device)// NDIS media: 1 = wireless LAN, 9 = native 802.11, 14 = Ethernet (802.3).if (adapter?.NdisPhysicalMedium === 1 || adapter?.NdisPhysicalMedium === 9) kind = 'wifi'else if (kind === 'other' && adapter?.NdisPhysicalMedium === 14) kind = 'ethernet'result.push({id: device,device,- displayName: hardwareName ?? adapter?.InterfaceDescription ?? device,+ // What the OS shows people: macOS's hardware port ("Wi-Fi", "iPhone USB"), else the device —+ // on Windows its alias ("Wi-Fi", "Ethernet 2"), on Linux its name (wlp2s0).+ displayName: hardwareName ?? device,addresses: usable,kind,mac: addresses.find((addr) => addr.mac && addr.mac !== '00:00:00:00:00:00')?.macdiff --git a/src/main/network/latency.ts b/src/main/network/latency.tsdeleted file mode 100644index 22e9468..0000000--- a/src/main/network/latency.ts+++ /dev/null@@ -1,69 +0,0 @@-import type { IpFamily, NetworkInterfaceInfo } from '../../shared/types'-import { connectRoute } from './deviceBinding'--const PROBE_HOSTS: { address: string; family: IpFamily }[][] = [- [- { address: '1.1.1.1', family: 4 },- { address: '2606:4700:4700::1111', family: 6 }- ],- [- { address: '8.8.8.8', family: 4 },- { address: '2001:4860:4860::8888', family: 6 }- ]-]-const PROBE_PORT = 443-const TIMEOUT_MS = 2000--/** Rough per-interface latency: time to open a TCP connection to a reliable- * host, sourced from that interface's local address. null means unreachable. */-function measureLatencyToHost(- iface: NetworkInterfaceInfo,- localAddress: string,- remoteAddress: string,- family: IpFamily-): Promise<number | null> {- return new Promise((resolve) => {- const start = Date.now()- const socket = connectRoute(- { device: iface.device, localAddress, remoteAddress, family },- PROBE_PORT- )- let settled = false-- const finish = (result: number | null): void => {- if (settled) return- settled = true- clearTimeout(timer)- socket.destroy()- resolve(result)- }-- const timer = setTimeout(() => finish(null), TIMEOUT_MS)- socket.once('connect', () => finish(Date.now() - start))- socket.once('error', () => finish(null))- })-}--async function measureLatency(iface: NetworkInterfaceInfo): Promise<number | null> {- for (const hosts of PROBE_HOSTS) {- const attempts = hosts.flatMap((host) =>- iface.addresses- .filter((local) => local.family === host.family)- .map((local) => measureLatencyToHost(iface, local.address, host.address, host.family))- )- const latencies = (await Promise.all(attempts)).filter(- (latency): latency is number => latency !== null- )- if (latencies.length > 0) return Math.min(...latencies)- }- return null-}--export async function measureLatencies(- interfaces: NetworkInterfaceInfo[]-): Promise<Record<string, number | null>> {- const entries = await Promise.all(- interfaces.map(async (iface) => [iface.id, await measureLatency(iface)] as const)- )- return Object.fromEntries(entries)-}diff --git a/src/main/settings.ts b/src/main/settings.tsindex 12d82c7..3a346dd 100644--- a/src/main/settings.ts+++ b/src/main/settings.ts@@ -85,6 +85,9 @@ function sanitizeSettings(parsed: unknown): AppSettings {const slowModeSpeed = byteCount(parsed.slowModeSpeed)if (slowModeSpeed !== undefined) settings.slowModeSpeed = slowModeSpeedif (parsed.slowMode === true) settings.slowMode = true+ if (parsed.speedUnit === 'bytes' || parsed.speedUnit === 'bits') {+ settings.speedUnit = parsed.speedUnit+ }return settings}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 609492e..cb6308d 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -24,7 +24,6 @@ const plexoApi = {initialState: ipcRenderer.sendSync(IpcChannels.getInitialState) as InitialState,listInterfaces: () => invoke('listInterfaces'),- pingInterfaces: () => invoke('pingInterfaces'),deviceBindingSupported: () => invoke('deviceBindingSupported'),openNetworkSettings: () => invoke('openNetworkSettings'),updateSettings: (patch: AppSettings) => invoke('updateSettings', patch),diff --git a/src/renderer/src/components/CombineDiagram.tsx b/src/renderer/src/components/CombineDiagram.tsxindex de321c2..9e6f55d 100644--- a/src/renderer/src/components/CombineDiagram.tsx+++ b/src/renderer/src/components/CombineDiagram.tsx@@ -1,4 +1,4 @@-import { formatSpeed } from '../utils/format'+import { useFormatSpeed } from '../hooks/useFormatSpeed'const ROW_HEIGHT = 36// Gaps between the label column and the rest of the diagram stay fixed — only the label@@ -35,6 +35,7 @@ export function CombineDiagram({muted?: booleanpaused?: boolean}): React.JSX.Element {+ const formatSpeed = useFormatSpeed()const height = Math.max(78, networks.length * ROW_HEIGHT + 10)const midY = height / 2diff --git a/src/renderer/src/components/LimitsDialog.tsx b/src/renderer/src/components/LimitsDialog.tsxindex 6cc5ede..6e80b0e 100644--- a/src/renderer/src/components/LimitsDialog.tsx+++ b/src/renderer/src/components/LimitsDialog.tsx@@ -10,7 +10,8 @@ import { useEffect, useId, useState } from 'react'import { useNetworkUsage } from '../hooks/useNetworks'import { useNetworkVisuals } from '../hooks/useNetworkVisuals'import { useAppStore } from '../store/useAppStore'-import { describeError, formatBytes, formatSpeed } from '../utils/format'+import { describeError, formatBytes, formatDataUsage } from '../utils/format'+import { useFormatSpeedLimit } from '../hooks/useFormatSpeed'import {AlertDialog,AlertDialogContent,@@ -41,10 +42,15 @@ const GENERAL_DEFAULTS = {downloadsAtOnce: DOWNLOADS_AT_ONCE.default} satisfies Partial<Draft>-const KB = 1024const MB = 1024 ** 2const GB = 1024 ** 3+/** A speed is typed in the unit picked in the footer; anything under one is a decimal. */+const SPEED_UNITS = {+ bytes: { label: 'MB/s', bytes: MB },+ bits: { label: 'Mbps', bytes: 1000 ** 2 / 8 }+}+const sectionClass = 'flex flex-col gap-2.5 border-t-[0.5px] border-border py-3'const headingClass = 'font-sans text-[14px] leading-none font-semibold'const hintClass = 'text-[12.5px] leading-snug text-[var(--text-secondary)]'@@ -58,7 +64,6 @@ function NumberInput({unitBytes,label,disabled = false,- showUnit = true,onChange}: {bytes: number@@ -66,11 +71,16 @@ function NumberInput({unitBytes: numberlabel: stringdisabled?: boolean- showUnit?: booleanonChange: (bytes: number) => void}): React.JSX.Element {- // Keep the draft as typed; changing units remounts it using the same byte value.- const [text, setText] = useState(() => String(bytes / unitBytes))+ // Keep the draft as typed; changing units remounts it using the same byte value. Rounded, as+ // bytes saved in one unit rarely come out whole in another (20 MB/s is 167.77216 Mbps) — but+ // under one by significant digits, not decimals: 1 KB/s is 0.000977 MB/s, and two decimals read+ // that as a 0 MB/s limit that still applies.+ const [text, setText] = useState(() => {+ const value = bytes / unitBytes+ return String(Number(value >= 1 ? value.toFixed(2) : value.toPrecision(3)))+ })return (<span className="flex items-center gap-2"><Input@@ -86,7 +96,7 @@ function NumberInput({}}className="w-20 text-right font-mono tabular-nums"/>- {showUnit && <span className="font-mono text-[12px] text-muted-foreground">{unit}</span>}+ <span className="font-mono text-[12px] text-muted-foreground">{unit}</span></span>)}@@ -102,38 +112,22 @@ function SpeedInput({disabled?: booleanonChange: (bytes: number) => void}): React.JSX.Element {- const [unit, setUnit] = useState<'KB/s' | 'MB/s'>(() => (bytes < MB ? 'KB/s' : 'MB/s'))+ const unit = SPEED_UNITS[useAppStore((store) => store.speedUnit)]return (- <div className="flex items-center gap-2">- <NumberInput- key={unit}- bytes={bytes}- unit={unit}- unitBytes={unit === 'KB/s' ? KB : MB}- label={`${label}, in ${unit}`}- disabled={disabled}- showUnit={false}- onChange={onChange}- />- <ToggleGroup- aria-label={`${label} unit`}- value={[unit]}- disabled={disabled}- onValueChange={(values) => {- if (values[0] === 'KB/s' || values[0] === 'MB/s') setUnit(values[0])- }}- size="sm"- spacing={0.5}- className="bg-secondary p-0.5"- >- <ToggleGroupItem value="KB/s">KB/s</ToggleGroupItem>- <ToggleGroupItem value="MB/s">MB/s</ToggleGroupItem>- </ToggleGroup>- </div>+ <NumberInput+ key={unit.label}+ bytes={bytes}+ unit={unit.label}+ unitBytes={unit.bytes}+ label={`${label}, in ${unit.label}`}+ disabled={disabled}+ onChange={onChange}+ />)}-/** No limit, or an editable limit. Turning it off retains the last value while open. */+/** No limit, or an editable limit: a speed when no unit is given. Turning it off retains the+ * last value while open. */function LimitChoice({label,value,@@ -147,8 +141,8 @@ function LimitChoice({label: stringvalue: number | undefinedfallback: number- unit: string- unitBytes: number+ unit?: string+ unitBytes?: numberonChange: (bytes: number | undefined) => void}): React.JSX.Element {const name = useId()@@ -184,7 +178,7 @@ function LimitChoice({/>Limit to</label>- {unit === 'MB/s' ? (+ {unit === undefined || unitBytes === undefined ? (<SpeedInputkey={enabled ? 'on' : 'off'}bytes={value ?? lastValue}@@ -240,8 +234,6 @@ function GeneralPage({label="Total speed"value={speedLimit}fallback={20 * MB}- unit="MB/s"- unitBytes={MB}onChange={(speedLimit) => change({ speedLimit })}/></section>@@ -387,8 +379,6 @@ function NetworkPage({label={`${name} speed`}value={preference?.speedLimit}fallback={10 * MB}- unit="MB/s"- unitBytes={MB}onChange={(speedLimit) => change({ speedLimit })}/></section>@@ -496,7 +486,7 @@ function NetworkPage({}/** "5.00 of 5 GB this month", with a bar that turns red once the limit is reached. */-export function UsageBar({+function UsageBar({used,limit,period = 'month'@@ -525,16 +515,20 @@ export function UsageBar({}/** One line under a network's name: its limits, or that it has reached one. */-function describeLimits(preference: NetworkPreference | undefined, used: number): string {+function describeLimits(+ preference: NetworkPreference | undefined,+ used: number,+ formatSpeedLimit: (bytesPerSec: number) => string+): string[] {if (preference?.dataLimit !== undefined && used >= preference.dataLimit) {- return 'Data limit reached'+ return ['Data limit reached']}- const parts = [- preference?.speedLimit !== undefined && formatSpeed(preference.speedLimit),- preference?.dataLimit !== undefined &&- `${formatBytes(preference.dataLimit)} per ${preference.dataLimitPeriod ?? 'month'}`- ].filter(Boolean)- return parts.length > 0 ? parts.join(' · ') : 'No limit'+ // A line each, said as the networks menu says them, so the two never read differently.+ const lines = [+ preference?.speedLimit !== undefined && `Limit ${formatSpeedLimit(preference.speedLimit)}`,+ preference?.dataLimit !== undefined && formatDataUsage(used, preference.dataLimit)+ ].filter((line): line is string => typeof line === 'string')+ return lines.length > 0 ? lines : ['No limit']}/** Speed & data limits: every download's together, and each network's. Nothing changes until@@ -574,6 +568,7 @@ function LimitsEditor({onPageChange: (page: string | null) => voidonClose: () => void}): React.JSX.Element {+ const formatSpeedLimit = useFormatSpeedLimit()const interfaces = useAppStore((store) => store.interfaces)const [draft, setDraft] = useState<Draft>(() => {const { speedLimit, slowMode, slowModeSpeed, downloadsAtOnce, networkPreferences } =@@ -618,7 +613,7 @@ function LimitsEditor({key: string | null,dot: string,name: string,- detail: string,+ detail: string[],warn = false): React.JSX.Element => (<button@@ -629,13 +624,17 @@ function LimitsEditor({className="flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring aria-[current=page]:bg-primary/10"><span className="mt-1.5 size-2 shrink-0 rounded-full" style={{ background: dot }} />- <span className="flex min-w-0 flex-col gap-1">+ <span className="flex min-w-0 flex-1 flex-col gap-1"><span className="truncate text-[13.5px] font-medium">{name}</span>- <span- className={`font-mono text-[11px] ${warn ? 'text-[var(--color-usb)]' : 'text-muted-foreground'}`}- >- {detail}- </span>+ {/* A line per fact, each cut off rather than wrapped: the sidebar is narrow. */}+ {detail.map((line) => (+ <span+ key={line}+ className={`truncate font-mono text-[11px] ${warn ? 'text-[var(--color-danger)]' : 'text-muted-foreground'}`}+ >+ {line}+ </span>+ ))}</span></button>)@@ -648,22 +647,27 @@ function LimitsEditor({<div className="flex min-h-0 flex-1"><nav className="flex w-[190px] shrink-0 flex-col gap-0.5 overflow-y-auto border-r-[0.5px] border-border p-2"><div className={navLabelClass}>General</div>- {navItem(- null,- 'var(--text-secondary)',- 'All downloads',- slowMode ? 'Slow mode on' : speedLimit ? formatSpeed(speedLimit) : 'No limit'- )}+ {navItem(null, 'var(--text-secondary)', 'All downloads', [+ slowMode+ ? 'Slow mode on'+ : speedLimit+ ? `Limit ${formatSpeedLimit(speedLimit)}`+ : 'No limit'+ ])}<div className={navLabelClass}>Networks</div>{interfaces.map((iface) => {const visual = networkVisual(iface.id, iface.kind, iface.displayName)- const detail = describeLimits(preferences[iface.id], usage[iface.id] ?? 0)+ const detail = describeLimits(+ preferences[iface.id],+ usage[iface.id] ?? 0,+ formatSpeedLimit+ )return navItem(iface.id,visual.solid,visual.name,detail,- detail === 'Data limit reached'+ detail[0] === 'Data limit reached')})}</nav>diff --git a/src/renderer/src/components/NetworkRow.tsx b/src/renderer/src/components/NetworkRow.tsxindex 636828b..053207b 100644--- a/src/renderer/src/components/NetworkRow.tsx+++ b/src/renderer/src/components/NetworkRow.tsx@@ -1,8 +1,10 @@-import type { HttpBlockState, HttpStreamState, NetworkStatus } from '@shared/types'+import type { HttpBlockState, HttpStreamState, NetworkStatus, SpeedUnit } from '@shared/types'import { useState } from 'react'import { DANGER, type NetworkVisual } from '../theme'import type { HttpNetworkGroup, NetworkGroup, TorrentNetworkGroup } from '../utils/format'-import { describeError, formatBytes, formatSpeed } from '../utils/format'+import { describeError, formatBytes, formatSpeedOfLimit } from '../utils/format'+import { useFormatSpeed } from '../hooks/useFormatSpeed'+import { useAppStore } from '../store/useAppStore'import { ColorBadge } from './ColorBadge'import { NetworkEditPopover } from './NetworkEditPopover'import { TruncatedText } from './TruncatedText'@@ -99,6 +101,7 @@ function HttpStreamRows({visual: NetworkVisualblocks?: HttpBlockState[]}): React.JSX.Element {+ const formatSpeed = useFormatSpeed()return (<>{group.streams.map((stream, index) => {@@ -207,6 +210,35 @@ function shareOf(part: number, whole: number): string {return percent === 0 ? '<1%' : `${percent}%`}+/** "8.0 / 10.0 MB/s": a network's speed against the limit set on it, the limit quieter. */+function SpeedOfLimit({+ speed,+ limit,+ unit+}: {+ speed: number+ limit: number+ unit: SpeedUnit+}): React.JSX.Element {+ const [value, max] = formatSpeedOfLimit(speed, limit, unit)+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <span>+ {value}+ <span className="font-medium text-muted-foreground">+ <span className="sr-only">, limited to {max}</span>+ <span aria-hidden> / {max}</span>+ </span>+ </span>+ }+ />+ <TooltipContent>Limited to {max}</TooltipContent>+ </Tooltip>+ )+}+/** Download, and upload once there is any: the arrows only when both are shown. */function TwoWay({down,@@ -214,7 +246,7 @@ function TwoWay({showUp,labels}: {- down: string+ down: React.ReactNodeup: stringshowUp: booleanlabels: [string, string]@@ -244,6 +276,7 @@ function PeerRows({group: TorrentNetworkGroupvisual: NetworkVisual}): React.JSX.Element {+ const formatSpeed = useFormatSpeed()// What the network's peers have sent between them: each one's share of it.const received = group.peers.reduce((sum, peer) => sum + peer.bytesDownloaded, 0)return (@@ -334,6 +367,9 @@ export function NetworkRow({blocks,onSwitch}: NetworkRowProps): React.JSX.Element {+ const formatSpeed = useFormatSpeed()+ const speedUnit = useAppStore((store) => store.speedUnit)+ const speedLimit = useAppStore((store) => store.networkPreferences[group.id]?.speedLimit)const [expanded, setExpanded] = useState(false)const connections = group.transfer === 'http' ? group.streams : group.peersconst isActive =@@ -432,7 +468,21 @@ export function NetworkRow({style={{ color: isActive ? visual.text : 'var(--text-tertiary)' }}><TwoWay- down={isActive ? formatSpeed(group.speedBytesPerSec) : '—'}+ down={+ speedLimit === undefined ? (+ isActive ? (+ formatSpeed(group.speedBytesPerSec)+ ) : (+ '—'+ )+ ) : (+ <SpeedOfLimit+ speed={isActive ? group.speedBytesPerSec : 0}+ limit={speedLimit}+ unit={speedUnit}+ />+ )+ }// Like down: a dash while nothing is going out. Each direction is idle on its own.up={group.transfer === 'torrent' && group.uploadSpeedBytesPerSec > 0diff --git a/src/renderer/src/components/NetworksMenu.tsx b/src/renderer/src/components/NetworksMenu.tsxindex 85cfd56..5e2e5e2 100644--- a/src/renderer/src/components/NetworksMenu.tsx+++ b/src/renderer/src/components/NetworksMenu.tsx@@ -1,32 +1,32 @@import { ChevronDown, ChevronRight } from 'lucide-react'import { useState } from 'react'-import { useLatencyPolling, useNetworkUsage } from '../hooks/useNetworks'+import { useNetworkUsage } from '../hooks/useNetworks'import { useNetworkVisuals } from '../hooks/useNetworkVisuals'import { useAppStore } from '../store/useAppStore'-import { formatSpeed } from '../utils/format'-import { UsageBar } from './LimitsDialog'+import { useFormatSpeed, useFormatSpeedLimit } from '../hooks/useFormatSpeed'+import { formatDataUsage } from '../utils/format'import { NetworkEditPopover } from './NetworkEditPopover'import { Popover, PopoverContent, PopoverTrigger } from './ui/popover'import { Button } from './ui/button'-import { Switch } from './ui/switch'+import { TruncatedText } from './TruncatedText'-/** The networks new downloads combine, switched on or off here; each download can still change- * its own. Also how fast each is going right now, and how much of its data limit is left. */+/** Every network the computer has, one row each: on the left what it is (its name, the system's+ * name for it, the limits set on it), on the right what it's doing (its speed). Which+ * networks a download uses is picked in New download, which remembers the last pick. */export function NetworksMenu({onOpenLimits}: {/** Opens Speed & data limits on that network's page, or General for null. */onOpenLimits: (page: string | null) => void}): React.JSX.Element {+ const formatSpeed = useFormatSpeed()+ const formatSpeedLimit = useFormatSpeedLimit()const interfaces = useAppStore((store) => store.interfaces)const preferences = useAppStore((store) => store.networkPreferences)- const setNetworkPreference = useAppStore((store) => store.setNetworkPreference)const downloads = useAppStore((store) => store.downloads)const networkVisual = useNetworkVisuals()- const latencies = useAppStore((store) => store.latencies)const [open, setOpen] = useState(false)const usage = useNetworkUsage(open)- useLatencyPolling(open)// Every running download's speed over each network, added up.const speeds = new Map<string, number>()@@ -37,7 +37,6 @@ export function NetworksMenu({}}const total = [...speeds.values()].reduce((sum, speed) => sum + speed, 0)- const on = interfaces.filter((iface) => !preferences[iface.id]?.off)return (<Popover open={open} onOpenChange={setOpen}>@@ -49,10 +48,7 @@ export function NetworksMenu({<spankey={iface.id}className="size-2 rounded-full"- style={{- background: networkVisual(iface.id, iface.kind, iface.displayName).solid,- opacity: preferences[iface.id]?.off ? 0.3 : 1- }}+ style={{ background: networkVisual(iface.id, iface.kind, iface.displayName).solid }}/>))}</span>@@ -60,7 +56,7 @@ export function NetworksMenu({<span className="text-[var(--color-danger)]">No network</span>) : (<>- {on.length} {on.length === 1 ? 'network' : 'networks'}+ {interfaces.length} {interfaces.length === 1 ? 'network' : 'networks'}{total > 0 && (<span className="font-mono text-[11.5px] text-muted-foreground">{formatSpeed(total)}@@ -71,84 +67,89 @@ export function NetworksMenu({<ChevronDown className="size-3.5 text-muted-foreground" /></PopoverTrigger><PopoverContent align="end" className="w-[340px] gap-0 p-0">- <div className="flex flex-col gap-1.5 border-b-[0.5px] border-border p-4">- <div className="text-[14px] font-semibold">Default networks</div>- <div className="text-[12.5px] leading-snug text-[var(--text-secondary)]">- New downloads combine the networks turned on here. You can change this for any single- download.- </div>+ <div className="border-b-[0.5px] border-border px-4 py-3 text-[14px] font-semibold">+ Networks</div>{interfaces.map((iface) => {const visual = networkVisual(iface.id, iface.kind, iface.displayName)const preference = preferences[iface.id]const used = usage[iface.id] ?? 0+ const speedLimit = preference?.speedLimitconst dataLimit = preference?.dataLimitconst reached = dataLimit !== undefined && used >= dataLimitconst speed = speeds.get(iface.id) ?? 0+ const lineClass =+ 'col-start-2 col-span-2 truncate font-mono text-[11px] text-muted-foreground'return (<divkey={iface.id}// The whole row opens this network's limits (the chevron's button stretches over it);- // the switch and the pencil sit above it and do their own thing.- className="group relative flex flex-col gap-2 border-b-[0.5px] border-border px-4 py-3 hover:bg-muted"+ // the pencil and the badge sit above it and do their own thing.+ className="group relative grid grid-cols-[8px_minmax(0,1fr)_auto_16px] items-center gap-x-3 gap-y-1 border-b-[0.5px] border-border px-4 py-3 hover:bg-muted">- <div className="flex items-center gap-3">- <span- className="size-2 shrink-0 rounded-full"- style={{ background: visual.solid }}- />- <div className="flex min-w-0 flex-1 flex-col gap-1">- <div className="flex min-w-0 items-center gap-1">- <span className="truncate text-[13.5px] font-medium">{visual.name}</span>- <span className="relative z-10 flex">- <NetworkEditPopover- interfaceId={iface.id}- interfaceKind={iface.kind}- osName={iface.displayName}- />- </span>- </div>- <div- className={`font-mono text-[11px] ${reached ? 'text-[var(--color-danger)]' : 'text-muted-foreground'}`}- >- {reached- ? 'Data limit reached'- : [- iface.displayName,- speed > 0 ? formatSpeed(speed) : 'Idle',- typeof latencies[iface.id] === 'number' &&- `${Math.round(latencies[iface.id]!)} ms`- ]- .filter(Boolean)- .join(' · ')}- </div>- </div>- <Switch- className="relative z-10"- aria-label={`Use ${visual.name} for new downloads`}- checked={!preference?.off}- onCheckedChange={(checked) =>- setNetworkPreference(iface.id, { off: checked ? undefined : true })- }- />- <button- type="button"- aria-label={`${visual.name} limits`}- className="text-muted-foreground outline-none group-hover:text-foreground after:absolute after:inset-0 focus-visible:after:ring-2 focus-visible:after:ring-ring focus-visible:after:ring-inset"- onClick={() => {- setOpen(false)- onOpenLimits(iface.id)- }}- >- <ChevronRight className="size-4" />- </button>+ <span className="size-2 rounded-full" style={{ background: visual.solid }} />+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="truncate text-[13.5px] font-medium">{visual.name}</span>+ <span className="relative z-10 flex">+ <NetworkEditPopover+ interfaceId={iface.id}+ interfaceKind={iface.kind}+ osName={iface.displayName}+ />+ </span>+ {/* The system's own name for the adapter, beside the user's. A long one (a Windows+ driver name) is cut off, and only then is there a tooltip with all of it. */}+ <span className="relative z-10 flex max-w-[110px] min-w-0 shrink-0 rounded-[4px] border-[0.5px] border-border bg-foreground/5 px-1.5 font-mono text-[10.5px] text-muted-foreground">+ <TruncatedText text={iface.displayName} />+ </span>+ </div>+ {/* What it's doing: a used-up network is paused, which says why it carries nothing. */}+ <div+ className="text-right font-mono text-[12px] font-medium whitespace-nowrap text-muted-foreground"+ style={+ reached+ ? { color: 'var(--color-danger)' }+ : speed > 0+ ? { color: visual.text }+ : undefined+ }+ >+ {reached ? 'Paused' : speed > 0 ? formatSpeed(speed) : 'Idle'}</div>+ <button+ type="button"+ aria-label={`${visual.name} limits`}+ className="text-muted-foreground outline-none group-hover:text-foreground after:absolute after:inset-0 focus-visible:after:ring-2 focus-visible:after:ring-ring focus-visible:after:ring-inset"+ onClick={() => {+ setOpen(false)+ onOpenLimits(iface.id)+ }}+ >+ <ChevronRight className="size-4" />+ </button>+ {/* A line per limit set on it, as short as it can be said; none, and the row is one+ line. "Limit", not "Max": a max reads as what the network can do. */}+ {speedLimit !== undefined && (+ <div className={lineClass}>Limit {formatSpeedLimit(speedLimit)}</div>+ )}+ {/* The figure, then a bar for how much is left at a glance. The period and when it+ resets are a click away, in the limits the row opens. */}{dataLimit !== undefined && (- <UsageBar- used={used}- limit={dataLimit}- period={preference?.dataLimitPeriod ?? 'month'}- />+ <div+ className="col-span-2 col-start-2 flex items-center gap-3 font-mono text-[11px] text-muted-foreground"+ style={reached ? { color: 'var(--color-danger)' } : undefined}+ >+ <span className="shrink-0">{formatDataUsage(used, dataLimit)}</span>+ <span className="h-1 min-w-0 flex-1 overflow-hidden rounded-full bg-foreground/10">+ <span+ className="block h-full rounded-full"+ style={{+ width: `${Math.min(100, (used / dataLimit) * 100)}%`,+ background: reached ? 'var(--color-danger)' : visual.solid+ }}+ />+ </span>+ </div>)}</div>)diff --git a/src/renderer/src/components/NewDownloadDialog.tsx b/src/renderer/src/components/NewDownloadDialog.tsxindex 64fad65..052c95d 100644--- a/src/renderer/src/components/NewDownloadDialog.tsx+++ b/src/renderer/src/components/NewDownloadDialog.tsx@@ -2,6 +2,8 @@ import type { ProbeResult } from '@shared/types'import { cn } from 'cn'import { AlertTriangle, FolderOpen, X } from 'lucide-react'import { useEffect, useRef, useState } from 'react'+import { useFormatSpeedLimit } from '../hooks/useFormatSpeed'+import { useNetworkUsage } from '../hooks/useNetworks'import { useNetworkVisuals } from '../hooks/useNetworkVisuals'import { useAppStore } from '../store/useAppStore'import {@@ -65,11 +67,15 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element.length >= store.downloadsAtOnce)const networkVisual = useNetworkVisuals()+ const networkPreferences = useAppStore((store) => store.networkPreferences)+ const setNetworkPreference = useAppStore((store) => store.setNetworkPreference)+ const usage = useNetworkUsage(true)+ const formatSpeedLimit = useFormatSpeedLimit()const linkInput = useRef<HTMLInputElement>(null)const [probe, setProbe] = useState<ProbeState>({ status: 'idle' })// Tracks deselections rather than selections, so a newly-detected interface starts selected.- // Starts from the default networks: the ones switched off in the networks menu.+ // Starts from the last download's pick: the networks it left out are saved as `off`.const [deselectedInterfaceIds, setDeselectedInterfaceIds] = useState<string[]>(() =>Object.entries(useAppStore.getState().networkPreferences).filter(([, preference]) => preference.off)@@ -144,8 +150,24 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Elementconst isSingleStreamOnly = ready !== null && !multiChunkAllowedconst detectedIds = interfaces.map((iface) => iface.id)- const enabledIds = detectedIds.filter((id) => !deselectedInterfaceIds.includes(id))- const selectedInterfaceIds = isSingleStreamOnly ? enabledIds.slice(0, 1) : enabledIds+ // A network that has used up its data limit can't carry anything, so it can't be picked.+ const isReached = (id: string): boolean => {+ const dataLimit = networkPreferences[id]?.dataLimit+ return dataLimit !== undefined && (usage[id] ?? 0) >= dataLimit+ }+ const availableIds = detectedIds.filter((id) => !isReached(id))+ const pickedIds = availableIds.filter((id) => !deselectedInterfaceIds.includes(id))+ // The last pick may be all used up. Then nothing is picked, rather than what was left out: a+ // network left out is often left out on purpose (a phone's metered data), so it's chosen here+ // by hand, never stood in for the one that ran out.+ const selectedInterfaceIds = isSingleStreamOnly ? pickedIds.slice(0, 1) : pickedIds+ // The networks of the last pick that have used up their data, to say why nothing is picked.+ const usedUpPick =+ pickedIds.length === 0 && availableIds.length > 0+ ? interfaces.filter(+ (iface) => isReached(iface.id) && !deselectedInterfaceIds.includes(iface.id)+ )+ : []const canStart =probe.status === 'ready' &&@@ -183,6 +205,7 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element}const handleToggleInterface = (id: string): void => {+ if (isReached(id)) returnif (isSingleStreamOnly) {// Single-stream mode can only download through 1 interface at a timesetDeselectedInterfaceIds(detectedIds.filter((otherId) => otherId !== id))@@ -191,7 +214,7 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.ElementsetDeselectedInterfaceIds((prev) => {if (prev.includes(id)) return prev.filter((entry) => entry !== id)// Keep at least 1 interface selected- const remaining = detectedIds.filter((other) => !prev.includes(other) && other !== id)+ const remaining = availableIds.filter((other) => !prev.includes(other) && other !== id)return remaining.length === 0 ? prev : [...prev, id]})}@@ -236,6 +259,16 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.ElementstreamsPerNetwork: streamsChoice === 'auto' ? undefined : streamsChoice})+ // Remembered for the next download, like the folder. Not a single-stream pick: that's one+ // network because the file allows no more, not because the others were unwanted.+ if (!isSingleStreamOnly) {+ for (const id of availableIds) {+ const off = !selectedInterfaceIds.includes(id)+ if (off !== Boolean(networkPreferences[id]?.off)) {+ setNetworkPreference(id, { off: off || undefined })+ }+ }+ }// Started: the link is spent, so the next download starts from an empty one. Its own// screen opens, unless it was only added to the queue.useAppStore.setState({@@ -386,17 +419,28 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element{interfaces.map((iface) => {const visual = networkVisual(iface.id, iface.kind, iface.displayName)const selected = selectedInterfaceIds.includes(iface.id)- return (+ const reached = isReached(iface.id)+ const speedLimit = networkPreferences[iface.id]?.speedLimit+ // What's worth knowing before it's picked: it can't be, or it's capped.+ const note = reached+ ? 'Data limit reached'+ : speedLimit !== undefined+ ? `Limited to ${formatSpeedLimit(speedLimit)}`+ : null+ const chip = (<buttonkey={iface.id}type="button"aria-pressed={selected}+ // Not `disabled`: a disabled button never gets the hover that says why.+ aria-disabled={reached || undefined}onClick={() => handleToggleInterface(iface.id)}className={cn('flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-[12.5px] transition-colors',selected? 'border-transparent'- : 'border-border text-[var(--text-secondary)] opacity-70'+ : 'border-border text-[var(--text-secondary)] opacity-70',+ reached && 'cursor-not-allowed line-through opacity-50')}style={selected ? { background: visual.bg, borderColor: visual.border } : undefined@@ -406,6 +450,14 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element{visual.name}</button>)+ return note === null ? (+ chip+ ) : (+ <Tooltip key={iface.id}>+ <TooltipTrigger render={chip} />+ <TooltipContent>{note}</TooltipContent>+ </Tooltip>+ )})}</div></div>@@ -445,6 +497,23 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Elementcomputer sends both down one route and they can’t be combined.</div>)}+ {usedUpPick.length > 0 && (+ <div className="flex items-start gap-2 text-[12px] leading-snug text-[var(--color-usb-text)]">+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />+ {usedUpPick+ .map((iface) => networkVisual(iface.id, iface.kind, iface.displayName).name)+ .join(' and ')}{' '}+ {usedUpPick.length === 1 ? 'has' : 'have'} reached{' '}+ {usedUpPick.length === 1 ? 'its' : 'their'} data limit. Choose another network for this+ download.+ </div>+ )}+ {interfaces.length > 0 && availableIds.length === 0 && (+ <div className="flex items-start gap-2 text-[12px] leading-snug text-[var(--color-usb-text)]">+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />+ Every network has reached its data limit. Raise one in Speed & data limits.+ </div>+ )}{isSingleStreamOnly && selectedInterfaceIds.length === 1 && interfaces.length > 1 && (<div className="text-[12px] text-muted-foreground">This download uses one connection on one network.diff --git a/src/renderer/src/components/StatusBar.tsx b/src/renderer/src/components/StatusBar.tsxindex 8dad46e..3c34616 100644--- a/src/renderer/src/components/StatusBar.tsx+++ b/src/renderer/src/components/StatusBar.tsx@@ -1,18 +1,63 @@+import type { SpeedUnit } from '@shared/types'import { useEffect, useState } from 'react'import { useAppStore } from '../store/useAppStore'-import { formatBytes, formatSpeed } from '../utils/format'+import { formatBytes } from '../utils/format'+import { useFormatSpeedLimit } from '../hooks/useFormatSpeed'import { ScreenFooter } from './ScreenFooter'import { ThemeToggle } from './ThemeToggle'import { Switch } from './ui/switch'+import { ToggleGroup, ToggleGroupItem } from './ui/toggle-group'+import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'import { UpdateIndicator } from './UpdateIndicator'const FREE_SPACE_POLL_MS = 30_000-/** Along the bottom of every screen: how fast everything is going and under what limit, the- * queue, the slow mode switch, and the room left where downloads are saved. */+/** MB/s or Mbps for every speed in the app; sits with the theme toggle as a view preference. */+function SpeedUnitToggle(): React.JSX.Element {+ const speedUnit = useAppStore((store) => store.speedUnit)+ const setSpeedUnit = useAppStore((store) => store.setSpeedUnit)+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <ToggleGroup+ aria-label="Speed units"+ value={[speedUnit]}+ onValueChange={(values) => {+ // Clicking the pressed one would unpress it; one unit is always on.+ if (values[0] !== undefined) setSpeedUnit(values[0] as SpeedUnit)+ }}+ size="xs"+ spacing={0.5}+ className="h-[26px] rounded-[6px] border-[0.5px] border-border p-0.5 [-webkit-app-region:no-drag]"+ >+ {(['bytes', 'bits'] as const).map((unit) => (+ <ToggleGroupItem+ key={unit}+ value={unit}+ className="h-full rounded-[4px] px-1.5 font-mono text-[11px] font-medium text-muted-foreground aria-pressed:bg-background aria-pressed:text-foreground"+ >+ {unit === 'bytes' ? 'MB/s' : 'Mbps'}+ </ToggleGroupItem>+ ))}+ </ToggleGroup>+ }+ />+ <TooltipContent>Speed units</TooltipContent>+ </Tooltip>+ )+}++/** Along the bottom of every screen: the room left where downloads are saved, the queue, the+ * slow mode switch, and view preferences. Speeds and their limits are left to the screens that+ * show them — repeated down here they only doubled up, or read as a limit with no cause. */export function StatusBar(): React.JSX.Element {- const downloads = useAppStore((store) => store.downloads)- const speedLimit = useAppStore((store) => store.speedLimit)+ const formatSpeedLimit = useFormatSpeedLimit()+ // A count, not the downloads: progress ticks don't re-render the footer.+ const waiting = useAppStore(+ (store) =>+ Object.values(store.downloads).filter((download) => download.status === 'queued').length+ )const slowMode = useAppStore((store) => store.slowMode)const slowModeSpeed = useAppStore((store) => store.slowModeSpeed)const setSlowMode = useAppStore((store) => store.setSlowMode)@@ -35,36 +80,32 @@ export function StatusBar(): React.JSX.Element {}}, [destinationDir])- let speed = 0- let waiting = 0- for (const download of Object.values(downloads)) {- if (download.status === 'downloading') speed += download.speedBytesPerSec- if (download.status === 'queued') waiting++- }- const limit = slowMode ? slowModeSpeed : speedLimit+ // Limits show by the speeds they cap (the Downloading screen, the networks menu), not here.+ const status = [+ free !== null && `${formatBytes(free)} free`,+ waiting > 0 && `${waiting} waiting`+ ].filter(Boolean)return (<ScreenFooter className="gap-4 font-mono text-[11.5px] text-muted-foreground">- {/* At rest it says nothing: a zero speed or an empty queue only reads as broken. */}- {(speed > 0 || limit !== undefined) && (- <span className="tabular-nums">- {speed > 0 && (- <>- ↓ <span className="text-foreground">{formatSpeed(speed)}</span>- </>- )}- {limit !== undefined && `${speed > 0 ? ' · ' : ''}limit ${formatSpeed(limit)}`}- </span>- )}- {waiting > 0 && <span>{waiting} waiting in the queue</span>}- <div className="flex-1" />- <label className="flex items-center gap-2">- Slow mode- <Switch checked={slowMode} onCheckedChange={setSlowMode} />- </label>- {free !== null && <span>{formatBytes(free)} free</span>}- <UpdateIndicator />- <ThemeToggle />+ <span className="min-w-0 flex-1 truncate tabular-nums">{status.join(' · ')}</span>+ {/* Controls, most-flipped first: the edge holds the set-once view preferences. */}+ <div className="flex shrink-0 items-center gap-3">+ <UpdateIndicator />+ <Tooltip>+ <TooltipTrigger+ render={+ <label className="flex items-center gap-2">+ Slow mode+ <Switch checked={slowMode} onCheckedChange={setSlowMode} />+ </label>+ }+ />+ <TooltipContent>Limit downloads to {formatSpeedLimit(slowModeSpeed)}</TooltipContent>+ </Tooltip>+ <SpeedUnitToggle />+ <ThemeToggle />+ </div></ScreenFooter>)}diff --git a/src/renderer/src/components/ThroughputChart.tsx b/src/renderer/src/components/ThroughputChart.tsxindex 631816f..b583264 100644--- a/src/renderer/src/components/ThroughputChart.tsx+++ b/src/renderer/src/components/ThroughputChart.tsx@@ -1,19 +1,33 @@-import { formatSpeed } from '../utils/format'+import { SPEED_HISTORY_SECONDS } from '@shared/types'+import { useState } from 'react'+import { useFormatSpeed } from '../hooks/useFormatSpeed'+import { useAppStore } from '../store/useAppStore'+import { speedTicks } from '../utils/format'const WIDTH = 560const HEIGHT = 130+const labelClass = 'font-mono text-[9px] leading-none text-muted-foreground tabular-nums'interface ThroughputChartProps {- order: Array<{ interfaceId: string; solid: string }>+ order: Array<{ interfaceId: string; solid: string; name: string }>historyByInterface: Record<string, number[]>+ /** Where the minute ends: now, or — the history only grows while it downloads — where it+ * paused, or where it finished. So a paused download's last speed never reads as "now". */+ endsAt?: 'now' | 'pause' | 'end'}/** Stacked area chart of recent throughput, split by physical network — the "whole divided- * by each physical network" readout from design v2, instead of one line per connection. */+ * by each physical network" readout from design v2, instead of one line per connection. A scale+ * to read it by, a time axis, and on hover every network's speed at that second. */export function ThroughputChart({order,- historyByInterface+ historyByInterface,+ endsAt = 'now'}: ThroughputChartProps): React.JSX.Element {+ const formatSpeed = useFormatSpeed()+ const speedUnit = useAppStore((store) => store.speedUnit)+ // The second under the pointer, as a slot of the minute (0 = a minute ago, last = now).+ const [hovered, setHovered] = useState<number | null>(null)const length = Math.max(0,...order.map((entry) => historyByInterface[entry.interfaceId]?.length ?? 0)@@ -22,20 +36,27 @@ export function ThroughputChart({const totals = Array.from({ length }, (_, i) =>order.reduce((sum, entry) => sum + (historyByInterface[entry.interfaceId]?.[i] ?? 0), 0))- const max = Math.max(1, ...totals)+ // Round steps to read values off, the top just clearing the fastest second: it moves less than+ // a scale topped by the data itself, and every gridline means a number.+ const { top, ticks } = speedTicks(Math.max(0, ...totals), speedUnit)// Fewer than two samples draws no area at all — but the empty gridlines still render, so the// chart keeps its height. It's the tallest thing in the hero band, and bailing out to `null`// for the first second of a download (or after a resume re-keys the history) collapsed the// band and shoved the whole screen up, then back down again.- const xStep = length > 1 ? WIDTH / (length - 1) : WIDTH- const toY = (value: number): number => HEIGHT - (value / max) * HEIGHT+ // A fixed minute, newest at the right edge, as Activity Monitor and Task Manager draw it: a+ // second is always the same width, so the shape only scrolls, and the first few seconds sit at+ // the right with the rest still empty instead of being stretched across the whole chart.+ const xStep = WIDTH / (SPEED_HISTORY_SECONDS - 1)+ const firstSlot = SPEED_HISTORY_SECONDS - length+ const firstX = firstSlot * xStep+ const toY = (value: number): number => HEIGHT - (value / top) * HEIGHTinterface Layer {solid: stringpoints: string}const toPoint = (value: number, i: number): string =>- `${(i * xStep).toFixed(1)},${toY(value).toFixed(1)}`+ `${(firstX + i * xStep).toFixed(1)},${toY(value).toFixed(1)}`const { layers } = order.reduce<{ cumulative: number[]; layers: Layer[] }>((acc, entry) => {const series = historyByInterface[entry.interfaceId] ?? []@@ -47,35 +68,131 @@ export function ThroughputChart({{ cumulative: new Array<number>(length).fill(0), layers: [] })- const outline = totals- .map((value, i) => `${(i * xStep).toFixed(1)},${toY(value).toFixed(1)}`)- .join(' ')+ const outline = totals.map(toPoint).join(' ')const peakTotal = Math.max(0, ...totals)const latestTotal = totals[totals.length - 1] ?? 0+ // Only a second that has a sample shows a readout: before the download's first, there's none.+ const sample = hovered === null ? -1 : hovered - firstSlot+ const readout = sample >= 0 && sample < length ? sample : null+ const slotPercent = (slot: number): string => `${(slot / (SPEED_HISTORY_SECONDS - 1)) * 100}%`+ const secondsAgo = SPEED_HISTORY_SECONDS - 1 - (hovered ?? 0)+return (- <svg- viewBox={`0 0 ${WIDTH} ${HEIGHT}`}- preserveAspectRatio="none"- className="mt-[7px] block h-[104px] w-full"- role="img"- aria-label={`Combined throughput over time. Currently ${formatSpeed(latestTotal)}, peak ${formatSpeed(peakTotal)}.`}- >- <g stroke="var(--border)" strokeWidth={1}>- <line x1={0} y1={HEIGHT * 0.33} x2={WIDTH} y2={HEIGHT * 0.33} />- <line x1={0} y1={HEIGHT * 0.66} x2={WIDTH} y2={HEIGHT * 0.66} />- </g>- {layers.map((layer, index) => (- <polygon key={index} points={layer.points} fill={layer.solid} fillOpacity={0.62} />- ))}- <polyline- points={outline}- fill="none"- stroke="var(--node-accent)"- strokeWidth={2}- strokeOpacity={0.85}- />- </svg>+ // Clear of the heading above: the top label centres on the top gridline, so it rises above it.+ <div className="mt-4 flex gap-2">+ {/* The scale, beside the plot rather than over the fills, where it would be hard to read.+ Each number with its unit, so any one reads on its own. */}+ <div className="shrink-0 text-right">+ <div className="relative h-[104px]">+ {/* The widest label, invisible, gives the column its width. */}+ <span className={`invisible block ${labelClass}`}>{ticks.at(-1)?.label}</span>+ {ticks.map((tick) => (+ <span+ key={tick.value}+ className={`absolute right-0 -translate-y-1/2 ${labelClass}`}+ style={{ top: `${(1 - tick.value / top) * 100}%` }}+ >+ {tick.label}+ </span>+ ))}+ </div>+ </div>+ <div className="min-w-0 flex-1">+ <div+ className="relative h-[104px]"+ onPointerMove={(event) => {+ const box = event.currentTarget.getBoundingClientRect()+ const fraction = Math.min(1, Math.max(0, (event.clientX - box.left) / box.width))+ setHovered(Math.round(fraction * (SPEED_HISTORY_SECONDS - 1)))+ }}+ onPointerLeave={() => setHovered(null)}+ >+ <svg+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}+ preserveAspectRatio="none"+ className="block h-full w-full"+ role="img"+ aria-label={`Combined throughput over the last minute. Currently ${formatSpeed(latestTotal)}, fastest ${formatSpeed(peakTotal)}.`}+ >+ {/* Muted ink at low opacity: quiet but seen in either theme, where --border all but+ vanished against the dark band. */}+ <g+ className="text-muted-foreground"+ stroke="currentColor"+ strokeOpacity={0.3}+ strokeWidth={1}+ vectorEffect="non-scaling-stroke"+ >+ {ticks.map((tick) => (+ <line+ key={tick.value}+ x1={0}+ y1={toY(tick.value)}+ x2={WIDTH}+ y2={toY(tick.value)}+ vectorEffect="non-scaling-stroke"+ />+ ))}+ </g>+ {layers.map((layer, index) => (+ <polygon key={index} points={layer.points} fill={layer.solid} fillOpacity={0.62} />+ ))}+ <polyline+ points={outline}+ fill="none"+ stroke="var(--node-accent)"+ strokeWidth={2}+ strokeOpacity={0.85}+ vectorEffect="non-scaling-stroke"+ />+ </svg>+ {readout !== null && hovered !== null && (+ <>+ <div+ className="pointer-events-none absolute inset-y-0 w-px bg-foreground/40"+ style={{ left: slotPercent(hovered) }}+ />+ {/* Every network at that second, so the pointer needn't land on a fill; on the side+ away from the edge it would run off. */}+ <div+ className="pointer-events-none absolute top-0 z-10 flex min-w-[150px] flex-col gap-1 rounded-md border-[0.5px] border-border bg-popover px-2.5 py-2 font-mono text-[11px] tabular-nums shadow-md"+ style={+ hovered > (SPEED_HISTORY_SECONDS - 1) / 2+ ? { right: `calc(100% - ${slotPercent(hovered)} + 8px)` }+ : { left: `calc(${slotPercent(hovered)} + 8px)` }+ }+ >+ <span className="text-[10px] text-muted-foreground">+ {secondsAgo === 0+ ? `${endsAt[0].toUpperCase()}${endsAt.slice(1)}`+ : `${secondsAgo}s ${endsAt === 'now' ? 'ago' : `before the ${endsAt}`}`}+ </span>+ {order.map((entry) => (+ <span key={entry.interfaceId} className="flex items-center gap-2">+ <span className="size-2 rounded-full" style={{ background: entry.solid }} />+ <span className="flex-1 truncate font-sans text-[11.5px]">{entry.name}</span>+ {formatSpeed(historyByInterface[entry.interfaceId]?.[readout] ?? 0)}+ </span>+ ))}+ {order.length > 1 && (+ <span className="flex items-center gap-2 border-t-[0.5px] border-border pt-1">+ <span className="flex-1 font-sans text-[11.5px]">Total</span>+ {formatSpeed(totals[readout])}+ </span>+ )}+ </div>+ </>+ )}+ </div>+ <div className={`mt-1 flex justify-between ${labelClass}`}>+ <span>+ {SPEED_HISTORY_SECONDS}s {endsAt === 'now' ? 'ago' : `before the ${endsAt}`}+ </span>+ <span>{endsAt}</span>+ </div>+ </div>+ </div>)}diff --git a/src/renderer/src/hooks/useFormatSpeed.ts b/src/renderer/src/hooks/useFormatSpeed.tsnew file mode 100644index 0000000..88bd340--- /dev/null+++ b/src/renderer/src/hooks/useFormatSpeed.ts@@ -0,0 +1,14 @@+import { useAppStore } from '../store/useAppStore'+import { formatSpeed, formatSpeedLimit } from '../utils/format'++/** formatSpeed in the unit picked in the footer; re-renders the caller when it changes. */+export function useFormatSpeed(): (bytesPerSec: number) => string {+ const unit = useAppStore((store) => store.speedUnit)+ return (bytesPerSec) => formatSpeed(bytesPerSec, unit)+}++/** formatSpeedLimit in the unit picked in the footer: for limits, which read as round figures. */+export function useFormatSpeedLimit(): (bytesPerSec: number) => string {+ const unit = useAppStore((store) => store.speedUnit)+ return (bytesPerSec) => formatSpeedLimit(bytesPerSec, unit)+}diff --git a/src/renderer/src/hooks/useNetworks.ts b/src/renderer/src/hooks/useNetworks.tsindex 37ffc66..1da2d8c 100644--- a/src/renderer/src/hooks/useNetworks.ts+++ b/src/renderer/src/hooks/useNetworks.ts@@ -1,8 +1,6 @@import { useEffect, useState } from 'react'import { useAppStore } from '../store/useAppStore'-const LATENCY_POLL_MS = 5000-/** Keeps the network list current for the lifetime of the app: the main process watches the* networks and says whenever one comes, goes or changes. */export function useNetworkEvents(): void {@@ -16,18 +14,6 @@ export function useNetworkEvents(): void {}, [loadInterfaces, receiveInterfaces])}-/** Keeps each network's latency readout fresh while `active` (something showing it is open). */-export function useLatencyPolling(active: boolean): void {- const refreshLatencies = useAppStore((store) => store.refreshLatencies)-- useEffect(() => {- if (!active) return- void refreshLatencies()- const interval = setInterval(refreshLatencies, LATENCY_POLL_MS)- return () => clearInterval(interval)- }, [active, refreshLatencies])-}-const USAGE_POLL_MS = 2000/** What each network has received in its selected calendar period, by id, kept fresh while `active` (a screen thatdiff --git a/src/renderer/src/screens/CompleteScreen.tsx b/src/renderer/src/screens/CompleteScreen.tsxindex ae89d43..5f7a770 100644--- a/src/renderer/src/screens/CompleteScreen.tsx+++ b/src/renderer/src/screens/CompleteScreen.tsx@@ -10,10 +10,10 @@ import {dirnameOf,formatBytes,formatDuration,- formatSpeed,toDisplayPath,wantedBytes} from '../utils/format'+import { useFormatSpeed } from '../hooks/useFormatSpeed'const sectionHeaderClass ='font-mono text-[10px] leading-none tracking-[0.16em] text-muted-foreground uppercase'@@ -24,6 +24,7 @@ export function CompleteScreen({/** Just finished, or as history keeps it. */download: DownloadState | FinishedDownload}): React.JSX.Element {+ const formatSpeed = useFormatSpeed()const homeDir = useAppStore((store) => store.homeDir)const networkVisual = useNetworkVisuals()const missing = 'missing' in download && download.missing === true@@ -147,8 +148,13 @@ export function CompleteScreen({<div className="mx-5 mb-4 flex flex-col gap-2"><h2 className={sectionHeaderClass}>Speed over the download</h2><ThroughputChart- order={groups.map((g, i) => ({ interfaceId: g.id, solid: visuals[i].solid }))}+ order={groups.map((g, i) => ({+ interfaceId: g.id,+ solid: visuals[i].solid,+ name: visuals[i].name+ }))}historyByInterface={download.speedHistory ?? {}}+ endsAt="end"/></div>diff --git a/src/renderer/src/screens/DownloadingScreen.tsx b/src/renderer/src/screens/DownloadingScreen.tsxindex b5b434b..97aeeb6 100644--- a/src/renderer/src/screens/DownloadingScreen.tsx+++ b/src/renderer/src/screens/DownloadingScreen.tsx@@ -1,4 +1,4 @@-import type { DownloadState } from '@shared/types'+import { SPEED_HISTORY_SECONDS, type DownloadState } from '@shared/types'import { Folder } from 'lucide-react'import { memo, useEffect, useState } from 'react'import { BlockGrid } from '../components/BlockGrid'@@ -25,14 +25,13 @@ import {formatBytes,formatEta,formatPercent,- formatSpeed,groupByNetwork,isFolder,networksInPlay,- splitFormattedBytes,toDisplayPath,wantedBytes} from '../utils/format'+import { useFormatSpeed, useFormatSpeedLimit } from '../hooks/useFormatSpeed'/** Inline "·" separator between adjacent stats. `shrink` pins it at its natural width inside a* flex row that might otherwise squeeze it (footer rows), matching each call site's prior style. */@@ -103,7 +102,12 @@ export const DownloadingScreen = memo(function DownloadingScreen({}: {download: DownloadState}): React.JSX.Element {+ const formatSpeed = useFormatSpeed()+ const formatSpeedLimit = useFormatSpeedLimit()const homeDir = useAppStore((store) => store.homeDir)+ const speedLimit = useAppStore((store) => store.speedLimit)+ const slowMode = useAppStore((store) => store.slowMode)+ const slowModeSpeed = useAppStore((store) => store.slowModeSpeed)const speedHistory = download.speedHistory ?? {}const peakSpeedBytesPerSec = download.peakSpeedBytesPerSecconst networkVisual = useNetworkVisuals()@@ -161,7 +165,14 @@ export const DownloadingScreen = memo(function DownloadingScreen({}const effectiveSpeed = isPaused ? 0 : download.speedBytesPerSec- const speed = splitFormattedBytes(effectiveSpeed)+ const [speedValue, speedUnit] = formatSpeed(effectiveSpeed).split(' ')+ // The cap over every download, beside the speed it holds down — slow mode named, so a low+ // number explains itself.+ const speedCap = slowMode+ ? ` · SLOW MODE ${formatSpeedLimit(slowModeSpeed)}`+ : speedLimit !== undefined+ ? ` · LIMIT ${formatSpeedLimit(speedLimit)}`+ : ''// Every network is a row, for switching it on or off; the charts draw only those in play.const rows = groupByNetwork(download)const rowVisuals = rows.map((row) => networkVisual(row.id, row.kind, row.label))@@ -209,9 +220,7 @@ export const DownloadingScreen = memo(function DownloadingScreen({? { label: isQueued ? 'QUEUED' : 'PAUSED', palette: KIND_PALETTE.usb }: null- const throughputStatusLabel = isPaused- ? null- : `LAST ${Object.values(speedHistory)[0]?.length ?? 0}S`+ const throughputStatusLabel = isPaused ? null : `LAST ${SPEED_HISTORY_SECONDS}S`const pauseResumeLabel = resuming ? 'Resuming…' : isPaused && !isQueued ? 'Resume' : 'Pause'return (@@ -228,6 +237,8 @@ export const DownloadingScreen = memo(function DownloadingScreen({</DetailHeader>{/* Hero band — always visible under the header */}<HeroBand>+ {/* At their designed size: a wider window opens a gap between the speed and the chart+ (ml-auto) rather than stretching the merge into rails or the chart into a ribbon. */}<div className="flex items-center gap-[14px]"><CombineDiagramnetworks={groups.map((group, index) => ({@@ -241,9 +252,9 @@ export const DownloadingScreen = memo(function DownloadingScreen({<div className="flex min-w-[130px] shrink-0 flex-col gap-[7px]"><><BigStat- label="TOTAL SPEED"- value={isPaused ? '—' : speed.value}- unit={isPaused ? undefined : `${speed.unit}/s`}+ label={`TOTAL SPEED${speedCap}`}+ value={isPaused ? '—' : speedValue}+ unit={isPaused ? undefined : speedUnit}valueClass={isPaused ? 'text-muted-foreground' : 'text-foreground'}/><div className="flex items-center gap-2 font-mono text-[10px] leading-none font-medium tabular-nums text-muted-foreground">@@ -281,7 +292,7 @@ export const DownloadingScreen = memo(function DownloadingScreen({</div><div- className={`min-w-0 flex-1 transition-opacity duration-200 ${+ className={`ml-auto min-w-0 max-w-[640px] flex-1 transition-opacity duration-200 ${isPaused ? 'opacity-45' : 'opacity-100'}`}>@@ -291,9 +302,11 @@ export const DownloadingScreen = memo(function DownloadingScreen({<ThroughputChartorder={groups.map((g, i) => ({interfaceId: g.id,- solid: visuals[i].solid+ solid: visuals[i].solid,+ name: visuals[i].name}))}historyByInterface={speedHistory}+ endsAt={isPaused ? 'pause' : 'now'}/></div></div>diff --git a/src/renderer/src/screens/DownloadsScreen.tsx b/src/renderer/src/screens/DownloadsScreen.tsxindex ca5d71e..b507d98 100644--- a/src/renderer/src/screens/DownloadsScreen.tsx+++ b/src/renderer/src/screens/DownloadsScreen.tsx@@ -1,4 +1,4 @@-import type { DownloadState, FinishedDownload, NetworkPreferences } from '@shared/types'+import type { DownloadState, FinishedDownload } from '@shared/types'import { ChevronRight, Pause, Play, Plus, RotateCw, X, type LucideIcon } from 'lucide-react'import { cn } from 'cn'import { Fragment, memo, useCallback, useEffect, useState } from 'react'@@ -30,13 +30,13 @@ import {formatBytes,formatEta,formatPercent,- formatSpeed,formatWhen,isFolder,linkExpired,sourceOf,wantedBytes} from '../utils/format'+import { useFormatSpeed } from '../hooks/useFormatSpeed'type Item = DownloadState | FinishedDownload@@ -144,7 +144,6 @@ export function DownloadsScreen(): React.JSX.Element {)// Stable, with the colors resolved once here, so a finished row skips every progress push.const networkVisual = useNetworkVisuals()- const networkPreferences = useAppStore((store) => store.networkPreferences)const selectRow = useCallback((id: string, on: boolean) => toggle([id], on), [toggle])const openRow = useCallback((id: string) => setView({ name: 'download', id }), [setView])const fixRow = useCallback((item: Item) => {@@ -434,7 +433,6 @@ export function DownloadsScreen(): React.JSX.Element {networkVisual={isFinished(item) || item.status === 'completed' ? undefined : networkVisual}- networkPreferences={networkPreferences}onSelect={selectRow}onOpen={openRow}onFix={fixRow}@@ -559,7 +557,6 @@ const DownloadRow = memo(function DownloadRow({now,selected,networkVisual,- networkPreferences,onSelect,onOpen,onFix,@@ -570,13 +567,12 @@ const DownloadRow = memo(function DownloadRow({selected: boolean/** Colors its progress bar and network dots; a finished row has none. */networkVisual?: ResolveNetworkVisual- /** The default networks (the networks menu), to tell a download set otherwise. */- networkPreferences: NetworkPreferencesonSelect: (id: string, on: boolean) => voidonOpen: (id: string) => voidonFix: (item: Item) => voidonAgain: (item: Item) => void}): React.JSX.Element {+ const formatSpeed = useFormatSpeed()const finished = isFinished(item) || item.status === 'completed'const badge = isFolder(item) ? 'DIR' : fileExtensionBadge(item.fileName)const wanted = wantedBytes(item)@@ -667,15 +663,13 @@ const DownloadRow = memo(function DownloadRow({color: networkVisual(network.id, network.kind, network.label).solid}))- // Set apart from the default networks: which it's on, at a glance. One on the defaults says+ // Which networks it's on, at a glance, when it isn't on all of them. One on every network says// nothing new, so it shows none.const dots =!finished &&networkVisual &&!isFinished(item) &&- item.networks.some(- (network) => network.enabled === Boolean(networkPreferences[network.id]?.off)- )+ item.networks.some((network) => !network.enabled)? item.networks.map((network) => {const visual = networkVisual(network.id, network.kind, network.label)return {diff --git a/src/renderer/src/store/useAppStore.ts b/src/renderer/src/store/useAppStore.tsindex e036d49..ba25b62 100644--- a/src/renderer/src/store/useAppStore.ts+++ b/src/renderer/src/store/useAppStore.ts@@ -7,6 +7,7 @@ import type {NetworkInterfaceInfo,NetworkPreference,NetworkPreferences,+ SpeedUnit,ThemeSource,UpdateInfo} from '@shared/types'@@ -23,7 +24,6 @@ interface AppStore {interfaces: NetworkInterfaceInfo[]interfacesStatus: LoadStatusinterfacesError: string | null- latencies: Record<string, number | null>/** User customizations (name/color) per network interface id — persisted in the main process. */networkPreferences: NetworkPreferences@@ -52,6 +52,8 @@ interface AppStore {speedLimit: number | undefinedslowMode: booleanslowModeSpeed: number+ /** Persisted — MB/s or Mbps, for every speed shown. */+ speedUnit: SpeedUnit/** Lifted out of the Idle screen so it survives a swap to/from the No-connections screen. */draftUrl: string@@ -63,7 +65,6 @@ interface AppStore {/** Asks the main process for the network list now; it also pushes every change. */loadInterfaces: () => Promise<void>receiveInterfaces: (interfaces: NetworkInterfaceInfo[]) => void- refreshLatencies: () => Promise<void>setNetworkPreference: (id: string, patch: NetworkPreference) => voidsetThemeSource: (source: ThemeSource) => voidcheckForUpdate: () => Promise<void>@@ -83,6 +84,7 @@ interface AppStore {setSpeedLimit: (bytesPerSec: number | undefined) => voidsetSlowMode: (on: boolean) => voidsetSlowModeSpeed: (bytesPerSec: number) => void+ setSpeedUnit: (unit: SpeedUnit) => voidsetDraftUrl: (url: string) => voidsetDestinationDir: (dir: string) => void}@@ -101,7 +103,6 @@ export const useAppStore = create<AppStore>((set, get) => ({interfaces: [],interfacesStatus: 'idle',interfacesError: null,- latencies: {},networkPreferences: initial.networkPreferences,themeSource: initial.themeSource,availableUpdate: null,@@ -119,6 +120,7 @@ export const useAppStore = create<AppStore>((set, get) => ({speedLimit: initial.speedLimit,slowMode: initial.slowMode,slowModeSpeed: initial.slowModeSpeed,+ speedUnit: initial.speedUnit,draftUrl: '',startedUrl: '',@@ -141,15 +143,6 @@ export const useAppStore = create<AppStore>((set, get) => ({receiveInterfaces: (interfaces) =>set({ interfaces, interfacesStatus: 'ready', interfacesError: null }),- refreshLatencies: async () => {- try {- const latencies = await window.plexo.pingInterfaces()- set({ latencies })- } catch {- // Latency is a nice-to-have readout — a failed probe just leaves stale values.- }- },-// An explicit `undefined` in `patch` clears that field; main drops an entry left with neither.setNetworkPreference: (id, patch) => {const networkPreferences = {@@ -232,6 +225,11 @@ export const useAppStore = create<AppStore>((set, get) => ({persist({ slowModeSpeed })},+ setSpeedUnit: (speedUnit) => {+ set({ speedUnit })+ persist({ speedUnit })+ },+setDraftUrl: (draftUrl) => set({ draftUrl }),setDestinationDir: (destinationDir) => {set({ destinationDir })diff --git a/src/renderer/src/utils/format.ts b/src/renderer/src/utils/format.tsindex fb9634b..bf79029 100644--- a/src/renderer/src/utils/format.ts+++ b/src/renderer/src/utils/format.ts@@ -4,6 +4,7 @@ import type {FinishedDownload,HttpDownloadNetwork,HttpDownloadState,+ SpeedUnit,TorrentDownloadNetwork,TorrentDownloadState} from '@shared/types'@@ -21,8 +22,89 @@ export function formatBytes(bytes: number): string {return `${value.toFixed(exponent === 0 ? 0 : 1)} ${UNITS[exponent]}`}-export function formatSpeed(bytesPerSec: number): string {- return `${formatBytes(bytesPerSec)}/s`+const BIT_UNITS = ['bps', 'Kbps', 'Mbps', 'Gbps', 'Tbps']++/** Bits count in thousands, as internet plans and speed tests do — not the 1024s of formatBytes. */+export function formatSpeed(bytesPerSec: number, unit: SpeedUnit): string {+ if (unit === 'bytes') return `${formatBytes(bytesPerSec)}/s`+ const bits = Number.isFinite(bytesPerSec) && bytesPerSec > 0 ? bytesPerSec * 8 : 0+ let exponent = bits < 1 ? 0 : Math.min(Math.floor(Math.log10(bits) / 3), BIT_UNITS.length - 1)+ // Whole numbers from 100 up: Mbps runs about 8x the digits of MB/s, so "943.2" would only jitter.+ const digits = (value: number): number => (exponent === 0 || value >= 99.95 ? 0 : 1)+ let value = bits / 1000 ** exponent+ if (exponent < BIT_UNITS.length - 1 && Number(value.toFixed(digits(value))) >= 1000) {+ exponent += 1+ value = bits / 1000 ** exponent+ }+ return `${value.toFixed(digits(value))} ${BIT_UNITS[exponent]}`+}++// Bytes a second in each unit formatSpeed reads in.+const SPEED_UNIT_BYTES: Record<string, number> = {+ 'B/s': 1,+ 'KB/s': 1024,+ 'MB/s': 1024 ** 2,+ 'GB/s': 1024 ** 3,+ 'TB/s': 1024 ** 4,+ bps: 1 / 8,+ Kbps: 1e3 / 8,+ Mbps: 1e6 / 8,+ Gbps: 1e9 / 8,+ Tbps: 1e12 / 8+}++/** A speed axis for speeds up to `max`: 2 or 3 gridlines at round steps (1, 2, 2.5 or 5 × 10ⁿ) in+ * the unit formatSpeed would read `max` in, the top one just clearing it, each labelled with it. */+export function speedTicks(+ max: number,+ unit: SpeedUnit+): { top: number; ticks: { value: number; label: string }[] } {+ if (!(max > 0)) return { top: 1, ticks: [] }+ const label = formatSpeed(max, unit).split(' ')[1]+ const size = SPEED_UNIT_BYTES[label]+ const third = max / size / 3+ const power = 10 ** Math.floor(Math.log10(third))+ const step = [1, 2, 2.5, 5, 10].map((m) => m * power).find((s) => s >= third)!+ const count = Math.ceil(max / size / step)+ const ticks = Array.from({ length: count }, (_, i) => {+ const value = Number(((i + 1) * step).toFixed(2))+ return { value: value * size, label: `${value} ${label}` }+ })+ return { top: count * step * size, ticks }+}++/** A speed someone set, as a round figure: whole from 10 up, never a trailing ".0". 58.7 Mbps+ * reads as something measured; 59 Mbps as something chosen. */+export function formatSpeedLimit(bytesPerSec: number, unit: SpeedUnit): string {+ const [value, label] = formatSpeed(bytesPerSec, unit).split(' ')+ const number = Number(value)+ return `${number >= 10 ? Math.round(number) : number} ${label}`+}++/** "11.7 of 50 GB": data used against a data limit, the unit said once when both share it. The+ * limit is a set figure, so no ".0" on it. */+export function formatDataUsage(used: number, limit: number): string {+ const max = formatBytes(limit).replace('.0 ', ' ')+ const [rounded, unit] = formatBytes(used).split(' ')+ // Down, not to the nearest: 4.96 GB of a 5 GB limit read "5.0 of 5 GB" while data was left.+ const exponent = UNITS.indexOf(unit)+ const value =+ exponent === 0 ? rounded : (Math.floor((used / 1024 ** exponent) * 10) / 10).toFixed(1)+ return max.endsWith(` ${unit}`) ? `${value} of ${max}` : `${value} ${unit} of ${max}`+}++/** A speed against its limit, ["8.0", "10 MB/s"] for "8.0 / 10 MB/s": the unit said once+ * when both share it. Split so the limit can be set in a quieter color. No speed reads "—". */+export function formatSpeedOfLimit(+ bytesPerSec: number,+ limit: number,+ unit: SpeedUnit+): [string, string] {+ const max = formatSpeedLimit(limit, unit)+ if (bytesPerSec <= 0) return ['—', max]+ const speed = formatSpeed(bytesPerSec, unit)+ const [value, speedUnit] = speed.split(' ')+ return [max.endsWith(` ${speedUnit}`) ? value : speed, max]}export function formatEta(seconds: number): string {@@ -118,12 +200,6 @@ export function formatDuration(seconds: number): string {return `${mins}:${String(secs).padStart(2, '0')}`}-/** "12.3 MB" -> { value: "12.3", unit: "MB" } — for readouts that size the number and unit separately. */-export function splitFormattedBytes(bytes: number): { value: string; unit: string } {- const [value, unit] = formatBytes(bytes).split(' ')- return { value, unit }-}-export function dirnameOf(path: string): string {const index = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))if (index < 0) return '.'diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.tsindex 83ac514..52c28e9 100644--- a/src/shared/ipc-channels.ts+++ b/src/shared/ipc-channels.ts@@ -1,6 +1,5 @@export const IpcChannels = {listInterfaces: 'network:list-interfaces',- pingInterfaces: 'network:ping-interfaces',deviceBindingSupported: 'network:device-binding-supported',openNetworkSettings: 'network:open-settings',probeUrl: 'download:probe',diff --git a/src/shared/ipc-contract.ts b/src/shared/ipc-contract.tsindex c988727..ed77d43 100644--- a/src/shared/ipc-contract.ts+++ b/src/shared/ipc-contract.ts@@ -15,7 +15,6 @@ import type {* is a compile error instead of a runtime one. */export interface IpcContract {listInterfaces: { args: []; result: NetworkInterfaceInfo[] }- pingInterfaces: { args: []; result: Record<string, number | null> }deviceBindingSupported: { args: []; result: boolean }openNetworkSettings: { args: []; result: void }updateSettings: { args: [patch: AppSettings]; result: void }diff --git a/src/shared/types.ts b/src/shared/types.tsindex eaec0b4..b0833dc 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -292,8 +292,8 @@ export interface NetworkPreference {/** One of the app's curated swatch ids (see NETWORK_COLOR_SWATCHES) — not a raw hex, so every* swatch is guaranteed to have a legible on-solid text color already picked out for it. */colorId?: string- /** Left out of new downloads by default (see the title bar's networks). A download can still- * be started on it. */+ /** Left out of the last download started, so New download starts without it too (it remembers+ * the last pick, like the folder). A click there puts it back. */off?: boolean/** Bytes a second all downloads together may take over it. */speedLimit?: number@@ -330,9 +330,17 @@ export interface AppSettings {/** While on, slowModeSpeed stands in for speedLimit: a one-click lower limit for calls. */slowMode?: booleanslowModeSpeed?: number+ /** How speeds are shown everywhere; sizes stay in bytes either way. */+ speedUnit?: SpeedUnit}+/** bytes: MB/s. bits: Mbps, as internet plans and speed tests count them. */+export type SpeedUnit = 'bytes' | 'bits'+export const DOWNLOADS_AT_ONCE = { default: 2, min: 1, max: 8 }+/** Seconds of speed history a download keeps (a sample a second), and so the span the throughput+ * chart always shows. */+export const SPEED_HISTORY_SECONDS = 60export const DEFAULT_SLOW_MODE_SPEED = 2 * 1024 ** 2/** Everything the renderer needs for its first paint, read synchronously by the preload so no@@ -346,6 +354,7 @@ export interface InitialState {speedLimit?: numberslowMode: booleanslowModeSpeed: number+ speedUnit: SpeedUnit/** The last folder picked, if it still exists — otherwise the renderer uses downloadsDir. */destinationDir?: string}