Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

Pick streams per network on the start screen, and let a lowered limit recover (#51)

Anmol Kapild57778db9257
diff --git a/README.md b/README.md
index 1025f7b..5830059 100644
--- a/README.md
+++ b/README.md
@@ -67,7 +67,7 @@ File ──→ Split ─────┤ ├─
## Features
-- 🚀 **Multi-interface, multi-connection downloads** — splits files into chunks of up to 8 MB and fans them out across worker connections bound to specific network interfaces, each kept open from one chunk to the next. Each interface starts with 8 connections and doubles once they are all receiving, up to 32; if the server refuses some of them (503, 429, 403) while serving the rest, the refused ones close and that interface stays at the ones left; a server refusing everything (busy, or an expired link) doesn't lower it.
+- 🚀 **Multi-interface, multi-connection downloads** — splits files into chunks of up to 8 MB and fans them out across worker connections bound to specific network interfaces, each kept open from one chunk to the next. Each interface starts with 8 connections and doubles once they are all receiving, up to 32. If the server refuses some (503, 429, 403), that interface drops to the ones it accepted, then gets one more back each minute without a refusal; a server refusing everything (busy, or an expired link) doesn't lower it. You can also pick a fixed 4, 8, 16 or 32 per interface on the start screen instead of Auto.
- 🔌 **Hardware interface detection** — queries Windows adapters via PowerShell `Get-NetAdapter` and macOS hardware ports via `networksetup` so Wi-Fi, Ethernet, tethered iPhones, and Thunderbolt bridges are labeled by real device names instead of bare BSD names (`en0`, `en6`).
- ⚖️ **Dynamic work-stealing queue** — chunks are leased from a shared pending queue; faster networks pull more chunks instead of waiting for slower connections to finish.
- ⏸️ **Resumable downloads** — cleanly pause and resume downloads with progress saved in a destination-side staging file.
diff --git a/e2e/concurrency.spec.ts b/e2e/concurrency.spec.ts
index 7514573..b4fc2c5 100644
--- a/e2e/concurrency.spec.ts
+++ b/e2e/concurrency.spec.ts
@@ -1,5 +1,10 @@
import { expect, test } from '@playwright/test'
-import { ConcurrencyController, type NetworkSnapshot } from '../src/main/download/concurrency'
+import {
+ ConcurrencyController,
+ RECOVER_MS,
+ type Action,
+ type NetworkSnapshot
+} from '../src/main/download/concurrency'
// M. How many streams each network runs. The controller is pure, so each rule is checked against
// the exact situation it is for.
@@ -24,31 +29,35 @@ test.describe('stream count', () => {
const controller = new ConcurrencyController(MAX)
const counts: number[] = []
for (let streams = 8; streams < MAX;) {
- const actions = controller.tick({ networks: [network('a', streams)], spareWork: 1000 })
+ const actions = controller.tick({
+ now: 0,
+ networks: [network('a', streams)],
+ spareWork: 1000
+ })
expect(actions).toHaveLength(1)
streams += actions[0].count
counts.push(streams)
}
expect(counts).toEqual([16, 32])
- expect(controller.tick({ networks: [network('a', MAX)], spareWork: 1000 })).toEqual([])
+ expect(controller.tick({ now: 0, networks: [network('a', MAX)], spareWork: 1000 })).toEqual([])
})
test('waits while any stream has yet to receive anything', () => {
const controller = new ConcurrencyController(MAX)
expect(
- controller.tick({ networks: [network('a', 8, { answered: 7 })], spareWork: 1000 })
+ controller.tick({ now: 0, networks: [network('a', 8, { answered: 7 })], spareWork: 1000 })
).toEqual([])
})
test('adds no more streams than the waiting blocks can keep busy', () => {
const controller = new ConcurrencyController(MAX)
- expect(controller.tick({ networks: [network('a', 8)], spareWork: 3 })).toEqual([
+ expect(controller.tick({ now: 0, networks: [network('a', 8)], spareWork: 3 })).toEqual([
{ kind: 'add', networkId: 'a', count: 3 }
])
- expect(controller.tick({ networks: [network('a', 8)], spareWork: 0 })).toEqual([])
+ expect(controller.tick({ now: 0, networks: [network('a', 8)], spareWork: 0 })).toEqual([])
// The waiting blocks are shared: the first network takes what it can use.
expect(
- controller.tick({ networks: [network('a', 8), network('b', 8)], spareWork: 10 })
+ controller.tick({ now: 0, networks: [network('a', 8), network('b', 8)], spareWork: 10 })
).toEqual([
{ kind: 'add', networkId: 'a', count: 8 },
{ kind: 'add', networkId: 'b', count: 2 }
@@ -59,14 +68,15 @@ test.describe('stream count', () => {
const controller = new ConcurrencyController(MAX)
expect(
controller.tick({
+ now: 0,
networks: [network('a', 16, { served: 10, refused: 6 })],
spareWork: 1000
})
).toEqual([{ kind: 'retire', networkId: 'a', count: 6 }])
- // Later, all well again: still no growth past 10.
- expect(controller.tick({ networks: [network('a', 10)], spareWork: 1000 })).toEqual([])
+ // All well again, but not yet for a minute: still no growth past 10.
+ expect(controller.tick({ now: 0, networks: [network('a', 10)], spareWork: 1000 })).toEqual([])
// A stream lost some other way is made up for, back to the limit and no further.
- expect(controller.tick({ networks: [network('a', 7)], spareWork: 1000 })).toEqual([
+ expect(controller.tick({ now: 0, networks: [network('a', 7)], spareWork: 1000 })).toEqual([
{ kind: 'add', networkId: 'a', count: 3 }
])
})
@@ -77,14 +87,19 @@ test.describe('stream count', () => {
const controller = new ConcurrencyController(MAX)
expect(
controller.tick({
+ now: 0,
networks: [network('a', 8, { answered: 0, served: 0, refused: 1 })],
spareWork: 1000
})
).toEqual([])
expect(
- controller.tick({ networks: [network('a', 8, { served: 7, refused: 1 })], spareWork: 1000 })
+ controller.tick({
+ now: 0,
+ networks: [network('a', 8, { served: 7, refused: 1 })],
+ spareWork: 1000
+ })
).toEqual([{ kind: 'retire', networkId: 'a', count: 1 }])
- expect(controller.tick({ networks: [network('a', 7)], spareWork: 1000 })).toEqual([])
+ expect(controller.tick({ now: 0, networks: [network('a', 7)], spareWork: 1000 })).toEqual([])
})
test('a server refusing while it sends nothing is not limiting connections: the count stays', () => {
@@ -94,25 +109,34 @@ test.describe('stream count', () => {
for (const refused of [16, 5, 11]) {
expect(
controller.tick({
+ now: 0,
networks: [network('a', 16, { served: 0, refused })],
spareWork: 1000
})
).toEqual([])
}
// Once it serves again, the network grows as before.
- expect(controller.tick({ networks: [network('a', 16)], spareWork: 1000 })).toEqual([
+ expect(controller.tick({ now: 0, networks: [network('a', 16)], spareWork: 1000 })).toEqual([
{ kind: 'add', networkId: 'a', count: 16 }
])
})
- test('a limit only ever comes down', () => {
+ test('a later refusal lowers the limit further', () => {
const controller = new ConcurrencyController(MAX)
- controller.tick({ networks: [network('a', 16, { served: 10, refused: 6 })], spareWork: 1000 })
- // A later partial refusal on fewer streams lowers it again; it never rises.
+ controller.tick({
+ now: 0,
+ networks: [network('a', 16, { served: 10, refused: 6 })],
+ spareWork: 1000
+ })
+ // A later partial refusal on fewer streams lowers it again.
expect(
- controller.tick({ networks: [network('a', 10, { served: 8, refused: 2 })], spareWork: 1000 })
+ controller.tick({
+ now: 0,
+ networks: [network('a', 10, { served: 8, refused: 2 })],
+ spareWork: 1000
+ })
).toEqual([{ kind: 'retire', networkId: 'a', count: 2 }])
- expect(controller.tick({ networks: [network('a', 6)], spareWork: 1000 })).toEqual([
+ expect(controller.tick({ now: 0, networks: [network('a', 6)], spareWork: 1000 })).toEqual([
{ kind: 'add', networkId: 'a', count: 2 }
])
})
@@ -122,13 +146,72 @@ test.describe('stream count', () => {
// b is refused and one of a's streams hasn't answered: only b changes, and a is untouched.
expect(
controller.tick({
+ now: 0,
networks: [network('a', 8, { answered: 7 }), network('b', 16, { served: 8, refused: 8 })],
spareWork: 1000
})
).toEqual([{ kind: 'retire', networkId: 'b', count: 8 }])
// A network that left and came back keeps its limit, and one that never refused grows.
expect(
- controller.tick({ networks: [network('a', 8), network('b', 8)], spareWork: 1000 })
+ controller.tick({ now: 0, networks: [network('a', 8), network('b', 8)], spareWork: 1000 })
).toEqual([{ kind: 'add', networkId: 'a', count: 8 }])
})
+
+ test('a lowered limit climbs back by one a minute without refusals, up to the maximum', () => {
+ const controller = new ConcurrencyController(MAX)
+ const tick = (now: number, streams: number, over: Partial<NetworkSnapshot> = {}): Action[] =>
+ controller.tick({ now, networks: [network('a', streams, over)], spareWork: 1000 })
+ expect(tick(0, 16, { served: 10, refused: 6 })).toEqual([
+ { kind: 'retire', networkId: 'a', count: 6 }
+ ])
+ expect(tick(RECOVER_MS - 1, 10)).toEqual([])
+ expect(tick(RECOVER_MS, 10)).toEqual([{ kind: 'add', networkId: 'a', count: 1 }])
+ expect(tick(RECOVER_MS + 1, 11)).toEqual([])
+ expect(tick(2 * RECOVER_MS, 11)).toEqual([{ kind: 'add', networkId: 'a', count: 1 }])
+ // Refused again at 12: back to 11, and the minute starts over.
+ expect(tick(2 * RECOVER_MS + 1, 12, { served: 11, refused: 1 })).toEqual([
+ { kind: 'retire', networkId: 'a', count: 1 }
+ ])
+ expect(tick(3 * RECOVER_MS, 11)).toEqual([])
+ expect(tick(3 * RECOVER_MS + 1, 11)).toEqual([{ kind: 'add', networkId: 'a', count: 1 }])
+ })
+
+ test('a limit recovered all the way lets the network double again', () => {
+ const controller = new ConcurrencyController(8)
+ controller.tick({
+ now: 0,
+ networks: [network('a', 8, { served: 7, refused: 1 })],
+ spareWork: 1000
+ })
+ expect(
+ controller.tick({ now: RECOVER_MS, networks: [network('a', 7)], spareWork: 1000 })
+ ).toEqual([{ kind: 'add', networkId: 'a', count: 1 }])
+ // Back at the maximum: nothing left to remember.
+ expect(
+ controller.tick({ now: RECOVER_MS + 1, networks: [network('a', 8)], spareWork: 1000 })
+ ).toEqual([])
+ })
+
+ test('a count the user picked is kept, not grown, and still backs off when refused', () => {
+ const controller = new ConcurrencyController(4, false)
+ expect(controller.tick({ now: 0, networks: [network('a', 4)], spareWork: 1000 })).toEqual([])
+ // A stream lost some other way is made up for.
+ expect(controller.tick({ now: 0, networks: [network('a', 3)], spareWork: 1000 })).toEqual([
+ { kind: 'add', networkId: 'a', count: 1 }
+ ])
+ expect(
+ controller.tick({
+ now: 0,
+ networks: [network('a', 4, { served: 3, refused: 1 })],
+ spareWork: 1000
+ })
+ ).toEqual([{ kind: 'retire', networkId: 'a', count: 1 }])
+ // And recovers to the pick, never past it.
+ expect(
+ controller.tick({ now: RECOVER_MS, networks: [network('a', 3)], spareWork: 1000 })
+ ).toEqual([{ kind: 'add', networkId: 'a', count: 1 }])
+ expect(
+ controller.tick({ now: 2 * RECOVER_MS, networks: [network('a', 4)], spareWork: 1000 })
+ ).toEqual([])
+ })
})
diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts
index 119f308..e142326 100644
--- a/e2e/fixtures.ts
+++ b/e2e/fixtures.ts
@@ -50,6 +50,8 @@ interface StartOptions {
networks?: string[]
/** Streams per network, fixed so a test can count requests; 'auto' lets the app decide. */
connections?: number | 'auto'
+ /** With connections 'auto': the streams per network picked on the start screen. */
+ streamsPerNetwork?: number
fileName?: string
destinationDir?: string
}
@@ -207,7 +209,8 @@ export class PlexoApp {
supportsRanges: multiChunk,
interfaceIds: multiChunk ? networks : networks.slice(0, 1),
etag: probe.etag,
- lastModified: probe.lastModified
+ lastModified: probe.lastModified,
+ streamsPerNetwork: options.streamsPerNetwork
})
this.tracked.set(id, { expectedSha, destBefore, destinationDir })
return id
diff --git a/e2e/streams.spec.ts b/e2e/streams.spec.ts
index 080076a..52c22d7 100644
--- a/e2e/streams.spec.ts
+++ b/e2e/streams.spec.ts
@@ -52,4 +52,11 @@ test.describe('automatic stream count', () => {
expect(state.chunks.length).toBeGreaterThan(8)
})
})
+
+ test('a count picked on the start screen is kept rather than grown', async ({ plexo, serve }) => {
+ const origin = await serve({ size: 96 * BLOCK, bytesPerSecond: 256 * 1024 })
+ await plexo.start(origin.url(), origin.sha256, { connections: 'auto', streamsPerNetwork: 4 })
+ await plexo.waitForStatus('completed', 40_000)
+ expect(peakStreams(plexo), 'Auto would have doubled to 8 and on').toBe(4)
+ })
})
diff --git a/src/main/download/concurrency.ts b/src/main/download/concurrency.ts
index bae2c0b..228c1bd 100644
--- a/src/main/download/concurrency.ts
+++ b/src/main/download/concurrency.ts
@@ -1,13 +1,17 @@
// How many streams each network runs. Deliberately simple, after Gopeed and aria2: no timers and
// no speed comparisons, so noise on a flaky network can't move it.
//
-// - A network starts with START_STREAMS_PER_NETWORK (see reconcile in downloadManager.ts).
+// - A network starts with START_STREAMS_PER_NETWORK (see reconcile in downloadManager.ts), or
+// with the count the user picked, which it then keeps rather than grows.
// - Once every one of its streams has received data, it doubles, up to the limit. Another
// connection costs little when the link is already full, and a server that caps each
// connection's speed is only outrun by more of them.
// - A server that refuses some of a network's streams (503, 429, 403) while it is sending data
// down others is saying it wants fewer connections from this address: the refused streams
-// close, and the network never goes above the ones left again for this download. Only the
+// close, and the network stays at the ones left. After RECOVER_MS without another refusal it
+// may have one more, and so on back up to the limit, as in Surge: a server that was only
+// briefly unwell doesn't cap the rest of a long download, and one that meant it costs one
+// refused request a minute. Only the
// streams refused count against it: one that failed some other way, or hasn't been answered
// yet, isn't a refusal. As in Gopeed, where a refused connection stops and the others carry on.
// - A server that refuses while sending nothing isn't limiting connections: it is busy, or the
@@ -16,8 +20,11 @@
// - Each network is decided on its own, so one that drops out or comes back never disturbs the
// others.
//
-// No I/O and no clock of its own: it reads a snapshot and says what to do, so every rule can be
-// checked against exact situations.
+// No I/O and no clock of its own: it reads a snapshot, time included, and says what to do, so
+// every rule can be checked against exact situations.
+
+/** How long a lowered limit holds before it may rise by one. */
+export const RECOVER_MS = 60_000
export interface NetworkSnapshot {
id: string
@@ -32,6 +39,7 @@ export interface NetworkSnapshot {
}
export interface Snapshot {
+ now: number
/** The networks in use: the ones it may grow. */
networks: readonly NetworkSnapshot[]
/** How many more streams the waiting blocks could keep busy. */
@@ -41,28 +49,44 @@ export interface Snapshot {
export type Action = { kind: 'add' | 'retire'; networkId: string; count: number }
export class ConcurrencyController {
- /** The most streams each network may run: lowered for good when its server refuses one. */
- private readonly ceilings = new Map<string, number>()
+ /** Networks a server has refused on: the most streams each may run for now, and when that was
+ * last changed. */
+ private readonly ceilings = new Map<string, { limit: number; since: number }>()
- constructor(private readonly maxPerNetwork: number) {}
+ constructor(
+ /** The most streams a network may run. */
+ private readonly maxPerNetwork: number,
+ /** false: keep each network at maxPerNetwork (the user's pick) rather than doubling to it. */
+ private readonly grows = true
+ ) {}
tick(snapshot: Snapshot): Action[] {
const actions: Action[] = []
+ const { now } = snapshot
let spare = snapshot.spareWork
for (const network of snapshot.networks) {
const { id, streams } = network
- if (network.refused > 0 && network.served > 0) {
- const ceiling = Math.max(1, streams - network.refused)
- this.ceilings.set(id, Math.min(ceiling, this.ceilings.get(id) ?? Infinity))
+ const refusedNow = network.refused > 0 && network.served > 0
+ let entry = this.ceilings.get(id)
+ if (refusedNow) {
+ const limit = Math.max(1, Math.min(streams - network.refused, entry?.limit ?? Infinity))
+ this.ceilings.set(id, (entry = { limit, since: now }))
+ } else if (entry && network.refused === 0 && now - entry.since >= RECOVER_MS) {
+ entry.limit++
+ entry.since = now
+ if (entry.limit >= this.maxPerNetwork) {
+ this.ceilings.delete(id)
+ entry = undefined
+ }
}
- const ceiling = Math.min(this.maxPerNetwork, this.ceilings.get(id) ?? Infinity)
+ const ceiling = Math.min(this.maxPerNetwork, entry?.limit ?? Infinity)
if (streams > ceiling) {
actions.push({ kind: 'retire', networkId: id, count: streams - ceiling })
continue
}
// Not while the server is turning requests away.
if (network.refused > 0 || streams === 0 || network.answered < streams) continue
- const count = Math.min(streams, ceiling - streams, spare)
+ const count = Math.min(this.grows ? streams : Infinity, ceiling - streams, spare)
if (count < 1) continue
spare -= count
actions.push({ kind: 'add', networkId: id, count })
diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.ts
index 190ae3f..d3e912e 100644
--- a/src/main/download/downloadManager.ts
+++ b/src/main/download/downloadManager.ts
@@ -301,9 +301,19 @@ function splittable(request: StartDownloadRequest): boolean {
/** How many streams a download runs is only for it to work out when there can be more than one,
* and unless a test fixes it. */
function concurrencyFor(request: StartDownloadRequest): ConcurrencyController | null {
- return splittable(request) && testStreamsPerNetwork() === null
+ if (!splittable(request) || testStreamsPerNetwork() !== null) return null
+ const picked = pickedStreams(request)
+ return picked === undefined
? new ConcurrencyController(MAX_STREAMS_PER_NETWORK)
- : null
+ : new ConcurrencyController(picked, false)
+}
+
+/** The streams per network the user picked for this download, if they didn't leave it on Auto. */
+function pickedStreams(request: StartDownloadRequest): number | undefined {
+ const picked = request.streamsPerNetwork
+ return Number.isInteger(picked) && picked! >= 1 && picked! <= MAX_STREAMS_PER_NETWORK
+ ? picked
+ : undefined
}
/** How often a stream with nothing to do looks for work again. */
const IDLE_POLL_MS = 250
@@ -1173,7 +1183,7 @@ export class DownloadManager {
? startingStreams(
runtime.blocks.filter((block) => block.status === 'pending').length,
joining.length,
- testStreamsPerNetwork() ?? undefined
+ testStreamsPerNetwork() ?? pickedStreams(runtime.requestPayload)
)
: 1
@@ -1820,7 +1830,7 @@ export class DownloadManager {
})
// A new stream takes a waiting block the moment it starts.
const waiting = runtime.blocks.filter((block) => block.status === 'pending').length
- return { networks, spareWork: waiting }
+ return { now: Date.now(), networks, spareWork: waiting }
}
/** New streams on `networkId`, put on the download's list for the caller to start. */
diff --git a/src/renderer/src/components/ui/toggle-group.tsx b/src/renderer/src/components/ui/toggle-group.tsx
new file mode 100644
index 0000000..7ab2456
--- /dev/null
+++ b/src/renderer/src/components/ui/toggle-group.tsx
@@ -0,0 +1,85 @@
+import * as React from 'react'
+import { Toggle as TogglePrimitive } from '@base-ui/react/toggle'
+import { ToggleGroup as ToggleGroupPrimitive } from '@base-ui/react/toggle-group'
+import { type VariantProps } from 'class-variance-authority'
+import { cn } from 'cn'
+
+import { toggleVariants } from '@renderer/components/ui/toggle'
+
+const ToggleGroupContext = React.createContext<
+ VariantProps<typeof toggleVariants> & {
+ spacing?: number
+ orientation?: 'horizontal' | 'vertical'
+ }
+>({
+ size: 'default',
+ variant: 'default',
+ spacing: 2,
+ orientation: 'horizontal'
+})
+
+function ToggleGroup({
+ className,
+ variant,
+ size,
+ spacing = 2,
+ orientation = 'horizontal',
+ children,
+ ...props
+}: ToggleGroupPrimitive.Props &
+ VariantProps<typeof toggleVariants> & {
+ spacing?: number
+ orientation?: 'horizontal' | 'vertical'
+ }): React.JSX.Element {
+ return (
+ <ToggleGroupPrimitive
+ data-slot="toggle-group"
+ data-variant={variant}
+ data-size={size}
+ data-spacing={spacing}
+ data-orientation={orientation}
+ style={{ '--gap': spacing } as React.CSSProperties}
+ className={cn(
+ 'group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] rounded-lg data-[size=sm]:rounded-[min(var(--radius-md),10px)] data-vertical:flex-col data-vertical:items-stretch',
+ className
+ )}
+ {...props}
+ >
+ <ToggleGroupContext.Provider value={{ variant, size, spacing, orientation }}>
+ {children}
+ </ToggleGroupContext.Provider>
+ </ToggleGroupPrimitive>
+ )
+}
+
+function ToggleGroupItem({
+ className,
+ children,
+ variant = 'default',
+ size = 'default',
+ ...props
+}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>): React.JSX.Element {
+ const context = React.useContext(ToggleGroupContext)
+
+ return (
+ <TogglePrimitive
+ data-slot="toggle-group-item"
+ data-variant={context.variant || variant}
+ data-size={context.size || size}
+ data-spacing={context.spacing}
+ className={cn(
+ 'shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-1.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-1.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-l-lg group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-t-lg group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-r-lg group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-b-lg group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t',
+ toggleVariants({
+ variant: context.variant || variant,
+ size: context.size || size
+ }),
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </TogglePrimitive>
+ )
+}
+
+export { ToggleGroup, ToggleGroupItem }
diff --git a/src/renderer/src/components/ui/toggle.tsx b/src/renderer/src/components/ui/toggle.tsx
new file mode 100644
index 0000000..7d43025
--- /dev/null
+++ b/src/renderer/src/components/ui/toggle.tsx
@@ -0,0 +1,48 @@
+import { Toggle as TogglePrimitive } from '@base-ui/react/toggle'
+import { cva, type VariantProps } from 'class-variance-authority'
+import { cn } from 'cn'
+
+const toggleVariants = cva(
+ "group/toggle inline-flex items-center justify-center gap-1 rounded-lg text-sm font-medium whitespace-nowrap transition-all outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted data-[state=on]:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ variant: {
+ default: 'bg-transparent',
+ outline: 'border border-input bg-transparent hover:bg-muted',
+ // A selectable preset pill (e.g. "1×"/"2×"/"4×"/"8×" stream-count pickers) — muted/outlined
+ // at rest, switches to the primary/accent color once picked.
+ pill: 'border border-border bg-muted font-mono text-[var(--text-secondary)] hover:bg-muted hover:text-[var(--text-secondary)] aria-pressed:border-primary aria-pressed:bg-primary aria-pressed:text-primary-foreground data-[state=on]:border-primary data-[state=on]:bg-primary data-[state=on]:text-primary-foreground'
+ },
+ size: {
+ default:
+ 'h-8 min-w-8 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2',
+ xs: "h-5 min-w-5 gap-1 rounded-[min(var(--radius-md),8px)] px-1.5 text-[10px] font-semibold [&_svg:not([class*='size-'])]:size-3",
+ sm: "h-7 min-w-7 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
+ lg: 'h-9 min-w-9 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2'
+ }
+ },
+ defaultVariants: {
+ variant: 'default',
+ size: 'default'
+ }
+ }
+)
+
+function Toggle({
+ className,
+ variant = 'default',
+ size = 'default',
+ ...props
+}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>): React.JSX.Element {
+ return (
+ <TogglePrimitive
+ data-slot="toggle"
+ className={cn(toggleVariants({ variant, size, className }))}
+ {...props}
+ />
+ )
+}
+
+export { Toggle }
+// eslint-disable-next-line react-refresh/only-export-components -- shadcn convention: variants ship alongside the component
+export { toggleVariants }
diff --git a/src/renderer/src/screens/IdleScreen.tsx b/src/renderer/src/screens/IdleScreen.tsx
index 45d2043..9bfce14 100644
--- a/src/renderer/src/screens/IdleScreen.tsx
+++ b/src/renderer/src/screens/IdleScreen.tsx
@@ -6,10 +6,15 @@ import { NetworkCard } from '../components/NetworkCard'
import { ScreenFooter } from '../components/ScreenFooter'
import { Alert, AlertDescription, AlertTitle } from '../components/ui/alert'
import { Button } from '../components/ui/button'
+import { ToggleGroup, ToggleGroupItem } from '../components/ui/toggle-group'
import { useLatencyPolling } from '../hooks/useNetworks'
import { useAppStore } from '../store/useAppStore'
import { describeError, formatBytes, toDisplayPath } from '../utils/format'
+type StreamsChoice = 'auto' | number
+/** Streams per network the user can pick instead of Auto. */
+const STREAMS_CHOICES: StreamsChoice[] = ['auto', 4, 8, 16, 32]
+
type ProbeState =
| { status: 'idle' }
| { status: 'probing' }
@@ -71,6 +76,8 @@ export function IdleScreen(): React.JSX.Element {
const [starting, setStarting] = useState(false)
const [startError, setStartError] = useState<string | null>(null)
const [fileNameOverride, setFileNameOverride] = useState<string | null>(null)
+ // Auto unless the user picks a count for this download; not remembered for the next one.
+ const [streamsChoice, setStreamsChoice] = useState<StreamsChoice>('auto')
const probeRequestId = useRef(0)
@@ -197,7 +204,8 @@ export function IdleScreen(): React.JSX.Element {
supportsRanges: multiChunkAllowed,
interfaceIds: selectedInterfaceIds,
etag: probe.result.etag,
- lastModified: probe.result.lastModified
+ lastModified: probe.result.lastModified,
+ streamsPerNetwork: streamsChoice === 'auto' ? undefined : streamsChoice
})
} catch (error) {
setStartError(describeError(error))
@@ -310,6 +318,43 @@ export function IdleScreen(): React.JSX.Element {
</Button>
</div>
+ <div
+ className={cn(
+ 'flex min-h-9 flex-wrap items-center gap-x-3 gap-y-1 rounded-[9px] border border-border px-3 py-1.5',
+ isSingleStreamOnly && 'opacity-60'
+ )}
+ >
+ <div id="idle-streams-label" className={fieldLabelClass}>
+ STREAMS
+ </div>
+ <ToggleGroup
+ value={[String(streamsChoice)]}
+ onValueChange={(values) => {
+ if (values.length === 0) return
+ setStreamsChoice(values[0] === 'auto' ? 'auto' : Number(values[0]))
+ }}
+ disabled={isSingleStreamOnly}
+ aria-labelledby="idle-streams-label"
+ variant="pill"
+ size="xs"
+ spacing={1}
+ >
+ {STREAMS_CHOICES.map((choice) => (
+ // h-6/min-w-6: WCAG 2.5.8's 24px floor — the xs toggle size is 20px.
+ <ToggleGroupItem key={choice} value={String(choice)} className="h-6 min-w-6 px-2">
+ {choice === 'auto' ? 'Auto' : choice}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ <div className="ml-auto font-mono text-[11px] whitespace-nowrap text-muted-foreground">
+ {isSingleStreamOnly
+ ? '1 stream'
+ : streamsChoice === 'auto'
+ ? 'per network, as many as help'
+ : 'per network'}
+ </div>
+ </div>
+
{startError && <ErrorAlert message={startError} />}
</div>
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 8eb1357..86c6a36 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -209,4 +209,6 @@ export interface StartDownloadRequest {
interfaceIds: string[]
etag: string | null
lastModified: string | null
+ /** Streams per network the user picked; left out, the count is decided automatically. */
+ streamsPerNetwork?: number
}