Speed up downloads by combining multiple network connections in parallel
TypeScript bandwidth-aggregationcross-platformdesktop-appdownloaderdownloadmanagerlinuxmacosmulticonnectionparallel-downloadswindows
feat: networks can join, leave and be switched during a download
Anmol Kapil806a261b2e66
diff --git a/e2e/concurrency.spec.ts b/e2e/concurrency.spec.tsindex 1ecc5f0..f01e28e 100644--- a/e2e/concurrency.spec.ts+++ b/e2e/concurrency.spec.ts@@ -260,6 +260,55 @@ test.describe('stream count', () => {})})+ test('a network joining or leaving mid-step undoes the step, and a network that rejoins can grow again', () => {+ const controller = new ConcurrencyController(POLICY)+ const received = new Map([+ ['a', 0],+ ['b', 0]+ ])+ const streams = new Map([+ ['a', 4],+ ['b', 4]+ ])+ let now = 0+ const tick = (ids: string[]): Action | undefined => {+ // A server that caps each connection at 0.5 MB/s: another stream always pays.+ for (const id of ids) received.set(id, received.get(id)! + streams.get(id)! * 0.25 * MB)+ now += TICK_MS+ return controller.tick({+ now,+ networks: ids.map((id) => ({+ id,+ streams: streams.get(id)!,+ received: received.get(id)!,+ rejected: 0+ })),+ spareWork: 1000,+ retiring: 0+ })+ }+ let action: Action | undefined+ while (!(action = tick(['a', 'b']))) expect(now).toBeLessThan(60_000)+ expect(action.kind).toBe('add')+ const grown = action.networkId+ const other = grown === 'a' ? 'b' : 'a'+ streams.set(grown, streams.get(grown)! + action.count)++ // The other network drops out before the step is judged: its speed going says nothing about+ // the step, so the step is undone rather than judged against it.+ expect(tick([grown])).toEqual({ kind: 'retire', networkId: grown, count: action.count })+ streams.set(grown, 4)++ // Back again, it is grown like any network that has just joined.+ for (let added = false; !added;) {+ const next = tick(['a', 'b'])+ if (next?.kind === 'add' && next.networkId === other) added = true+ else if (next?.kind === 'add')+ streams.set(next.networkId, streams.get(next.networkId)! + next.count)+ expect(now).toBeLessThan(120_000)+ }+ })+test('a pause mid-step gives back the untried streams; what was settled stays settled', () => {const controller = new ConcurrencyController(POLICY)const tick = (now: number, streams: number, received: number): Action | undefined =>diff --git a/e2e/download.spec.ts b/e2e/download.spec.tsindex b66aa62..058decc 100644--- a/e2e/download.spec.ts+++ b/e2e/download.spec.ts@@ -9,7 +9,7 @@ test.describe('happy paths @smoke', () => {await plexo.relaunch({ PLEXO_E2E_INTERFACES: 'a=::1' })await plexo.start(origin.url(), origin.sha256)const state = await plexo.waitForStatus('completed')- expect(state.chunks.every((chunk) => chunk.retryCount === 0)).toBe(true)+ expect(state.networks.every((network) => network.retries === 0)).toBe(true)expect(origin.chunkRequests().every((request) => request.from === '::1')).toBe(true)})diff --git a/e2e/downloadUpdate.spec.ts b/e2e/downloadUpdate.spec.tsindex 27ca49e..4d330d4 100644--- a/e2e/downloadUpdate.spec.ts+++ b/e2e/downloadUpdate.spec.ts@@ -25,6 +25,7 @@ const update = (seq: number, blocks: BlockState[], id = 'd1'): DownloadUpdate =>bytesDownloaded: blocks.reduce((sum, entry) => sum + entry.bytesDownloaded, 0),speedBytesPerSec: 0,status: 'downloading',+ networks: [],chunks: [],totalBlocks: 4,startedAt: 0diff --git a/e2e/fixtures.ts b/e2e/fixtures.tsindex a22589d..504930d 100644--- a/e2e/fixtures.ts+++ b/e2e/fixtures.ts@@ -248,13 +248,14 @@ export class PlexoApp {if (state && predicate(state)) return stateawait new Promise((resolve) => setTimeout(resolve, 50))}- const chunks = state?.chunks.map(- (chunk) => `${chunk.status}${chunk.error ? ` (${chunk.error})` : ''}`+ const networks = state?.networks.map(+ (network) => `${network.id}:${network.status}${network.error ? ` (${network.error})` : ''}`)+ const chunks = state?.chunks.map((chunk) => `${chunk.interfaceId}:${chunk.status}`)throw new Error(`Timed out after ${timeout} ms waiting on the download. Last seen: ${state- ? `status=${state.status}${state.error ? `, error="${state.error}"` : ''}, bytes=${state.bytesDownloaded}/${state.totalBytes}, chunks=[${chunks?.join(', ')}]`+ ? `status=${state.status}${state.error ? `, error="${state.error}"` : ''}, bytes=${state.bytesDownloaded}/${state.totalBytes}, networks=[${networks?.join(', ')}], chunks=[${chunks?.join(', ')}]`: 'no current download'}`)@@ -267,7 +268,8 @@ const ALLOWED_NEXT: Record<DownloadStatus, DownloadStatus[]> = {downloading: ['downloading', 'paused', 'completed', 'error', 'cancelled'],paused: ['paused', 'downloading', 'error', 'cancelled'],completed: ['completed'],- error: ['error'],+ // Resumed.+ error: ['error', 'downloading'],cancelled: ['cancelled']}@@ -366,6 +368,9 @@ export async function checkFinalState(app: PlexoApp): Promise<void> {const tracked = app.tracked.get(state.id) ?? app.nextDownloadconst terminal = ['completed', 'error', 'cancelled'].includes(state.status)if (!tracked || !terminal) return+ // A failed download keeps its progress to be resumed until the user moves on, as the window's+ // New Download does: after that, nothing may be left.+ if (state.status === 'error') await app.api.removeDownload(state.id)if (state.status === 'completed') {const bytes = await readFile(state.destinationPath)diff --git a/e2e/hedge.spec.ts b/e2e/hedge.spec.tsindex 8b06d2e..7f71a16 100644--- a/e2e/hedge.spec.ts+++ b/e2e/hedge.spec.ts@@ -77,7 +77,7 @@ test.describe('racing a slow block', () => {const state = await plexo.waitForStatus('completed', 10_000)expect(- state.chunks.reduce((sum, chunk) => sum + chunk.retryCount, 0),+ state.networks.reduce((sum, network) => sum + network.retries, 0),'a failed hedge is not a retry').toBe(0)// It was tried, once: the only network there is had just got nothing from the block.diff --git a/e2e/integrity.spec.ts b/e2e/integrity.spec.tsindex 4dc3f16..3537885 100644--- a/e2e/integrity.spec.ts+++ b/e2e/integrity.spec.ts@@ -32,7 +32,7 @@ test.describe('transient server faults are retried to a correct file @smoke', ()await plexo.start(origin.url(), origin.sha256, { connections: 2 })const state = await plexo.waitForStatus('completed')expect(faulted, 'the fault was actually injected').toBeGreaterThanOrEqual(3)- expect(state.chunks.reduce((sum, chunk) => sum + chunk.retryCount, 0)).toBeGreaterThan(0)+ expect(state.networks.reduce((sum, network) => sum + network.retries, 0)).toBeGreaterThan(0)})}@@ -80,7 +80,7 @@ test.describe('a connection stuck at a crawl @smoke', () => {entry.range!.start <= slow.range!.end!)expect(resumed, 'the block resumed from where the slow connection stopped').toBeTruthy()- expect(state.chunks.reduce((sum, chunk) => sum + chunk.retryCount, 0)).toBe(0)+ expect(state.networks.reduce((sum, network) => sum + network.retries, 0)).toBe(0)})}diff --git a/e2e/lifecycle.spec.ts b/e2e/lifecycle.spec.tsindex 7596c26..c5ae785 100644--- a/e2e/lifecycle.spec.ts+++ b/e2e/lifecycle.spec.ts@@ -214,7 +214,7 @@ test.describe('resume safety checks @smoke', () => {await plexo.waitForStatus('completed')})- test('network gone while paused → stays paused with a message, resumes once it is back', async ({+ test('network gone while paused → resumes waiting for it, and finishes once it is back', async ({plexo,serve}) => {@@ -234,13 +234,20 @@ test.describe('resume safety checks @smoke', () => {await setInterfaces(interfacesEnv({ b: NETWORKS['b'] }))await plexo.api.resumeDownload(id)- const stuck = await plexo.waitUntil((state) => Boolean(state.error))- expect(stuck.status).toBe('paused')- expect(stuck.error).toMatch(/not currently available|None of the networks/)+ const waiting = await plexo.waitUntil(+ (state) => state.networks.find((network) => network.id === 'a')?.status === 'offline'+ )+ expect(waiting.status).toBe('downloading')+ expect(waiting.chunks, 'no streams on a network that is not there').toHaveLength(0)+ // b turned up meanwhile: listed, but off, since it wasn't picked.+ expect(waiting.networks.find((network) => network.id === 'b')).toMatchObject({+ enabled: false,+ status: 'off'+ })await setInterfaces(interfacesEnv(NETWORKS))- await plexo.api.resumeDownload(id)await plexo.waitForStatus('completed')+ expect(origin.chunkRequests().every((request) => request.from === '127.0.0.1')).toBe(true)})test('resume against a server without range support', async ({ plexo, serve }) => {diff --git a/e2e/liveNetworks.spec.ts b/e2e/liveNetworks.spec.tsnew file mode 100644index 0000000..9c66911--- /dev/null+++ b/e2e/liveNetworks.spec.ts@@ -0,0 +1,151 @@+import {+ BLOCK,+ expect,+ interfacesEnv,+ LAN_ADDRESS,+ NETWORKS,+ test,+ type PlexoApp+} from './fixtures'+import type { LoggedRequest } from './origin'+import type { DownloadState } from '../src/shared/types'++// O. Networks that come, go, and are switched on and off while a download runs.++/** What the computer's networks are now, as the app will see them at its next look. */+const setNetworks = (plexo: PlexoApp, networks: Record<string, string>): Promise<void> =>+ plexo.evaluateMain((_electron, value) => {+ process.env['PLEXO_E2E_INTERFACES'] = value+ }, interfacesEnv(networks))++const overB = (request: Pick<LoggedRequest, 'from'>): boolean => request.from !== '127.0.0.1'+const network = (state: DownloadState, id: string): DownloadState['networks'][number] | undefined =>+ state.networks.find((entry) => entry.id === id)+const streamsOn = (state: DownloadState, id: string): number =>+ state.chunks.filter((chunk) => chunk.interfaceId === id).length+const settle = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))++test('the only network drops for a while: the download waits, then picks up where it was @smoke', async ({+ plexo,+ serve+}) => {+ const origin = await serve({ size: 64 * BLOCK, bytesPerSecond: 256 * 1024 })+ await plexo.start(origin.url(), origin.sha256)+ await plexo.waitUntil((state) => state.bytesDownloaded > 0)++ await setNetworks(plexo, {})+ await plexo.waitUntil((state) => network(state, 'a')?.status === 'offline')+ const gone = (await plexo.current())!+ // Far longer than a stream's retries used to last before the download failed and its+ // progress was thrown away (five of them, 20 ms apart and doubling, in these tests).+ await settle(1500)+ const waited = (await plexo.current())!+ expect(waited.status).toBe('downloading')+ expect(waited.chunks).toHaveLength(0)+ expect(waited.bytesDownloaded, 'nothing it had was lost').toBe(gone.bytesDownloaded)++ await setNetworks(plexo, { a: NETWORKS['a'] })+ await plexo.waitForStatus('completed')+})++test.describe('two networks @smoke', () => {+ test.skip(!LAN_ADDRESS, 'needs a LAN address to act as the second network')++ test('a network that drops out and comes back is used again', async ({ plexo, serve }) => {+ const origin = await serve({ size: 128 * BLOCK, bytesPerSecond: 256 * 1024 })+ await plexo.start(origin.url(), origin.sha256, { networks: ['a', 'b'], connections: 2 })+ await plexo.waitUntil((state) => (network(state, 'b')?.bytesDownloaded ?? 0) > 0)++ await setNetworks(plexo, { a: NETWORKS['a'] })+ const gone = await plexo.waitUntil(+ (state) => network(state, 'b')?.status === 'offline' && streamsOn(state, 'b') === 0+ )+ expect(network(gone, 'b')?.enabled, 'still the user’s pick').toBe(true)+ const goneAt = origin.log.length++ await setNetworks(plexo, NETWORKS)+ await plexo.waitForStatus('completed')+ expect(origin.log.slice(goneAt).some(overB), 'b carried more once it was back').toBe(true)+ })++ test('switching a network off stops its traffic; switched on, it carries on', async ({+ plexo,+ serve+ }) => {+ const origin = await serve({ size: 128 * BLOCK, bytesPerSecond: 256 * 1024 })+ const id = await plexo.start(origin.url(), origin.sha256, {+ networks: ['a', 'b'],+ connections: 2+ })+ await plexo.waitUntil((state) => (network(state, 'b')?.bytesDownloaded ?? 0) > 0)++ await plexo.api.setDownloadNetwork(id, 'b', false)+ const off = await plexo.waitUntil((state) => streamsOn(state, 'b') === 0)+ expect(network(off, 'b')).toMatchObject({ enabled: false, status: 'off' })+ expect(network(off, 'b')!.bytesDownloaded, 'what it delivered stays its own').toBeGreaterThan(0)+ const offAt = origin.log.length++ // The last network in use can't be switched off: pausing is how a download stops.+ await plexo.api.setDownloadNetwork(id, 'a', false)+ expect(network((await plexo.current())!, 'a')?.enabled).toBe(true)++ await settle(500)+ expect(origin.log.slice(offAt).some(overB), 'nothing over b while it is off').toBe(false)++ await plexo.api.setDownloadNetwork(id, 'b', true)+ await plexo.waitForStatus('completed')+ expect(origin.log.slice(offAt).some(overB), 'b back at work once switched on').toBe(true)+ })++ test('a network that turns up mid-download is listed, off, until switched on', async ({+ plexo,+ serve+ }) => {+ await setNetworks(plexo, { a: NETWORKS['a'] })+ const origin = await serve({ size: 128 * BLOCK, bytesPerSecond: 256 * 1024 })+ const id = await plexo.start(origin.url(), origin.sha256, { connections: 2 })+ await plexo.waitUntil((state) => state.bytesDownloaded > 0)+ expect(network((await plexo.current())!, 'b')).toBeUndefined()++ await setNetworks(plexo, NETWORKS)+ const listed = await plexo.waitUntil((state) => network(state, 'b') !== undefined)+ expect(network(listed, 'b')).toMatchObject({ enabled: false, status: 'off' })+ await settle(500)+ expect(origin.chunkRequests().some(overB), 'not used until switched on').toBe(false)++ await plexo.api.setDownloadNetwork(id, 'b', true)+ await plexo.waitForStatus('completed')+ expect(origin.chunkRequests().some(overB)).toBe(true)+ })+})++test.describe('a network that can’t reach the server @smoke', () => {+ test.use({ appEnv: { PLEXO_E2E_SILENT_MS: '500' } })++ test('keeps one stream trying, and gets its streams back once it is through', async ({+ plexo,+ serve+ }) => {+ test.skip(!LAN_ADDRESS, 'needs a LAN address to act as the second network')+ const origin = await serve({ size: 128 * BLOCK, bytesPerSecond: 256 * 1024 })+ let blocked = true+ // Every connection over b drops before a byte of the file: connected, but not getting through.+ origin.setRule((request) =>+ blocked && overB(request) && request.range && request.range.end !== 0 ? { cutAfter: 0 } : 'ok'+ )+ await plexo.start(origin.url(), origin.sha256, { networks: ['a', 'b'], connections: 2 })++ const cut = await plexo.waitUntil(+ (state) => network(state, 'b')?.status === 'unreachable' && streamsOn(state, 'b') === 1+ )+ expect(network(cut, 'b')?.enabled).toBe(true)+ expect(cut.status, 'the download carries on over a').toBe('downloading')++ blocked = false+ await plexo.waitUntil(+ (state) => network(state, 'b')?.status === 'on' && streamsOn(state, 'b') === 2+ )+ await plexo.waitForStatus('completed')+ expect(network((await plexo.current())!, 'b')!.bytesDownloaded).toBeGreaterThan(0)+ })+})diff --git a/e2e/network.spec.ts b/e2e/network.spec.tsindex 1de40e5..8fdcd0b 100644--- a/e2e/network.spec.ts+++ b/e2e/network.spec.ts@@ -34,7 +34,7 @@ test('AAAA-only hostname connects over IPv6 and keeps its HTTP Host header @smok})await new Promise<void>((resolve) => server.listen(0, '::1', resolve))const connection = new StreamConnection(- { ...iface, addresses: [{ address: '::1', family: 6 }] },+ () => ({ ...iface, addresses: [{ address: '::1', family: 6 }] }),2000,async () => [{ address: '::1', family: 6 }])@@ -55,13 +55,13 @@ test('a working route gets time to answer after an earlier route fails @smoke',})await new Promise<void>((resolve) => server.listen(0, '::1', resolve))const connection = new StreamConnection(- {+ () => ({...iface,addresses: [{ address: '127.0.0.1', family: 4 },{ address: '::1', family: 6 }]- },+ }),3000,async () => [{ address: '127.0.0.1', family: 4 },@@ -80,7 +80,11 @@ test('a working route gets time to answer after an earlier route fails @smoke',})test('DNS resolution obeys the request deadline @smoke', async () => {- const connection = new StreamConnection(iface, 100, () => new Promise(() => {}))+ const connection = new StreamConnection(+ () => iface,+ 100,+ () => new Promise(() => {})+ )await expect(connection.request(new URL('http://unresolved.example.test/file'), {})).rejects.toThrow('Could not resolve the download host in time')@@ -98,7 +102,7 @@ test('a kept-alive connection the server dropped is replaced without failing the})server.on('connection', () => connections++)await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))- const connection = new StreamConnection(loopback, 2000)+ const connection = new StreamConnection(() => loopback, 2000)try {const url = new URL(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`)expect(await body((await connection.request(url, {})).res)).toBe('answer 1')@@ -113,7 +117,11 @@ test('a kept-alive connection the server dropped is replaced without failing thetest('a request abandoned while still connecting gives up the connection with it @smoke', async () => {// DNS that never answers stands in for any connect that hangs: the abort has to end it, not the// deadline.- const connection = new StreamConnection(iface, 5000, () => new Promise(() => {}))+ const connection = new StreamConnection(+ () => iface,+ 5000,+ () => new Promise(() => {})+ )const abort = new AbortController()const started = Date.now()setTimeout(() => abort.abort(), 100)@@ -123,3 +131,21 @@ test('a request abandoned while still connecting gives up the connection with itexpect(Date.now() - started).toBeLessThan(1000)connection.close()})++test('a network that comes back with a new address is reached at that one @smoke', async () => {+ const server = createServer((_req, res) => res.end('ok'))+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ // Gone, and then back: every new socket asks for the network as it is now.+ let current: NetworkInterfaceInfo | undefined+ const connection = new StreamConnection(() => current, 2000)+ try {+ const url = new URL(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`)+ await expect(connection.request(url, {})).rejects.toThrow(/not connected/)+ current = loopback+ const { res } = await connection.request(url, {})+ expect(await body(res)).toBe('ok')+ } finally {+ connection.close()+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+})diff --git a/e2e/plan.spec.ts b/e2e/plan.spec.tsindex a760843..161e908 100644--- a/e2e/plan.spec.ts+++ b/e2e/plan.spec.ts@@ -7,19 +7,19 @@ import {MIN_BLOCK_BYTES,planBlocks,planDownload,- START_STREAMS_PER_NETWORK+ START_STREAMS_PER_NETWORK,+ startingStreams} from '../src/main/download/plan'-// I. How a download is cut into blocks and streams. Pure, so it's checked over the whole input-// space instead of hand-picked sizes.+// I. How a download is cut into blocks, and how many streams a network starts on them. Pure, so+// it's checked over the whole input space instead of hand-picked sizes.const MIB = 1024 * 1024const splittable = fc.record({totalBytes: fc.integer({ min: 1, max: 2 ** 42 }),splittable: fc.constant(true),- networkCount: fc.integer({ min: 1, max: 6 }),- streamsPerNetwork: fc.option(fc.integer({ min: 1, max: 20 }), { nil: undefined })+ networkCount: fc.integer({ min: 1, max: 6 })})test.describe('download plan', () => {@@ -37,59 +37,28 @@ test.describe('download plan', () => {)})- test('every network gets a stream, and never one with no block to claim', () => {+ test('a joining network gets a stream, and never one with no block to claim', () => {fc.assert(- fc.property(splittable, (request) => {- const { streamNetworks, blockCount } = planDownload(request)- const perNetwork = new Map<number, number>()- for (const network of streamNetworks) {- perNetwork.set(network, (perNetwork.get(network) ?? 0) + 1)- }- expect(perNetwork.size).toBe(request.networkCount)- for (const count of perNetwork.values()) {- expect(count).toBeLessThanOrEqual(request.streamsPerNetwork ?? START_STREAMS_PER_NETWORK)+ fc.property(+ fc.nat(10_000),+ fc.integer({ min: 1, max: 6 }),+ fc.option(fc.integer({ min: 1, max: 20 }), { nil: undefined }),+ (waiting, networkCount, requested) => {+ const count = startingStreams(waiting, networkCount, requested)+ expect(count).toBeGreaterThanOrEqual(1)+ expect(count).toBeLessThanOrEqual(requested ?? START_STREAMS_PER_NETWORK)expect(count).toBeLessThanOrEqual(MAX_STREAMS_PER_NETWORK)- // Streams beyond the block count would idle — except the one each network keeps.- expect(count).toBeLessThanOrEqual(- Math.max(1, Math.ceil(blockCount / request.networkCount))- )- }- })- )- })-- test('streams start fairly: no network is ever more than one ahead of another', () => {- fc.assert(- fc.property(splittable, (request) => {- const { streamNetworks } = planDownload(request)- const started = new Array<number>(request.networkCount).fill(0)- for (const network of streamNetworks) {- started[network]++- expect(Math.max(...started) - Math.min(...started)).toBeLessThanOrEqual(1)+ // Streams beyond the waiting blocks would idle — except the one each network keeps.+ expect(count).toBeLessThanOrEqual(Math.max(1, Math.ceil(waiting / networkCount)))}- })+ ))})- test('the first stream on each network starts before any network gets a second', () => {- const plan = planDownload({- totalBytes: 50.8 * MIB,- splittable: true,- networkCount: 2,- streamsPerNetwork: 8- })- expect(plan.streamNetworks.slice(0, 4)).toEqual([0, 1, 0, 1])- })-- test('a file too small to split is one block, with every network still listed', () => {- const plan = planDownload({- totalBytes: 300 * 1024,- splittable: true,- networkCount: 2,- streamsPerNetwork: 8- })+ test('a file too small to split is one block, and each network still gets a stream', () => {+ const plan = planDownload({ totalBytes: 300 * 1024, splittable: true, networkCount: 2 })expect(plan.blockCount).toBe(1)- expect(plan.streamNetworks).toEqual([0, 1])+ expect(startingStreams(plan.blockCount, 2, 8)).toBe(1)})test('a large file keeps 8 MB blocks', () => {@@ -99,7 +68,7 @@ test.describe('download plan', () => {test('each network starts with four streams, with blocks enough to grow to its limit', () => {const plan = planDownload({ totalBytes: 512 * MIB, splittable: true, networkCount: 2 })- expect(plan.streamNetworks).toEqual([0, 1, 0, 1, 0, 1, 0, 1])+ expect(startingStreams(plan.blockCount, 2)).toBe(4)// Streams added later need waiting blocks to take: two each, at the most every network can have.expect(plan.blockCount).toBeGreaterThanOrEqual(2 * MAX_STREAMS_PER_NETWORK * 2)})@@ -119,21 +88,18 @@ test.describe('download plan', () => {totalBytes: 40 * 64 * 1024,splittable: true,networkCount: 1,- streamsPerNetwork: 4,maxBlockBytes: 64 * 1024})expect(plan.blockSizeBytes).toBe(64 * 1024)expect(plan.blockCount).toBe(40)})- test('no range support or unknown size: one stream on the first network', () => {+ test('no range support or unknown size: one block', () => {for (const request of [{ totalBytes: 10 * MIB, splittable: false },{ totalBytes: 0, splittable: true }]) {- const plan = planDownload({ ...request, networkCount: 3, streamsPerNetwork: 8 })- expect(plan.blockCount).toBe(1)- expect(plan.streamNetworks).toEqual([0])+ expect(planDownload({ ...request, networkCount: 3 }).blockCount).toBe(1)}})@@ -158,7 +124,8 @@ test.describe('download plan', () => {expect(planBlocks(0, 0)).toMatchObject([{ rangeStart: 0, rangeEnd: null }])})- test('interleave keeps each group in order', () => {+ test('interleave serves every group before any twice, keeping each group in order', () => {+ expect(interleave(['a', 'a', 'a', 'b', 'b'], (id) => id)).toEqual(['a', 'b', 'a', 'b', 'a'])fc.assert(fc.property(fc.array(fc.tuple(fc.integer({ min: 0, max: 3 }), fc.nat())), (items) => {const out = interleave(items, ([group]) => group)diff --git a/e2e/scheduler.spec.ts b/e2e/scheduler.spec.tsindex e24893e..d50de21 100644--- a/e2e/scheduler.spec.ts+++ b/e2e/scheduler.spec.ts@@ -114,7 +114,7 @@ test.describe('scheduler: taking the next block', () => {fc.array(fc.record({interfaceId: fc.constantFrom(...networks),- status: fc.constantFrom<ChunkStatus>('pending', 'downloading', 'retrying', 'error')+ status: fc.constantFrom<ChunkStatus>('pending', 'downloading', 'retrying', 'paused')}),{ minLength: 1, maxLength: 8 }),diff --git a/src/main/download/chunkDownloader.ts b/src/main/download/chunkDownloader.tsindex cb1f103..0d8b703 100644--- a/src/main/download/chunkDownloader.ts+++ b/src/main/download/chunkDownloader.ts@@ -1,7 +1,7 @@import type { Writable } from 'node:stream'import type { ClientRequest, IncomingMessage } from 'node:http'import { URL } from 'node:url'-import type { StreamConnection } from '../network/routes'+import { asConnectionError, type StreamConnection } from '../network/routes'import { testKnobs } from '../testKnobs'import { compareVersion, type FileVersion, type VersionCheck } from './fileVersion'@@ -130,7 +130,7 @@ export function downloadChunk(options: ChunkDownloadOptions): Promise<void> {const resetWatchdog = (): void => {clearWatchdog()stallWatchdog = setTimeout(() => {- fail(new Error('Connection stalled: no response from server'))+ fail(asConnectionError(new Error('Connection stalled: no response from server')))}, STALL_TIMEOUT_MS)}@@ -179,7 +179,9 @@ export function downloadChunk(options: ChunkDownloadOptions): Promise<void> {return}currentReq = req- req.on('error', fail)+ // The connection dropping mid-answer; one the server answered wrongly fails below.+ const dropped = (error: Error): void => fail(asConnectionError(error))+ req.on('error', dropped)const status = res.statusCode ?? 0if (status >= 300 && status < 400) {@@ -248,7 +250,7 @@ export function downloadChunk(options: ChunkDownloadOptions): Promise<void> {const fileStream = createDestination()currentFileStream = fileStream- res.on('error', fail)+ res.on('error', dropped)fileStream.on('error', fail)// Arm watchdog for incoming body bytes — drops and retries if the server sendsdiff --git a/src/main/download/concurrency.ts b/src/main/download/concurrency.tsindex 908d788..cd68e12 100644--- a/src/main/download/concurrency.ts+++ b/src/main/download/concurrency.ts@@ -17,6 +17,9 @@// - A step that doesn't pay is undone and that network grows no further. So is one whose new// streams are turned away: failing before they receive anything is how a server says it wants// fewer connections.+// - Networks join and leave while a download runs. Speeds measured before say nothing about+// the networks there are now, so a step under way is then undone unjudged and measuring starts+// over; a network that joins (or comes back) is new to it, whatever was found out before.//// 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.@@ -33,6 +36,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. */spareWork: number@@ -95,10 +99,18 @@ export class ConcurrencyController {private readonly settled = new Set<string>()/** Where the next look for a network to grow starts, so each gets its turn. */private next = 0+ /** The networks the last tick saw. */+ private members: Set<string> | null = nullconstructor(private readonly policy: ConcurrencyPolicy) {}tick(snapshot: Snapshot): Action | undefined {+ const known = this.members+ const members = (this.members = new Set(snapshot.networks.map((network) => network.id)))+ if (known && (known.size !== members.size || [...members].some((id) => !known.has(id)))) {+ return this.regroup(snapshot, known)+ }+const phase = (this.phase ??= { kind: 'measure', measurement: this.measurement(snapshot) })switch (phase.kind) {case 'measure': {@@ -144,6 +156,16 @@ export class ConcurrencyController {: undefined}+ /** Networks joined or left: see the top of this file. */+ private regroup(snapshot: Snapshot, known: Set<string>): Action | undefined {+ for (const { id } of snapshot.networks) if (!known.has(id)) this.settled.delete(id)+ const phase = this.phase+ this.phase = { kind: 'measure', measurement: this.measurement(snapshot) }+ return phase?.kind === 'trial'+ ? { kind: 'retire', networkId: phase.networkId, count: phase.added }+ : undefined+ }+private measurement(snapshot: Snapshot): Measurement {return { startAt: snapshot.now + this.policy.warmupMs, from: null, last: null, windows: 0 }}diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.tsindex 4d0d5b4..5e61c82 100644--- a/src/main/download/downloadManager.ts+++ b/src/main/download/downloadManager.ts@@ -7,10 +7,12 @@ import { IpcChannels } from '../../shared/ipc-channels'import type {BlockState,ChunkState,+ DownloadNetwork,DownloadState,DownloadStatus,DownloadUpdate,NetworkInterfaceInfo,+ NetworkStatus,StartDownloadRequest} from '../../shared/types'import { testKnobs, testStreamsPerNetwork } from '../testKnobs'@@ -25,11 +27,19 @@ import { downloadChunk, fetchRange, RemoteChangedError } from './chunkDownloaderimport { DownloadFile } from './downloadFile'import { compareVersion, type FileVersion } from './fileVersion'import { ensureDirectory, reserveDestinationPath } from './paths'-import { interleave, MAX_STREAMS_PER_NETWORK, planBlocks, planDownload } from './plan'+import {+ interleave,+ MAX_STREAMS_PER_NETWORK,+ planBlocks,+ planDownload,+ startingStreams+} from './plan'import { restoreBlocks, saveBlocks, type SavedBlocks } from './savedProgress'import { pickWork, type SchedulerPolicy, type Work } from './scheduler'+import type { NetworkMonitor } from '../network/interfaces'import {compatibleInterfaces,+ ConnectionError,NoCompatibleRouteError,resolveTargetWithin,StreamConnection,@@ -83,6 +93,9 @@ type AttemptOutcome =interface ChunkRuntime {/** Aborts the whole stream: pause and cancel. */controller: AbortController+ /** Cuts its waits short — a backoff, a look for work — when the stream stops, or when the run+ * has nothing left for it to do. */+ wait: AbortSignal/** Its one connection to the server, reused from block to block. */connection: StreamConnection/** What the stream is fetching right now, if anything. */@@ -97,6 +110,9 @@ interface ChunkRuntime {receivedBytes: number/** Failed attempts in a row, for backoff. */failures: number+ /** Of those, the ones the server answered wrongly: MAX_CHUNK_RETRIES of them and it gives up.+ * A connection that failed isn't one — see finishFailed. */+ strikes: number/** Stopped for good, and to leave the list once its worker has (see retireStreams). */retiring: boolean}@@ -111,8 +127,15 @@ interface DownloadRuntime {publicationPath?: stringpublicationIdentity?: { dev: number; ino: number }requestPayload: StartDownloadRequest- activeInterfaces: NetworkInterfaceInfo[]chunkRuntimes: Map<number, ChunkRuntime>+ /** The running streams' workers, by stream id. Empty unless the download is running. */+ workers: Map<number, Promise<void>>+ /** Aborted once the current run is over — stopped (a pause, a cancel, an error) or every+ * block in — so nothing starts streams for it and no stream waits on. */+ stop: AbortController+ /** Each network's status as reconcile last left it; how it tells a network that has just come+ * into use. Cleared at the start of each run. */+ reconciled: Map<string, NetworkStatus>file: DownloadFilerunPromise?: Promise<void>publishing: boolean@@ -136,9 +159,10 @@ interface DownloadRuntime {attempts: Map<number, Attempt[]>/** Hedges started per block index, capped at SCHEDULER_POLICY.maxHedgesPerBlock. */hedgesByBlock: Map<number, number>- /** Everything each network's streams have received, by network id: what the stream count is- * judged by (see concurrency.ts). */- receivedByNetwork: Map<string, number>+ /** By network id: everything its streams have received, which is what the stream count is+ * judged by (see concurrency.ts), and when it last showed it was alive — received something,+ * or came into use. */+ traffic: Map<string, { received: number; aliveAt: number }>/** Decides how many streams each network runs; kept for the whole download, so a pause and* resume doesn't forget what it has found out. */concurrency: ConcurrencyController | null@@ -154,7 +178,9 @@ interface PersistedDownloadBase {publicationPath?: stringpublicationIdentity?: { dev: number; ino: number }requestPayload: StartDownloadRequest- activeInterfaces: NetworkInterfaceInfo[]+ /** The networks, as saved before a download listed them in its state. Read only to fill in+ * `networks` for a download saved that way. */+ activeInterfaces?: NetworkInterfaceInfo[]}type PersistedDownload = PersistedDownloadBase &@@ -172,6 +198,8 @@ const debug: (...args: unknown[]) => void = process.env['PLEXO_DEBUG']: () => {}const UI_UPDATE_MS = 200+/** How often a running download takes stock (see run). */+const TICK_MS = 500// Syncing a growing file can briefly monopolize a slow destination drive. Keep recovery// checkpoints independent of UI updates; pause and publication still force an immediate sync.const CHECKPOINT_INTERVAL_MS = 15_000@@ -227,7 +255,8 @@ const SLOW_RATIO = 0.1const SLOW_WARMUP_MS = testKnobs.slowWarmupMsconst SLOW_FOR_MS = testKnobs.slowForMs// A connection that has received nothing this long, while the file is being served to others, is-// dead rather than slow (a network that isn't answering, a stuck handshake).+// dead rather than slow (a network that isn't answering, a stuck handshake). A whole network+// that has received nothing this long, while its connections fail, can't reach the server.const SILENT_AFTER_MS = testKnobs.silentAfterMs// Bounds every case where refreshing can't help (the whole network got slower, a stale// reference): at worst a block pays for a couple of cheap reconnects, then is left alone.@@ -244,10 +273,16 @@ const CONCURRENCY_POLICY: ConcurrencyPolicy = {maxWindows: 4}-/** How many streams a download runs is only for it to work out when there can be more than one- * — a download without ranges or a known size is a single request — and unless a test fixes it. */+/** Whether the file can be fetched in parts. Otherwise one request has to carry all of it: one+ * stream, on one network. */+function splittable(request: StartDownloadRequest): boolean {+ return request.supportsRanges && request.totalBytes > 0+}++/** 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 request.supportsRanges && request.totalBytes > 0 && testStreamsPerNetwork() === null+ return splittable(request) && testStreamsPerNetwork() === null? new ConcurrencyController(CONCURRENCY_POLICY): null}@@ -261,17 +296,32 @@ function median(values: number[]): number {return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2}-/** Total live speed across a download's worker connections (bounded by MAX_CHUNKS, unlike blocks). */-function sumChunkSpeeds(runtime: DownloadRuntime, now = Date.now()): number {+/** Brings every stream's speed up to date, and each network's and the download's with them. */+function updateSpeeds(runtime: DownloadRuntime, now = Date.now()): void {let total = 0+ const byNetwork = new Map<string, number>()for (const chunk of runtime.state.chunks) {if (chunk.status === 'downloading') {const samples = runtime.speedSamplesByChunk.get(chunk.id)chunk.speedBytesPerSec = calculateCurrentSpeed(samples, now)}total += chunk.speedBytesPerSec+ byNetwork.set(+ chunk.interfaceId,+ (byNetwork.get(chunk.interfaceId) ?? 0) + chunk.speedBytesPerSec+ )+ }+ for (const network of runtime.state.networks) {+ network.speedBytesPerSec = byNetwork.get(network.id) ?? 0}- return total+ runtime.state.speedBytesPerSec = total+}++/** Nothing is moving: a paused or stopped download reads 0 everywhere. */+function clearSpeeds(state: DownloadState): void {+ state.speedBytesPerSec = 0+ for (const chunk of state.chunks) chunk.speedBytesPerSec = 0+ for (const network of state.networks) network.speedBytesPerSec = 0}/** Waits, but returns early if the signal aborts (pause/cancel shouldn't wait out a retry backoff). */@@ -293,18 +343,62 @@ function delay(ms: number, signal: AbortSignal): Promise<void> {})}-function newStream(id: number, iface: NetworkInterfaceInfo): ChunkState {+function newStream(id: number, networkId: string): ChunkState {return {id,- interfaceId: iface.id,- interfaceLabel: iface.displayName,- interfaceKind: iface.kind,+ interfaceId: networkId,rangeStart: 0,rangeEnd: null,bytesDownloaded: 0,speedBytesPerSec: 0,- status: 'pending',- retryCount: 0+ status: 'pending'+ }+}++function newNetwork(iface: NetworkInterfaceInfo, enabled: boolean): DownloadNetwork {+ return {+ id: iface.id,+ label: iface.displayName,+ kind: iface.kind,+ enabled,+ status: enabled ? 'on' : 'off',+ bytesDownloaded: 0,+ speedBytesPerSec: 0,+ retries: 0+ }+}++/** A runtime for `state`, with nothing running. */+function newRuntime(+ state: DownloadState,+ requestPayload: StartDownloadRequest,+ file: DownloadFile,+ blocks: BlockState[]+): DownloadRuntime {+ return {+ state,+ requestPayload,+ chunkRuntimes: new Map(),+ workers: new Map(),+ stop: new AbortController(),+ reconciled: new Map(),+ file,+ publishing: false,+ speedSamplesByChunk: new Map(),+ pushScheduled: false,+ blocks,+ totalBlocks: state.totalBlocks ?? blocks.length,+ persistenceChain: Promise.resolve(),+ removed: false,+ acceptedVersions: [requestedVersion(requestPayload)],+ refreshesByBlock: new Map(),+ avoidNetworkByBlock: new Map(),+ attempts: new Map(),+ hedgesByBlock: new Map(),+ traffic: new Map(),+ concurrency: concurrencyFor(requestPayload),+ sentUpdates: 0,+ sentBlocks: []}}@@ -343,8 +437,7 @@ export class DownloadManager {constructor(private getWindow: () => BrowserWindow | null,- private getInterfaceById: (id: string) => NetworkInterfaceInfo | undefined,- private refreshInterfaces: () => Promise<NetworkInterfaceInfo[]>+ private networks: NetworkMonitor) {this.initialization = this.restorePersistedDownloads()}@@ -385,24 +478,21 @@ export class DownloadManager {? persisted.state.blocks: undefinedif (!blocks) return- const state: DownloadState = { ...persisted.state, blocks }+ const state: DownloadState = {+ ...persisted.state,+ // Saved before downloads listed their networks: the ones it ran on, all in use.+ networks:+ (persisted.state.networks as DownloadNetwork[] | undefined) ??+ (persisted.activeInterfaces ?? []).map((iface) => newNetwork(iface, true)),+ // Streams are only for a run; a resumed download starts its own.+ chunks: [],+ blocks+ }if (state.status === 'downloading') {state.status = 'paused'state.pausedAt = persisted.savedAt || Date.now()}- state.speedBytesPerSec = 0- for (const chunk of state.chunks) {- chunk.speedBytesPerSec = 0- chunk.currentBlockIndex = undefined- chunk.hedge = undefined- if (- chunk.status === 'downloading' ||- chunk.status === 'retrying' ||- chunk.status === 'pending'- ) {- chunk.status = 'paused'- }- }+ clearSpeeds(state)for (const block of blocks) {if (block.status === 'downloading') block.status = 'pending'}@@ -439,6 +529,7 @@ export class DownloadManager {state.status = 'error'state.error ='The partial download file is missing. Remove this download and start again.'+ state.resumable = false} else {for (const block of blocks) {const length = block.rangeEnd === null ? 0 : block.rangeEnd - block.rangeStart + 1@@ -455,31 +546,11 @@ export class DownloadManager {}}- restored.push({- state,- publicationPath: persisted.publicationPath,- publicationIdentity: persisted.publicationIdentity,- requestPayload: persisted.requestPayload,- activeInterfaces: persisted.activeInterfaces,- chunkRuntimes: new Map(),- file,- publishing: false,- speedSamplesByChunk: new Map(),- pushScheduled: false,- blocks,- totalBlocks: state.totalBlocks ?? blocks.length,- persistenceChain: Promise.resolve(),- removed: false,- acceptedVersions: [requestedVersion(persisted.requestPayload)],- refreshesByBlock: new Map(),- avoidNetworkByBlock: new Map(),- attempts: new Map(),- hedgesByBlock: new Map(),- receivedByNetwork: new Map(),- concurrency: concurrencyFor(persisted.requestPayload),- sentUpdates: 0,- sentBlocks: []- })+ const runtime = newRuntime(state, persisted.requestPayload, file, blocks)+ runtime.publicationPath = persisted.publicationPath+ runtime.publicationIdentity = persisted.publicationIdentity+ this.recomputeAggregates(runtime)+ restored.push(runtime)} catch {// Ignore incomplete or corrupt manifests; other downloads can still be restored.}@@ -544,35 +615,26 @@ export class DownloadManager {throw new Error('A download is already in progress — finish or remove it first.')}- const selected = requestPayload.interfaceIds- .map((interfaceId) => this.getInterfaceById(interfaceId))- .filter((iface): iface is NetworkInterfaceInfo => Boolean(iface))-+ const available = await this.networks.refresh()+ const selected = available.filter((iface) => requestPayload.interfaceIds.includes(iface.id))if (selected.length === 0) {throw new Error('Select at least one network interface')}const target = new URL(requestPayload.url)- const interfaces = compatibleInterfaces(+ // A selected network that can't reach the host's address family starts switched off.+ const usable = compatibleInterfaces(selected,await resolveTargetWithin(targetHost(target), testKnobs.stallTimeoutMs))- if (interfaces.length === 0) throw new NoCompatibleRouteError(targetHost(target))-- return this.startWithInterfaces(requestPayload, interfaces)- }+ if (usable.length === 0) throw new NoCompatibleRouteError(targetHost(target))- private async startWithInterfaces(- requestPayload: StartDownloadRequest,- interfaces: NetworkInterfaceInfo[]- ): Promise<string> {await ensureDirectory(requestPayload.destinationDir)await ensureDiskSpace(requestPayload.destinationDir, requestPayload.totalBytes)const plan = planDownload({totalBytes: requestPayload.totalBytes,splittable: requestPayload.supportsRanges,- networkCount: interfaces.length,- streamsPerNetwork: testStreamsPerNetwork() ?? undefined,+ networkCount: usable.length,maxBlockBytes: testKnobs.blockBytes // 8 MB outside tests})@@ -592,10 +654,13 @@ export class DownloadManager {// blocks rather than by shrinking their count here.const blocks = planBlocks(requestPayload.totalBytes, plan.blockSizeBytes)- const chunks = plan.streamNetworks.map((networkIndex, id) =>- newStream(id, interfaces[networkIndex])- )- const activeInterfaces = [...new Set(plan.streamNetworks)].map((index) => interfaces[index])+ // The computer's other networks are listed too, switched off, for the user to turn on.+ const networks = available.map((iface) => newNetwork(iface, usable.includes(iface)))+ // Unsplittable: one network carries it (IdleScreen lets only one be picked).+ if (!splittable(requestPayload)) {+ for (const network of networks) network.enabled &&= network.id === usable[0].id+ for (const network of networks) network.status = network.enabled ? 'on' : 'off'+ }const state: DownloadState = {id,@@ -606,42 +671,21 @@ export class DownloadManager {bytesDownloaded: 0,speedBytesPerSec: 0,status: 'downloading',- chunks,- peakStreams: chunks.length,+ networks,+ chunks: [],+ peakStreams: 0,blocks,totalBlocks: blocks.length,blockSizeBytes: plan.blockSizeBytes,startedAt: Date.now()}- const runtime: DownloadRuntime = {- state,- requestPayload,- activeInterfaces,- chunkRuntimes: new Map(),- file,- publishing: false,- speedSamplesByChunk: new Map(),- pushScheduled: false,- blocks,- totalBlocks: blocks.length,- persistenceChain: Promise.resolve(),- removed: false,- acceptedVersions: [requestedVersion(requestPayload)],- refreshesByBlock: new Map(),- avoidNetworkByBlock: new Map(),- attempts: new Map(),- hedgesByBlock: new Map(),- receivedByNetwork: new Map(),- concurrency: concurrencyFor(requestPayload),- sentUpdates: 0,- sentBlocks: []- }+ const runtime = newRuntime(state, requestPayload, file, blocks)this.runtimes.set(id, runtime)await this.persistNow(runtime)this.pushUpdate(runtime)- runtime.runPromise = this.runChunksToCompletion(runtime, runtime.state.chunks)+ runtime.runPromise = this.run(runtime)return id}@@ -651,14 +695,14 @@ export class DownloadManager {if (!runtime || runtime.state.status !== 'downloading' || runtime.publishing) returnruntime.state.status = 'paused'- runtime.state.speedBytesPerSec = 0runtime.state.pausedAt = Date.now()+ clearSpeeds(runtime.state)for (const chunk of runtime.state.chunks) {if (chunk.status !== 'completed') {chunk.status = 'paused'}- chunk.speedBytesPerSec = 0chunk.currentBlockIndex = undefined+ chunk.hedge = undefined}for (const block of runtime.blocks) {if (block.status === 'downloading') {@@ -666,10 +710,7 @@ export class DownloadManager {}}runtime.avoidNetworkByBlock.clear()- for (const chunk of runtime.state.chunks) chunk.hedge = undefined- for (const chunkRuntime of runtime.chunkRuntimes.values()) {- chunkRuntime.controller.abort()- }+ this.stopRun(runtime)this.pushUpdate(runtime)await runtime.runPromiseawait this.persistNow(runtime)@@ -677,50 +718,23 @@ export class DownloadManager {resume(id: string): void {const runtime = this.runtimes.get(id)- if (!runtime || (runtime.state.status !== 'paused' && runtime.state.status !== 'error')) return+ if (!runtime) return+ const { status, resumable } = runtime.state+ if (status !== 'paused' && !(status === 'error' && resumable !== false)) returnvoid this.resumeAfterVerifying(runtime)}// A file that changed on the server while this download was paused is caught by the first// chunk request after resuming: its response is checked against the version the download- // started on (see runWorker), which can tell a real change from a relabelled server.+ // started on (see runWorker), which can tell a real change from a relabelled server. Whether a+ // network is there to resume on is the run's business: with none, it waits for one.private async resumeAfterVerifying(runtime: DownloadRuntime): Promise<void> {- const { url } = runtime.requestPayload// The paused run can still be winding down: a writer closing, a sample check in flight. A new// one must not start beside it — both would go on to publish, and act on each other's streams.await runtime.runPromise-- let availableInterfaces: NetworkInterfaceInfo[]- try {- availableInterfaces = await this.refreshInterfaces()- } catch {- runtime.state.error = 'Could not refresh network interfaces. Try resuming again.'- this.pushUpdate(runtime)- return- }- if (runtime.state.status !== 'paused' && runtime.state.status !== 'error') return-- const selectedIds = new Set(runtime.requestPayload.interfaceIds)- runtime.activeInterfaces = availableInterfaces.filter((iface) => selectedIds.has(iface.id))- const selectedAvailable = runtime.activeInterfaces.length > 0- try {- runtime.activeInterfaces = compatibleInterfaces(- runtime.activeInterfaces,- await resolveTargetWithin(targetHost(new URL(url)), testKnobs.stallTimeoutMs)- )- } catch {- runtime.state.error = 'Could not resolve the download host. Try resuming again.'- this.pushUpdate(runtime)- return- }- if (runtime.activeInterfaces.length === 0) {- runtime.state.error = selectedAvailable- ? `No selected network has an address compatible with ${targetHost(new URL(url))}.`- : 'None of the networks selected for this download are currently available. Reconnect one and try again.'- this.pushUpdate(runtime)- return- }+ // Just after launch the networks may not have been looked at yet.+ await this.networks.refresh()if ((await runtime.file.size().catch(() => -1)) < 0) {runtime.state.error =@@ -730,18 +744,16 @@ export class DownloadManager {}if (runtime.state.status !== 'paused' && runtime.state.status !== 'error') return- for (let index = 0; index < runtime.state.chunks.length; index++) {- const chunk = runtime.state.chunks[index]- const iface =- runtime.activeInterfaces.find((entry) => entry.id === chunk.interfaceId) ??- runtime.activeInterfaces[index % runtime.activeInterfaces.length]- chunk.interfaceId = iface.id- chunk.interfaceLabel = iface.displayName- chunk.interfaceKind = iface.kind- }-runtime.state.status = 'downloading'runtime.state.error = undefined+ runtime.state.resumable = undefined+ // A network that had failed, or couldn't get through, gets another go.+ for (const network of runtime.state.networks) {+ if (network.status === 'failed' || network.status === 'unreachable') {+ network.status = 'on'+ network.error = undefined+ }+ }if (runtime.state.pausedAt) {runtime.state.totalPausedMs =(runtime.state.totalPausedMs || 0) + (Date.now() - runtime.state.pausedAt)@@ -762,14 +774,36 @@ export class DownloadManager {runtime.avoidNetworkByBlock.clear()this.pushUpdate(runtime)- // Streams start in the order given, and each claims a block on the spot: interleaved, so a- // paused download saved before that was the rule can't hand every block to one network.- const pending = runtime.state.chunks.filter((chunk) => chunk.status !== 'completed')- const toRun = pending.length > 0 ? pending : runtime.state.chunks- runtime.runPromise = this.runChunksToCompletion(- runtime,- interleave(toRun, (chunk) => chunk.interfaceId)- )+ runtime.runPromise = this.run(runtime)+ }++ /** Switches one of a download's networks on or off, running or paused. The last network in+ * use can't be switched off: pausing is how a download stops. */+ setNetworkEnabled(id: string, networkId: string, enabled: boolean): void {+ const runtime = this.runtimes.get(id)+ const status = runtime?.state.status+ if (!runtime || (status !== 'downloading' && status !== 'paused')) return+ const { networks } = runtime.state+ const network = networks.find((entry) => entry.id === networkId)+ if (!network || network.enabled === enabled) return+ if (!enabled && !networks.some((other) => other !== network && other.enabled)) return+ // A download that can't be split runs over one network: switching one on switches it over.+ if (enabled && !splittable(runtime.requestPayload)) {+ for (const other of networks) other.enabled = false+ }+ network.enabled = enabled+ this.reconcile(runtime)+ this.pushUpdate(runtime)+ }++ /** The computer's networks changed (see NetworkMonitor). */+ networksChanged(): void {+ for (const runtime of this.runtimes.values()) {+ const { status } = runtime.state+ if (status !== 'downloading' && status !== 'paused') continue+ this.reconcile(runtime)+ this.scheduleUpdate(runtime)+ }}async cancel(id: string): Promise<void> {@@ -784,14 +818,9 @@ export class DownloadManager {returnruntime.state.status = 'cancelled'- runtime.state.speedBytesPerSec = 0- for (const chunk of runtime.state.chunks) {- chunk.speedBytesPerSec = 0- chunk.status = 'cancelled'- }- for (const chunkRuntime of runtime.chunkRuntimes.values()) {- chunkRuntime.controller.abort()- }+ clearSpeeds(runtime.state)+ for (const chunk of runtime.state.chunks) chunk.status = 'cancelled'+ this.stopRun(runtime)this.pushUpdate(runtime, false)await runtime.runPromiseawait runtime.file.discard()@@ -823,75 +852,45 @@ export class DownloadManager {)}- /** Runs (or resumes) the streams in parallel, leasing blocks until all are completed, and adds- * or retires streams as measurements say (see concurrency.ts). */- private async runChunksToCompletion(- runtime: DownloadRuntime,- chunks: ChunkState[]- ): Promise<void> {- /** Running workers, by stream id. */- const active = new Map<number, Promise<void>>()- const startWorker = (chunk: ChunkState): void => {- active.set(- chunk.id,- this.runWorker(runtime, chunk).finally(() => {- active.delete(chunk.id)- if (runtime.chunkRuntimes.get(chunk.id)?.retiring) this.removeStream(runtime, chunk)- })- )- }- for (const chunk of chunks) startWorker(chunk)-- const adjustStreams = (action: Action | undefined): void => {- if (action?.kind === 'add') {- for (const chunk of this.addStreams(runtime, action.networkId, action.count)) {- startWorker(chunk)- }- } else if (action?.kind === 'retire') {- for (const chunk of this.retireStreams(runtime, action.networkId, action.count)) {- // One that already stopped has no worker left to remove it.- if (!active.has(chunk.id)) this.removeStream(runtime, chunk)- }- }- }+ /**+ * Runs the download until every block is in, or it is stopped. Each TICK_MS, and whenever a+ * stream ends, it takes stock: speeds, stuck connections, which networks run streams (see+ * reconcile) and how many (see concurrency.ts). With no network to use, it waits for one.+ */+ private async run(runtime: DownloadRuntime): Promise<void> {+ if (runtime.stop.signal.aborted) runtime.stop = new AbortController()+ runtime.reconciled.clear()+ const { signal } = runtime.stop+ this.reconcile(runtime)- const speedTicker = setInterval(() => {- if (runtime.state.status !== 'downloading') return+ while (+ runtime.state.status === 'downloading' &&+ runtime.blocks.some((block) => block.status !== 'completed')+ ) {+ await Promise.race([delay(TICK_MS, signal), ...runtime.workers.values()])+ if ((runtime.state.status as DownloadStatus) !== 'downloading') breakconst now = Date.now()- const prevSpeed = runtime.state.speedBytesPerSec- const newSpeed = sumChunkSpeeds(runtime, now)- if (newSpeed !== prevSpeed) {- runtime.state.speedBytesPerSec = newSpeed- this.scheduleUpdate(runtime)- }+ const speed = runtime.state.speedBytesPerSec+ updateSpeeds(runtime, now)+ if (runtime.state.speedBytesPerSec !== speed) this.scheduleUpdate(runtime)this.refreshStuckConnections(runtime, now)- adjustStreams(runtime.concurrency?.tick(this.concurrencySnapshot(runtime, now)))- }, 500)- speedTicker.unref()-- try {- while (active.size > 0) await Promise.race(active.values())- } finally {- clearInterval(speedTicker)+ this.reconcile(runtime)+ this.adjustStreams(runtime, runtime.concurrency?.tick(this.concurrencySnapshot(runtime, now)))}+ // The last blocks are in, or the run was stopped: its streams wind down.+ runtime.stop.abort()+ await Promise.all(runtime.workers.values())// Stopped partway through a step: streams it added were never judged, so they don't stay.- if (runtime.state.status !== 'downloading') adjustStreams(runtime.concurrency?.interrupt())-- if (- runtime.state.status === 'downloading' &&- runtime.blocks.some((b) => b.status !== 'completed')- ) {- runtime.state.status = 'error'- runtime.state.error =- runtime.state.chunks.find((chunk) => chunk.error)?.error ??- 'No network could finish the remaining blocks'+ if (runtime.state.status !== 'downloading') {+ this.adjustStreams(runtime, runtime.concurrency?.interrupt())}if (runtime.state.status !== 'downloading') {- // Paused, errored, or cancelled — nothing left to do right now.- if (runtime.state.status === 'error' || runtime.state.status === 'cancelled') {+ // Paused, errored, or cancelled — nothing left to do right now. An error keeps what it has+ // unless it can't be resumed (see failDownload); cancel() discards it.+ if (runtime.state.status === 'error') {this.pushUpdate(runtime)- await runtime.file.discard()+ if (runtime.state.resumable === false) await runtime.file.discard()}return}@@ -930,6 +929,187 @@ export class DownloadManager {this.pushUpdate(runtime)}+ /** Stops the current run: every stream, and the run's own wait. */+ private stopRun(runtime: DownloadRuntime): void {+ runtime.stop.abort()+ for (const self of runtime.chunkRuntimes.values()) self.controller.abort()+ }++ /** Ends the download in an error. What it has downloaded stays for a resume, unless+ * `discard`: bytes that are no use any more. */+ private failDownload(runtime: DownloadRuntime, message: string, discard = false): void {+ if (runtime.state.status !== 'downloading') return+ runtime.state.status = 'error'+ runtime.state.error = message+ runtime.state.resumable = !discard+ this.notify('Download Failed', `${runtime.state.fileName}: ${message}`)+ this.stopRun(runtime)+ }++ /** The server keeps refusing requests over this network: it stops being used until the user+ * switches it off and on, it reconnects, or the download is resumed. */+ private failNetwork(runtime: DownloadRuntime, network: DownloadNetwork, message: string): void {+ network.status = 'failed'+ network.error = message+ this.reconcile(runtime)+ }++ private network(runtime: DownloadRuntime, id: string): DownloadNetwork {+ const network = runtime.state.networks.find((entry) => entry.id === id)+ if (!network) throw new Error(`Unknown network ${id}`)+ return network+ }++ /**+ * Brings the download's networks up to date with the computer's, and each network's streams in+ * line with what it can do now. Runs every tick and whenever something changes — a network+ * came or went, the user switched one, one stopped getting through — and is safe to run any+ * time.+ *+ * Networks: every one on the computer is listed; one that turns up mid-download starts off,+ * for the user to switch on. A network the download never used is dropped once it goes.+ *+ * Streams, while the download runs:+ * - A network that has just come into use (on) starts a set of them (see startingStreams);+ * from there concurrency.ts sizes it.+ * - One that can't reach the server (unreachable) keeps a single stream trying, to find out+ * when it can again.+ * - One that is off, offline or failed runs none. Retiring a stream costs nothing: what it+ * wrote stays, and whoever takes its block next resumes from there.+ * A download that can't be split runs one stream, on the first network able to carry it.+ */+ private reconcile(runtime: DownloadRuntime): void {+ const { state } = runtime+ const present = this.networks.current+ // Until the monitor has looked, nothing is known to be gone.+ const known = present !== null+ if (known) {+ state.networks = state.networks.filter(+ (network) =>+ network.enabled ||+ network.bytesDownloaded > 0 ||+ present.some((iface) => iface.id === network.id) ||+ state.chunks.some((chunk) => chunk.interfaceId === network.id)+ )+ for (const iface of present) {+ if (!state.networks.some((network) => network.id === iface.id)) {+ state.networks.push(newNetwork(iface, false))+ }+ }+ }++ for (const network of state.networks) {+ const iface = this.networks.find(network.id)+ if (iface) {+ network.label = iface.displayName+ network.kind = iface.kind+ }+ const status: NetworkStatus = !network.enabled+ ? 'off'+ : !iface && known+ ? 'offline'+ : network.status === 'off' || network.status === 'offline'+ ? 'on'+ : network.status+ if (status !== network.status) {+ network.status = status+ network.error = undefined+ }+ }+ if (state.status !== 'downloading' || runtime.stop.signal.aborted) return++ const enabled = state.networks.filter((network) => network.enabled)+ if (enabled.length > 0 && enabled.every((network) => network.status === 'failed')) {+ this.failDownload(runtime, enabled[0].error ?? 'No network could reach the server')+ return+ }++ const canSplit = splittable(runtime.requestPayload)+ const usable = state.networks.filter(+ (network) => network.status === 'on' || network.status === 'unreachable'+ )+ const running = canSplit ? usable : usable.slice(0, 1)+ const joining = running.filter(+ (network) =>+ network.status === 'on' &&+ (runtime.reconciled.get(network.id) !== 'on' ||+ this.liveStreams(runtime, network.id).length === 0)+ )+ const starting = canSplit+ ? startingStreams(+ runtime.blocks.filter((block) => block.status === 'pending').length,+ joining.length,+ testStreamsPerNetwork() ?? undefined+ )+ : 1++ const now = Date.now()+ const toStart: ChunkState[] = []+ for (const network of state.networks) {+ const live = this.liveStreams(runtime, network.id)+ const target = !running.includes(network)+ ? 0+ : network.status === 'unreachable'+ ? 1+ : joining.includes(network)+ ? Math.max(live.length, starting)+ : live.length+ if (joining.includes(network)) this.traffic(runtime, network.id).aliveAt = now+ if (live.length > target) this.retireStreams(runtime, network.id, live.length - target)+ // Streams kept from before a pause start again.+ for (const chunk of live.slice(0, target)) {+ if (!runtime.workers.has(chunk.id)) toStart.push(chunk)+ }+ if (target > live.length) {+ toStart.push(...this.addStreams(runtime, network.id, target - live.length))+ }+ runtime.reconciled.set(network.id, network.status)+ }+ // Each stream claims a block the moment it starts, so every network gets its first before+ // any gets a second: a small file shouldn't all go to whichever network came first.+ this.startStreams(+ runtime,+ interleave(toStart, (chunk) => chunk.interfaceId)+ )+ }++ /** A network's streams that aren't on their way out. */+ private liveStreams(runtime: DownloadRuntime, networkId: string): ChunkState[] {+ return runtime.state.chunks.filter(+ (chunk) => chunk.interfaceId === networkId && !runtime.chunkRuntimes.get(chunk.id)?.retiring+ )+ }++ private traffic(+ runtime: DownloadRuntime,+ networkId: string+ ): { received: number; aliveAt: number } {+ let traffic = runtime.traffic.get(networkId)+ if (!traffic) runtime.traffic.set(networkId, (traffic = { received: 0, aliveAt: 0 }))+ return traffic+ }++ private startStreams(runtime: DownloadRuntime, chunks: ChunkState[]): void {+ for (const chunk of chunks) {+ runtime.workers.set(+ chunk.id,+ this.runWorker(runtime, chunk).finally(() => {+ runtime.workers.delete(chunk.id)+ if (runtime.chunkRuntimes.get(chunk.id)?.retiring) this.removeStream(runtime, chunk)+ })+ )+ }+ if (chunks.length > 0) this.scheduleUpdate(runtime)+ }++ private adjustStreams(runtime: DownloadRuntime, action: Action | undefined): void {+ if (action?.kind === 'add') {+ this.startStreams(runtime, this.addStreams(runtime, action.networkId, action.count))+ } else if (action?.kind === 'retire') {+ this.retireStreams(runtime, action.networkId, action.count)+ }+ }+/*** Reconnects a connection that isn't carrying its weight. Reconnecting is cheap — the block* resumes from the staging file — and a fresh connection usually lands somewhere healthy.@@ -1062,7 +1242,6 @@ export class DownloadManager {runtime: DownloadRuntime,chunk: ChunkState,self: ChunkRuntime,- iface: NetworkInterfaceInfo,work: Work): Attempt {const { block } = work@@ -1070,7 +1249,7 @@ export class DownloadManager {kind: work.kind,block,streamId: chunk.id,- networkId: iface.id,+ networkId: chunk.interfaceId,startOffset: null,received: 0,networkReceived: 0,@@ -1086,7 +1265,7 @@ export class DownloadManager {if (work.kind === 'primary') {block.status = 'downloading'- block.interfaceId = iface.id+ block.interfaceId = chunk.interfaceIdruntime.avoidNetworkByBlock.delete(block.index)} else {runtime.hedgesByBlock.set(block.index, (runtime.hedgesByBlock.get(block.index) ?? 0) + 1)@@ -1186,17 +1365,22 @@ export class DownloadManager {): void {const now = Date.now()self.receivedBytes += deltaBytes- runtime.receivedByNetwork.set(- chunk.interfaceId,- (runtime.receivedByNetwork.get(chunk.interfaceId) ?? 0) + deltaBytes- )+ const traffic = this.traffic(runtime, chunk.interfaceId)+ traffic.received += deltaBytes+ traffic.aliveAt = now+ const network = this.network(runtime, chunk.interfaceId)+ if (network.status === 'unreachable') {+ // Through again: the next reconcile gives it back its streams.+ network.status = 'on'+ self.failures = 0+ }let samples = runtime.speedSamplesByChunk.get(chunk.id)if (!samples) {samples = []runtime.speedSamplesByChunk.set(chunk.id, samples)}chunk.speedBytesPerSec = pushSpeedSample(samples, self.receivedBytes, now)- runtime.state.speedBytesPerSec = sumChunkSpeeds(runtime)+ updateSpeeds(runtime, now)this.scheduleUpdate(runtime)}@@ -1205,6 +1389,7 @@ export class DownloadManager {// re-fetches bytes the other already has.const gained = advanceBlock(attempt.block, attempt.networkId, this.attemptPosition(attempt))chunk.bytesDownloaded += gained+ this.network(runtime, attempt.networkId).bytesDownloaded += gained// This runs on every completed writer callback, so it folds the delta in rather than re-summing// every block — that sum is O(blocks), and a large file has thousands of them. The other@@ -1219,14 +1404,13 @@ export class DownloadManager {runtime: DownloadRuntime,chunk: ChunkState,self: ChunkRuntime,- iface: NetworkInterfaceInfo,attempt: Attempt,outcome: AttemptOutcome): Promise<'continue' | 'stop'> {debug('attempt', {block: attempt.block.index,stream: chunk.id,- network: iface.displayName,+ network: attempt.networkId,kind: attempt.kind,outcome: outcome.type === 'aborted' ? `aborted:${outcome.reason}` : outcome.type,networkBytes: attempt.networkReceived,@@ -1275,6 +1459,7 @@ export class DownloadManager {1000}self.failures = 0+ self.strikes = 0// Whoever is still racing for the block has lost.for (const rival of runtime.attempts.get(block.index) ?? []) this.abortAttempt(rival, 'lost')this.recomputeAggregates(runtime)@@ -1311,7 +1496,7 @@ export class DownloadManager {// A moment before this stream asks again, so that a connection already proven fast, if// there is one, gets to the block before this one does.this.scheduleUpdate(runtime)- await delay(REFRESH_HANDOFF_MS, self.controller.signal)+ await delay(REFRESH_HANDOFF_MS, self.wait)self.warmSince = Date.now()self.slowSince = null}@@ -1326,7 +1511,7 @@ export class DownloadManager {error: unknown): Promise<'continue' | 'stop'> {const message = error instanceof Error ? error.message : String(error)- chunk.error = message+ const network = this.network(runtime, attempt.networkId)const deliveredNothing = attempt.networkReceived === 0if (error instanceof RemoteChangedError) {@@ -1344,63 +1529,65 @@ export class DownloadManager {if (compareVersion(runtime.acceptedVersions, error.seen).kind !== 'same') {runtime.acceptedVersions.push(error.seen)}- chunk.error = undefinedthis.letGo(runtime, chunk, self, attempt, false)return 'continue'}if (verdict === 'different') {// Every other worker would hit the same new version, so stop them all now rather than- // let each burn through its retries first.- this.letGo(runtime, chunk, self, attempt, false)- chunk.status = 'error'- runtime.state.status = 'error'- runtime.state.error = message- for (const other of runtime.chunkRuntimes.values()) other.controller.abort()- return 'stop'+ // let each burn through its retries first. What's on disk is of the old version: no use.+ this.failDownload(runtime, message, true)+ return this.finishStopped(runtime, chunk, self, attempt)}// 'unknown' — nothing to compare yet, or the check itself failed: retry like any other// failed request. Nothing wrong was written either way.}if (error instanceof NoCompatibleRouteError) {- // A redirect can move this worker to a host its network cannot reach. Return its block- // to the shared queue so another compatible worker can finish it.+ // A redirect can move this worker to a host its network cannot reach, and no retry over+ // it will change that. Its block goes back to the queue for another network.this.letGo(runtime, chunk, self, attempt, deliveredNothing)- chunk.status = 'error'- if (runtime.state.chunks.every((entry) => entry.status === 'error')) {- runtime.state.status = 'error'- runtime.state.error = message- }- this.scheduleUpdate(runtime)+ this.failNetwork(runtime, network, message)return 'stop'}+ // What the server's answer says about the network: a connection failing while the whole+ // network has gone quiet means the network can't reach the server — dropped, or connected+ // with no way through. It stops being used, bar one stream that keeps trying (see reconcile).+ if (+ error instanceof ConnectionError &&+ network.status === 'on' &&+ Date.now() - this.traffic(runtime, network.id).aliveAt >= SILENT_AFTER_MS+ ) {+ network.status = 'unreachable'+ this.reconcile(runtime)+ }+// A hedge is optional work: its failure isn't retried, and what it did write stays.if (attempt.kind === 'hedge') {this.letGo(runtime, chunk, self, attempt, deliveredNothing)return 'continue'}+ // A network that can't get through retries as a matter of course: that's not news.+ if (network.status === 'on') network.retries += 1self.failures += 1- chunk.retryCount += 1// Back to the queue, so any available worker can pick it up.this.letGo(runtime, chunk, self, attempt, deliveredNothing)- if (self.failures > MAX_CHUNK_RETRIES) {- chunk.status = 'error'- const allErrored = runtime.state.chunks.every((c) => c.status === 'error')- if (allErrored && (runtime.state.status as DownloadStatus) === 'downloading') {- runtime.state.status = 'error'- runtime.state.error = message- this.notify('Download Failed', `${runtime.state.fileName}: ${message}`)- for (const other of runtime.chunkRuntimes.values()) other.controller.abort()+ // A connection that failed is the network's doing, and is tried again for as long as the+ // network is there. A server that answered wrongly gets MAX_CHUNK_RETRIES in a row; then this+ // stream gives up, and once all its network's have, so does the network.+ if (!(error instanceof ConnectionError) && ++self.strikes > MAX_CHUNK_RETRIES) {+ self.retiring = true+ if (this.liveStreams(runtime, network.id).length === 0) {+ this.failNetwork(runtime, network, message)}return 'stop'}chunk.status = 'retrying'this.scheduleUpdate(runtime)- await delay(retryDelayMs(self.failures), self.controller.signal)+ await delay(retryDelayMs(self.failures), self.wait)const statusAfterDelay = runtime.state.status as DownloadStatusif (self.controller.signal.aborted || statusAfterDelay !== 'downloading') {chunk.status = statusAfterDelay === 'paused' ? 'paused' : 'cancelled'@@ -1434,21 +1621,16 @@ export class DownloadManager {}private concurrencySnapshot(runtime: DownloadRuntime, now: number): Snapshot {- const networks = runtime.activeInterfaces.map((iface) => {+ const inUse = runtime.state.networks.filter((network) => network.status === 'on')+ const networks = inUse.map(({ id }) => {let streams = 0let rejected = 0- for (const chunk of runtime.state.chunks) {+ for (const chunk of this.liveStreams(runtime, id)) {const self = runtime.chunkRuntimes.get(chunk.id)- if (chunk.interfaceId !== iface.id || self?.retiring) continuestreams++if (self && self.failures > 0 && self.receivedBytes === 0) rejected++}- return {- id: iface.id,- streams,- rejected,- received: runtime.receivedByNetwork.get(iface.id) ?? 0- }+ return { id, streams, rejected, received: this.traffic(runtime, id).received }})let retiring = 0for (const self of runtime.chunkRuntimes.values()) if (self.retiring) retiring++@@ -1459,76 +1641,61 @@ export class DownloadManager {/** New streams on `networkId`, put on the download's list for the caller to start. */private addStreams(runtime: DownloadRuntime, networkId: string, count: number): ChunkState[] {- const iface = runtime.activeInterfaces.find((entry) => entry.id === networkId)- if (!iface) return []let id = Math.max(-1, ...runtime.state.chunks.map((chunk) => chunk.id))- const added = Array.from({ length: count }, () => newStream(++id, iface))+ const added = Array.from({ length: count }, () => newStream(++id, networkId))runtime.state.chunks.push(...added)runtime.state.peakStreams = Math.max(runtime.state.peakStreams ?? 0,runtime.state.chunks.length)- debug('streams', { network: iface.displayName, added: count })+ debug('streams', { network: networkId, added: count })this.scheduleUpdate(runtime)return added}/** Stops the newest `count` streams on `networkId` for good. Stopping partway through a block* costs nothing: what it wrote stays, and whoever takes the block next resumes from there. */- private retireStreams(runtime: DownloadRuntime, networkId: string, count: number): ChunkState[] {- const live = runtime.state.chunks.filter(- (chunk) => chunk.interfaceId === networkId && !runtime.chunkRuntimes.get(chunk.id)?.retiring- )- const retired = live.slice(-count)- for (const chunk of retired) {+ private retireStreams(runtime: DownloadRuntime, networkId: string, count: number): void {+ if (count < 1) return+ for (const chunk of this.liveStreams(runtime, networkId).slice(-count)) {const self = runtime.chunkRuntimes.get(chunk.id)- if (!self) continue- self.retiring = true- self.controller.abort()+ if (self && runtime.workers.has(chunk.id)) {+ // Its worker takes it off the list once it has stopped.+ self.retiring = true+ self.controller.abort()+ } else {+ this.removeStream(runtime, chunk)+ }}debug('streams', { network: networkId, retired: count })- return retired}- /** Takes a retired stream off the list. What it downloaded and its retries pass to a stream- * still on its network, since the per-network totals on screen are summed from the streams. */+ /** Takes a retired stream off the list. */private removeStream(runtime: DownloadRuntime, chunk: ChunkState): void {runtime.chunkRuntimes.delete(chunk.id)runtime.speedSamplesByChunk.delete(chunk.id)const index = runtime.state.chunks.indexOf(chunk)if (index < 0) returnruntime.state.chunks.splice(index, 1)- const heir = runtime.state.chunks.find((entry) => entry.interfaceId === chunk.interfaceId)- if (heir) {- heir.bytesDownloaded += chunk.bytesDownloaded- heir.retryCount += chunk.retryCount- }this.scheduleUpdate(runtime)}private async runWorker(runtime: DownloadRuntime, chunk: ChunkState): Promise<void> {- const iface =- runtime.activeInterfaces.find((i) => i.id === chunk.interfaceId) ??- runtime.activeInterfaces[chunk.id % runtime.activeInterfaces.length] ??- runtime.activeInterfaces[0]-- if (!iface) {- chunk.status = 'error'- chunk.error = 'No active network interface available'- this.scheduleUpdate(runtime)- return- }-const controller = new AbortController()const self: ChunkRuntime = {controller,- connection: new StreamConnection(iface, testKnobs.stallTimeoutMs),+ wait: AbortSignal.any([controller.signal, runtime.stop.signal]),+ connection: new StreamConnection(+ () => this.networks.find(chunk.interfaceId),+ testKnobs.stallTimeoutMs+ ),attempt: null,warmSince: Date.now(),slowSince: null,lastBlockSpeed: 0,receivedBytes: 0,failures: 0,+ strikes: 0,retiring: false}runtime.chunkRuntimes.set(chunk.id, self)@@ -1546,7 +1713,7 @@ export class DownloadManager {avoid: runtime.avoidNetworkByBlock,hedgesUsed: runtime.hedgesByBlock},- { id: chunk.id, networkId: iface.id },+ { id: chunk.id, networkId: chunk.interfaceId },Date.now(),SCHEDULER_POLICY)@@ -1556,7 +1723,7 @@ export class DownloadManager {// or turns out to be slow enough to be worth racing.if (runtime.blocks.some((b) => b.status === 'pending' || b.status === 'downloading')) {this.scheduleUpdate(runtime)- await delay(250, controller.signal)+ await delay(250, self.wait)continue}chunk.status = 'completed'@@ -1564,12 +1731,12 @@ export class DownloadManager {break}- const attempt = this.beginAttempt(runtime, chunk, self, iface, work)+ const attempt = this.beginAttempt(runtime, chunk, self, work)this.scheduleUpdate(runtime)const outcome = await this.executeAttempt(runtime, chunk, self, attempt)let next: 'continue' | 'stop'try {- next = await this.finishAttempt(runtime, chunk, self, iface, attempt, outcome)+ next = await this.finishAttempt(runtime, chunk, self, attempt, outcome)} finally {this.endAttempt(runtime, self, attempt)}@@ -1642,12 +1809,21 @@ export class DownloadManager {return compared > 0 ? 'same' : 'unknown'}+ /** Re-derives the byte counts from the blocks: the download's, and each network's. */private recomputeAggregates(runtime: DownloadRuntime): void {- runtime.state.bytesDownloaded = runtime.blocks.reduce(- (sum, entry) => sum + entry.bytesDownloaded,- 0- )- runtime.state.speedBytesPerSec = sumChunkSpeeds(runtime)+ let total = 0+ const byNetwork = new Map<string, number>()+ for (const block of runtime.blocks) {+ total += block.bytesDownloaded+ for (const [id, bytes] of Object.entries(block.bytesByInterface)) {+ byNetwork.set(id, (byNetwork.get(id) ?? 0) + bytes)+ }+ }+ runtime.state.bytesDownloaded = total+ for (const network of runtime.state.networks) {+ network.bytesDownloaded = byNetwork.get(network.id) ?? 0+ }+ updateSpeeds(runtime)}private scheduleUpdate(runtime: DownloadRuntime): void {@@ -1667,7 +1843,7 @@ export class DownloadManager {const window = this.getWindow()if (!window || window.isDestroyed()) returnif (runtime.state.status === 'paused' || runtime.state.status === 'cancelled') {- runtime.state.speedBytesPerSec = 0+ clearSpeeds(runtime.state)}window.webContents.send(IpcChannels.downloadUpdated, this.takeUpdate(runtime))}@@ -1728,8 +1904,7 @@ export class DownloadManager {partialPath: runtime.file.path,publicationPath: runtime.publicationPath,publicationIdentity: runtime.publicationIdentity,- requestPayload: runtime.requestPayload,- activeInterfaces: runtime.activeInterfaces+ requestPayload: runtime.requestPayload}if (runtime.state.status === 'downloading' || runtime.state.status === 'paused') {await runtime.file.sync()diff --git a/src/main/download/plan.ts b/src/main/download/plan.tsindex 72f4531..8aa2fbc 100644--- a/src/main/download/plan.ts+++ b/src/main/download/plan.ts@@ -1,8 +1,9 @@import type { BlockState } from '../../shared/types'-// How a download is cut into blocks and how many streams start on them. Pure, so every rule here-// can be checked against exact situations. How many streams a network ends up with is decided-// while the download runs (see concurrency.ts); the plan only has to leave them enough blocks.+// How a download is cut into blocks, and how many streams a network starts on them. Pure, so+// every rule here can be checked against exact situations. How many streams a network ends up+// with is decided while the download runs (see concurrency.ts); the plan only has to leave them+// enough blocks.const MIB = 1024 * 1024@@ -32,9 +33,6 @@ export interface DownloadPlan {/** Bytes per block; the last block holds the remainder. */blockSizeBytes: numberblockCount: number- /** The network (an index into the selected networks) each stream runs on, in the order the- * streams start — interleaved, so every network is served before any is served twice. */- streamNetworks: number[]}export interface PlanRequest {@@ -42,9 +40,8 @@ export interface PlanRequest {totalBytes: number/** false when the server can't serve byte ranges. */splittable: boolean+ /** The networks it starts on. More can join later; this only sizes the blocks. */networkCount: number- /** Streams to start on each network; START_STREAMS_PER_NETWORK unless a test pins it. */- streamsPerNetwork?: numbermaxBlockBytes?: number}@@ -74,35 +71,32 @@ export function planDownload(request: PlanRequest): DownloadPlan {const { totalBytes, splittable } = requestconst networkCount = Math.max(1, Math.floor(request.networkCount))- // One request has to carry the whole file, so one stream, on the first network.+ // One request has to carry the whole file.if (!splittable || totalBytes <= 0) {- return { blockSizeBytes: Math.max(totalBytes, 0), blockCount: 1, streamNetworks: [0] }+ return { blockSizeBytes: Math.max(totalBytes, 0), blockCount: 1 }}const maxBlockBytes = request.maxBlockBytes ?? DEFAULT_MAX_BLOCK_BYTES- const requested = clamp(- Math.floor(request.streamsPerNetwork ?? START_STREAMS_PER_NETWORK),- 1,- MAX_STREAMS_PER_NETWORK- )-const targetBlocks = networkCount * MAX_STREAMS_PER_NETWORK * BLOCKS_PER_STREAMconst blockSizeBytes = clamp(Math.ceil(totalBytes / targetBlocks),Math.min(MIN_BLOCK_BYTES, maxBlockBytes),maxBlockBytes)- const blockCount = Math.ceil(totalBytes / blockSizeBytes)-- // A stream with no block to claim would only sit idle, so a small file gets fewer of them —- // but every network keeps one, so it still shows up and can take over a block that fails.- const perNetwork = Math.max(1, Math.min(requested, Math.ceil(blockCount / networkCount)))- const streamNetworks = interleave(- Array.from({ length: networkCount * perNetwork }, (_, i) => Math.floor(i / perNetwork)),- (network) => network- )+ return { blockSizeBytes, blockCount: Math.ceil(totalBytes / blockSizeBytes) }+}- return { blockSizeBytes, blockCount, streamNetworks }+/** Streams to start on each of `networkCount` networks joining a download with `waiting` blocks+ * nobody has taken: START_STREAMS_PER_NETWORK, unless a test pins `requested`. A stream with no+ * block to claim would only sit idle, so near the end, or on a small file, fewer — but never+ * none, so a network that joins can still race a slow block (see scheduler.ts). */+export function startingStreams(+ waiting: number,+ networkCount: number,+ requested = START_STREAMS_PER_NETWORK+): number {+ const perNetwork = Math.ceil(waiting / Math.max(1, networkCount))+ return Math.max(1, Math.min(clamp(Math.floor(requested), 1, MAX_STREAMS_PER_NETWORK), perNetwork))}/** The blocks a file of `totalBytes` is cut into, none of them started. An unknown size is onediff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.tsindex 668c804..35acb68 100644--- a/src/main/ipc/handlers.ts+++ b/src/main/ipc/handlers.ts@@ -11,13 +11,13 @@ import {} from 'electron'import { IpcChannels } from '../../shared/ipc-channels'import type { IpcContract } from '../../shared/ipc-contract'-import type { InitialState, NetworkInterfaceInfo, ThemeSource } from '../../shared/types'+import type { InitialState, ThemeSource } from '../../shared/types'import { DownloadManager } from '../download/downloadManager'import { getDefaultDownloadsDir, getHomeDir } from '../download/paths'import { probeUrl } from '../download/probe'import { deviceBindingSupported } from '../network/deviceBinding'import { measureLatencies } from '../network/latency'-import { listActiveInterfaces } from '../network/interfaces'+import { NetworkMonitor } from '../network/interfaces'import { loadSettings, saveSettings } from '../settings'import { testKnobs } from '../testKnobs'import { checkForUpdate, UPDATE_PAGE_URL } from '../updateCheck'@@ -56,22 +56,17 @@ function handle<K extends keyof IpcContract>(const DESTINATION_CHECK_MS = 300export function registerIpcHandlers(getWindow: () => BrowserWindow | null): DownloadManager {- let cachedInterfaces: NetworkInterfaceInfo[] = []-- const refreshInterfaces = async (): Promise<NetworkInterfaceInfo[]> => {- cachedInterfaces = await listActiveInterfaces()- return cachedInterfaces- }-- const manager = new DownloadManager(- getWindow,- (id) => cachedInterfaces.find((iface) => iface.id === id),- refreshInterfaces- )+ // The main process keeps the network list, for downloads and the window alike.+ const networks = new NetworkMonitor((list) => {+ manager.networksChanged()+ const window = getWindow()+ if (window && !window.isDestroyed()) window.webContents.send(IpcChannels.networksChanged, list)+ })+ const manager = new DownloadManager(getWindow, networks)- handle('listInterfaces', refreshInterfaces)+ handle('listInterfaces', () => networks.refresh())- handle('pingInterfaces', async () => measureLatencies(cachedInterfaces))+ handle('pingInterfaces', async () => measureLatencies(networks.current ?? []))// Started now so it has settled before the first ping or download needs it.const bindingSupport = deviceBindingSupported()@@ -163,6 +158,10 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Downmanager.resume(id)})+ handle('setDownloadNetwork', async (_event, id, networkId, enabled) => {+ manager.setNetworkEnabled(id, networkId, enabled)+ })+handle('cancelDownload', async (_event, id) => manager.cancel(id))handle('removeDownload', async (_event, id) => manager.remove(id))diff --git a/src/main/network/interfaces.ts b/src/main/network/interfaces.tsindex a540fa3..9e20456 100644--- a/src/main/network/interfaces.ts+++ b/src/main/network/interfaces.ts@@ -98,6 +98,13 @@ export function ipv4Subnet(address: string, netmask: string): string | null {return `${subnetParts.join('.')}/${maskBits}`}+/** What the OS calls each device, looked up again only when the set of devices changes: it+ * takes a child process, while the addresses themselves are one cheap system call. */+let labels: {+ devices: string+ lookup: Promise<[Map<string, string>, Map<string, WindowsAdapter>]>+} | null = null+/*** Active non-loopback interfaces, with every usable local address on each device.*/@@ -105,9 +112,12 @@ export async function listActiveInterfaces(): Promise<NetworkInterfaceInfo[]> {const overridden = testInterfaces()if (overridden) return overridden- const hardwarePorts = await getMacHardwarePortNames()- const windowsAdapters = await getWindowsAdapters()const all = networkInterfaces()+ const devices = Object.keys(all).sort().join('\n')+ if (labels?.devices !== devices) {+ labels = { devices, lookup: Promise.all([getMacHardwarePortNames(), getWindowsAdapters()]) }+ }+ const [hardwarePorts, windowsAdapters] = await labels.lookupconst result: NetworkInterfaceInfo[] = []for (const [device, addresses] of Object.entries(all)) {@@ -149,3 +159,44 @@ export async function listActiveInterfaces(): Promise<NetworkInterfaceInfo[]> {return result}++const POLL_MS = 1000++/**+ * The computer's networks, kept current: nothing tells a process when a network appears, drops+ * or gets a new address, so it looks every second. `onChange` hears of every change.+ */+export class NetworkMonitor {+ private list: NetworkInterfaceInfo[] | null = null+ private polling: Promise<NetworkInterfaceInfo[]> = Promise.resolve([])++ constructor(private readonly onChange: (networks: NetworkInterfaceInfo[]) => void) {+ void this.refresh()+ setInterval(() => void this.refresh(), POLL_MS).unref()+ }++ /** Null until the first look has finished. */+ get current(): NetworkInterfaceInfo[] | null {+ return this.list+ }++ find(id: string): NetworkInterfaceInfo | undefined {+ return this.list?.find((iface) => iface.id === id)+ }++ /** Looks now, rather than at the next poll. Looks run one at a time, so the last word is+ * always the newest. */+ refresh(): Promise<NetworkInterfaceInfo[]> {+ this.polling = this.polling+ .catch(() => [])+ .then(async () => {+ const next = await listActiveInterfaces().catch(() => this.list ?? [])+ if (JSON.stringify(next) !== JSON.stringify(this.list)) {+ this.list = next+ this.onChange(next)+ }+ return next+ })+ return this.polling+ }+}diff --git a/src/main/network/routes.ts b/src/main/network/routes.tsindex 45b11fe..ab0df62 100644--- a/src/main/network/routes.ts+++ b/src/main/network/routes.ts@@ -69,6 +69,23 @@ export class NoCompatibleRouteError extends Error {}}+/** The connection failed — it couldn't be opened, or it dropped or went silent before the+ * server had finished — rather than the server answering wrongly. It says something about the+ * network, not the server, so a download never gives up on it (see downloadManager.ts). */+export class ConnectionError extends Error {+ constructor(cause: Error) {+ super(cause.message, { cause })+ }+}++/** `error` as a ConnectionError, unless it is one already or means something else: an abort,+ * or a network that has no route to the host. */+export function asConnectionError(error: unknown): Error {+ if (error instanceof ConnectionError || error instanceof NoCompatibleRouteError) return error+ if (error instanceof Error && error.name === 'AbortError') return error+ return new ConnectionError(error instanceof Error ? error : new Error(String(error)))+}+/** DNS is part of opening a connection, so it must not outlive the connection's deadline. */export function resolveTargetWithin(host: string,@@ -223,6 +240,9 @@ export interface ResponseStart {* rather than on every block. A new socket is only opened when there is none to reuse: the first* request, after the server closes an idle one, or after an abort destroyed it, which is how a* stuck connection gets swapped for a fresh one.+ *+ * Every new socket asks for the network as it is now, so one that comes back with a new+ * address is reached at that one.*/export class StreamConnection {private readonly lifetime = new AbortController()@@ -230,13 +250,16 @@ export class StreamConnection {private readonly https: HttpsAgentconstructor(- readonly iface: NetworkInterfaceInfo,+ /** The network, or undefined while it isn't connected. */+ network: () => NetworkInterfaceInfo | undefined,/** How long a request may take to get its response headers, connecting included. */private readonly timeoutMs: number,resolveHost?: ResolveHost) {- const open: Open = (options, secure) =>- connectOnInterface(+ const open: Open = async (options, secure) => {+ const iface = network()+ if (!iface) throw new Error('The network is not connected')+ return connectOnInterface(iface,options.host ?? '',Number(options.port),@@ -249,6 +272,7 @@ export class StreamConnection {: this.lifetime.signal,resolveHost)+ }this.http = new RoutedHttpAgent(open)this.https = new RoutedHttpsAgent(open)}@@ -311,7 +335,7 @@ export class StreamConnection {if (retryStale && req.reusedSocket && !timedOut && !signal?.aborted) {resolve(this.send(target, headers, signal, false))} else {- reject(error)+ reject(asConnectionError(error))}})signal?.addEventListener('abort', onAbort, { once: true })diff --git a/src/preload/index.ts b/src/preload/index.tsindex 28e1d05..583652c 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -1,7 +1,12 @@import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'import { IpcChannels } from '../shared/ipc-channels'import type { IpcContract } from '../shared/ipc-contract'-import type { AppSettings, DownloadUpdate, InitialState } from '../shared/types'+import type {+ AppSettings,+ DownloadUpdate,+ InitialState,+ NetworkInterfaceInfo+} from '../shared/types'/** Typed wrapper around ipcRenderer.invoke — the channel name picks its args/result shape out of* IpcContract, so a call here that doesn't match what registerIpcHandlers (main) actually handles@@ -32,6 +37,8 @@ const plexoApi = {getCurrentDownload: () => invoke('getCurrentDownload'),pauseDownload: (downloadId: string) => invoke('pauseDownload', downloadId),resumeDownload: (downloadId: string) => invoke('resumeDownload', downloadId),+ setDownloadNetwork: (downloadId: string, networkId: string, enabled: boolean) =>+ invoke('setDownloadNetwork', downloadId, networkId, enabled),cancelDownload: (downloadId: string) => invoke('cancelDownload', downloadId),removeDownload: (downloadId: string) => invoke('removeDownload', downloadId),checkForUpdate: () => invoke('checkForUpdate'),@@ -40,6 +47,13 @@ const plexoApi = {const listener = (_event: IpcRendererEvent, update: DownloadUpdate): void => callback(update)ipcRenderer.on(IpcChannels.downloadUpdated, listener)return () => ipcRenderer.removeListener(IpcChannels.downloadUpdated, listener)+ },++ onNetworksChanged: (callback: (networks: NetworkInterfaceInfo[]) => void): (() => void) => {+ const listener = (_event: IpcRendererEvent, networks: NetworkInterfaceInfo[]): void =>+ callback(networks)+ ipcRenderer.on(IpcChannels.networksChanged, listener)+ return () => ipcRenderer.removeListener(IpcChannels.networksChanged, listener)}}diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex 97ff416..27f3011 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -5,6 +5,7 @@ import { NetworkBindingDialog } from './components/NetworkBindingDialog'import { UpdateDialog } from './components/UpdateDialog'import { TooltipProvider } from './components/ui/tooltip'import { useDownloadEvents } from './hooks/useDownloadEvents'+import { useNetworkEvents } from './hooks/useNetworks'import { CompleteScreen } from './screens/CompleteScreen'import { DownloadingScreen } from './screens/DownloadingScreen'import { ErrorScreen } from './screens/ErrorScreen'@@ -29,7 +30,7 @@ function renderDownload(screen: <DownloadingScreen download={download} />,titleBarStatus: {kind: 'combined',- networkCount: new Set(download.chunks.map((chunk) => chunk.interfaceId)).size+ networkCount: download.networks.filter((network) => network.status === 'on').length}}case 'paused':@@ -37,7 +38,7 @@ function renderDownload(screen: <DownloadingScreen download={download} />,titleBarStatus: {kind: 'paused',- networkCount: new Set(download.chunks.map((chunk) => chunk.interfaceId)).size+ networkCount: download.networks.filter((network) => network.enabled).length}}case 'completed':@@ -64,6 +65,7 @@ function renderDownload(function App(): React.JSX.Element {useDownloadEvents()+ useNetworkEvents()const interfaces = useAppStore((store) => store.interfaces)const interfacesStatus = useAppStore((store) => store.interfacesStatus)diff --git a/src/renderer/src/components/BlockGrid.tsx b/src/renderer/src/components/BlockGrid.tsxindex a7ccc20..da76534 100644--- a/src/renderer/src/components/BlockGrid.tsx+++ b/src/renderer/src/components/BlockGrid.tsx@@ -174,7 +174,7 @@ export function BlockGrid({const visualByInterfaceId = new Map<string, NetworkVisual>()groups.forEach((g, idx) => {if (visuals[idx]) {- visualByInterfaceId.set(g.interfaceId, visuals[idx])+ visualByInterfaceId.set(g.id, visuals[idx])}})@@ -182,7 +182,7 @@ export function BlockGrid({// Squares keep their size and the grid wraps; how many rows that takes is the file's business,// not the window's. Only the width decides the wrap, exactly like a paragraph reflowing.const cols = Math.min(blocks.length, Math.max(MIN_COLS, fittedCols))- const orderedInterfaceIds = groups.map((g) => g.interfaceId)+ const orderedInterfaceIds = groups.map((g) => g.id)const cells = gridWidth > 0 ? describeBlocks(blocks, orderedInterfaceIds) : []const chunkBytes =blocks[0].rangeEnd !== null ? blocks[0].rangeEnd - blocks[0].rangeStart + 1 : 0@@ -214,7 +214,7 @@ export function BlockGrid({const visual = visuals[idx]return (<div- key={group.interfaceId}+ key={group.id}className="flex items-center gap-[5.5px] font-mono text-[10.5px] leading-none font-medium text-[var(--text-secondary)]"><span@@ -338,7 +338,7 @@ export function BlockGrid({<>{groups.map((group, index) => (<div- key={group.interfaceId}+ key={group.id}style={{flex: group.bytesDownloaded || 0.0001,background: visuals[index].soliddiff --git a/src/renderer/src/components/NetworkRow.tsx b/src/renderer/src/components/NetworkRow.tsxindex 19f33ce..f4db3bd 100644--- a/src/renderer/src/components/NetworkRow.tsx+++ b/src/renderer/src/components/NetworkRow.tsx@@ -1,4 +1,4 @@-import type { BlockState, ChunkState } from '@shared/types'+import type { BlockState, ChunkState, NetworkStatus } from '@shared/types'import { useState } from 'react'import { DANGER, type NetworkVisual } from '../theme'import type { NetworkGroup } from '../utils/format'@@ -7,6 +7,7 @@ import { ColorBadge } from './ColorBadge'import { NetworkEditPopover } from './NetworkEditPopover'import { TruncatedText } from './TruncatedText'import { Button } from './ui/button'+import { Checkbox } from './ui/checkbox'interface NetworkRowProps {group: NetworkGroup@@ -14,6 +15,17 @@ interface NetworkRowProps {sharePercent: numbertotalBytes?: number | nullblocks?: BlockState[]+ /** False for the last network in use, which can't be switched off. */+ canSwitch: boolean+ onSwitch: (enabled: boolean) => void+}++/** What a network not in use is doing instead. One in use shows its streams. */+const STATUS_TEXT: Record<Exclude<NetworkStatus, 'on'>, string> = {+ off: 'Off',+ offline: 'Not connected',+ unreachable: 'Can’t reach server',+ failed: 'Failed'}// Every row — this one and each expanded stream row — is a direct col-span-full subgrid child of@@ -79,10 +91,12 @@ export function NetworkRow({visual,sharePercent,totalBytes,- blocks+ blocks,+ canSwitch,+ onSwitch}: NetworkRowProps): React.JSX.Element {const [expanded, setExpanded] = useState(false)- const hasError = group.chunks.some((chunk) => chunk.status === 'error')+ const hasError = group.status === 'failed'const isActive = group.chunks.some((chunk) => chunk.status === 'downloading')const rounded = Math.round(sharePercent)@@ -105,28 +119,57 @@ export function NetworkRow({}}/><div role="cell" className="flex min-w-0 items-center gap-[6px]">+ <span+ className="flex shrink-0"+ title={canSwitch ? undefined : 'The last network in use stays on. Pause to stop.'}+ >+ <Checkbox+ checked={group.enabled}+ disabled={!canSwitch}+ onCheckedChange={(checked) => onSwitch(checked)}+ aria-label={`Use ${visual.name}`}+ className="data-checked:border-transparent"+ style={+ group.enabled ? { background: visual.solid, color: visual.onSolid } : undefined+ }+ />+ </span><TruncatedTexttext={visual.name}- className="font-sans text-[12.5px] leading-[1.2] font-semibold text-foreground"+ className={`font-sans text-[12.5px] leading-[1.2] font-semibold ${+ group.enabled ? 'text-foreground' : 'text-[var(--text-secondary)]'+ }`}/><NetworkEditPopover- interfaceId={group.interfaceId}- interfaceKind={group.interfaceKind}- osName={group.interfaceLabel}+ interfaceId={group.id}+ interfaceKind={group.kind}+ osName={group.label}/>- <Button- type="button"- variant="outline"- size="xs"- onClick={() => setExpanded((v) => !v)}- aria-expanded={expanded}- className="h-auto cursor-pointer rounded-[4px] border-[0.5px] bg-card px-[7px] py-[3px] font-mono text-[10.5px] leading-none font-medium text-[var(--text-secondary)] aria-expanded:bg-secondary dark:bg-card"- >- {group.chunks.length} {group.chunks.length === 1 ? 'stream' : 'streams'}- <span aria-hidden className="text-[7.5px] opacity-75">- {expanded ? '▲' : '▼'}+ {group.chunks.length > 0 && (+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={() => setExpanded((v) => !v)}+ aria-expanded={expanded}+ className="h-auto cursor-pointer rounded-[4px] border-[0.5px] bg-card px-[7px] py-[3px] font-mono text-[10.5px] leading-none font-medium text-[var(--text-secondary)] aria-expanded:bg-secondary dark:bg-card"+ >+ {group.chunks.length} {group.chunks.length === 1 ? 'stream' : 'streams'}+ <span aria-hidden className="text-[7.5px] opacity-75">+ {expanded ? '▲' : '▼'}+ </span>+ </Button>+ )}+ {group.status !== 'on' && (+ <span+ title={group.error}+ className={`font-mono text-[10px] whitespace-nowrap ${+ hasError ? 'text-destructive' : 'text-muted-foreground'+ }`}+ >+ {STATUS_TEXT[group.status]}</span>- </Button>+ )}</div><ProgressBarclassName="h-1.5"@@ -165,7 +208,6 @@ export function NetworkRow({const isFirst = index === 0const isLast = index === group.chunks.length - 1const isChunkActive = chunk.status === 'downloading'- const isChunkError = chunk.status === 'error'const stream = describeStream(chunk, blocks)const statusText = stream.done? 'Done'@@ -173,9 +215,7 @@ export function NetworkRow({? 'Paused': chunk.status === 'retrying'? 'Retrying…'- : chunk.status === 'error'- ? 'Failed'- : 'Idle'+ : 'Idle'return (<div@@ -189,11 +229,7 @@ export function NetworkRow({<divclassName="size-[5px] rounded-full"style={{- background: isChunkError- ? DANGER- : isChunkActive || stream.done- ? visual.solid- : 'var(--icon-muted)',+ background: isChunkActive || stream.done ? visual.solid : 'var(--icon-muted)',opacity: isChunkActive || stream.done ? 1 : 0.4}}/>@@ -241,7 +277,7 @@ export function NetworkRow({className="h-[5px]"label={`Stream #${index + 1} progress`}percent={stream.percent}- color={isChunkError ? DANGER : visual.solid}+ color={visual.solid}/><divdiff --git a/src/renderer/src/hooks/useNetworkPolling.ts b/src/renderer/src/hooks/useNetworkPolling.tsdeleted file mode 100644index 40597a7..0000000--- a/src/renderer/src/hooks/useNetworkPolling.ts+++ /dev/null@@ -1,27 +0,0 @@-import { useEffect } from 'react'-import { useAppStore } from '../store/useAppStore'--const POLL_INTERVAL_MS = 5000--/** Keeps the interface list and their latency readouts fresh while a screen that shows them is mounted —- * e.g. so plugging in a phone over USB, or losing Wi-Fi, is reflected without the user restarting Plexo. */-export function useNetworkPolling(enabled: boolean): void {- const loadInterfaces = useAppStore((store) => store.loadInterfaces)- const refreshLatencies = useAppStore((store) => store.refreshLatencies)-- useEffect(() => {- if (!enabled) return-- let cancelled = false- const tick = async (): Promise<void> => {- await loadInterfaces()- if (!cancelled) await refreshLatencies()- }- void tick()- const interval = setInterval(tick, POLL_INTERVAL_MS)- return () => {- cancelled = true- clearInterval(interval)- }- }, [enabled, loadInterfaces, refreshLatencies])-}diff --git a/src/renderer/src/hooks/useNetworkVisuals.ts b/src/renderer/src/hooks/useNetworkVisuals.tsindex 4bbb192..c84e3f6 100644--- a/src/renderer/src/hooks/useNetworkVisuals.ts+++ b/src/renderer/src/hooks/useNetworkVisuals.ts@@ -12,13 +12,13 @@ export type ResolveNetworkVisual = (* current download), so each screen agrees on which network is which color. */export function useNetworkVisuals(): ResolveNetworkVisual {const interfaces = useAppStore((store) => store.interfaces)- const chunks = useAppStore((store) => store.currentDownload?.chunks)+ const downloadNetworks = useAppStore((store) => store.currentDownload?.networks)const preferences = useAppStore((store) => store.networkPreferences)const networks = new Map<string, NetworkInterfaceKind>()for (const iface of interfaces) networks.set(iface.id, iface.kind)- for (const chunk of chunks ?? []) {- if (!networks.has(chunk.interfaceId)) networks.set(chunk.interfaceId, chunk.interfaceKind)+ for (const network of downloadNetworks ?? []) {+ if (!networks.has(network.id)) networks.set(network.id, network.kind)}const colors = assignNetworkColors(networks, preferences)diff --git a/src/renderer/src/hooks/useNetworks.ts b/src/renderer/src/hooks/useNetworks.tsnew file mode 100644index 0000000..fc0c63c--- /dev/null+++ b/src/renderer/src/hooks/useNetworks.ts@@ -0,0 +1,28 @@+import { useEffect } 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 {+ const loadInterfaces = useAppStore((store) => store.loadInterfaces)+ const receiveInterfaces = useAppStore((store) => store.receiveInterfaces)++ useEffect(() => {+ const unsubscribe = window.plexo.onNetworksChanged(receiveInterfaces)+ void loadInterfaces()+ return unsubscribe+ }, [loadInterfaces, receiveInterfaces])+}++/** Keeps each network's latency readout fresh while a screen that shows it is mounted. */+export function useLatencyPolling(): void {+ const refreshLatencies = useAppStore((store) => store.refreshLatencies)++ useEffect(() => {+ void refreshLatencies()+ const interval = setInterval(refreshLatencies, LATENCY_POLL_MS)+ return () => clearInterval(interval)+ }, [refreshLatencies])+}diff --git a/src/renderer/src/screens/CompleteScreen.tsx b/src/renderer/src/screens/CompleteScreen.tsxindex d492156..cfe0f43 100644--- a/src/renderer/src/screens/CompleteScreen.tsx+++ b/src/renderer/src/screens/CompleteScreen.tsx@@ -5,14 +5,7 @@ import { ThroughputChart } from '../components/ThroughputChart'import { Button } from '../components/ui/button'import { useNetworkVisuals } from '../hooks/useNetworkVisuals'import { useAppStore } from '../store/useAppStore'-import {- dirnameOf,- formatBytes,- formatDuration,- formatSpeed,- groupChunksByInterface,- toDisplayPath-} from '../utils/format'+import { dirnameOf, formatBytes, formatDuration, formatSpeed, toDisplayPath } from '../utils/format'const sectionHeaderClass ='font-mono text-[10px] leading-none tracking-[0.16em] text-muted-foreground uppercase'@@ -40,12 +33,11 @@ export function CompleteScreen({const avgSpeed = elapsedSeconds > 0 ? finalSize / elapsedSeconds : 0const [avgSpeedValue, avgSpeedUnit] = formatSpeed(avgSpeed).split(' ')- const groups = groupChunksByInterface(download.chunks)- const visuals = groups.map((group) =>- networkVisual(group.interfaceId, group.interfaceKind, group.interfaceLabel)- )+ // The networks that carried part of the file.+ const groups = download.networks.filter((network) => network.bytesDownloaded > 0)+ const visuals = groups.map((group) => networkVisual(group.id, group.kind, group.label))const totalWeight = groups.reduce((sum, group) => sum + group.bytesDownloaded, 0) || 1- const totalRetries = download.chunks.reduce((sum, chunk) => sum + chunk.retryCount, 0)+ const totalRetries = download.networks.reduce((sum, network) => sum + network.retries, 0)// "Chunks" in the block grid means byte ranges, not parallel connections.const totalChunkCount = download.totalBlocks ?? download.blocks?.length ?? 1@@ -123,7 +115,7 @@ 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.interfaceId, solid: visuals[i].solid }))}+ order={groups.map((g, i) => ({ interfaceId: g.id, solid: visuals[i].solid }))}historyByInterface={speedHistoryByInterface}/></div>@@ -133,14 +125,14 @@ export function CompleteScreen({<div className="flex h-2.5 gap-0.5 overflow-hidden rounded-full bg-muted">{groups.map((group, index) => (<div- key={group.interfaceId}+ key={group.id}style={{ flex: group.bytesDownloaded || 0.0001, background: visuals[index].solid }}/>))}</div><div className="flex flex-col gap-[9px]">{groups.map((group, index) => (- <div key={group.interfaceId} className="flex items-center gap-[9px]">+ <div key={group.id} className="flex items-center gap-[9px]"><divclassName="size-[7px] shrink-0 rounded-full"style={{ background: visuals[index].solid }}diff --git a/src/renderer/src/screens/DownloadingScreen.tsx b/src/renderer/src/screens/DownloadingScreen.tsxindex b28b2d5..b2e68ef 100644--- a/src/renderer/src/screens/DownloadingScreen.tsx+++ b/src/renderer/src/screens/DownloadingScreen.tsx@@ -22,7 +22,6 @@ import {} from '../components/ui/alert-dialog'import { Button, buttonVariants } from '../components/ui/button'import { Tooltip, TooltipContent, TooltipTrigger } from '../components/ui/tooltip'-import { useNetworkPolling } from '../hooks/useNetworkPolling'import { useNetworkVisuals } from '../hooks/useNetworkVisuals'import { useAppStore } from '../store/useAppStore'import { KIND_PALETTE, NETWORK_ROW_GRID_COLUMNS } from '../theme'@@ -33,7 +32,8 @@ import {formatEta,formatPercent,formatSpeed,- groupChunksByInterface,+ groupByNetwork,+ networksInPlay,splitFormattedBytes,toDisplayPath} from '../utils/format'@@ -85,9 +85,17 @@ function BigStat({)}-export function DownloadingScreen({ download }: { download: DownloadState }): React.JSX.Element {- useNetworkPolling(true)+/** What the download is waiting on, when no network is carrying it. */+function waitingFor(download: DownloadState): string | null {+ if (download.status !== 'downloading') return null+ const enabled = download.networks.filter((network) => network.enabled)+ if (enabled.some((network) => network.status === 'on')) return null+ return enabled.some((network) => network.status === 'unreachable')+ ? 'Can’t reach the server. Retrying…'+ : 'Waiting for a network. Reconnect one or switch one on.'+}+export function DownloadingScreen({ download }: { download: DownloadState }): React.JSX.Element {const homeDir = useAppStore((store) => store.homeDir)const speedHistory = useAppStore((store) => store.speedHistory)const speedHistoryByInterface = useAppStore((store) => store.speedHistoryByInterface)@@ -145,14 +153,17 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Reconst effectiveSpeed = isPaused ? 0 : download.speedBytesPerSecconst speed = splitFormattedBytes(effectiveSpeed)- const groups = groupChunksByInterface(download.chunks)- const totalDownloadedByNetworks = groups.reduce((sum, g) => sum + g.bytesDownloaded, 0)- const visuals = groups.map((group) =>- networkVisual(group.interfaceId, group.interfaceKind, group.interfaceLabel)- )+ // 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))+ const enabledCount = rows.filter((row) => row.enabled).length+ const groups = networksInPlay(rows)+ const visuals = groups.map((group) => networkVisual(group.id, group.kind, group.label))+ const totalDownloadedByNetworks = rows.reduce((sum, row) => sum + row.bytesDownloaded, 0)const [chipModeIndex, setChipModeIndex] = useState(0)+ const waiting = waitingFor(download)- const totalRetries = download.chunks.reduce((sum, chunk) => sum + chunk.retryCount, 0)+ const totalRetries = rows.reduce((sum, row) => sum + row.retries, 0)const remainingBytes = knownSize ? Math.max(0, download.totalBytes - download.bytesDownloaded) : 0const avgSpeedBytesPerSec = elapsedSeconds > 0 ? download.bytesDownloaded / elapsedSeconds : 0@@ -216,13 +227,13 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re<Dot /><InlineStat label="PEAK" value={formatSpeed(peakSpeedBytesPerSec)} /></div>- {isPaused- ? download.error && (+ {isPaused || waiting+ ? (download.error || waiting) && (<divrole="alert"className="mt-0.5 font-sans text-[11px] leading-[1.2] font-medium text-destructive">- {download.error}+ {download.error ?? waiting}</div>): activeChipOption && (@@ -249,7 +260,7 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re</div><ThroughputChartorder={groups.map((g, i) => ({- interfaceId: g.interfaceId,+ interfaceId: g.id,solid: visuals[i].solid}))}historyByInterface={speedHistoryByInterface}@@ -342,18 +353,23 @@ export function DownloadingScreen({ download }: { download: DownloadState }): ReDownloaded</div></div>- {groups.map((group, index) => (+ {rows.map((row, index) => (<NetworkRow- key={group.interfaceId}- group={group}- visual={visuals[index]}+ key={row.id}+ group={row}+ visual={rowVisuals[index]}sharePercent={totalDownloadedByNetworks > 0- ? (group.bytesDownloaded / totalDownloadedByNetworks) * 100+ ? (row.bytesDownloaded / totalDownloadedByNetworks) * 100: 0}totalBytes={download.totalBytes}blocks={download.blocks}+ // The last network in use stays on: Pause is how a download stops.+ canSwitch={!(row.enabled && enabledCount === 1)}+ onSwitch={(enabled) =>+ void window.plexo.setDownloadNetwork(download.id, row.id, enabled)+ }/>))}</div>diff --git a/src/renderer/src/screens/ErrorScreen.tsx b/src/renderer/src/screens/ErrorScreen.tsxindex 4af174e..7cbe85d 100644--- a/src/renderer/src/screens/ErrorScreen.tsx+++ b/src/renderer/src/screens/ErrorScreen.tsx@@ -15,7 +15,10 @@ export function ErrorScreen({onDownloadAgain: () => void}): React.JSX.Element {const [copied, setCopied] = useState(false)+ const [resuming, setResuming] = useState(false)const cancelled = download.status === 'cancelled'+ // What it downloaded is still there to pick up from.+ const resumable = !cancelled && download.resumable !== false && download.bytesDownloaded > 0const knownSize = download.totalBytes > 0const percent = knownSize? Math.min(100, Math.round((download.bytesDownloaded / download.totalBytes) * 100))@@ -130,7 +133,23 @@ export function ErrorScreen({{/* Action Buttons in Center */}<div className="mt-1 flex w-full justify-center gap-2.5">- <Button type="button" onClick={onDownloadAgain}>+ {resumable && (+ <Button+ type="button"+ disabled={resuming}+ onClick={() => {+ setResuming(true)+ void window.plexo.resumeDownload(download.id).finally(() => setResuming(false))+ }}+ >+ {resuming ? 'Resuming…' : 'Resume'}+ </Button>+ )}+ <Button+ type="button"+ variant={resumable ? 'secondary' : 'default'}+ onClick={onDownloadAgain}+ >Download Again</Button><Button type="button" variant="secondary" onClick={onNewDownload}>diff --git a/src/renderer/src/screens/IdleScreen.tsx b/src/renderer/src/screens/IdleScreen.tsxindex f1d1893..45d2043 100644--- a/src/renderer/src/screens/IdleScreen.tsx+++ b/src/renderer/src/screens/IdleScreen.tsx@@ -6,7 +6,7 @@ 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 { useNetworkPolling } from '../hooks/useNetworkPolling'+import { useLatencyPolling } from '../hooks/useNetworks'import { useAppStore } from '../store/useAppStore'import { describeError, formatBytes, toDisplayPath } from '../utils/format'@@ -55,7 +55,7 @@ function InfoAlert({ title, message }: { title?: string; message: string }): Rea}export function IdleScreen(): React.JSX.Element {- useNetworkPolling(true)+ useLatencyPolling()const interfaces = useAppStore((store) => store.interfaces)const homeDir = useAppStore((store) => store.homeDir)diff --git a/src/renderer/src/screens/NoConnectionsScreen.tsx b/src/renderer/src/screens/NoConnectionsScreen.tsxindex a05c04e..7dfff2c 100644--- a/src/renderer/src/screens/NoConnectionsScreen.tsx+++ b/src/renderer/src/screens/NoConnectionsScreen.tsx@@ -1,7 +1,6 @@import { CombineDiagram } from '../components/CombineDiagram'import { ScreenFooter } from '../components/ScreenFooter'import { Button } from '../components/ui/button'-import { useNetworkPolling } from '../hooks/useNetworkPolling'import { useAppStore } from '../store/useAppStore'// Colors are irrelevant here — the diagram is rendered `muted`, which overrides them all to@@ -13,8 +12,6 @@ const PLACEHOLDER_NETWORKS = []export function NoConnectionsScreen(): React.JSX.Element {- useNetworkPolling(true)-const loadInterfaces = useAppStore((store) => store.loadInterfaces)return (diff --git a/src/renderer/src/store/useAppStore.ts b/src/renderer/src/store/useAppStore.tsindex 53fbe43..25026ff 100644--- a/src/renderer/src/store/useAppStore.ts+++ b/src/renderer/src/store/useAppStore.ts@@ -10,7 +10,6 @@ import type {UpdateInfo} from '@shared/types'import { create } from 'zustand'-import { groupChunksByInterface } from '../utils/format'type LoadStatus = 'idle' | 'loading' | 'ready' | 'error'@@ -54,7 +53,9 @@ interface AppStore {/** Persisted — the last folder picked, falling back to downloadsDir. */destinationDir: string+ /** Asks the main process for the network list now; it also pushes every change. */loadInterfaces: () => Promise<void>+ receiveInterfaces: (interfaces: NetworkInterfaceInfo[]) => voidrefreshLatencies: () => Promise<void>setNetworkPreference: (id: string, patch: NetworkPreference) => voidsetThemeSource: (source: ThemeSource) => void@@ -98,14 +99,11 @@ export const useAppStore = create<AppStore>((set, get) => ({destinationDir: initial.destinationDir ?? initial.downloadsDir,loadInterfaces: async () => {- // A re-scan keeps showing the last result. Dropping back to 'loading' would swap App off the- // no-connections screen, and every screen re-scans on mount — so with zero networks the- // two screens would remount each other in an endless loop.+ // A re-scan keeps showing the last result rather than flashing back to 'loading'.if (get().interfacesStatus !== 'ready') set({ interfacesStatus: 'loading' })set({ interfacesError: null })try {- const interfaces = await window.plexo.listInterfaces()- set({ interfaces, interfacesStatus: 'ready' })+ get().receiveInterfaces(await window.plexo.listInterfaces())} catch (error) {set({interfacesStatus: 'error',@@ -114,6 +112,9 @@ export const useAppStore = create<AppStore>((set, get) => ({}},+ receiveInterfaces: (interfaces) =>+ set({ interfaces, interfacesStatus: 'ready', interfacesError: null }),+refreshLatencies: async () => {try {const latencies = await window.plexo.pingInterfaces()@@ -175,9 +176,9 @@ export const useAppStore = create<AppStore>((set, get) => ({speedHistory = [...speedHistory, download.speedBytesPerSec].slice(-SPEED_HISTORY_LENGTH)const nextByInterface: Record<string, number[]> = {}- for (const group of groupChunksByInterface(download.chunks)) {- const previousSeries = speedHistoryByInterface[group.interfaceId] ?? []- nextByInterface[group.interfaceId] = [...previousSeries, group.speedBytesPerSec].slice(+ for (const network of download.networks) {+ const previousSeries = speedHistoryByInterface[network.id] ?? []+ nextByInterface[network.id] = [...previousSeries, network.speedBytesPerSec].slice(-SPEED_HISTORY_LENGTH)}diff --git a/src/renderer/src/utils/format.ts b/src/renderer/src/utils/format.tsindex d86a8e6..7bc8d1d 100644--- a/src/renderer/src/utils/format.ts+++ b/src/renderer/src/utils/format.ts@@ -1,4 +1,4 @@-import type { ChunkState, NetworkInterfaceKind } from '@shared/types'+import type { ChunkState, DownloadNetwork, DownloadState } from '@shared/types'const UNITS = ['B', 'KB', 'MB', 'GB', 'TB']@@ -71,43 +71,24 @@ export function dirnameOf(path: string): string {return path.slice(0, index)}-export interface NetworkGroup {- interfaceId: string- interfaceLabel: string- interfaceKind: NetworkInterfaceKind+/** A download's network with the streams it runs: what one row on screen shows. */+export interface NetworkGroup extends DownloadNetwork {chunks: ChunkState[]- bytesDownloaded: number- speedBytesPerSec: number}-/** Chunks are the unit of transfer, but a physical network is the unit the user thinks and- * decides in — a network can carry several chunks (via "chunks per network", or ones split- * off by dynamic rebalancing). Groups chunks by their interface, in order of first appearance,- * with per-network totals so the UI can show one row per physical network. */-export function groupChunksByInterface(chunks: ChunkState[]): NetworkGroup[] {- const order: string[] = []- const groups = new Map<string, NetworkGroup>()-- for (const chunk of chunks) {- let group = groups.get(chunk.interfaceId)- if (!group) {- group = {- interfaceId: chunk.interfaceId,- interfaceLabel: chunk.interfaceLabel,- interfaceKind: chunk.interfaceKind,- chunks: [],- bytesDownloaded: 0,- speedBytesPerSec: 0- }- groups.set(chunk.interfaceId, group)- order.push(chunk.interfaceId)- }- group.chunks.push(chunk)- group.bytesDownloaded += chunk.bytesDownloaded- group.speedBytesPerSec += chunk.speedBytesPerSec- }+export function groupByNetwork(+ download: Pick<DownloadState, 'networks' | 'chunks'>+): NetworkGroup[] {+ return download.networks.map((network) => ({+ ...network,+ chunks: download.chunks.filter((chunk) => chunk.interfaceId === network.id)+ }))+}- return order.map((interfaceId) => groups.get(interfaceId)!)+/** The networks worth drawing in a download's charts and legends: the ones in use, and any that+ * carried part of the file. */+export function networksInPlay<T extends DownloadNetwork>(networks: T[]): T[] {+ return networks.filter((network) => network.enabled || network.bytesDownloaded > 0)}/** Shortens an absolute path under the user's home directory to a "~/..." form for display. */diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.tsindex 5adb8fa..e0ba3df 100644--- a/src/shared/ipc-channels.ts+++ b/src/shared/ipc-channels.ts@@ -13,8 +13,10 @@ export const IpcChannels = {getCurrentDownload: 'download:get-current',pauseDownload: 'download:pause',resumeDownload: 'download:resume',+ setDownloadNetwork: 'download:set-network',cancelDownload: 'download:cancel',removeDownload: 'download:remove',downloadUpdated: 'download:updated',+ networksChanged: 'network:changed',checkForUpdate: 'update:check'} as constdiff --git a/src/shared/ipc-contract.ts b/src/shared/ipc-contract.tsindex 646c143..c24a0f9 100644--- a/src/shared/ipc-contract.ts+++ b/src/shared/ipc-contract.ts@@ -8,7 +8,7 @@ import type {} from './types'/** The request/response half of the IPC surface (every IpcChannels entry except the- * main->renderer push event, downloadUpdated) — one source of truth for+ * main->renderer push events, downloadUpdated and networksChanged) — one source of truth for* both plexoApi (preload) and registerIpcHandlers (main), so a signature drift between the two* is a compile error instead of a runtime one. */export interface IpcContract {@@ -25,6 +25,7 @@ export interface IpcContract {getCurrentDownload: { args: []; result: DownloadUpdate | null }pauseDownload: { args: [id: string]; result: void }resumeDownload: { args: [id: string]; result: void }+ setDownloadNetwork: { args: [id: string, networkId: string, enabled: boolean]; result: void }cancelDownload: { args: [id: string]; result: void }removeDownload: { args: [id: string]; result: void }checkForUpdate: { args: []; result: UpdateInfo | null }diff --git a/src/shared/types.ts b/src/shared/types.tsindex 5a0eefd..8eb1357 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -39,24 +39,24 @@ export type DownloadStatus = 'downloading' | 'paused' | 'completed' | 'error' |/** A stream's state. `pending` means it is waiting for work: it holds no block, either because* none is free for it right now or because it hasn't started. `downloading` always means it is- * fetching one (`currentBlockIndex` says which). */+ * fetching one (`currentBlockIndex` says which). A stream that fails for good leaves the list;+ * what went wrong is its network's to report (see DownloadNetwork). */export type ChunkStatus =- 'pending' | 'downloading' | 'retrying' | 'paused' | 'completed' | 'error' | 'cancelled'+ 'pending' | 'downloading' | 'retrying' | 'paused' | 'completed' | 'cancelled'+/** One connection to the server, through one network. Streams come and go as the download+ * runs; what a network has done is kept on its DownloadNetwork. */export interface ChunkState {id: number+ /** The network it runs on: a DownloadNetwork's id. */interfaceId: string- interfaceLabel: string- interfaceKind: NetworkInterfaceKindrangeStart: number/** null means an open-ended range (download to end of file). */rangeEnd: number | null+ /** New bytes it has delivered. */bytesDownloaded: numberspeedBytesPerSec: numberstatus: ChunkStatus- error?: string- /** Number of times this chunk's connection has been retried after a dropped/failed attempt. */- retryCount: number/** The block this stream is fetching. Unset whenever it holds none (idle, retrying, paused, done). */currentBlockIndex?: number/** True while this stream is racing another stream for `currentBlockIndex`, because that one@@ -83,6 +83,35 @@ export interface BlockState {bytesByInterface: Record<string, number>}+/**+ * - on: in use.+ * - off: the user switched it off. A network that turns up mid-download starts off.+ * - offline: not connected to this computer. It's used again as soon as it is.+ * - unreachable: connected, but the server can't be reached through it. One connection keeps+ * trying, and the rest follow once it gets through.+ * - failed: the server kept refusing requests over it (`error` says how). Switching it off and+ * on, reconnecting it, or resuming tries again.+ */+export type NetworkStatus = 'on' | 'off' | 'offline' | 'unreachable' | 'failed'++/** A network as one download sees it: whether the user has it on, and how it is doing. */+export interface DownloadNetwork {+ /** A NetworkInterfaceInfo id. */+ id: string+ /** Its name and kind as the OS last reported them. */+ label: string+ kind: NetworkInterfaceKind+ /** The user's choice; `status` is what came of it. */+ enabled: boolean+ status: NetworkStatus+ error?: string+ /** Bytes of the file it delivered. */+ bytesDownloaded: number+ speedBytesPerSec: number+ /** Requests over it that failed and were tried again. */+ retries: number+}+export interface DownloadState {id: stringurl: string@@ -93,6 +122,9 @@ export interface DownloadState {bytesDownloaded: numberspeedBytesPerSec: numberstatus: DownloadStatus+ /** Every network on this computer, and any the download used that has since gone, in the+ * order it first saw them. */+ networks: DownloadNetwork[]chunks: ChunkState[]/** The most streams it has run at once. */peakStreams?: number@@ -100,6 +132,9 @@ export interface DownloadState {totalBlocks?: numberblockSizeBytes?: numbererror?: string+ /** For an error: whether resuming can pick up where it stopped. False when the progress was+ * thrown away, e.g. the file changed on the server. */+ resumable?: booleanstartedAt: numberpausedAt?: numbertotalPausedMs?: number@@ -170,6 +205,7 @@ export interface StartDownloadRequest {/** 0 means unknown. */totalBytes: numbersupportsRanges: boolean+ /** The networks to start on. Every other one starts switched off. */interfaceIds: string[]etag: string | nulllastModified: string | null