Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

Torrents, download queue, selection actions, and speed & data limits (#64)

Anmol Kapil5404d920fcfd
diff --git a/README.md b/README.md
index cd29526..e27e7d2 100644
--- a/README.md
+++ b/README.md
@@ -2,400 +2,206 @@
[![Sponsor](https://img.shields.io/badge/Sponsor-GitHub-ea4aaa?logo=githubsponsors)](https://github.com/sponsors/anmolkapil)
-A fast download manager for Windows, macOS, and Linux that speeds up downloads by pulling chunks in parallel across **multiple network connections at the same time**.
+Plexo is a download manager for Windows, macOS, and Linux that downloads one file over several internet connections at the same time. If your computer has Wi-Fi and a phone tethered over USB, Plexo uses both for the same download. It handles direct links, magnet links, and `.torrent` files, with a queue, a downloads list, and speed and data limits for each network.
-For example, if your computer has:
-
-- Wi-Fi
-- Ethernet
-- USB-tethered phone (iPhone or Android)
-- Cellular
+https://github.com/user-attachments/assets/e57728f4-fb63-441f-839c-174eef954b17
-Plexo can utilize all of them simultaneously to download the **same file**.
+## Download Plexo
-https://github.com/user-attachments/assets/e57728f4-fb63-441f-839c-174eef954b17
+Get the installer for your computer from [getplexo.app](https://getplexo.app/#downloads), or pick a file from [GitHub Releases](https://github.com/anmolkapil/plexo/releases). Builds are available for macOS (Apple silicon and Intel), Windows 10 and 11 (x64 and ARM64), and Linux (AppImage and `.deb`, x86_64 and ARM64).
----
+Plexo isn't code-signed yet, so the first launch needs one extra step:
-## ⚠️ Before you start
+- **macOS** says Plexo is damaged: move it to Applications, run `xattr -dr com.apple.quarantine /Applications/Plexo.app` in Terminal, and open it again
+- **Windows** shows "Windows protected your PC": click **More info**, then **Run anyway**
-### Combining multiple network connections?
+## What Plexo does
-To successfully combine bandwidth across multiple network adapters (on Windows, macOS, or Linux):
+Plexo splits each download across every network you select, so a second connection adds to your speed instead of sitting idle.
-- **Use distinct internet connections:**
- - Each connection must have its own gateway / subnet (e.g., **Wi-Fi** via home router + **USB Tethering** via mobile phone, or two distinct WAN networks).
- - Connecting both Wi-Fi and Ethernet to the **same router** (same local subnet like `192.168.1.0/24`) will not increase speeds: both share the same upstream broadband connection, and operating system routing will send all packets through whichever interface has the lower metric or higher priority (usually Ethernet).
+### Direct downloads
-### Wi-Fi disconnecting when Ethernet is plugged in on Windows?
+- **Several networks, many streams each**: a file is split into blocks of up to 8 MB that streams on every network fetch in parallel. Each network starts with 8 streams and doubles to 16 and 32 once they're all receiving. You can also pick a fixed 4, 8, 16, or 32 in the **New download** dialog.
+- **Faster networks do more of the work**: a stream takes the next block as soon as it's free, so a fast network fetches more blocks than a slow one.
+- **No slow finish**: near the end, a free stream races a slow block from where it got to, and the first to finish wins
+- **Pause and resume**: progress is saved as you go. Before resuming, Plexo checks the file on the server hasn't changed, and refuses rather than mixing two versions.
+- **Survives restarts and sleep**: a download running when Plexo quits comes back paused. Streams restart as soon as the computer wakes or a network gets a new address, and Plexo keeps the computer awake while a download runs.
+- **Fix expired links**: paste a fresh link to the same file and the download carries on from where it stopped
+- **Backs off when a server asks**: if a server refuses some streams (403, 429, 503, or no answer), that network drops to the streams it accepted, then gets one more back each minute
-Some Windows 10/11 installations automatically disconnect or sleep Wi-Fi when an active Ethernet cable is detected.
+### Torrents
-If Wi-Fi turns off when Ethernet is plugged in: open **Group Policy Editor** (`gpedit.msc`) → _Computer Configuration_ → _Administrative Templates_ → _Network_ → _Windows Connection Manager_ → set **"Minimize the number of simultaneous connections to the Internet or a Windows domain"** to **Disabled**.
+- **Magnet links and `.torrent` files**: paste a link or open a file in Plexo. You can also open a `.torrent` with Plexo from your file manager, and on macOS and Linux, a magnet link from your browser. Plexo never makes itself the default over a torrent client you already have.
+- **Choose files**: pick which files to download before it starts, and change your choice while it runs
+- **Peers spread across networks**: each new peer connects through the network with the fewest. Switching a network off moves its peers to the others.
+- **Uploads on every network**: peers get pieces back over each network, USB-tethered ones included, so they keep sending to you
-### Using Android USB tethering on macOS?
+### Queue and downloads list
-macOS does not natively provide an RNDIS driver, so Android phones with USB tethering enabled won't appear as network interfaces out of the box (this is also why legacy kernel extensions like `HoRNDIS` stopped working on Apple Silicon and modern macOS).
+- **Queue**: two downloads run at once by default, and you can set one to eight. The rest wait and start on their own when a slot opens.
+- **Downloads list**: downloads are grouped as Downloading, Queued, Paused, Needs attention, and Finished, and finished downloads stay in the list after a restart
+- **Actions on several downloads at once**: select downloads to pause, resume, retry, cancel, remove them from the list, or move their files to Trash
+- **Links from the clipboard**: opening **New download** fills in a link you've copied
-To use your Android phone's connection over USB, install **TetherKit** — a kext-free, user-space RNDIS driver.
+### Limits and networks
-See [Using a USB-tethered Android phone](#using-a-usb-tethered-android-phone) for setup instructions.
+- **Speed limits**: a total limit for all downloads, a per-network limit, and **Slow mode**, a one-click lower limit (2 MB/s by default) for when you're on a call
+- **Data limits**: a daily, weekly, or monthly allowance per network. Plexo stops using a network once its allowance is used up.
+- **Named networks**: Plexo shows adapters by their real names (Wi-Fi, Ethernet, iPhone) instead of `en0`. You can rename and recolor them.
+- **Live view**: throughput charts, time left, per-stream stats, and a grid of every block colored by the network that fetched it
-> Plexo can only route traffic through connections that your operating system recognizes as network interfaces.
+## Set up more than one network
----
+Plexo adds speed only when each network reaches the internet through its own connection. Wi-Fi from your home router plus a phone tethered over USB works. Wi-Fi and Ethernet plugged into the same router doesn't: both share the router's single connection, so the total stays the same.
-## Why Plexo?
+Plexo can only use a connection your operating system shows as a network adapter. Two setups need an extra step:
-A single TCP connection rarely saturates your actual bandwidth. Even when your computer has multiple active networks — such as Wi-Fi and a tethered mobile phone — the operating system routes all traffic through a single default gateway, leaving the other interfaces completely idle.
+- **Windows turns Wi-Fi off when Ethernet is plugged in**: open the Group Policy Editor (`gpedit.msc`), go to _Computer Configuration_ › _Administrative Templates_ › _Network_ › _Windows Connection Manager_, and set **Minimize the number of simultaneous connections to the Internet or a Windows domain** to **Disabled**
+- **An Android phone over USB on macOS**: macOS has no driver for Android's USB tethering. Install TetherKit, as described in [Use an Android phone over USB on macOS](#use-an-android-phone-over-usb-on-macos).
-Plexo changes that: it splits the file into independent byte ranges and downloads them simultaneously through distinct physical network interfaces.
+On Windows, install your phone maker's driver if the phone doesn't appear in Network Settings. An adapter appearing in Plexo doesn't guarantee it reaches the internet: VPN, virtual, and isolated adapters show up too. Check each network's latency and speed in Plexo.
-```text
- ┌── Wi-Fi (IP: 192.168.1.40) ──────┐
- │ │
- ├── Ethernet (IP: 10.0.0.12) ──────┤
-File ──→ Split ─────┤ ├──→ Assembled File
- ├── USB Tether (IP: 172.20.10.3) ──┤
- │ │
- └── Cellular (IP: 21.169.64.78) ───┘
-```
+## Manage your downloads
-**Multiple networks → concurrent HTTP range requests → aggregated bandwidth**
+The menu in the header filters the list to **All downloads**, **In progress**, **Finished**, or **Needs attention**. Click a download's name to see its progress in detail.
----
+Tick downloads to select them, or use **Select all** for the filtered list. The header then shows each action with how many of the selected downloads it applies to:
-## Features
+- **Pause** downloading or queued downloads, and **Resume** paused ones
+- **Retry** downloads that failed and can recover. A download whose link expired has its own **Fix link** button, and one that can't resume has **Download again**.
+- **Remove from list** takes finished downloads off the list and leaves their files on your computer. **Clear finished list** does this for every finished download.
+- **Cancel downloads…** stops unfinished downloads and deletes what they downloaded so far
+- **Move files to Trash…** moves finished downloads' files to the Trash, or the Recycle Bin on Windows. For a torrent, Plexo moves only the files it downloaded and leaves anything else you added to the folder.
-- 🚀 **Multi-interface, multi-connection downloads** — splits files into chunks of up to 8 MB and fans them out across worker connections bound to specific network interfaces, each kept open from one chunk to the next. Each interface starts with 8 connections and doubles once they are all receiving, up to 32. If the server refuses some (503, 429, 403, or leaves them unanswered), that interface drops to the ones it accepted, then gets one more back each minute without a refusal; a server refusing everything (busy, or an expired link) doesn't lower it. You can also pick a fixed 4, 8, 16 or 32 per interface on the start screen instead of Auto.
-- 🔌 **Hardware interface detection** — queries Windows adapters via PowerShell `Get-NetAdapter` and macOS hardware ports via `networksetup` so Wi-Fi, Ethernet, tethered iPhones, and Thunderbolt bridges are labeled by real device names instead of bare BSD names (`en0`, `en6`).
-- ⚖️ **Dynamic work-stealing queue** — chunks are leased from a shared pending queue; faster networks pull more chunks instead of waiting for slower connections to finish.
-- ⏸️ **Resumable downloads** — cleanly pause and resume downloads with progress saved in a destination-side staging file.
-- 💾 **Relaunch recovery** — interrupted downloads are restored as paused after Plexo restarts, with a small manifest in application data.
-- 🛡️ **Safe, integrity-checked resume** — re-verifies remote `ETag` and `Last-Modified` validators before resuming, refusing to resume (rather than corrupting the file) if the server-side file has changed.
-- 🔁 **Automatic retry with backoff** — failed chunks go back to the queue and are retried with jittered exponential backoff (1s–15s). A dropped connection is retried for as long as its network is there; a busy server (429, 503, …) is waited out, honouring `Retry-After`; a server that answers wrongly gets 5 retries.
-- 🔄 **Network changes and sleep** — a network that gets a new address, or a computer that wakes from sleep, gets its connections going again at once instead of waiting out a backoff; the computer is kept awake while a download runs.
-- 💤 **Stall detection & watchdog** — automatically drops and re-queues connections that remain open but silent (>20s without incoming data, not counting time spent waiting on the disk).
-- 🔔 **Desktop notifications** — native desktop alerts when downloads complete or encounter errors.
-- 💾 **Upfront disk-space verification** — checks the destination volume before writing the staging file.
-- 🔀 **Mid-download redirect handling** — transparently follows 3xx HTTP redirects (up to 5 hops) during probing and individual chunk downloads.
-- 📊 **Real-time telemetry** — live throughput graphs, rolling-window ETA calculation, and per-connection transfer stats.
-- 🗺️ **Interactive progress grid** — 1:1 visual map of individual chunks, color-coded by the network interface that fetched each chunk with accurate per-network byte attribution.
-- 🎨 **Network customization** — rename and recolor physical network interfaces with persistent user preferences.
-- 🌓 **Light & Dark modes** — full theme support with an instant toggle between light and dark modes.
+Cancel and Move to Trash ask you to confirm first.
----
+## Set speed and data limits
-# How it works
+Open **Speed & data limits…** from the networks menu. Changes apply as you make them.
-Instead of downloading a file linearly over a single socket, Plexo requests arbitrary slices of the file simultaneously across multiple physical network interfaces. Three core technical primitives make this work:
+Under **All downloads**, set the total speed limit, the Slow mode speed, and how many downloads run at once. While Slow mode is on, its speed replaces the total limit, and per-network limits still apply.
-### 1. HTTP range requests (`206 Partial Content`)
+Choose a network to set its speed limit in KB/s or MB/s, and its data allowance in GB per **Day**, **Week**, or **Month**. The allowance counts what Plexo downloads on that network, torrents included; uploads and other apps don't count. Days reset at midnight, weeks on Monday, and months on the 1st, all in your local time, and usage is kept across restarts.
-Most modern HTTP servers support byte-level slicing:
+Two buttons manage a network's limits, and both ask you to confirm:
-```http
-GET /ubuntu-26.04.1-desktop-amd64.iso HTTP/1.1
-Host: releases.ubuntu.com
-Range: bytes=8388608-16777215
-```
+- **Reset data usage…** sets the network's usage for the current period back to zero, so a network that hit its allowance can be used again
+- **Remove limits…** clears the network's speed and data limits and keeps its recorded usage
-Servers advertise this capability with the `Accept-Ranges: bytes` response header and reply with HTTP status `206 Partial Content`. Because byte slices are stateless and independent, Plexo can request dozens of chunks at once, in any order, and stitch them together later.
+## How Plexo combines networks
-#### Probing before downloading
+Your operating system sends all of a computer's traffic through one default connection and leaves the others idle. Plexo opens its own connections on each network you select, and downloads different parts of the file on each.
-Before starting a multi-connection download, Plexo sends a **1-byte ranged GET** (`Range: bytes=0-0`), following any redirects:
+```text
+ ┌── Wi-Fi (192.168.1.40) ──────┐
+ │ │
+File ──→ Split ─────┼── Ethernet (10.0.0.12) ──────┼──→ Assembled file
+ │ │
+ └── USB tether (172.20.10.3) ──┘
+```
-- Unlike a `HEAD` request (which servers and CDNs frequently misreport), receiving a `206 Partial Content` response conclusively proves that range requests are supported and functional.
-- The probe response provides the total file size (`Content-Range` / `Content-Length`), suggested filename (`Content-Disposition`), and cache validators (`ETag` and `Last-Modified`).
-- If the server answers with `200 OK` (ignoring the `Range` header), Plexo falls back to a standard single-connection stream instead of failing.
+It needs no virtual adapter, VPN, kernel extension, or administrator rights.
-### 2. Multi-interface socket binding
+### Direct downloads use HTTP range requests
-Every active network interface on your computer has local IP addresses — Wi-Fi might have both IPv4 and IPv6, while a USB-tethered phone has its own addresses.
+Most servers can send any slice of a file on request. A request with `Range: bytes=8388608-16777215` gets back bytes 8 MB to 16 MB with status `206 Partial Content`. Plexo first asks for a single byte. A `206` answer proves the server supports ranges and tells Plexo the file's size, name, and version (`ETag` and `Last-Modified`). A server that ignores ranges gets an ordinary single-stream download.
-A standard TCP socket leaves interface selection to the operating system's routing table. Plexo resolves the server, chooses an address of the same IP family on each selected interface, then binds that address for its HTTP/HTTPS connections. On Linux it also pins the socket to the device.
+Each stream connects from one network's own address, so its traffic goes out through that network. On Linux, Plexo also pins the socket to the network device.
-```js
+```typescript
https.request({
hostname: 'releases.ubuntu.com',
path: '/ubuntu-26.04.1-desktop-amd64.iso',
- localAddress: '172.20.10.3', // Source address on the USB tether
- headers: {
- Range: 'bytes=8388608-16777215'
- }
+ localAddress: '172.20.10.3', // the USB tether's address
+ headers: { Range: 'bytes=8388608-16777215' }
})
```
-The interface binding keeps each worker on its selected network:
-
-- **No virtual network adapters or VPN tunnels**
-- **No packet bonding or link aggregation**
-- **No kernel extensions (`kext`) or root privileges**
+### Streams share one queue of blocks
-### 3. Dynamic work-stealing queue
+Splitting a file into equal halves, one per network, makes the download only as fast as the slower network. Plexo cuts the file into blocks of up to 8 MB instead, and puts them all in one queue:
-If you statically divide a 6 GB file into equal shares (e.g. 3 GB on Wi-Fi and 3 GB on mobile data), the total download speed is bottlenecked by the slower network.
+1. Each stream takes the next block in the queue, fetches it, then takes another. It keeps its connection to the server open between blocks, so it connects only once.
+2. A faster network finishes its blocks sooner and takes more of them. If a network slows down or drops, the others keep draining the queue.
+3. Once the queue is empty, a free stream can race a block that another stream is fetching too slowly. The first to finish wins. The streams table marks the racing stream **BACKUP**.
-Instead, Plexo uses a **dynamic work-stealing queue**:
+8 MB keeps the queue balanced between mismatched networks, and caps what a failed stream throws away. Small files get smaller blocks, never under 1 MB, so every stream has at least two.
-1. The file is split into **chunks of up to 8 MB** (smaller for small files, so every network gets a share).
-2. All chunks enter a centralized pending queue.
-3. A pool of worker connections continuously lease the next chunk from the queue as soon as they become free. Each keeps its one connection to the server from chunk to chunk, so it pays for the handshake and TCP's slow start once, not per chunk. Connections start interleaved across networks, so each network is served before any is served twice.
- - **How many.** Each network starts with 8 connections, and once every one of them is receiving it doubles, up to 32, never more than there are chunks for. Another connection costs little when the link is already full, and a server that caps each connection's speed is only outrun by more of them. A server that refuses some of a network's connections (503, 429, 403, or leaves them unanswered for 5 seconds) while still sending data down the others is asking for fewer: the refused ones close, their chunks go back to the queue to carry on from where they got to, and that network stays at the ones left. After a minute without another refusal it may have one more, and so on back up. A server that refuses everything (busy, or an expired link) isn't limiting connections, so the count stays. On the start screen you can pick a fixed 4, 8, 16 or 32 per network instead of Auto.
-4. Faster interfaces finish chunks quicker and immediately pick up new ones; slower interfaces pull fewer chunks.
-5. **Racing the tail.** Once no chunk is left waiting, a free connection can start a second attempt at a chunk another connection is fetching too slowly (as soon as the free connection would finish it in under half the time the chunk still needs; a chunk whose second attempt is stuck too can get one more), picking up from where the first had got to. Whichever finishes first wins and the other is dropped. It costs a few bytes fetched twice at the very end, and it means one slow connection — or one slow network — can no longer hold the whole download back. A stream doing this is marked **BACKUP** in the streams table.
-
-```text
-Shared Pending Queue: [Chunk #4] [Chunk #5] [Chunk #6] [Chunk #7] [Chunk #8] ...
- ↑ ↑ ↑ ↑
- Worker 1 Worker 2 Worker 3 Worker 4
- (Wi-Fi) (Ethernet) (USB Tether) (Cellular)
-```
+Each block is written straight to its place in `<filename>.plexo`, a staging file next to the destination. When every block is in, Plexo renames it to the final name, picking a numbered name if that one is taken. The destination needs room for one copy of the file.
-Work distribution is dynamically proportional to each interface's real-time throughput. If one network slows down or disconnects, remaining workers continue draining the queue without stalled shares.
+### Torrents pin each peer to a network
-### 4. Direct-to-destination storage
+Plexo runs torrents with [WebTorrent](https://github.com/webtorrent/webtorrent) and opens every peer connection from one network's address. To keep every peer on a network Plexo chose, it turns off the parts that would connect on their own: uTP, web seeds, UPnP and NAT-PMP port mapping, and local peer discovery. Peers are found through trackers and the DHT. Torrents that are v2-only aren't supported yet.
-Each worker writes its assigned byte range at its final offset in one staging file beside the chosen destination. Workers use separate file handles and explicit byte positions, so non-overlapping ranges can be written in parallel.
+### Resuming checks the file hasn't changed
-While downloading, the folder contains `<filename>.plexo` and no empty file under the final name. Once every range is complete, Plexo flushes the partial file, checks for a filename collision, and renames it into place in the same folder. If the final name is taken, Plexo chooses a numbered name. This works on drives such as exFAT without a full-file assembly copy, so the destination needs approximately one file's worth of space.
+Pausing closes every connection and keeps the staging file plus a small progress record in Plexo's app data. Resuming asks the server for the file's `ETag` and `Last-Modified` again. If they match, each block continues from the last saved byte. If they don't, the file changed on the server, and Plexo refuses to resume instead of joining two versions into a corrupt file.
----
+## Use an Android phone over USB on macOS
-# Downloads are resumable
+macOS has no driver for RNDIS (Remote Network Driver Interface Specification), the protocol Android's USB tethering uses. The phone charges, but no network adapter appears. [TetherKit](https://github.com/XiaoMiku01/TetherKit) is an open-source driver that runs without a kernel extension and adds one.
-When you pause a download:
-
-- Plexo aborts all active HTTP socket connections via `AbortController`.
-- The staging file remains beside the chosen destination, and progress is saved in a small manifest.
-
-When you resume:
-
-1. **Validator check**: Plexo sends a probe request to compare the server's current `ETag` and `Last-Modified` headers against the values recorded when the download started.
-2. **Safe resume**: If the validators match, Plexo resumes each range from the last saved byte offset in the staging file.
-3. **Guard against corruption**: If the file on the server has changed, Plexo refuses to resume to prevent combining incompatible slices into a corrupt file.
-
-Download manifests are stored under Plexo's application-data directory; large partial data stays beside the destination. If Plexo quits or crashes during a transfer, it restores that transfer as paused on the next launch. Cancelling or removing a download deletes its staging file.
-
----
-
-# What is a chunk?
-
-A **chunk** is the atomic unit of work in Plexo:
-
-- **Size**: Up to 8 MB, with the final chunk sized to the remaining bytes. A file that is small next to its connection count gets smaller chunks (never under 1 MB) — at least two per connection — so a fast network can out-pull a slow one instead of being stuck behind it.
-- **Transport**: One independent HTTP range request (`Range: bytes=START-END`).
-- **Storage**: Written at its final byte offset in the destination-side staging file.
-- **Assignment**: Leased to an individual worker socket bound to a specific network interface.
-
-```text
-Chunk #0 → Range: bytes=0-8388607 → staging offset 0 (Wi-Fi)
-Chunk #1 → Range: bytes=8388608-16777215 → staging offset 8388608 (Ethernet)
-Chunk #2 → Range: bytes=16777216-25165823 → staging offset 16777216 (USB Tether)
-Chunk #3 → Range: bytes=25165824-33554431 → staging offset 25165824 (Cellular)
-```
+1. Install TetherKit:
-### Why up to 8 MB?
+ ```bash
+ brew install XiaoMiku01/tap/tetherkit
+ ```
-8 MB provides the optimal balance: large enough to minimize HTTP connection overhead and TLS handshakes, yet small enough to keep the work-stealing queue fluid, ensure fine-grained load balancing across mismatched connections, and keep retries cheap (a failed or stalled connection only discards at most 8 MB). Below about 1 MB a request costs more in round trips than splitting saves, so that is the floor; a file that small is one chunk.
+2. Connect your phone over USB.
+3. On the phone, open **Settings › Network & internet › Hotspot & tethering** and turn on **USB tethering**.
+4. Open Plexo. The phone appears in the networks list.
----
+Thanks to [@XiaoMiku01](https://github.com/XiaoMiku01) for building and open-sourcing TetherKit.
-# What is the progress grid?
+## Build Plexo from source
-The progress grid provides a real-time visual map of the entire download.
-
-Every chunk maps **1:1 to its own square** in the grid. Square #N directly corresponds to the **Chunk #N** badge shown in the active streams table, allowing you to cross-reference active connections with their location in the file.
-
-```text
-Active Streams:
-[Wi-Fi] → Chunk #4
-[Ethernet] → Chunk #5
-[USB Tether] → Chunk #6
-[Cellular] → Chunk #7
-
-Progress Grid:
-[#1][#2][#3][#4][#5][#6][#7][#8]...
-```
-
----
-
-# Getting started
-
-Plexo currently doesn't have pre-built releases, so you'll need to run it from source.
-
-## Requirements
-
-- **Windows 10/11, macOS, or Linux**: Windows uses its built-in Windows PowerShell for adapter metadata; macOS uses `networksetup`; Linux provides fallback interface detection and desktop network settings integration.
-- **Node.js**: 22.12+ (Node 22 LTS recommended).
-- **npm**: v9+ recommended.
-
----
-
-## Run Plexo locally
-
-Clone the repository:
+You need Node.js 22.12 or later and npm 9 or later.
```bash
git clone https://github.com/anmolkapil/plexo.git
cd plexo
-```
-
-Install dependencies:
-
-```bash
npm install
-```
-
-Start the application in development mode:
-
-```bash
npm run dev
```
----
-
-## Running tests
-
-Plexo includes an automated end-to-end test suite driven by Playwright:
-
-```bash
-npm run test:e2e:smoke # quick smoke tests
-npm run test:e2e # full E2E test suite (including integrity and chaos tests)
-```
-
-See [CONTRIBUTING.md](CONTRIBUTING.md#end-to-end-tests) for testing options and debugging flags.
-
----
-
-# Build the macOS app
-
-To package Plexo as a standalone macOS application bundle:
+Run the end-to-end tests with Playwright. [CONTRIBUTING.md](CONTRIBUTING.md#end-to-end-tests) covers the options and debugging flags.
```bash
-npm run build:mac
-```
-
-The compiled application will be generated at:
-
-```text
-dist/mac/Plexo.app
+npm run test:e2e:smoke # smoke tests
+npm run test:e2e # the full suite
```
-> **Note on Gatekeeper:** The app is unsigned because it is not distributed with a paid Apple Developer certificate. However, because you compile it locally on your machine, macOS will not apply the quarantine flag (`com.apple.quarantine`). Gatekeeper only quarantines files downloaded from the web (via browsers, curl, etc.), so your locally built `Plexo.app` will launch cleanly without quarantine warnings.
-
-## Build the Windows app
+Package the app for each platform:
-Run these commands from PowerShell in the project directory:
+- **macOS**: `npm run build:mac` writes `dist/mac/Plexo.app`. A build made on your own Mac isn't quarantined, so it opens without the first-launch step.
+- **Windows**: `npm run build:win`, from PowerShell, writes the installer to `dist/`. For an app you run without installing, use `npm run build:unpack` and open `dist/win-unpacked/plexo.exe`.
+- **Linux**: `npm run build:linux` writes the AppImage and `.deb` packages to `dist/`
-```powershell
-npm install
-npm run build:win
-```
-
-The installer is generated at `dist/plexo-1.0.0-setup.exe`. For an unpacked app, run
-`npm run build:unpack` and launch `dist/win-unpacked/plexo.exe`.
Local builds are unsigned.
-Windows uses native window controls, Ctrl+V hints, File Explorer integration, and Windows
-Network Settings. Download filenames are normalized to Windows filename rules.
-
-### USB tethering on Windows
-
-Enable USB tethering on your phone and check that its adapter appears in Windows Network
-Settings. Install the phone manufacturer's Windows driver if Windows does not recognize it.
-TetherKit is only needed for the macOS setup below.
-
-Each selected network needs a working IPv4 connection and a route to the download server.
-Adapter detection does not guarantee Internet access: VPN, virtual, and isolated adapters may
-also appear. Check per-network latency and transfer stats. Combined throughput depends on the
-networks, Windows routing, and the server; it needs testing with your particular connections.
-
-Linux packaging remains available via `npm run build:linux` (see [Build the Linux app](#build-the-linux-app)).
-
----
-
-## Build the Linux app
-
-To package Plexo for Linux:
-
-```bash
-npm run build:linux
-```
-
-The package will be generated in `dist/`.
-
----
-
-# Using a USB-tethered Android phone
-
-Android USB tethering requires an additional setup step on macOS.
-
-macOS lacks native support for the **RNDIS (Remote Network Driver Interface Specification)** protocol. An Android phone with USB tethering enabled will charge and support MTP/ADB, but macOS will not expose it as a network interface (this is also why legacy kernel extensions like `HoRNDIS` stopped functioning on modern macOS and Apple Silicon).
-
-## Install TetherKit
-
-[TetherKit](https://github.com/XiaoMiku01/TetherKit) is an open-source, kext-free, user-space RNDIS driver that makes Android USB tethering available as a standard network interface on macOS.
-
-Install it via Homebrew:
-
-```bash
-brew install XiaoMiku01/tap/tetherkit
-```
-
-### Steps:
-
-1. Connect your Android device via USB.
-2. On your phone, navigate to **Settings → Network & Internet → Hotspot & tethering** and enable **USB tethering**.
-3. Once TetherKit is active, macOS registers the device as a network interface.
-4. Open Plexo — the new interface will be automatically detected and ready to carry download chunks.
-
-Special thanks to [@XiaoMiku01](https://github.com/XiaoMiku01) for developing and open-sourcing TetherKit!
-
----
-
-# Contributing
-
-Contributions are welcome! Whether you're optimizing download concurrency, improving UI responsiveness, or testing new tethering setups:
-
-- 🐛 Fix bugs & edge cases
-- 🚀 Improve download engine & socket throughput
-- 🌐 Expand multi-interface detection to other platforms (Linux)
-- 🎨 Enhance UI/UX and dark mode styling
-- 🧪 Test diverse multi-network environments (5G tethering, Wi-Fi 6, 10GbE)
-- 📖 Improve documentation & guides
-
-For development setup, coding standards, and PR workflows, see [CONTRIBUTING.md](CONTRIBUTING.md).
-
----
+## Contributing
-# Tech stack
+Contributions are welcome, from download engine work to testing Plexo on new network setups. Areas that need help:
-Plexo is built with:
+- Download and torrent throughput
+- Network adapter names on Linux
+- Testing with 5G tethering, Wi-Fi 6, and 10 GbE
+- The interface and documentation
-- **Electron** — desktop runtime
-- **React 19** — declarative UI
-- **Tailwind CSS v4** & **Base UI** — modern styling and accessible component primitives
-- **TypeScript** — end-to-end type safety
-- **Zustand** — lightweight client state management
-- **Lucide React** — icons
-- **Playwright** — end-to-end testing suite
-- **electron-vite** — fast HMR and build tooling
-- **electron-builder** — multi-platform packaging (macOS, Windows, Linux)
+See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, code style, and how to open a pull request.
----
+## Built with
-# Support
+Electron, React 19, TypeScript, Tailwind CSS v4, Base UI, Zustand, WebTorrent, and Lucide icons. electron-vite builds it, electron-builder packages it, and Playwright tests it.
-If Plexo is useful to you, you can support it by:
+## Support Plexo
-- ⭐ Starring the repo
-- 🐛 [Reporting bugs and suggesting features](https://github.com/anmolkapil/plexo/issues)
-- ❤️ [Sponsoring development](https://github.com/sponsors/anmolkapil)
+If Plexo is useful to you:
----
+- Star the repository
+- [Report a bug or suggest a feature](https://github.com/anmolkapil/plexo/issues)
+- [Sponsor development](https://github.com/sponsors/anmolkapil)
-# License
+## License
-MIT — see [LICENSE](LICENSE).
+MIT. See [LICENSE](LICENSE).
diff --git a/docs/changelog.js b/docs/changelog.js
index bf416de..0757776 100644
--- a/docs/changelog.js
+++ b/docs/changelog.js
@@ -9,6 +9,41 @@
'use strict'
root.PlexoChangelog = [
+ {
+ version: 'v1.0.0-rc.12',
+ items: [
+ {
+ kind: 'new',
+ title: 'Torrents',
+ text: 'Open magnet links and `.torrent` files. Peers spread across your networks, and you can choose which files to download before it starts or while it runs.'
+ },
+ {
+ kind: 'new',
+ title: 'A download queue',
+ text: 'Two downloads run at once by default, or set one to eight. The rest wait and start on their own, and finished downloads stay in the list after a restart.'
+ },
+ {
+ kind: 'new',
+ title: 'Speed and data limits',
+ text: 'Set a total speed limit, a limit per network, and Slow mode for calls. Give a network a daily, weekly or monthly data allowance and Plexo stops using it once it is spent.'
+ },
+ {
+ kind: 'new',
+ title: 'Act on many downloads at once',
+ text: 'Select downloads to pause, resume, retry, cancel, remove them from the list, or move their files to the Trash.'
+ },
+ {
+ kind: 'new',
+ title: 'Fix expired links',
+ text: 'Paste a fresh link to the same file and the download carries on from where it stopped.'
+ },
+ {
+ kind: 'improved',
+ title: 'A more compact window',
+ text: 'Slimmer title bar and header. Speed, the queue, Slow mode, free space and the update button now sit in the bar along the bottom.'
+ }
+ ]
+ },
{
version: 'v1.0.0-rc.11',
items: [
diff --git a/e2e/blockProgress.spec.ts b/e2e/blockProgress.spec.ts
index 29a0438..63a9d12 100644
--- a/e2e/blockProgress.spec.ts
+++ b/e2e/blockProgress.spec.ts
@@ -6,13 +6,14 @@ import fc from 'fast-check'
import { advanceBlock, retractBlock } from '../src/main/download/blockProgress'
import { DownloadFile } from '../src/main/download/downloadFile'
import { reserveDestinationPath } from '../src/main/download/paths'
-import type { BlockState } from '../src/shared/types'
+import type { HttpBlockState } from '../src/shared/types'
// K. What a block's byte counts mean when two attempts race for it, and how range writes land
// in the one destination-side staging file.
const LENGTH = 1000
-const fresh = (): BlockState => ({
+const fresh = (): HttpBlockState => ({
+ kind: 'http',
index: 0,
rangeStart: 0,
rangeEnd: LENGTH - 1,
@@ -20,7 +21,7 @@ const fresh = (): BlockState => ({
bytesDownloaded: 0,
bytesByInterface: {}
})
-const attributed = (block: BlockState): number =>
+const attributed = (block: HttpBlockState): number =>
Object.values(block.bytesByInterface).reduce((sum, bytes) => sum + bytes, 0)
test.describe('block progress', () => {
diff --git a/e2e/download.spec.ts b/e2e/download.spec.ts
index e9029c9..2fc6d9f 100644
--- a/e2e/download.spec.ts
+++ b/e2e/download.spec.ts
@@ -8,7 +8,7 @@ test.describe('happy paths @smoke', () => {
const origin = await serve({ size: 4 * BLOCK, host: '::1' })
await plexo.relaunch({ PLEXO_E2E_INTERFACES: 'a=::1' })
await plexo.start(origin.url(), origin.sha256)
- const state = await plexo.waitForStatus('completed')
+ const state = await plexo.waitForHttpStatus('completed')
expect(state.networks.every((network) => network.retries === 0)).toBe(true)
expect(origin.chunkRequests().every((request) => request.from === '::1')).toBe(true)
})
@@ -19,7 +19,7 @@ test.describe('happy paths @smoke', () => {
}) => {
const origin = await serve({ size: BLOCK, host: '::1' })
await expect(plexo.start(origin.url(), origin.sha256)).rejects.toThrow(/No selected network/)
- expect(await plexo.current()).toBeNull()
+ expect(await plexo.currentHttp()).toBeNull()
})
for (const [label, size] of [
@@ -29,7 +29,7 @@ test.describe('happy paths @smoke', () => {
test(`ranged download: ${label}`, async ({ plexo, serve }) => {
const origin = await serve({ size })
await plexo.start(origin.url(), origin.sha256, { connections: 4 })
- const state = await plexo.waitForStatus('completed')
+ const state = await plexo.waitForHttpStatus('completed')
expect(state.bytesDownloaded).toBe(size)
expect(state.totalBlocks).toBe(Math.ceil(size / BLOCK))
})
@@ -38,8 +38,8 @@ test.describe('happy paths @smoke', () => {
test('each stream keeps its connection from one block to the next', async ({ plexo, serve }) => {
const origin = await serve({ size: 20 * BLOCK + 123 })
await plexo.start(origin.url(), origin.sha256, { connections: 4 })
- const state = await plexo.waitForStatus('completed')
- expect(state.chunks).toHaveLength(4)
+ const state = await plexo.waitForHttpStatus('completed')
+ expect(state.streams).toHaveLength(4)
const requests = origin.chunkRequests()
expect(new Set(requests.map((request) => request.connection)).size).toBe(4)
expect(requests.length).toBeGreaterThan(4)
@@ -52,7 +52,7 @@ test.describe('happy paths @smoke', () => {
test.skip(!LAN_ADDRESS, 'needs a LAN address to act as the second network')
const origin = await serve({ size: 40 * BLOCK })
await plexo.start(origin.url(), origin.sha256, { networks: ['a', 'b'], connections: 2 })
- const state = await plexo.waitForStatus('completed')
+ const state = await plexo.waitForHttpStatus('completed')
const served = { a: 0, b: 0 }
for (const entry of origin.chunkRequests()) {
@@ -71,8 +71,13 @@ test.describe('happy paths @smoke', () => {
test('after the first, updates carry only the blocks that changed', async ({ plexo, serve }) => {
const origin = await serve({ size: 64 * BLOCK, bytesPerSecond: 500_000 })
const id = await plexo.start(origin.url(), origin.sha256)
- await plexo.waitForStatus('completed')
- const sent = plexo.updates.at(-1)!.filter((update) => update.state.id === id)
+ await plexo.waitForHttpStatus('completed')
+ const sent = plexo.updates
+ .at(-1)!
+ .filter((update) => update.state.id === id && 'blocks' in update)
+ .filter(
+ (update): update is import('../src/shared/types').HttpDownloadUpdate => 'blocks' in update
+ )
expect(sent.length, 'progress kept coming while it downloaded').toBeGreaterThan(5)
expect(sent[0].blocks).toHaveLength(64)
// Two streams move a few blocks between one update and the next, not all 64.
@@ -82,14 +87,14 @@ test.describe('happy paths @smoke', () => {
test('server without range support: one stream, whole file', async ({ plexo, serve }) => {
const origin = await serve({ size: 10 * BLOCK, ranges: false })
await plexo.start(origin.url(), origin.sha256)
- const state = await plexo.waitForStatus('completed')
- expect(state.chunks).toHaveLength(1)
+ const state = await plexo.waitForHttpStatus('completed')
+ expect(state.streams).toHaveLength(1)
})
test('unknown size (no Content-Length)', async ({ plexo, serve }) => {
const origin = await serve({ size: 10 * BLOCK, ranges: false, contentLength: false })
await plexo.start(origin.url(), origin.sha256)
- const state = await plexo.waitForStatus('completed')
+ const state = await plexo.waitForHttpStatus('completed')
expect(state.totalBytes).toBe(0)
})
@@ -97,7 +102,7 @@ test.describe('happy paths @smoke', () => {
const origin = await serve({ size: 12 * BLOCK })
origin.setRule(({ path }) => (path === '/start' ? { redirect: '/files/test.bin' } : 'ok'))
await plexo.start(origin.url('/start'), origin.sha256)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
// The chunk requests follow redirects too (a signed CDN URL rotating mid-download).
const next = await serve({ size: 12 * BLOCK, seed: 7 })
@@ -109,7 +114,7 @@ test.describe('happy paths @smoke', () => {
return 'ok'
})
await plexo.start(next.url(), next.sha256)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
expect(redirected).toBeGreaterThan(0)
})
})
@@ -123,7 +128,7 @@ test.describe('file names @smoke', () => {
test(label, async ({ plexo, serve, dirs }) => {
const origin = await serve({ size: 3 * BLOCK, contentDisposition: disposition })
await plexo.start(origin.url(), origin.sha256)
- const state = await plexo.waitForStatus('completed')
+ const state = await plexo.waitForHttpStatus('completed')
expect(state.fileName).toMatch(expected)
expect(state.destinationPath.startsWith(dirs.dest)).toBe(true)
})
@@ -135,11 +140,11 @@ test.describe('file names @smoke', () => {
}) => {
const first = await serve({ size: 3 * BLOCK, seed: 1 })
await plexo.start(first.url(), first.sha256)
- const one = await plexo.waitForStatus('completed')
+ const one = await plexo.waitForHttpStatus('completed')
const second = await serve({ size: 5 * BLOCK, seed: 2 })
await plexo.start(second.url(), second.sha256)
- const two = await plexo.waitForStatus('completed')
+ const two = await plexo.waitForHttpStatus('completed')
expect(one.fileName).toBe('test.bin')
expect(two.fileName).toBe('test (1).bin')
@@ -153,7 +158,7 @@ test.describe('edge cases', () => {
test('a 0-byte file @smoke', async ({ plexo, serve }) => {
const origin = await serve({ size: 0 })
await plexo.start(origin.url(), origin.sha256)
- await plexo.waitForStatus('completed', 5000)
+ await plexo.waitForHttpStatus('completed', 5000)
})
test('a server that never answers the link check → an error, not endless "Checking…" @smoke', async ({
@@ -167,19 +172,59 @@ test.describe('edge cases', () => {
expect(Date.now() - started).toBeLessThan(10_000)
})
- test('starting a second download while one is active is refused @smoke', async ({
+ test('a link that expired mid-download carries on from a fresh one, not one to another file', async ({
plexo,
serve
}) => {
- const origin = await serve({ size: 10 * BLOCK })
- const reached = origin.hold(BLOCK)
- await plexo.start(origin.url(), origin.sha256)
- await reached
-
- const other = await serve({ size: BLOCK, seed: 3 })
- await expect(plexo.start(other.url(), other.sha256)).rejects.toThrow(/already in progress/)
-
+ const origin = await serve({ size: 16 * BLOCK, seed: 7 })
+ const held = origin.hold(4 * BLOCK)
+ const id = await plexo.start(origin.url(), origin.sha256)
+ await held
+ origin.setRule(() => ({ status: 403 }))
origin.release()
- await plexo.waitForStatus('completed')
+ const failed = await plexo.waitUntil((state) => state.status === 'error', 30_000)
+ expect(failed.error).toMatch(/status 403/)
+ const kept = failed.bytesDownloaded
+ expect(kept).toBeGreaterThan(0)
+
+ const other = await serve({ size: 8 * BLOCK, seed: 8 })
+ await expect(plexo.api.relinkDownload(id, other.url())).rejects.toThrow(/different file/)
+
+ const fresh = await serve({ size: 16 * BLOCK, seed: 7 })
+ await plexo.api.relinkDownload(id, fresh.url())
+ await plexo.waitForHttpStatus('completed')
+ // Only what was missing came from the fresh link.
+ const fetched = fresh.chunkRequests().reduce((sum, entry) => sum + entry.bytesSent, 0)
+ expect(fetched).toBeLessThanOrEqual(16 * BLOCK - kept + 4 * BLOCK)
+ })
+
+ test('past two at once, downloads wait in the queue and start as room frees @smoke', async ({
+ plexo,
+ serve
+ }) => {
+ const origins = await Promise.all([1, 2, 3].map((seed) => serve({ size: 4 * BLOCK, seed })))
+ const held = origins.map((origin) => origin.hold(BLOCK))
+ const ids: string[] = []
+ for (const origin of origins) ids.push(await plexo.start(origin.url(), origin.sha256))
+ await Promise.all(held.slice(0, 2))
+ const status = async (index: number): Promise<string | undefined> =>
+ (await plexo.byId(ids[index]))?.status
+ expect(await status(2)).toBe('queued')
+
+ // A pause makes room: the queued one starts.
+ await plexo.api.pauseDownload(ids[0])
+ await held[2]
+ expect(await status(2)).toBe('downloading')
+ // Resumed while two run, it waits, first in line, for the next to finish.
+ await plexo.api.resumeDownload(ids[0])
+ await expect.poll(() => status(0)).toBe('queued')
+ origins[1].release()
+ await expect.poll(() => status(1)).toBe('completed')
+ await expect.poll(() => status(0)).not.toBe('queued')
+
+ for (const origin of origins) origin.release()
+ for (let index = 0; index < 3; index++) {
+ await expect.poll(() => status(index), { timeout: 20_000 }).toBe('completed')
+ }
})
})
diff --git a/e2e/downloadUpdate.spec.ts b/e2e/downloadUpdate.spec.ts
index 4d330d4..59d3097 100644
--- a/e2e/downloadUpdate.spec.ts
+++ b/e2e/downloadUpdate.spec.ts
@@ -1,11 +1,17 @@
import { expect, test } from '@playwright/test'
import { applyDownloadUpdate } from '../src/shared/downloadUpdate'
-import type { BlockState, DownloadUpdate } from '../src/shared/types'
+import type {
+ HttpBlockState,
+ HttpDownloadUpdate,
+ TorrentDownloadUpdate,
+ TorrentPieceState
+} from '../src/shared/types'
// O. How the window puts a download back together from the updates the main process sends: a
// snapshot, then only the blocks that changed.
-const block = (index: number, bytesDownloaded = 0): BlockState => ({
+const block = (index: number, bytesDownloaded = 0): HttpBlockState => ({
+ kind: 'http',
index,
rangeStart: index * 100,
rangeEnd: index * 100 + 99,
@@ -14,9 +20,10 @@ const block = (index: number, bytesDownloaded = 0): BlockState => ({
bytesByInterface: bytesDownloaded ? { a: bytesDownloaded } : {}
})
-const update = (seq: number, blocks: BlockState[], id = 'd1'): DownloadUpdate => ({
+const update = (seq: number, blocks: HttpBlockState[], id = 'd1'): HttpDownloadUpdate => ({
seq,
state: {
+ kind: 'http',
id,
url: 'http://example.test/file',
fileName: 'file',
@@ -26,24 +33,28 @@ const update = (seq: number, blocks: BlockState[], id = 'd1'): DownloadUpdate =>
speedBytesPerSec: 0,
status: 'downloading',
networks: [],
- chunks: [],
+ streams: [],
+ peakStreams: 0,
totalBlocks: 4,
+ blockSizeBytes: 100,
startedAt: 0
},
blocks
})
-const full = (seq: number, id = 'd1'): DownloadUpdate =>
+const full = (seq: number, id = 'd1'): HttpDownloadUpdate =>
update(seq, [block(0), block(1), block(2), block(3)], id)
test.describe('download updates', () => {
test('changed blocks land on the ones already there', () => {
const start = applyDownloadUpdate(null, full(1))
const next = applyDownloadUpdate(start, update(2, [block(1, 50)]))!
- expect(next.blocks!.map((entry) => entry.bytesDownloaded)).toEqual([0, 50, 0, 0])
+ expect(next.kind).toBe('http')
+ if (next.kind !== 'http' || start?.kind !== 'http') throw new Error('Expected HTTP state')
+ expect(next.blocks.map((entry) => entry.bytesDownloaded)).toEqual([0, 50, 0, 0])
expect(next.seq).toBe(2)
// What was there is left untouched.
- expect(start!.blocks![1].bytesDownloaded).toBe(0)
+ expect(start.blocks[1].bytesDownloaded).toBe(0)
})
test('an update sent before a snapshot was taken, arriving after it, is ignored', () => {
@@ -65,4 +76,49 @@ test.describe('download updates', () => {
// A new download's first update has every block, and stands on its own.
expect(applyDownloadUpdate(previous, full(1, 'new'))?.id).toBe('new')
})
+
+ test('torrent piece updates merge independently from live peer state', () => {
+ const piece = (index: number, provisionalBytes = 0): TorrentPieceState => ({
+ kind: 'torrent',
+ index,
+ rangeStart: index * 100,
+ rangeEnd: index * 100 + 99,
+ status: provisionalBytes > 0 ? 'downloading' : 'pending',
+ bytesDownloaded: 0,
+ provisionalBytes,
+ bytesByInterface: {}
+ })
+ const torrentUpdate = (seq: number, pieces: TorrentPieceState[]): TorrentDownloadUpdate => ({
+ seq,
+ state: {
+ kind: 'torrent',
+ id: 'torrent',
+ url: 'magnet:?xt=urn:btih:test',
+ fileName: 'files',
+ destinationPath: '/tmp/files',
+ totalBytes: 200,
+ bytesDownloaded: 0,
+ speedBytesPerSec: 0,
+ status: 'downloading',
+ networks: [],
+ peers: [],
+ peakPeers: 0,
+ totalPieces: 2,
+ pieceLength: 100,
+ files: { chosen: 1, total: 1 },
+ folder: false,
+ skippedBytes: 0,
+ bytesUploaded: 0,
+ uploadSpeedBytesPerSec: 0,
+ startedAt: 0
+ },
+ pieces
+ })
+ const start = applyDownloadUpdate(null, torrentUpdate(1, [piece(0), piece(1)]))
+ const next = applyDownloadUpdate(start, torrentUpdate(2, [piece(1, 40)]))
+ expect(next?.kind).toBe('torrent')
+ if (next?.kind !== 'torrent') throw new Error('Expected torrent state')
+ expect(next.pieces.map((entry) => entry.provisionalBytes)).toEqual([0, 40])
+ expect(next.peers).toEqual([])
+ })
})
diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts
index e142326..2081ea4 100644
--- a/e2e/fixtures.ts
+++ b/e2e/fixtures.ts
@@ -1,25 +1,44 @@
import type {} from '../src/preload/globals'
import { execFile } from 'node:child_process'
import { existsSync } from 'node:fs'
-import { mkdir, mkdtemp, readdir, readFile, realpath, rm } from 'node:fs/promises'
+import { mkdir, mkdtemp, readdir, readFile, realpath, rm, stat } from 'node:fs/promises'
import { tmpdir } from 'node:os'
-import { join, resolve } from 'node:path'
+import { join, relative, resolve, sep } from 'node:path'
import { promisify } from 'node:util'
import {
_electron as electron,
expect,
test as base,
type ElectronApplication,
+ type Locator,
type Page
} from '@playwright/test'
import type { IpcContract } from '../src/shared/ipc-contract'
import { applyDownloadUpdate } from '../src/shared/downloadUpdate'
-import type { DownloadState, DownloadStatus, DownloadUpdate } from '../src/shared/types'
+import type {
+ DownloadState,
+ DownloadStatus,
+ DownloadUpdate,
+ HttpDownloadState,
+ TorrentDownloadState
+} from '../src/shared/types'
import { Origin, sha256, type OriginOptions } from './origin'
export { expect }
-const PROJECT_ROOT = resolve(__dirname, '..')
+export function expectHttp(state: DownloadState): HttpDownloadState {
+ expect(state.kind).toBe('http')
+ if (state.kind !== 'http') throw new Error('Expected an HTTP download')
+ return state
+}
+
+export function expectTorrent(state: DownloadState): TorrentDownloadState {
+ expect(state.kind).toBe('torrent')
+ if (state.kind !== 'torrent') throw new Error('Expected a torrent download')
+ return state
+}
+
+export const PROJECT_ROOT = resolve(__dirname, '..')
/** Small blocks so a ~1 MB test file still splits into many of them. */
export const BLOCK = 64 * 1024
@@ -54,6 +73,8 @@ interface StartOptions {
streamsPerNetwork?: number
fileName?: string
destinationDir?: string
+ /** For a torrent: the files to download, by index. */
+ selectedFiles?: number[]
}
interface Tracked {
@@ -84,13 +105,14 @@ export class PlexoApp {
private extraEnv: Record<string, string> = {}
) {}
- async launch(extraEnv: Record<string, string> = {}): Promise<this> {
+ /** `args` follow the app on its command line, as a link the OS hands over would. */
+ async launch(extraEnv: Record<string, string> = {}, args: string[] = []): Promise<this> {
Object.assign(this.extraEnv, extraEnv)
let retries = 5
while (true) {
try {
this.electronApp = await electron.launch({
- args: [PROJECT_ROOT, ...(process.platform === 'linux' ? ['--no-sandbox'] : [])],
+ args: [PROJECT_ROOT, ...args, ...(process.platform === 'linux' ? ['--no-sandbox'] : [])],
env: {
...(process.env as Record<string, string>),
PLEXO_USER_DATA: this.dirs.userData,
@@ -106,6 +128,8 @@ export class PlexoApp {
// Fixed for the same reason, and for downloads started through the UI.
PLEXO_E2E_STREAMS: '2',
PLEXO_E2E_INTERFACES: interfacesEnv(NETWORKS),
+ // Torrent tests find their peers from the link itself; a run never joins the real DHT.
+ PLEXO_E2E_DHT: '0',
...this.extraEnv
}
})
@@ -129,11 +153,16 @@ export class PlexoApp {
const updates: DownloadUpdate[] = []
this.sessions.push(session)
this.updates.push(updates)
- // Kept whole, the way the window puts them together.
+ // Kept whole, the way the window puts them together: each download from its own last state.
+ const latest = new Map<string, DownloadState>()
await this.page.exposeFunction('__plexoRecord', (update: DownloadUpdate) => {
updates.push(update)
- const state = applyDownloadUpdate(session.at(-1) ?? null, update)
- if (state && state !== session.at(-1)) session.push(state)
+ const previous = latest.get(update.state.id) ?? null
+ const state = applyDownloadUpdate(previous, update)
+ if (state && state !== previous) {
+ latest.set(state.id, state)
+ session.push(state)
+ }
})
await this.page.evaluate(() => {
const w = window as unknown as { __plexoRecord: (s: unknown) => void }
@@ -201,7 +230,7 @@ export class PlexoApp {
const destinationDir = options.destinationDir ?? this.dirs.dest
const destBefore = existsSync(destinationDir) ? await readdir(destinationDir) : []
- const id = await this.api.startDownload({
+ const common = {
url: probe.finalUrl,
destinationDir,
suggestedFileName: options.fileName ?? probe.suggestedFileName,
@@ -209,9 +238,18 @@ export class PlexoApp {
supportsRanges: multiChunk,
interfaceIds: multiChunk ? networks : networks.slice(0, 1),
etag: probe.etag,
- lastModified: probe.lastModified,
- streamsPerNetwork: options.streamsPerNetwork
- })
+ lastModified: probe.lastModified
+ }
+ const id = await this.api.startDownload(
+ probe.kind === 'torrent'
+ ? {
+ ...common,
+ kind: 'torrent',
+ infoHash: probe.torrent.infoHash,
+ selectedFiles: options.selectedFiles
+ }
+ : { ...common, kind: 'http', streamsPerNetwork: options.streamsPerNetwork }
+ )
this.tracked.set(id, { expectedSha, destBefore, destinationDir })
return id
}
@@ -228,9 +266,41 @@ export class PlexoApp {
nextDownload: Tracked | null = null
+ /** Opens New download as its button does, and gives its link field. */
+ async newDownload(): Promise<Locator> {
+ const link = this.page.getByRole('textbox', { name: 'Link' })
+ if (!(await link.isVisible())) {
+ await this.page.getByRole('button', { name: 'New download' }).first().click()
+ }
+ return link
+ }
+
+ /** Every download, running or finished, oldest first. A finished one comes from history, so it
+ * has no work units left. */
+ async all(): Promise<DownloadState[]> {
+ const running = (await this.api.listDownloads()).map((snapshot) =>
+ applyDownloadUpdate(null, snapshot)!
+ )
+ // As the window was last sent it, when this launch saw it finish: blocks and all.
+ const seen = this.sessions.at(-1) ?? []
+ const finished = (await this.api.listHistory()).map((entry): DownloadState => {
+ const last = seen.findLast((state) => state.id === entry.id)
+ if (last?.status === 'completed') return last
+ return entry.kind === 'http'
+ ? { ...entry, blocks: [], streams: [] }
+ : { ...entry, pieces: [], peers: [] }
+ })
+ return [...running, ...finished].sort((a, b) => a.startedAt - b.startedAt)
+ }
+
+ /** The download started last. */
async current(): Promise<DownloadState | null> {
- const snapshot = await this.api.getCurrentDownload()
- return snapshot && applyDownloadUpdate(null, snapshot)
+ return (await this.all()).at(-1) ?? null
+ }
+
+ /** One download by id, wherever it is. */
+ async byId(id: string): Promise<DownloadState | null> {
+ return (await this.all()).find((state) => state.id === id) ?? null
}
async waitForStatus(
@@ -241,6 +311,30 @@ export class PlexoApp {
return this.waitUntil((state) => wanted.includes(state.status), timeout)
}
+ async waitForHttpStatus(
+ status: DownloadStatus | DownloadStatus[],
+ timeout = 20_000
+ ): Promise<HttpDownloadState> {
+ return expectHttp(await this.waitForStatus(status, timeout))
+ }
+
+ async waitForTorrentStatus(
+ status: DownloadStatus | DownloadStatus[],
+ timeout = 20_000
+ ): Promise<TorrentDownloadState> {
+ return expectTorrent(await this.waitForStatus(status, timeout))
+ }
+
+ async currentHttp(): Promise<HttpDownloadState | null> {
+ const state = await this.current()
+ return state ? expectHttp(state) : null
+ }
+
+ async currentTorrent(): Promise<TorrentDownloadState | null> {
+ const state = await this.current()
+ return state ? expectTorrent(state) : null
+ }
+
/** Waits until the download state matches `predicate`. A timeout says what the state was
* instead, so a hang shows the last progress and state. */
async waitUntil(
@@ -257,11 +351,15 @@ export class PlexoApp {
const networks = state?.networks.map(
(network) => `${network.id}:${network.status}${network.error ? ` (${network.error})` : ''}`
)
- const chunks = state?.chunks.map((chunk) => `${chunk.interfaceId}:${chunk.status}`)
+ const connections = state
+ ? (state.kind === 'http' ? state.streams : state.peers).map(
+ (connection) => `${connection.interfaceId}:${connection.status}`
+ )
+ : undefined
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}, networks=[${networks?.join(', ')}], chunks=[${chunks?.join(', ')}]`
+ ? `status=${state.status}${state.error ? `, error="${state.error}"` : ''}, bytes=${state.bytesDownloaded}/${state.totalBytes}, networks=[${networks?.join(', ')}], connections=[${connections?.join(', ')}]`
: 'no current download'
}`
)
@@ -271,11 +369,13 @@ export class PlexoApp {
// --- invariants --------------------------------------------------------------------------------
const ALLOWED_NEXT: Record<DownloadStatus, DownloadStatus[]> = {
+ queued: ['queued', 'downloading', 'paused', 'cancelled'],
downloading: ['downloading', 'paused', 'completed', 'error', 'cancelled'],
- paused: ['paused', 'downloading', 'error', 'cancelled'],
+ // Resumed: at once, or into the queue when it's full.
+ paused: ['paused', 'downloading', 'queued', 'error', 'cancelled'],
completed: ['completed'],
- // Resumed.
- error: ['error', 'downloading'],
+ // Resumed, or removed by the user.
+ error: ['error', 'downloading', 'queued', 'cancelled'],
cancelled: ['cancelled']
}
@@ -290,46 +390,69 @@ export function checkEvents(sessions: DownloadState[][]): void {
state.totalBytes
)
}
+ const units = state.kind === 'http' ? state.blocks : state.pieces
expect(
- state.blocks?.every((block, index) => block?.index === index),
- `${label}: every block is there, in order`
+ units.every((unit, index) => unit.index === index),
+ `${label}: every work unit is there, in order`
).toBe(true)
- expect(state.blocks?.length, `${label}: as many blocks as planned`).toBe(state.totalBlocks)
- for (const block of state.blocks ?? []) {
- const attributed = Object.values(block.bytesByInterface).reduce((a, b) => a + b, 0)
- expect(attributed, `${label}: block ${block.index} attribution sums to its bytes`).toBe(
- block.bytesDownloaded
+ expect(units.length, `${label}: as many work units as planned`).toBe(
+ state.kind === 'http' ? state.totalBlocks : state.totalPieces
+ )
+ for (const unit of units) {
+ const attributed = Object.values(unit.bytesByInterface).reduce((a, b) => a + b, 0)
+ expect(attributed, `${label}: unit ${unit.index} attribution sums to its bytes`).toBe(
+ unit.bytesDownloaded
)
- if (block.rangeEnd !== null) {
- const size = block.rangeEnd - block.rangeStart + 1
+ if (unit.rangeEnd !== null) {
+ const size = unit.rangeEnd - unit.rangeStart + 1
expect(
- block.bytesDownloaded,
- `${label}: block ${block.index} within its size`
+ unit.bytesDownloaded,
+ `${label}: unit ${unit.index} within its size`
).toBeLessThanOrEqual(size)
- if (block.status === 'completed') {
- expect(block.bytesDownloaded, `${label}: completed block ${block.index} is full`).toBe(
+ if (unit.status === 'completed') {
+ expect(unit.bytesDownloaded, `${label}: completed unit ${unit.index} is full`).toBe(
size
)
}
}
+ if (unit.kind === 'torrent') {
+ expect(unit.provisionalBytes).toBeGreaterThanOrEqual(0)
+ expect(unit.provisionalBytes).toBeLessThanOrEqual(
+ unit.rangeEnd === null ? 0 : unit.rangeEnd - unit.rangeStart + 1
+ )
+ }
}
- if (state.status === 'downloading') {
+ if (state.kind === 'torrent') {
+ // Peers are connections, not piece owners. Each belongs to one known network and exposes
+ // only transfer telemetry; verified progress belongs to pieces above.
+ for (const peer of state.peers) {
+ expect(
+ state.networks.map((network) => network.id),
+ `${label}: peer ${peer.id} is on a network of this download`
+ ).toContain(peer.interfaceId)
+ expect(['connected', 'receiving']).toContain(peer.status)
+ }
+ const uploaded = state.networks.reduce((sum, network) => sum + network.bytesUploaded, 0)
+ expect(uploaded, `${label}: the networks' uploads add up to the download's`).toBe(
+ state.bytesUploaded
+ )
+ } else if (state.status === 'downloading') {
// A stream holds a block exactly while it is fetching it. A block has at most one stream
// fetching it for real and two racing it as hedges, and is in flight whenever the first
// is there. What the stream rows show is only as true as this.
const primaries = new Map<number, number>()
const hedges = new Map<number, number>()
- for (const chunk of state.chunks) {
- const holding = chunk.currentBlockIndex !== undefined
- expect(holding, `${label}: stream ${chunk.id} (${chunk.status}) holds a block`).toBe(
- chunk.status === 'downloading'
+ for (const stream of state.streams) {
+ const holding = stream.currentBlockIndex !== undefined
+ expect(holding, `${label}: stream ${stream.id} (${stream.status}) holds a block`).toBe(
+ stream.status === 'downloading'
)
- if (chunk.currentBlockIndex === undefined) {
- expect(chunk.hedge, `${label}: idle stream ${chunk.id} is not racing`).toBeFalsy()
+ if (stream.currentBlockIndex === undefined) {
+ expect(stream.hedge, `${label}: idle stream ${stream.id} is not racing`).toBeFalsy()
continue
}
- const tally = chunk.hedge ? hedges : primaries
- tally.set(chunk.currentBlockIndex, (tally.get(chunk.currentBlockIndex) ?? 0) + 1)
+ const tally = stream.hedge ? hedges : primaries
+ tally.set(stream.currentBlockIndex, (tally.get(stream.currentBlockIndex) ?? 0) + 1)
}
for (const [index, count] of primaries) {
expect(count, `${label}: block ${index} has one stream fetching it`).toBe(1)
@@ -338,7 +461,7 @@ export function checkEvents(sessions: DownloadState[][]): void {
expect(count, `${label}: block ${index} has at most two hedges`).toBeLessThanOrEqual(2)
}
for (const index of primaries.keys()) {
- expect(state.blocks?.[index]?.status, `${label}: held block ${index} is in flight`).toBe(
+ expect(state.blocks[index]?.status, `${label}: held block ${index} is in flight`).toBe(
'downloading'
)
}
@@ -354,6 +477,31 @@ export function checkEvents(sessions: DownloadState[][]): void {
}
}
+/** A folder's files as one hash: each file's path (relative, with `/`) and the SHA-256 of its
+ * bytes, in path order. What a multi-file torrent's download is checked against. */
+export function treeSha(files: { path: string; data: Buffer }[]): string {
+ const lines = files
+ .map((file) => `${file.path}\0${sha256(file.data)}\n`)
+ .sort()
+ .join('')
+ return sha256(Buffer.from(lines))
+}
+
+/** sha256 of a file, or treeSha of a folder. */
+export async function shaOfPath(path: string): Promise<string> {
+ if (!(await stat(path)).isDirectory()) return sha256(await readFile(path))
+ const entries = await readdir(path, { recursive: true, withFileTypes: true })
+ const files = await Promise.all(
+ entries
+ .filter((entry) => entry.isFile())
+ .map(async (entry) => {
+ const full = join(entry.parentPath, entry.name)
+ return { path: relative(path, full).split(sep).join('/'), data: await readFile(full) }
+ })
+ )
+ return treeSha(files)
+}
+
async function openFilesUnder(pid: number, roots: string[]): Promise<string[]> {
try {
const { stdout } = await promisify(execFile)('lsof', ['-Fn', '-p', String(pid)])
@@ -372,36 +520,51 @@ async function openFilesUnder(pid: number, roots: string[]): Promise<string[]> {
* exactly right. The one that matters most: `completed` never means wrong bytes.
*/
export async function checkFinalState(app: PlexoApp): Promise<void> {
- const state = await app.current()
- if (!state) return
- const tracked = app.tracked.get(state.id) ?? app.nextDownload
- const 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)
- expect(sha256(bytes), 'completed file matches the source byte for byte').toBe(
- tracked.expectedSha
- )
- } else {
- expect(existsSync(state.destinationPath), 'no file left at the destination').toBe(false)
- }
+ const states = await app.all()
+ const latest = states.at(-1)
+ const checked = states.flatMap((state) => {
+ const tracked = app.tracked.get(state.id) ?? (state === latest ? app.nextDownload : null)
+ return tracked ? [{ state, tracked }] : []
+ })
+ // Any still under way: there's no final state to check yet.
+ const terminal = (status: DownloadStatus): boolean =>
+ ['completed', 'error', 'cancelled'].includes(status)
+ if (checked.length === 0 || !checked.every(({ state }) => terminal(state.status))) return
+
+ for (const { state, tracked } of checked) {
+ // 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') {
+ expect(await shaOfPath(state.destinationPath), 'completed download matches its source').toBe(
+ tracked.expectedSha
+ )
+ } else {
+ expect(existsSync(state.destinationPath), 'no file left at the destination').toBe(false)
+ }
- const destAfter = existsSync(tracked.destinationDir) ? await readdir(tracked.destinationDir) : []
- const added = destAfter.filter((name) => !tracked.destBefore.includes(name))
- const expectedAdded =
- state.status === 'completed' ? [state.destinationPath.split(/[\\/]/).pop()] : []
- expect(added, 'no stray files (placeholders, partials) in the destination folder').toEqual(
- expectedAdded
- )
+ const stagingPath = `${state.destinationPath}.plexo`
+ await expect
+ .poll(() => existsSync(stagingPath), { message: 'staging file cleaned up', timeout: 5000 })
+ .toBe(false)
+ }
- const stagingPath = `${state.destinationPath}.plexo`
- await expect
- .poll(() => existsSync(stagingPath), { message: 'staging file cleaned up', timeout: 5000 })
- .toBe(false)
+ // Each folder gains exactly the downloads that completed into it, and nothing else.
+ for (const destinationDir of new Set(checked.map(({ tracked }) => tracked.destinationDir))) {
+ const into = checked.filter(({ tracked }) => tracked.destinationDir === destinationDir)
+ // As the folder was before the first of them started (later ones saw the earlier ones' files).
+ const before = new Set(into[0].tracked.destBefore)
+ const destAfter = existsSync(destinationDir) ? await readdir(destinationDir) : []
+ const added = destAfter.filter((name) => !before.has(name)).sort()
+ const expectedAdded = into
+ .filter(({ state }) => state.status === 'completed')
+ .map(({ state }) => state.destinationPath.split(/[\\/]/).pop())
+ .sort()
+ expect(added, 'no stray files (placeholders, partials) in the destination folder').toEqual(
+ expectedAdded
+ )
+ }
const pid = app.electronApp.process().pid
if (pid) {
diff --git a/e2e/hedge.spec.ts b/e2e/hedge.spec.ts
index 81652e2..6849b61 100644
--- a/e2e/hedge.spec.ts
+++ b/e2e/hedge.spec.ts
@@ -36,7 +36,7 @@ test.describe('racing a slow block', () => {
const started = Date.now()
await plexo.start(origin.url(), origin.sha256, { connections: 4 })
- await plexo.waitForStatus('completed', 10_000)
+ await plexo.waitForHttpStatus('completed', 10_000)
expect(Date.now() - started).toBeLessThan(10_000)
const requests = origin.chunkRequests().filter((r) => inSlowBlock(r.range))
@@ -56,7 +56,7 @@ test.describe('racing a slow block', () => {
)
await plexo.start(origin.url(), origin.sha256, { connections: 4 })
- await plexo.waitForStatus('completed', 10_000)
+ await plexo.waitForHttpStatus('completed', 10_000)
const requests = origin.chunkRequests().filter((r) => inSlowBlock(r.range))
expect(requests.length).toBeGreaterThanOrEqual(2)
@@ -84,11 +84,11 @@ test.describe('racing a slow block', () => {
.toBeGreaterThanOrEqual(2)
await plexo.api.pauseDownload(id)
- const paused = await plexo.waitForStatus('paused')
- expect(paused.chunks.some((chunk) => chunk.hedge)).toBe(false)
+ const paused = await plexo.waitForHttpStatus('paused')
+ expect(paused.streams.some((chunk) => chunk.hedge)).toBe(false)
await plexo.api.resumeDownload(id)
- await plexo.waitForStatus('completed', 15_000)
+ await plexo.waitForHttpStatus('completed', 15_000)
})
test('a second network rescues a block the first is crawling through, and is credited for it', async ({
@@ -106,7 +106,7 @@ test.describe('racing a slow block', () => {
})
await plexo.start(origin.url(), origin.sha256, { networks: ['a', 'b'], connections: 1 })
- const state = await plexo.waitForStatus('completed', 10_000)
+ const state = await plexo.waitForHttpStatus('completed', 10_000)
const shared = (state.blocks ?? []).filter(
(block) => (block.bytesByInterface['a'] ?? 0) > 0 && (block.bytesByInterface['b'] ?? 0) > 0
diff --git a/e2e/lifecycle.spec.ts b/e2e/lifecycle.spec.ts
index e326d49..a317783 100644
--- a/e2e/lifecycle.spec.ts
+++ b/e2e/lifecycle.spec.ts
@@ -22,12 +22,12 @@ test.describe('pause and resume @smoke', () => {
await reached
await plexo.api.pauseDownload(id)
- const paused = await plexo.waitForStatus('paused')
+ const paused = await plexo.waitForHttpStatus('paused')
expect(paused.speedBytesPerSec).toBe(0)
origin.release()
await plexo.api.resumeDownload(id)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
}
@@ -41,7 +41,7 @@ test.describe('pause and resume @smoke', () => {
await plexo.api.resumeDownload(id)
}
origin.release()
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
test('resuming while a paused stream is still winding down waits for it, not runs beside it', async ({
@@ -74,12 +74,12 @@ test.describe('pause and resume @smoke', () => {
const id = await plexo.start(origin.url(), origin.sha256)
await expect.poll(() => stalled, { message: 'the sample request hung' }).toBe(true)
const pausing = plexo.api.pauseDownload(id)
- await plexo.waitForStatus('paused')
+ await plexo.waitForHttpStatus('paused')
await plexo.api.resumeDownload(id)
await pausing
// Two runs side by side would each try to finish the download, and the one left behind would
// call it failed.
- await plexo.waitForStatus('completed', 30_000)
+ await plexo.waitForHttpStatus('completed', 30_000)
})
})
@@ -93,16 +93,19 @@ test.describe('pause during a retry backoff', () => {
failing && range && range.start === 4 * BLOCK ? { status: 500 } : 'ok'
)
const id = await plexo.start(origin.url(), origin.sha256, { connections: 2 })
- await plexo.waitUntil((state) => state.chunks.some((chunk) => chunk.status === 'retrying'))
+ await plexo.waitUntil(
+ (state) =>
+ state.kind === 'http' && state.streams.some((stream) => stream.status === 'retrying')
+ )
const before = Date.now()
await plexo.api.pauseDownload(id)
- await plexo.waitForStatus('paused', 2000)
+ await plexo.waitForHttpStatus('paused', 2000)
expect(Date.now() - before).toBeLessThan(2000)
failing = false
await plexo.api.resumeDownload(id)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
})
@@ -115,13 +118,13 @@ test.describe('resume safety checks @smoke', () => {
): Promise<{
id: string
resumedAt: number
- paused: import('../src/shared/types').DownloadState
+ paused: import('../src/shared/types').HttpDownloadState
}> {
const reached = origin.hold(5 * BLOCK)
const id = await plexo.start(origin.url(), origin.sha256)
await reached
await plexo.api.pauseDownload(id)
- const paused = await plexo.waitForStatus('paused')
+ const paused = await plexo.waitForHttpStatus('paused')
change()
origin.release()
const resumedAt = origin.log.length
@@ -135,7 +138,7 @@ test.describe('resume safety checks @smoke', () => {
}) => {
const origin = await serve({ size: SIZE })
await pauseThenChange(plexo, origin, () => origin.setContent(seededBytes(SIZE, 9), '"v2"'))
- const state = await plexo.waitForStatus('error')
+ const state = await plexo.waitForHttpStatus('error')
expect(state.error).toMatch(/changed/)
})
@@ -147,11 +150,11 @@ test.describe('resume safety checks @smoke', () => {
const { resumedAt, paused } = await pauseThenChange(plexo, origin, () =>
origin.setContent(origin.content, '"migrated"')
)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
// Kept, not restarted: after resuming, no block that was already complete was fetched again
// — only the small samples that confirmed the bytes match.
- const done = (paused.blocks ?? []).filter((block) => block.status === 'completed')
+ const done = paused.blocks.filter((block) => block.status === 'completed')
const afterResume = origin.log.slice(resumedAt)
const refetchedDone = afterResume.filter((entry) =>
done.some((block) => entry.range?.start === block.rangeStart && entry.bytesSent > 16 * 1024)
@@ -169,10 +172,10 @@ test.describe('resume safety checks @smoke', () => {
const id = await plexo.start(origin.url(), origin.sha256)
await reached
await plexo.api.pauseDownload(id)
- await plexo.waitForStatus('paused')
+ await plexo.waitForHttpStatus('paused')
origin.release()
await plexo.api.resumeDownload(id)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
test('resume against a server without range support', async ({ plexo, serve }) => {
@@ -181,10 +184,10 @@ test.describe('resume safety checks @smoke', () => {
const id = await plexo.start(origin.url(), origin.sha256)
await reached
await plexo.api.pauseDownload(id)
- await plexo.waitForStatus('paused')
+ await plexo.waitForHttpStatus('paused')
origin.release()
await plexo.api.resumeDownload(id)
- await plexo.waitForStatus('completed', 10_000)
+ await plexo.waitForHttpStatus('completed', 10_000)
})
})
@@ -195,22 +198,22 @@ test.describe('cancel and remove @smoke', () => {
const id = await plexo.start(origin.url(), origin.sha256)
await reached
await plexo.api.pauseDownload(id)
- const paused = await plexo.waitForStatus('paused')
+ const paused = await plexo.waitForHttpStatus('paused')
const staging = `${paused.destinationPath}.plexo`
expect(existsSync(staging), 'pausing keeps the staging file').toBe(true)
origin.release()
await plexo.api.cancelDownload(id)
- await plexo.waitForStatus('cancelled')
+ await plexo.waitForHttpStatus('cancelled')
await expect.poll(() => existsSync(staging), { message: 'cancelling removes it' }).toBe(false)
})
test('remove after completion keeps the file', async ({ plexo, serve, dirs }) => {
const origin = await serve({ size: SIZE })
const id = await plexo.start(origin.url(), origin.sha256)
- const state = await plexo.waitForStatus('completed')
+ const state = await plexo.waitForHttpStatus('completed')
await plexo.api.removeDownload(id)
- expect(await plexo.current()).toBeNull()
+ expect(await plexo.currentHttp()).toBeNull()
expect(sha256(await readFile(state.destinationPath))).toBe(origin.sha256)
await expect.poll(() => existsSync(join(dirs.userData, 'downloads', id))).toBe(false)
})
@@ -220,11 +223,11 @@ test.describe('cancel and remove @smoke', () => {
const reached = origin.hold(7 * BLOCK)
const id = await plexo.start(origin.url(), origin.sha256)
await reached
- const { destinationPath } = (await plexo.current())!
+ const { destinationPath } = (await plexo.currentHttp())!
await plexo.api.removeDownload(id)
origin.release()
- expect(await plexo.current()).toBeNull()
+ expect(await plexo.currentHttp()).toBeNull()
await expect.poll(() => existsSync(destinationPath)).toBe(false)
await expect.poll(() => existsSync(join(dirs.userData, 'downloads', id))).toBe(false)
})
diff --git a/e2e/limits.spec.ts b/e2e/limits.spec.ts
new file mode 100644
index 0000000..81472f3
--- /dev/null
+++ b/e2e/limits.spec.ts
@@ -0,0 +1,196 @@
+import { writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { dataPeriodKey, nextDataReset } from '../src/shared/dataLimits'
+import { BLOCK, expect, test } from './fixtures'
+import { seededBytes, sha256 } from './origin'
+import { named, Swarm, torrentFileOnDisk } from './torrentSwarm'
+
+// Speed & data limits (main/network/limits.ts): every byte received goes through them, whether
+// an HTTP response's or a torrent peer's. The checks fixture verifies each finished download's
+// bytes, which is what matters most here: holding a connection back must never garble it.
+
+const KB = 1024
+
+test.describe('speed and data limits', () => {
+ test('a total speed limit holds a download to it', async ({ plexo, serve }) => {
+ const origin = await serve({ size: 16 * BLOCK })
+ await plexo.api.updateSettings({ speedLimit: 256 * KB })
+ const started = Date.now()
+ await plexo.start(origin.url(), origin.sha256)
+ await plexo.waitForHttpStatus('completed', 30_000)
+ // 1 MB at 256 KB/s: four seconds, less the second's worth a bucket may hold.
+ expect(Date.now() - started).toBeGreaterThan(2500)
+ })
+
+ test('slow mode holds downloads to its speed, the default one included', async ({
+ plexo,
+ serve
+ }) => {
+ const origin = await serve({ size: 96 * BLOCK })
+ // Switched on as the status bar does, its speed never changed: 2 MB/s.
+ await plexo.api.updateSettings({ slowMode: true })
+ const started = Date.now()
+ await plexo.start(origin.url(), origin.sha256)
+ await plexo.waitForHttpStatus('completed', 30_000)
+ // 6 MB at 2 MB/s: three seconds, less the second's worth a bucket may hold.
+ expect(Date.now() - started).toBeGreaterThan(1800)
+ })
+
+ for (const period of ['day', 'week', 'month'] as const) {
+ test(`a network stops at its ${period} limit and resumes when it is raised`, async ({
+ plexo,
+ serve
+ }) => {
+ const origin = await serve({ size: 16 * BLOCK })
+ await plexo.api.updateSettings({
+ networkPreferences: { a: { dataLimit: 4 * BLOCK, dataLimitPeriod: period } }
+ })
+ const id = await plexo.start(origin.url(), origin.sha256)
+
+ const stopped = await plexo.waitUntil((state) =>
+ state.networks.some((network) => network.id === 'a' && network.status === 'limit')
+ )
+ expect(stopped.status).toBe('downloading')
+ expect(stopped.bytesDownloaded).toBeLessThan(16 * BLOCK)
+ expect((await plexo.api.networkUsage()).a).toBeGreaterThanOrEqual(4 * BLOCK)
+
+ await plexo.api.updateSettings({
+ networkPreferences: { a: { dataLimit: 1024 * BLOCK, dataLimitPeriod: period } }
+ })
+ await plexo.waitForHttpStatus('completed')
+ expect((await plexo.byId(id))?.status).toBe('completed')
+ })
+ }
+
+ test('a torrent under a speed limit still arrives whole', async ({ plexo }) => {
+ const swarm = await new Swarm().start()
+ try {
+ const data = seededBytes(1024 * KB, 31)
+ const torrent = await swarm.seed([named(data, 'limited.bin')], { pieceLength: 64 * KB })
+ await plexo.api.updateSettings({ speedLimit: 384 * KB })
+ const started = Date.now()
+ await plexo.start(await torrentFileOnDisk(torrent), sha256(data))
+ await plexo.waitForTorrentStatus('completed', 30_000)
+ expect(Date.now() - started).toBeGreaterThan(1500)
+ } finally {
+ await swarm.stop()
+ }
+ })
+})
+
+test('usage survives period switches and restart, and expired calendar periods reset', async ({
+ plexo,
+ dirs
+}) => {
+ await plexo.quit()
+ const now = Date.now()
+ await writeFile(
+ join(dirs.userData, 'network-usage.json'),
+ JSON.stringify({
+ version: 2,
+ periods: Object.fromEntries(
+ ['day', 'week', 'month'].map((period, index) => [
+ period,
+ {
+ key: dataPeriodKey(period as 'day' | 'week' | 'month', now),
+ bytes: { a: (index + 1) * 1024 }
+ }
+ ])
+ )
+ })
+ )
+ await plexo.launch()
+ for (const [period, count] of [
+ ['day', 1024],
+ ['week', 2048],
+ ['month', 3072]
+ ] as const) {
+ await plexo.api.updateSettings({
+ networkPreferences: { a: { dataLimit: 1024 ** 3, dataLimitPeriod: period } }
+ })
+ expect((await plexo.api.networkUsage()).a).toBe(count)
+ }
+ await plexo.quit()
+ await plexo.launch()
+ expect((await plexo.api.networkUsage()).a).toBe(3072)
+ const future = nextDataReset('month', now).getTime() + 8 * 86400_000
+ await plexo.evaluateMain((_electron, at) => {
+ const original = Date.now
+ ;(globalThis as Record<string, unknown>).__originalDateNow = original
+ Date.now = () => at
+ }, future)
+ try {
+ for (const period of ['day', 'week', 'month'] as const) {
+ await plexo.api.updateSettings({
+ networkPreferences: { a: { dataLimit: 1024 ** 3, dataLimitPeriod: period } }
+ })
+ expect((await plexo.api.networkUsage()).a ?? 0).toBe(0)
+ }
+ } finally {
+ await plexo.evaluateMain(() => {
+ Date.now = (globalThis as Record<string, unknown>).__originalDateNow as () => number
+ delete (globalThis as Record<string, unknown>).__originalDateNow
+ }, null)
+ }
+})
+
+test('existing monthly usage remains available after migration', async ({ plexo, dirs }) => {
+ await plexo.quit()
+ await writeFile(
+ join(dirs.userData, 'network-usage.json'),
+ JSON.stringify({
+ month: dataPeriodKey('month', Date.now()),
+ bytes: { a: 12345 }
+ })
+ )
+ await plexo.launch()
+ expect((await plexo.api.networkUsage()).a).toBe(12345)
+ await plexo.api.updateSettings({ networkPreferences: { a: { dataLimitPeriod: 'day' } } })
+ expect((await plexo.api.networkUsage()).a).toBe(0)
+ await plexo.api.updateSettings({ networkPreferences: { a: { dataLimitPeriod: 'month' } } })
+ expect((await plexo.api.networkUsage()).a).toBe(12345)
+})
+
+test('calendar periods use local midnight, Monday weeks, and correct year boundaries', () => {
+ const sunday = new Date(2026, 9, 4, 23, 59, 59, 999).getTime()
+ const monday = new Date(2026, 9, 5).getTime()
+ expect(dataPeriodKey('week', sunday)).toBe('2026-09-28')
+ expect(dataPeriodKey('week', monday)).toBe('2026-10-05')
+ expect(nextDataReset('day', sunday).getTime()).toBe(monday)
+ expect(nextDataReset('week', sunday).getTime()).toBe(monday)
+ expect(nextDataReset('week', monday).getTime()).toBe(new Date(2026, 9, 12).getTime())
+ expect(nextDataReset('month', new Date(2026, 11, 31, 23).getTime()).getTime()).toBe(
+ new Date(2027, 0, 1).getTime()
+ )
+ expect(dataPeriodKey('month', new Date(2027, 0, 1).getTime())).toBe('2027-01')
+})
+
+for (const period of ['day', 'week', 'month'] as const) {
+ test(`resetting ${period} usage preserves other periods and networks and survives restart`, async ({
+ plexo,
+ serve
+ }) => {
+ const origin = await serve({ size: BLOCK })
+ await plexo.start(origin.url(), origin.sha256)
+ await plexo.waitForStatus('completed')
+ const before = await plexo.api.networkUsage()
+ const id = Object.keys(before).find((key) => before[key] > 0)!
+ expect(id).toBeTruthy()
+ await plexo.api.updateSettings({ networkPreferences: { [id]: { dataLimitPeriod: period } } })
+ await plexo.api.resetNetworkUsage(id)
+ expect((await plexo.api.networkUsage())[id]).toBe(0)
+ for (const [other, bytes] of Object.entries(before)) {
+ if (other !== id) expect((await plexo.api.networkUsage())[other]).toBe(bytes)
+ }
+ for (const otherPeriod of ['day', 'week', 'month'] as const) {
+ if (otherPeriod === period) continue
+ await plexo.api.updateSettings({
+ networkPreferences: { [id]: { dataLimitPeriod: otherPeriod } }
+ })
+ expect((await plexo.api.networkUsage())[id]).toBe(before[id])
+ }
+ await plexo.api.updateSettings({ networkPreferences: { [id]: { dataLimitPeriod: period } } })
+ await plexo.relaunch()
+ expect((await plexo.api.networkUsage())[id]).toBe(0)
+ })
+}
diff --git a/e2e/liveNetworks.spec.ts b/e2e/liveNetworks.spec.ts
index 7fee177..b0424d4 100644
--- a/e2e/liveNetworks.spec.ts
+++ b/e2e/liveNetworks.spec.ts
@@ -22,7 +22,7 @@ const overB = (request: Pick<LoggedRequest, 'from'>): boolean => request.from !=
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
+ state.kind === 'http' ? state.streams.filter((stream) => stream.interfaceId === id).length : 0
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 ({
@@ -35,17 +35,17 @@ test('the only network drops for a while: the download waits, then picks up wher
await setNetworks(plexo, {})
await plexo.waitUntil((state) => network(state, 'a')?.status === 'offline')
- const gone = (await plexo.current())!
+ const gone = (await plexo.currentHttp())!
// 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())!
+ const waited = (await plexo.currentHttp())!
expect(waited.status).toBe('downloading')
- expect(waited.chunks).toHaveLength(0)
+ expect(waited.streams).toHaveLength(0)
expect(waited.bytesDownloaded, 'nothing it had was lost').toBe(gone.bytesDownloaded)
await setNetworks(plexo, { a: NETWORKS['a'] })
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
test.describe('two networks @smoke', () => {
@@ -64,7 +64,7 @@ test.describe('two networks @smoke', () => {
const goneAt = origin.log.length
await setNetworks(plexo, NETWORKS)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
expect(origin.log.slice(goneAt).some(overB), 'b carried more once it was back').toBe(true)
})
@@ -76,7 +76,7 @@ test.describe('two networks @smoke', () => {
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()
+ expect(network((await plexo.currentHttp())!, 'b')).toBeUndefined()
await setNetworks(plexo, NETWORKS)
const listed = await plexo.waitUntil((state) => network(state, 'b') !== undefined)
@@ -135,13 +135,13 @@ test.describe('two networks @smoke', () => {
await plexo.api.setDownloadNetwork(id, 'a', true)
await plexo.api.setDownloadNetwork(id, 'a', false)
await settle(1000)
- const left = (await plexo.current())!
+ const left = (await plexo.currentHttp())!
expect(left.status).toBe('paused')
expect(network(left, 'a')?.enabled).toBe(false)
// …and switching it on once more still resumes it.
await plexo.api.setDownloadNetwork(id, 'a', true)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
test('resumed with none on, it picks a network that is still there', async ({ plexo, serve }) => {
@@ -162,7 +162,7 @@ test.describe('two networks @smoke', () => {
const resumed = await plexo.waitUntil((state) => state.status === 'downloading')
expect(network(resumed, 'a')?.enabled).toBe(true)
expect(network(resumed, 'b')?.enabled).toBe(false)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
})
@@ -192,8 +192,8 @@ test.describe('a network that can’t reach the server @smoke', () => {
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)
+ await plexo.waitForHttpStatus('completed')
+ expect(network((await plexo.currentHttp())!, 'b')!.bytesDownloaded).toBeGreaterThan(0)
})
})
@@ -212,8 +212,10 @@ test.describe('a network that changes address', () => {
overB(request) && request.range && request.range.end !== 0 ? { cutAfter: 0 } : 'ok'
)
await plexo.start(origin.url(), origin.sha256, { networks: ['a', 'b'], connections: 2 })
- await plexo.waitUntil((state) =>
- state.chunks.some((chunk) => chunk.interfaceId === 'b' && chunk.status === 'retrying')
+ await plexo.waitUntil(
+ (state) =>
+ state.kind === 'http' &&
+ state.streams.some((stream) => stream.interfaceId === 'b' && stream.status === 'retrying')
)
// A new DHCP lease, say: b is now reached at another address, which gets through.
@@ -240,12 +242,12 @@ test.describe('the computer wakes from sleep', () => {
)
await plexo.start(origin.url(), origin.sha256, { connections: 2 })
await plexo.waitUntil((state) => state.bytesDownloaded >= 15 * BLOCK)
- expect((await plexo.current())!.status).toBe('downloading')
+ expect((await plexo.currentHttp())!.status).toBe('downloading')
await plexo.evaluateMain((electron) => {
electron.powerMonitor.emit('resume')
}, null)
- await plexo.waitForStatus('completed', 5000)
+ await plexo.waitForHttpStatus('completed', 5000)
expect(stalled, 'the block was asked for again').toBeGreaterThan(1)
})
})
diff --git a/e2e/openLinks.spec.ts b/e2e/openLinks.spec.ts
new file mode 100644
index 0000000..cbd9dfb
--- /dev/null
+++ b/e2e/openLinks.spec.ts
@@ -0,0 +1,73 @@
+import type { Locator } from '@playwright/test'
+import { spawn } from 'node:child_process'
+import { createRequire } from 'node:module'
+import { expect, PROJECT_ROOT, test, type PlexoApp } from './fixtures'
+import { seededBytes } from './origin'
+import { named, Swarm, torrentFileOnDisk } from './torrentSwarm'
+
+// Links the OS hands Plexo — a magnet link clicked in a browser, a .torrent opened from the file
+// manager — open New download with it filled in, for the user to look at and start; nothing starts
+// on its own.
+
+const MAGNET = `magnet:?xt=urn:btih:${'cd'.repeat(20)}&dn=handed.over`
+
+/** A .torrent of one small file, on disk. */
+async function aTorrentFile(): Promise<string> {
+ const swarm = await new Swarm().start()
+ try {
+ return await torrentFileOnDisk(await swarm.seed([named(seededBytes(1000, 91), 'clip.mov')]))
+ } finally {
+ await swarm.stop()
+ }
+}
+
+const linkField = (plexo: PlexoApp): Locator => plexo.page.getByRole('textbox', { name: 'Link' })
+
+test.describe('links handed over by the OS', () => {
+ test('a .torrent on the command line (Windows, Linux) fills in the link', async ({ plexo }) => {
+ const path = await aTorrentFile()
+ await plexo.quit()
+ await plexo.launch({}, [path])
+
+ await expect(linkField(plexo)).toHaveValue(path)
+ await expect(plexo.page.getByRole('group', { name: 'Files' })).toBeVisible({ timeout: 15_000 })
+ // Shown, not started.
+ expect(await plexo.current()).toBeNull()
+ })
+
+ test('a second launch hands its magnet link to the first window, and exits', async ({
+ plexo
+ }) => {
+ const electronBinary = createRequire(__filename)('electron') as string
+ const second = spawn(electronBinary, [PROJECT_ROOT, MAGNET], {
+ env: { ...process.env, PLEXO_USER_DATA: plexo.dirs.userData, PLEXO_E2E_HIDE_WINDOW: '1' },
+ stdio: 'ignore'
+ })
+ const exitCode = await new Promise<number | null>((resolve) => second.once('exit', resolve))
+
+ expect(exitCode).toBe(0)
+ await expect(linkField(plexo)).toHaveValue(MAGNET)
+ })
+
+ test('macOS’s open-url and open-file fill in the link; anything else is ignored', async ({
+ plexo
+ }) => {
+ const emit = (event: 'open-url' | 'open-file', link: string): Promise<unknown> =>
+ plexo.evaluateMain(
+ ({ app }, [name, value]) => app.emit(name, { preventDefault: () => undefined }, value),
+ [event, link] as const
+ )
+
+ await emit('open-url', 'https://example.com/not-a-torrent')
+ await emit('open-file', '/no/such/file.torrent')
+ // Neither is taken: New download doesn't open for them.
+ await expect(linkField(plexo)).toBeHidden()
+
+ await emit('open-url', MAGNET)
+ await expect(linkField(plexo)).toHaveValue(MAGNET)
+
+ const path = await aTorrentFile()
+ await emit('open-file', path)
+ await expect(linkField(plexo)).toHaveValue(path)
+ })
+})
diff --git a/e2e/plan.spec.ts b/e2e/plan.spec.ts
index c22dbb6..047f017 100644
--- a/e2e/plan.spec.ts
+++ b/e2e/plan.spec.ts
@@ -60,14 +60,8 @@ test.describe('download plan', () => {
expect(startingStreams(plan.blockCount, 2, 8)).toBe(1)
})
- test('a large file keeps 8 MB blocks', () => {
- const plan = planDownload({ totalBytes: 4 * 1024 * MIB, splittable: true, networkCount: 2 })
- expect(plan.blockSizeBytes).toBe(DEFAULT_MAX_BLOCK_BYTES)
- })
-
- test('each network starts with eight streams, with blocks enough to grow to its limit', () => {
+ test('a big file has blocks enough for every network to grow to its limit', () => {
const plan = planDownload({ totalBytes: 512 * MIB, splittable: true, networkCount: 2 })
- expect(startingStreams(plan.blockCount, 2)).toBe(8)
// 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)
})
diff --git a/e2e/recovery.spec.ts b/e2e/recovery.spec.ts
index 8d63f37..7326231 100644
--- a/e2e/recovery.spec.ts
+++ b/e2e/recovery.spec.ts
@@ -1,7 +1,8 @@
-import { cp, readFile, rm, truncate, writeFile } from 'node:fs/promises'
+import { cp, mkdir, readFile, rm, truncate, writeFile } from 'node:fs/promises'
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import { BLOCK, expect, test } from './fixtures'
+import { seededBytes } from './origin'
// D. Quitting, crashing and restarting. kill() is SIGKILL: no before-quit, no final save —
// what's on disk is whatever the app had managed to persist, exactly as after a crash or a
@@ -20,13 +21,13 @@ test.describe('restart @smoke', () => {
origin.release()
await plexo.launch()
- const restored = await plexo.current()
+ const restored = await plexo.currentHttp()
expect(restored?.id).toBe(id)
expect(restored?.status).toBe('paused')
expect(restored?.bytesDownloaded).toBeGreaterThan(0)
await plexo.api.resumeDownload(id)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
})
@@ -46,12 +47,12 @@ test.describe('crash (SIGKILL) and recover @smoke', () => {
origin.release()
await plexo.launch()
- const restored = await plexo.current()
+ const restored = await plexo.currentHttp()
expect(restored?.id).toBe(id)
expect(restored?.status).toBe('paused')
await plexo.api.resumeDownload(id)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
}
})
@@ -67,7 +68,7 @@ test.describe('persisted state on disk @smoke', () => {
const id = await plexo.start(origin.url(), origin.sha256)
await reached
await plexo.api.pauseDownload(id)
- await plexo.waitForStatus('paused')
+ await plexo.waitForHttpStatus('paused')
origin.release()
return { id, origin }
}
@@ -77,15 +78,17 @@ test.describe('persisted state on disk @smoke', () => {
await plexo.quit()
await writeFile(join(dirs.userData, 'downloads', id, 'manifest.json'), 'not json {')
await plexo.launch()
- expect(await plexo.current()).toBeNull()
+ expect(await plexo.currentHttp()).toBeNull()
+ // Nothing can bring it back: its folder is cleared rather than kept forever.
+ await expect.poll(() => existsSync(join(dirs.userData, 'downloads', id))).toBe(false)
// And a new download still works.
const origin = await serve({ size: 4 * BLOCK, seed: 99 })
await plexo.start(origin.url(), origin.sha256)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
- test('two saved downloads: only the newest is restored, the other is removed', async ({
+ test('two saved downloads of one partial file: only the newest is restored', async ({
plexo,
serve,
dirs
@@ -104,11 +107,11 @@ test.describe('persisted state on disk @smoke', () => {
await writeFile(manifestPath, JSON.stringify(manifest))
await plexo.launch()
- expect((await plexo.current())?.id).toBe(id)
+ expect((await plexo.currentHttp())?.id).toBe(id)
await expect.poll(() => existsSync(join(root, olderId))).toBe(false)
await plexo.api.resumeDownload(id)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
test('staging file deleted while the app was closed → reports lost progress', async ({
@@ -116,46 +119,71 @@ test.describe('persisted state on disk @smoke', () => {
serve
}) => {
await pausedDownload(plexo, serve)
- const partial = `${(await plexo.current())!.destinationPath}.plexo`
+ const partial = `${(await plexo.currentHttp())!.destinationPath}.plexo`
await plexo.quit()
await rm(partial)
await plexo.launch()
- expect((await plexo.current())?.status).toBe('error')
- expect((await plexo.current())?.error).toMatch(/partial download file is missing/)
+ expect((await plexo.currentHttp())?.status).toBe('error')
+ expect((await plexo.currentHttp())?.error).toMatch(/partial download file is missing/)
})
- test('a download saved by the previous version resumes where it was', async ({
+ test('downloads an older version saved are cleared, partial data and all', async ({
plexo,
serve,
dirs
}) => {
- const { id, origin } = await pausedDownload(plexo, serve)
- const paused = (await plexo.current())!
+ // A paused download of this version's, which the clearing must leave alone.
+ const { id } = await pausedDownload(plexo, serve)
await plexo.quit()
-
- // What version 4 wrote: every block whole, inside the state.
- const manifestPath = join(dirs.userData, 'downloads', id, 'manifest.json')
- const manifest = JSON.parse(await readFile(manifestPath, 'utf-8'))
- delete manifest.progress
- await writeFile(
- manifestPath,
- JSON.stringify({
- ...manifest,
- version: 4,
- state: { ...manifest.state, blocks: paused.blocks }
- })
- )
+ const root = join(dirs.userData, 'downloads')
+ const manifest = (folder: string, content: object): Promise<void> =>
+ mkdir(join(root, folder), { recursive: true }).then(() =>
+ writeFile(join(root, folder, 'manifest.json'), JSON.stringify(content))
+ )
+
+ // What rc.1–rc.9 left: manifest version 2, the parts in a folder of their own, and the final
+ // name claimed as an empty file.
+ const oldId = '00000000-0000-4000-8000-000000000002'
+ const placeholder = join(dirs.dest, 'old-movie.mkv')
+ await manifest(oldId, {
+ version: 2,
+ state: { id: oldId, destinationPath: placeholder, status: 'paused' }
+ })
+ await mkdir(join(root, oldId, 'parts'))
+ await writeFile(join(root, oldId, 'parts', '0'), seededBytes(1000, 5))
+ await writeFile(placeholder, '')
+
+ // A layout this version doesn't read, with its staging file beside the destination.
+ const laterId = '00000000-0000-4000-8000-000000000005'
+ const staging = join(dirs.dest, 'other.iso.plexo')
+ await manifest(laterId, {
+ version: 5,
+ partialPath: staging,
+ state: { id: laterId, destinationPath: join(dirs.dest, 'other.iso'), status: 'paused' }
+ })
+ await writeFile(staging, seededBytes(1000, 6))
+
+ // An old manifest naming a file that holds something: never Plexo's to delete.
+ const realId = '00000000-0000-4000-8000-000000000003'
+ const realFile = join(dirs.dest, 'mine.txt')
+ await manifest(realId, {
+ version: 2,
+ state: { id: realId, destinationPath: realFile, status: 'paused' }
+ })
+ await writeFile(realFile, 'keep me')
await plexo.launch()
- expect((await plexo.current())?.bytesDownloaded).toBe(paused.bytesDownloaded)
- const before = origin.chunkRequests().length
+ expect((await plexo.currentHttp())?.id).toBe(id)
+ for (const gone of [join(root, oldId), placeholder, join(root, laterId), staging]) {
+ await expect.poll(() => existsSync(gone), { message: `${gone} cleared` }).toBe(false)
+ }
+ await expect.poll(() => existsSync(join(root, realId))).toBe(false)
+ expect(await readFile(realFile, 'utf-8')).toBe('keep me')
+ // Ours, not the download's: out of the way of the end-of-test check for stray files.
+ await rm(realFile)
+
await plexo.api.resumeDownload(id)
- await plexo.waitForStatus('completed')
- const refetched = origin
- .chunkRequests()
- .slice(before)
- .some((request) => request.range!.start < paused.bytesDownloaded / 2)
- expect(refetched, 'what was already there is not fetched again').toBe(false)
+ await plexo.waitForHttpStatus('completed')
})
test('a staging file cut short while the app was closed is fetched again', async ({
@@ -165,7 +193,7 @@ test.describe('persisted state on disk @smoke', () => {
// What a power cut can do: the manifest says a block is done, but its data never all
// reached the disk.
const { id } = await pausedDownload(plexo, serve)
- const state = (await plexo.current())!
+ const state = (await plexo.currentHttp())!
const done = state.blocks!.find((block) => block.status === 'completed')!
await plexo.quit()
const staging = `${state.destinationPath}.plexo`
@@ -173,6 +201,6 @@ test.describe('persisted state on disk @smoke', () => {
await plexo.launch()
await plexo.api.resumeDownload(id)
- await plexo.waitForStatus('completed')
+ await plexo.waitForHttpStatus('completed')
})
})
diff --git a/e2e/removal.spec.ts b/e2e/removal.spec.ts
new file mode 100644
index 0000000..607734a
--- /dev/null
+++ b/e2e/removal.spec.ts
@@ -0,0 +1,288 @@
+import { existsSync } from 'node:fs'
+import { mkdir, readFile, rename, symlink, unlink, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { BLOCK, expect, test, treeSha, type PlexoApp } from './fixtures'
+import { seededBytes } from './origin'
+import { named, Swarm, torrentFileOnDisk } from './torrentSwarm'
+
+/** Hold the actual history save, rather than relying on a quick click landing in its window. */
+async function holdHistoryWrite(plexo: PlexoApp): Promise<void> {
+ await plexo.evaluateMain(() => {
+ const fs = process.getBuiltinModule('node:fs/promises')
+ const { basename } = process.getBuiltinModule('node:path')
+ const original = fs.rename
+ const globals = globalThis as Record<string, unknown>
+ let release!: () => void
+ const held = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ globals.__releaseHistory = () => {
+ fs.rename = original
+ release()
+ }
+ fs.rename = async (...args: Parameters<typeof original>) => {
+ if (basename(String(args[1])) === 'history.json') {
+ globals.__historyHeld = true
+ await held
+ }
+ return original(...args)
+ }
+ }, null)
+}
+
+async function releaseHistoryWrite(plexo: PlexoApp): Promise<void> {
+ await plexo.evaluateMain(() => {
+ const globals = globalThis as Record<string, unknown>
+ if (typeof globals.__releaseHistory === 'function') globals.__releaseHistory()
+ }, null)
+}
+
+async function waitForHistoryWrite(plexo: PlexoApp): Promise<void> {
+ await expect
+ .poll(() =>
+ plexo.evaluateMain(() => (globalThis as Record<string, unknown>).__historyHeld, null)
+ )
+ .toBe(true)
+}
+
+async function stubTrash(plexo: PlexoApp, destination: string): Promise<void> {
+ await mkdir(destination)
+ await plexo.evaluateMain(({ shell }, dest) => {
+ shell.trashItem = async (path: string): Promise<void> => {
+ const { rename } = process.getBuiltinModule('node:fs/promises')
+ const { basename, join } = process.getBuiltinModule('node:path')
+ await rename(path, join(dest, basename(path)))
+ }
+ }, destination)
+}
+
+test.describe('removal during completion @smoke', () => {
+ for (const action of ['remove', 'clear', 'trash'] as const) {
+ test(`${action} waits for the pending history save and stays removed after restart`, async ({
+ plexo,
+ serve,
+ dirs
+ }) => {
+ const trash = join(dirs.dest, 'test-trash')
+ if (action === 'trash') await stubTrash(plexo, trash)
+ await holdHistoryWrite(plexo)
+ try {
+ const origin = await serve({ size: BLOCK })
+ const id = await plexo.start(origin.url(), origin.sha256)
+ await waitForHistoryWrite(plexo)
+ const completed = (await plexo.api.listDownloads()).find(
+ (entry) => entry.state.id === id
+ )!.state
+ expect(completed.status).toBe('completed')
+
+ const removing =
+ action === 'clear'
+ ? plexo.api.clearHistory()
+ : plexo.api.removeDownload(id, { trashFile: action === 'trash' })
+ // Sent after removal on the same renderer IPC connection: removal has reached main.
+ await plexo.api.listDownloads()
+ await releaseHistoryWrite(plexo)
+ await removing
+
+ expect((await plexo.api.listHistory()).find((entry) => entry.id === id)).toBeUndefined()
+ expect(
+ (await plexo.api.listDownloads()).find((entry) => entry.state.id === id)
+ ).toBeUndefined()
+ expect(existsSync(completed.destinationPath)).toBe(action !== 'trash')
+ if (action === 'trash') expect(existsSync(join(trash, completed.fileName))).toBe(true)
+ await plexo.relaunch()
+ expect(await plexo.all()).toEqual([])
+ } finally {
+ if (plexo.alive) await releaseHistoryWrite(plexo).catch(() => {})
+ }
+ })
+ }
+
+ test('trashing a just-finished torrent waits for its owned-file history record', async ({
+ plexo,
+ dirs
+ }) => {
+ const swarm = await new Swarm().start()
+ try {
+ const files = [
+ named(seededBytes(BLOCK, 121), 'a.bin'),
+ named(seededBytes(BLOCK, 122), 'b.bin')
+ ]
+ const torrent = await swarm.seed(files, { folder: 'Finished', pieceLength: 16 * 1024 })
+ const trash = join(dirs.dest, 'test-trash')
+ await stubTrash(plexo, trash)
+ await holdHistoryWrite(plexo)
+ const id = await plexo.start(
+ await torrentFileOnDisk(torrent),
+ treeSha(files.map((data) => ({ path: (data as { name?: string }).name!, data })))
+ )
+ await waitForHistoryWrite(plexo)
+ const completed = (await plexo.api.listDownloads()).find(
+ (entry) => entry.state.id === id
+ )!.state
+ await writeFile(join(completed.destinationPath, 'personal.txt'), 'keep me')
+ const removing = plexo.api.removeDownload(id, { trashFile: true })
+ await plexo.api.listDownloads()
+ await releaseHistoryWrite(plexo)
+ await removing
+
+ expect(await readFile(join(completed.destinationPath, 'personal.txt'), 'utf8')).toBe(
+ 'keep me'
+ )
+ for (const name of ['a.bin', 'b.bin']) {
+ expect(existsSync(join(completed.destinationPath, name))).toBe(false)
+ expect(existsSync(join(trash, name))).toBe(true)
+ }
+ expect(await plexo.all()).toEqual([])
+ } finally {
+ if (plexo.alive) await releaseHistoryWrite(plexo).catch(() => {})
+ await swarm.stop()
+ }
+ })
+})
+
+test('failed torrent cancellation stays visible across restart and can be retried @smoke', async ({
+ plexo,
+ dirs
+}) => {
+ const swarm = await new Swarm().start()
+ try {
+ const files = [
+ named(seededBytes(32 * BLOCK, 111), 'a.bin'),
+ named(seededBytes(32 * BLOCK, 112), 'b.bin')
+ ]
+ const torrent = await swarm.seed(files, {
+ folder: 'Partial',
+ pieceLength: 16 * 1024,
+ uploadLimit: 64 * 1024
+ })
+ const id = await plexo.start(
+ await torrentFileOnDisk(torrent),
+ treeSha(files.map((data) => ({ path: (data as { name?: string }).name!, data })))
+ )
+ await plexo.api.pauseDownload(id)
+ const paused = await plexo.waitForTorrentStatus('paused')
+ await writeFile(join(paused.destinationPath, 'personal.txt'), 'keep me')
+ const original = paused.destinationPath + '.original'
+ await rename(paused.destinationPath, original)
+ await symlink(original, paused.destinationPath, 'junction')
+
+ await expect(plexo.api.removeDownload(id)).rejects.toThrow(/folder is now a link/)
+ const failed = await plexo.waitForTorrentStatus('error')
+ expect(failed.error).toMatch(/folder is now a link/)
+ expect(failed.resumable).toBe(false)
+ const row = plexo.page.getByRole('button', { name: `Open ${paused.fileName}`, exact: true })
+ await expect(row).toBeVisible()
+ expect(
+ plexo.sessions
+ .flat()
+ .filter((state) => state.id === id)
+ .some((state) => state.status === 'cancelled')
+ ).toBe(false)
+ const manifest = join(dirs.userData, 'downloads', id, 'manifest.json')
+ expect(JSON.parse(await readFile(manifest, 'utf8')).state.status).toBe('error')
+
+ await plexo.relaunch()
+ await expect(
+ plexo.page.getByRole('button', { name: `Open ${paused.fileName}`, exact: true })
+ ).toBeVisible()
+ expect((await plexo.waitForTorrentStatus('error')).error).toMatch(/folder is now a link/)
+ await unlink(paused.destinationPath)
+ await rename(original, paused.destinationPath)
+ await plexo.api.removeDownload(id)
+ expect(await plexo.all()).toEqual([])
+ expect(existsSync(manifest)).toBe(false)
+ expect(await readFile(join(paused.destinationPath, 'personal.txt'), 'utf8')).toBe('keep me')
+ for (const name of ['a.bin', 'b.bin'])
+ expect(existsSync(join(paused.destinationPath, name))).toBe(false)
+ } finally {
+ await swarm.stop()
+ }
+})
+
+test('cleanup failure keeps an active HTTP download visible and blocks resume during cancellation @smoke', async ({
+ plexo,
+ serve,
+ dirs
+}) => {
+ const origin = await serve({ size: 24 * BLOCK })
+ const reached = origin.hold(7 * BLOCK)
+ const id = await plexo.start(origin.url(), origin.sha256)
+ await reached
+ const state = (await plexo.currentHttp())!
+ const staging = `${state.destinationPath}.plexo`
+ await plexo.evaluateMain((_electron, path) => {
+ const fs = process.getBuiltinModule('node:fs/promises')
+ const original = fs.rm
+ const globals = globalThis as Record<string, unknown>
+ let release!: () => void
+ const held = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ globals.__releaseDiscard = () => {
+ fs.rm = original
+ release()
+ }
+ fs.rm = async (...args: Parameters<typeof original>) => {
+ if (args[0] === path) {
+ globals.__discardHeld = true
+ await held
+ throw Object.assign(new Error('Permission denied removing partial data'), {
+ code: 'EACCES'
+ })
+ }
+ return original(...args)
+ }
+ }, staging)
+ try {
+ const removing = plexo.api.removeDownload(id).then(
+ () => null,
+ (error: Error) => error.message
+ )
+ await expect
+ .poll(() =>
+ plexo.evaluateMain(() => (globalThis as Record<string, unknown>).__discardHeld, null)
+ )
+ .toBe(true)
+ const alsoRemoving = plexo.api.removeDownload(id).then(
+ () => null,
+ (error: Error) => error.message
+ )
+ await plexo.api.resumeDownload(id)
+ expect(
+ (await plexo.api.listDownloads()).find((entry) => entry.state.id === id)?.state.status
+ ).toBe('paused')
+ await expect(
+ plexo.page.getByRole('button', { name: `Open ${state.fileName}`, exact: true })
+ ).toBeVisible()
+ await plexo.evaluateMain(() => {
+ ;((globalThis as Record<string, unknown>).__releaseDiscard as () => void)()
+ }, null)
+ expect(await removing).toMatch(/Permission denied/)
+ expect(await alsoRemoving).toMatch(/Permission denied/)
+ const failed = await plexo.waitForHttpStatus('error')
+ expect(failed.resumable).toBe(false)
+ expect(existsSync(staging)).toBe(true)
+ expect(
+ plexo.sessions
+ .flat()
+ .filter((entry) => entry.id === id)
+ .some((entry) => entry.status === 'cancelled')
+ ).toBe(false)
+ expect(
+ JSON.parse(await readFile(join(dirs.userData, 'downloads', id, 'manifest.json'), 'utf8'))
+ .state.status
+ ).toBe('error')
+ await plexo.api.removeDownload(id)
+ expect(existsSync(staging)).toBe(false)
+ expect(await plexo.all()).toEqual([])
+ } finally {
+ if (plexo.alive)
+ await plexo
+ .evaluateMain(() => {
+ ;((globalThis as Record<string, unknown>).__releaseDiscard as () => void)()
+ }, null)
+ .catch(() => {})
+ origin.release()
+ }
+})
diff --git a/e2e/savedProgress.spec.ts b/e2e/savedProgress.spec.ts
index cac0ecd..e8295a2 100644
--- a/e2e/savedProgress.spec.ts
+++ b/e2e/savedProgress.spec.ts
@@ -1,7 +1,7 @@
import { expect, test } from '@playwright/test'
-import { planBlocks } from '../src/main/download/plan'
-import { restoreBlocks, saveBlocks } from '../src/main/download/savedProgress'
-import type { BlockState } from '../src/shared/types'
+import { planBlocks, planPieces } from '../src/main/download/plan'
+import { restoreBlocks, restorePieces, saveBlocks } from '../src/main/download/savedProgress'
+import type { HttpBlockState } from '../src/shared/types'
// P. What a download's saved progress says, and what it's trusted to say when read back.
@@ -9,7 +9,7 @@ const MIB = 1024 * 1024
const plan = { totalBytes: 10 * MIB, blockSizeBytes: 4 * MIB, totalBlocks: 3 }
/** A download of `plan` with some progress: block 0 done by two networks, block 1 partway. */
-function inProgress(): BlockState[] {
+function inProgress(): HttpBlockState[] {
const blocks = planBlocks(plan.totalBytes, plan.blockSizeBytes)
Object.assign(blocks[0], {
status: 'completed',
@@ -59,7 +59,7 @@ test.describe('saved progress', () => {
const saved = saveBlocks(inProgress())
for (const blockSizeBytes of [0, -1, NaN, 1.5, undefined]) {
expect(
- restoreBlocks({ ...plan, blockSizeBytes }, saved),
+ restoreBlocks({ ...plan, blockSizeBytes: blockSizeBytes as number }, saved),
String(blockSizeBytes)
).toBeUndefined()
}
@@ -86,4 +86,24 @@ test.describe('saved progress', () => {
).toBe(true)
}
})
+
+ test('torrent checkpoints restore verified bytes, never provisional bytes', () => {
+ const pieces = planPieces(250, 100)
+ Object.assign(pieces[0], {
+ status: 'completed',
+ bytesDownloaded: 100,
+ bytesByInterface: { wifi: 100 }
+ })
+ Object.assign(pieces[1], { status: 'downloading', provisionalBytes: 75 })
+ const restored = restorePieces(
+ { totalBytes: 250, pieceLength: 100, totalPieces: 3 },
+ saveBlocks(pieces)
+ )!
+ expect(restored.map((piece) => [piece.status, piece.bytesDownloaded])).toEqual([
+ ['completed', 100],
+ ['pending', 0],
+ ['pending', 0]
+ ])
+ expect(restored.every((piece) => piece.provisionalBytes === 0)).toBe(true)
+ })
})
diff --git a/e2e/scheduler.spec.ts b/e2e/scheduler.spec.ts
index 391abf6..d143346 100644
--- a/e2e/scheduler.spec.ts
+++ b/e2e/scheduler.spec.ts
@@ -6,7 +6,7 @@ import {
type SchedulerPolicy,
type SchedulerState
} from '../src/main/download/scheduler'
-import type { BlockState, BlockStatus, ChunkStatus } from '../src/shared/types'
+import type { HttpBlockState, HttpBlockStatus, HttpStreamStatus } from '../src/shared/types'
// J. Who fetches what. Pure, so the races that decide it (which stream asked first, how far
// along the holder is) are pinned down as inputs instead of left to timing.
@@ -15,7 +15,8 @@ const POLICY: SchedulerPolicy = { hedgeAfterMs: 5000, maxHedgesPerBlock: 2, star
const NOW = 100_000
const LENGTH = 1000
-const block = (index: number, status: BlockStatus = 'pending', bytes = 0): BlockState => ({
+const block = (index: number, status: HttpBlockStatus = 'pending', bytes = 0): HttpBlockState => ({
+ kind: 'http',
index,
rangeStart: index * LENGTH,
rangeEnd: index * LENGTH + LENGTH - 1,
@@ -27,7 +28,7 @@ const block = (index: number, status: BlockStatus = 'pending', bytes = 0): Block
const stream = (
id: number,
interfaceId: string,
- status: ChunkStatus,
+ status: HttpStreamStatus,
speedBytesPerSec = 0
): SchedulerState['streams'][number] => ({ id, interfaceId, status, speedBytesPerSec })
@@ -39,7 +40,7 @@ const attempt = (
): AttemptView => ({ kind, streamId, networkId, startedAt: NOW - ageMs })
function state(parts: {
- blocks: BlockState[]
+ blocks: HttpBlockState[]
streams?: SchedulerState['streams']
attempts?: [number, AttemptView[]][]
avoid?: [number, string][]
@@ -112,14 +113,19 @@ test.describe('scheduler: taking the next block', () => {
const networks = ['a', 'b', 'c']
fc.assert(
fc.property(
- fc.array(fc.constantFrom<BlockStatus>('pending', 'downloading', 'completed'), {
+ fc.array(fc.constantFrom<HttpBlockStatus>('pending', 'downloading', 'completed'), {
minLength: 1,
maxLength: 8
}),
fc.array(
fc.record({
interfaceId: fc.constantFrom(...networks),
- status: fc.constantFrom<ChunkStatus>('pending', 'downloading', 'retrying', 'paused')
+ status: fc.constantFrom<HttpStreamStatus>(
+ 'pending',
+ 'downloading',
+ 'retrying',
+ 'paused'
+ )
}),
{ minLength: 1, maxLength: 8 }
),
@@ -311,7 +317,7 @@ test.describe('scheduler: racing a slow block', () => {
fc.property(
fc.array(
fc.record({
- status: fc.constantFrom<BlockStatus>('pending', 'downloading', 'completed'),
+ status: fc.constantFrom<HttpBlockStatus>('pending', 'downloading', 'completed'),
bytes: fc.integer({ min: 0, max: LENGTH }),
holderNetwork: fc.constantFrom(...networks),
holderAge: fc.integer({ min: 0, max: 20_000 }),
diff --git a/e2e/selection.spec.ts b/e2e/selection.spec.ts
new file mode 100644
index 0000000..ab611e4
--- /dev/null
+++ b/e2e/selection.spec.ts
@@ -0,0 +1,170 @@
+import { existsSync } from 'node:fs'
+import { mkdir, readFile, writeFile } from 'node:fs/promises'
+import { basename, join } from 'node:path'
+import { BLOCK, expect, test, treeSha } from './fixtures'
+import { seededBytes } from './origin'
+import { named, Swarm, torrentFileOnDisk } from './torrentSwarm'
+
+async function stubTrash(plexo: import('./fixtures').PlexoApp, destination: string): Promise<void> {
+ await mkdir(destination)
+ await plexo.evaluateMain(({ shell }, dest) => {
+ shell.trashItem = async (path: string): Promise<void> => {
+ const { rename } = process.getBuiltinModule('node:fs/promises')
+ const { basename, join } = process.getBuiltinModule('node:path')
+ await rename(path, join(dest, basename(path)))
+ }
+ }, destination)
+}
+
+test('mixed selection applies actions only to eligible downloads and keeps finished files', async ({
+ plexo,
+ serve
+}) => {
+ const complete = await serve({ size: BLOCK })
+ await plexo.start(complete.url(), complete.sha256, { fileName: 'finished.bin' })
+ const finished = await plexo.waitForStatus('completed')
+ const failed = await serve({ size: 16 * BLOCK })
+ const held = failed.hold(4 * BLOCK)
+ await plexo.start(failed.url(), failed.sha256, { fileName: 'expired.bin' })
+ await held
+ failed.setRule(() => ({ status: 403 }))
+ failed.release()
+ await plexo.waitForStatus('error')
+ const paused = await serve({ size: 16 * BLOCK })
+ const pausedHeld = paused.hold(4 * BLOCK)
+ const pausedId = await plexo.start(paused.url(), paused.sha256, { fileName: 'paused.bin' })
+ await pausedHeld
+ await plexo.api.pauseDownload(pausedId)
+ paused.release()
+ await plexo.waitForStatus('paused')
+
+ const page = plexo.page
+ const beforeSelection = await page
+ .getByRole('button', { name: 'Open paused.bin', exact: true })
+ .boundingBox()
+ await page.getByRole('checkbox', { name: 'Select paused.bin', exact: true }).check()
+ const toolbar = page.getByRole('toolbar', { name: 'Selected downloads' })
+ await expect(page.getByRole('heading', { level: 1 })).toBeHidden()
+ await toolbar.getByRole('button', { name: 'Select all', exact: true }).click()
+ await expect(toolbar.getByText('3 selected', { exact: true })).toBeVisible()
+ await expect(page.locator('[data-selected=true]')).toHaveCount(3)
+ const afterSelection = await page
+ .getByRole('button', { name: 'Open paused.bin', exact: true })
+ .boundingBox()
+ expect(afterSelection?.y).toBe(beforeSelection?.y)
+ await expect(page.getByRole('button', { name: 'Resume (1)', exact: true })).toBeVisible()
+ await expect(page.getByRole('button', { name: /^Retry/ })).toHaveCount(0)
+ await expect(page.getByRole('button', { name: 'Fix link', exact: true })).toBeVisible()
+ await expect(
+ page.getByRole('button', { name: 'Cancel downloads… (2)', exact: true })
+ ).toBeVisible()
+ await plexo.page.getByRole('button', { name: 'Remove from list (1)', exact: true }).click()
+ await expect(page.getByRole('button', { name: 'Open finished.bin', exact: true })).toBeHidden()
+ expect(existsSync(finished.destinationPath)).toBe(true)
+ await expect(toolbar.getByText('2 selected', { exact: true })).toBeVisible()
+ await page.getByRole('button', { name: 'Cancel downloads… (2)', exact: true }).click()
+ const confirmation = page.getByRole('alertdialog')
+ await expect(confirmation.getByText(/deletes their downloaded data/)).toBeVisible()
+ await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(toolbar.getByText('2 selected', { exact: true })).toBeVisible()
+ await page.getByRole('button', { name: 'Cancel downloads… (2)', exact: true }).click()
+ await page
+ .getByRole('alertdialog')
+ .getByRole('button', { name: 'Cancel downloads', exact: true })
+ .click()
+ await expect(page.getByText('No downloads yet', { exact: true })).toBeVisible()
+ expect(existsSync(finished.destinationPath)).toBe(true)
+})
+
+test('missing finished files can leave the list but are excluded from file removal', async ({
+ plexo,
+ serve
+}) => {
+ const origin = await serve({ size: BLOCK })
+ await plexo.start(origin.url(), origin.sha256)
+ const complete = await plexo.waitForStatus('completed')
+ // Rename instead of delete so automatic fixture integrity checks can still inspect the bytes.
+ const { rename } = await import('node:fs/promises')
+ await rename(complete.destinationPath, `${complete.destinationPath}.moved`)
+ await plexo.page.reload()
+ await plexo.page
+ .getByRole('checkbox', { name: `Select ${complete.fileName}`, exact: true })
+ .check()
+ await expect(plexo.page.getByRole('button', { name: /^Move files/ })).toHaveCount(0)
+ await plexo.page.getByRole('button', { name: 'Remove from list (1)', exact: true }).click()
+ await expect(plexo.page.getByText('No downloads yet', { exact: true })).toBeVisible()
+ await rename(`${complete.destinationPath}.moved`, complete.destinationPath)
+})
+
+test('trashing finished torrent files preserves unrelated files in the torrent folder', async ({
+ plexo,
+ dirs
+}) => {
+ const swarm = await new Swarm().start()
+ try {
+ const files = [named(seededBytes(BLOCK, 81), 'a.bin'), named(seededBytes(BLOCK, 82), 'b.bin')]
+ const torrent = await swarm.seed(files, { folder: 'Owned', pieceLength: 16 * 1024 })
+ await plexo.start(
+ await torrentFileOnDisk(torrent),
+ treeSha(
+ files.map((data) => ({
+ path: (data as { name?: string }).name!,
+ data
+ }))
+ )
+ )
+ const completed = await plexo.waitForTorrentStatus('completed')
+ await writeFile(join(completed.destinationPath, 'personal.txt'), 'keep me')
+ const trash = join(dirs.dest, 'test-trash')
+ await stubTrash(plexo, trash)
+ await plexo.page
+ .getByRole('checkbox', { name: `Select ${completed.fileName}`, exact: true })
+ .check()
+ await plexo.page.getByRole('button', { name: /^Move files to Trash…/ }).click()
+ await plexo.page
+ .getByRole('alertdialog')
+ .getByRole('button', { name: 'Move files to Trash', exact: true })
+ .click()
+ await expect(plexo.page.getByText('No downloads yet', { exact: true })).toBeVisible()
+ expect(await readFile(join(completed.destinationPath, 'personal.txt'), 'utf8')).toBe('keep me')
+ for (const file of files)
+ expect(existsSync(join(trash, basename((file as { name?: string }).name!)))).toBe(true)
+ } finally {
+ await swarm.stop()
+ }
+})
+
+test('cancelling an unfinished torrent preserves unrelated files in its folder', async ({
+ plexo
+}) => {
+ const swarm = await new Swarm().start()
+ try {
+ const files = [
+ named(seededBytes(32 * BLOCK, 91), 'a.bin'),
+ named(seededBytes(32 * BLOCK, 92), 'b.bin')
+ ]
+ const torrent = await swarm.seed(files, {
+ folder: 'Partial',
+ pieceLength: 16 * 1024,
+ uploadLimit: 64 * 1024
+ })
+ const id = await plexo.start(
+ await torrentFileOnDisk(torrent),
+ treeSha(
+ files.map((data) => ({
+ path: (data as { name?: string }).name!,
+ data
+ }))
+ )
+ )
+ await plexo.api.pauseDownload(id)
+ const paused = await plexo.waitForTorrentStatus('paused')
+ await writeFile(join(paused.destinationPath, 'personal.txt'), 'keep me')
+ await plexo.api.removeDownload(id)
+ expect(await readFile(join(paused.destinationPath, 'personal.txt'), 'utf8')).toBe('keep me')
+ expect(existsSync(join(paused.destinationPath, 'a.bin'))).toBe(false)
+ expect(existsSync(join(paused.destinationPath, 'b.bin'))).toBe(false)
+ } finally {
+ await swarm.stop()
+ }
+})
diff --git a/e2e/streams.spec.ts b/e2e/streams.spec.ts
index b1cad56..90e8e8a 100644
--- a/e2e/streams.spec.ts
+++ b/e2e/streams.spec.ts
@@ -1,11 +1,14 @@
import { BLOCK, expect, test } from './fixtures'
+import type { DownloadState } from '../src/shared/types'
// N. How many streams a download runs, decided while it runs (see concurrency.ts), against a
// server that limits it in each of the ways that matter.
test.describe('automatic stream count', () => {
- const peakStreams = (plexo: { sessions: { chunks: unknown[] }[][] }): number =>
- Math.max(...plexo.sessions.at(-1)!.map((state) => state.chunks.length))
+ const peakStreams = (plexo: { sessions: DownloadState[][] }): number =>
+ Math.max(
+ ...plexo.sessions.at(-1)!.map((state) => (state.kind === 'http' ? state.streams.length : 0))
+ )
test('a server that turns extra connections away keeps the ones it accepted', async ({
plexo,
@@ -23,9 +26,9 @@ test.describe('automatic stream count', () => {
})
await plexo.start(origin.url(), origin.sha256, { connections: 'auto' })
- const state = await plexo.waitForStatus('completed', 40_000)
+ const state = await plexo.waitForHttpStatus('completed', 40_000)
expect(peakStreams(plexo), 'more streams were tried').toBe(8)
- expect(state.chunks).toHaveLength(4)
+ expect(state.streams).toHaveLength(4)
expect(origin.log.some((request) => request.status === 503)).toBe(true)
})
@@ -49,9 +52,9 @@ test.describe('automatic stream count', () => {
})
await plexo.start(origin.url(), origin.sha256, { connections: 'auto' })
- const state = await plexo.waitForStatus('completed', 40_000)
+ const state = await plexo.waitForHttpStatus('completed', 40_000)
expect(peakStreams(plexo), 'more streams were tried').toBe(8)
- expect(state.chunks).toHaveLength(4)
+ expect(state.streams).toHaveLength(4)
})
})
@@ -71,18 +74,18 @@ test.describe('automatic stream count', () => {
})
await plexo.start(origin.url(), origin.sha256, { connections: 'auto' })
- const state = await plexo.waitForStatus('completed', 40_000)
+ const state = await plexo.waitForHttpStatus('completed', 40_000)
expect(origin.log.some((request) => request.status === 503)).toBe(true)
// Every stream was turned away alike, so none was closed for it, and the count still grew.
expect(peakStreams(plexo), 'the count grew once the server served').toBeGreaterThan(8)
- expect(state.chunks.length).toBeGreaterThan(8)
+ expect(state.streams.length).toBeGreaterThan(8)
})
})
test('a count picked on the start screen is kept rather than grown', async ({ plexo, serve }) => {
const origin = await serve({ size: 96 * BLOCK, bytesPerSecond: 256 * 1024 })
await plexo.start(origin.url(), origin.sha256, { connections: 'auto', streamsPerNetwork: 4 })
- await plexo.waitForStatus('completed', 40_000)
+ await plexo.waitForHttpStatus('completed', 40_000)
expect(peakStreams(plexo), 'Auto would have doubled to 8 and on').toBe(4)
})
})
diff --git a/e2e/torrent.spec.ts b/e2e/torrent.spec.ts
new file mode 100644
index 0000000..7388ab5
--- /dev/null
+++ b/e2e/torrent.spec.ts
@@ -0,0 +1,240 @@
+import type { Torrent, Wire } from 'webtorrent'
+import { expect, LAN_ADDRESS, test, treeSha } from './fixtures'
+import { seededBytes, sha256 } from './origin'
+import { named, Swarm, torrentFileOnDisk } from './torrentSwarm'
+
+// Downloading torrents: every byte right, every peer on a network, and the networks' controls,
+// pause and relaunch working as they do for HTTP. The swarm is local (see torrentSwarm.ts); the
+// checks fixture verifies each finished download's bytes and that nothing else was left behind.
+
+const KB = 1024
+const MB = 1024 * KB
+const PIECE = 64 * KB
+
+let swarm: Swarm
+test.beforeEach(async () => {
+ swarm = await new Swarm().start()
+})
+test.afterEach(async () => {
+ await swarm.stop()
+})
+
+test.describe('torrent downloads', () => {
+ test('a single-file torrent', async ({ plexo }) => {
+ const data = seededBytes(2 * MB, 11)
+ const torrent = await swarm.seed([named(data, 'movie.mkv')], { pieceLength: PIECE })
+
+ await plexo.start(await torrentFileOnDisk(torrent), sha256(data))
+ const done = await plexo.waitForTorrentStatus('completed', 30_000)
+ expect(done.kind).toBe('torrent')
+ expect(done.fileName).toBe('movie.mkv')
+ expect(done.totalPieces).toBe((2 * MB) / PIECE)
+ })
+
+ test('a torrent of several files, published as its folder', async ({ plexo }) => {
+ const files = [
+ named(seededBytes(300 * KB, 21), 'a.bin'),
+ named(seededBytes(700 * KB + 3, 22), 'b.bin'),
+ named(seededBytes(5, 23), 'tiny.txt')
+ ]
+ const torrent = await swarm.seed(files, { folder: 'Album', pieceLength: PIECE })
+
+ const expected = treeSha(
+ files.map((data) => ({ path: (data as { name?: string }).name!, data }))
+ )
+ await plexo.start(await torrentFileOnDisk(torrent), expected)
+ const done = await plexo.waitForTorrentStatus('completed', 30_000)
+ expect(done.fileName).toBe('Album')
+ })
+
+ test('pause, quit, relaunch and resume: the pieces already done aren’t fetched again', async ({
+ plexo
+ }) => {
+ const data = seededBytes(6 * MB, 31)
+ const file = named(data, 'big.iso')
+ // Slow enough to stop partway: three seeders at 300 KB/s each.
+ let torrent = await swarm.seed([file], { pieceLength: PIECE, uploadLimit: 300 * KB })
+ for (let seeder = 1; seeder < 3; seeder++) {
+ torrent = await swarm.seed([file], { pieceLength: PIECE, uploadLimit: 300 * KB })
+ }
+
+ const id = await plexo.start(await torrentFileOnDisk(torrent), sha256(data))
+ await plexo.waitUntil((state) => state.bytesDownloaded >= 2 * MB, 30_000)
+ await plexo.relaunch()
+ const paused = await plexo.waitForTorrentStatus('paused')
+ expect(paused.bytesDownloaded).toBeGreaterThanOrEqual(2 * MB)
+
+ const sentBefore = swarm.uploaded()
+ await plexo.api.resumeDownload(id)
+ await plexo.waitForTorrentStatus('completed', 60_000)
+ // What was missing, plus at most a few pieces each peer had half-sent when it stopped.
+ expect(swarm.uploaded() - sentBefore).toBeLessThanOrEqual(
+ data.length - paused.bytesDownloaded + 6 * PIECE
+ )
+ })
+})
+
+test.describe('choosing files', () => {
+ /** Files of sizes that don't line up with pieces, so pieces straddle chosen and skipped ones. */
+ function album(size: number, seed: number): Buffer[] {
+ return ['a.bin', 'b.bin', 'c.bin', 'd.bin'].map((name, index) =>
+ named(seededBytes(size + 7 * index + 5, seed + index), name)
+ )
+ }
+ const shaOf = (files: Buffer[]): string =>
+ treeSha(files.map((data) => ({ path: (data as { name?: string }).name!, data })))
+
+ test('only the chosen files are downloaded and published', async ({ plexo }) => {
+ const files = album(300 * KB, 61)
+ const torrent = await swarm.seed(files, { folder: 'Album', pieceLength: PIECE })
+
+ // a and c chosen: b and d never appear, though the pieces at their edges are fetched.
+ await plexo.start(await torrentFileOnDisk(torrent), shaOf([files[0], files[2]]), {
+ selectedFiles: [0, 2]
+ })
+ const done = await plexo.waitForTorrentStatus('completed', 30_000)
+ expect(done.skippedBytes).toBeGreaterThan(0)
+ expect(done.bytesDownloaded).toBe(done.totalBytes - done.skippedBytes!)
+ expect(done.pieces.filter((piece) => piece.status === 'skipped').length).toBeGreaterThan(0)
+ })
+
+ test('the choice is kept through a quit, a relaunch and a resume', async ({ plexo }) => {
+ const files = album(1500 * KB, 71)
+ let torrent = await swarm.seed(files, {
+ folder: 'Set',
+ pieceLength: PIECE,
+ uploadLimit: 300 * KB
+ })
+ for (let seeder = 1; seeder < 3; seeder++) {
+ torrent = await swarm.seed(files, {
+ folder: 'Set',
+ pieceLength: PIECE,
+ uploadLimit: 300 * KB
+ })
+ }
+
+ const id = await plexo.start(await torrentFileOnDisk(torrent), shaOf([files[1], files[3]]), {
+ selectedFiles: [1, 3]
+ })
+ await plexo.waitUntil((state) => state.bytesDownloaded >= 1 * MB, 30_000)
+ const before = await plexo.currentTorrent()
+ await plexo.relaunch()
+ const paused = await plexo.waitForTorrentStatus('paused')
+ expect(paused.skippedBytes).toBe(before!.skippedBytes)
+ await plexo.api.resumeDownload(id)
+ await plexo.waitForTorrentStatus('completed', 60_000)
+ })
+
+ test('the choice changes as it runs: a file dropped never appears, one added comes in', async ({
+ plexo
+ }) => {
+ const files = album(1500 * KB, 81)
+ let torrent = await swarm.seed(files, {
+ folder: 'Mix',
+ pieceLength: PIECE,
+ uploadLimit: 300 * KB
+ })
+ for (let seeder = 1; seeder < 3; seeder++) {
+ torrent = await swarm.seed(files, {
+ folder: 'Mix',
+ pieceLength: PIECE,
+ uploadLimit: 300 * KB
+ })
+ }
+
+ // a and b chosen, then b swapped for c before either is near done.
+ const id = await plexo.start(await torrentFileOnDisk(torrent), shaOf([files[0], files[2]]), {
+ selectedFiles: [0, 1]
+ })
+ await plexo.waitUntil((state) => state.bytesDownloaded > 0, 30_000)
+ await plexo.api.chooseTorrentFiles(id, [0, 2])
+ const changed = await plexo.currentTorrent()
+ expect(changed!.status).toBe('downloading')
+ expect(changed!.files).toEqual({ chosen: 2, total: 4, selected: [0, 2] })
+ await plexo.waitForTorrentStatus('completed', 60_000)
+ })
+})
+
+test.describe('torrents over two networks', () => {
+ test.skip(!LAN_ADDRESS, 'needs a second local address to stand in for a second network')
+
+ /** Three seeders of `data`, at `uploadLimit` each. */
+ async function seedThree(data: Buffer, name: string, uploadLimit?: number): Promise<Torrent> {
+ const file = named(data, name)
+ let torrent = await swarm.seed([file], { pieceLength: PIECE, uploadLimit })
+ for (let seeder = 1; seeder < 3; seeder++) {
+ torrent = await swarm.seed([file], { pieceLength: PIECE, uploadLimit })
+ }
+ return torrent
+ }
+
+ test('both networks carry peers and deliver pieces', async ({ plexo }) => {
+ const data = seededBytes(4 * MB, 41)
+ const torrent = await seedThree(data, 'both.bin', 1 * MB)
+
+ await plexo.start(await torrentFileOnDisk(torrent), sha256(data), { networks: ['a', 'b'] })
+ const done = await plexo.waitForTorrentStatus('completed', 30_000)
+ for (const id of ['a', 'b']) {
+ const network = done.networks.find((entry) => entry.id === id)!
+ expect(network.bytesDownloaded, `network ${id} delivered pieces`).toBeGreaterThan(0)
+ }
+ const seen = new Set(
+ plexo.sessions.flat().flatMap((state) => (state.kind === 'torrent' ? state.peers : []))
+ )
+ expect(new Set([...seen].map((peer) => peer.interfaceId))).toEqual(new Set(['a', 'b']))
+ })
+
+ test('switching a network off moves its peers to the other', async ({ plexo }) => {
+ const data = seededBytes(6 * MB, 42)
+ const torrent = await seedThree(data, 'switch.bin', 300 * KB)
+
+ const id = await plexo.start(await torrentFileOnDisk(torrent), sha256(data), {
+ networks: ['a', 'b']
+ })
+ await plexo.waitUntil(
+ (state) => state.networks.every((network) => network.bytesDownloaded > 0),
+ 30_000
+ )
+ await plexo.api.setDownloadNetwork(id, 'b', false)
+ await plexo.waitUntil(
+ (state) => state.kind === 'torrent' && !state.peers.some((peer) => peer.interfaceId === 'b')
+ )
+ const done = await plexo.waitForTorrentStatus('completed', 60_000)
+ expect(done.networks.find((network) => network.id === 'b')?.enabled).toBe(false)
+ })
+})
+
+test.describe('uploading', () => {
+ test.skip(!LAN_ADDRESS, 'needs a second local address to stand in for the network')
+ // A USB-tethered network, the one kind once left out: every network uploads, whatever its kind.
+ test.use({ appEnv: { PLEXO_E2E_INTERFACES: `b=${LAN_ADDRESS}==usb` } })
+
+ test('peers get pieces back over every network, USB-tethered ones too', async ({ plexo }) => {
+ const data = seededBytes(4 * MB, 51)
+ const torrent = await swarm.seed([named(data, 'shared.bin')], {
+ pieceLength: PIECE,
+ uploadLimit: 400 * KB
+ })
+ const other = await swarm.leech(torrent)
+ let fromPlexo = 0
+ let connected = false
+ other.on('wire', (wire: Wire, address: string) => {
+ // Plexo dials over network b, from the LAN address. A dual-stack listener reports it
+ // IPv4-mapped: ::ffff:<address>:<port>.
+ if (!address.replace(/^::ffff:/, '').startsWith(`${LAN_ADDRESS}:`)) return
+ connected = true
+ wire.on('download', (bytes: number) => (fromPlexo += bytes))
+ })
+
+ await plexo.start(await torrentFileOnDisk(torrent), sha256(data), { networks: ['b'] })
+ const done = await plexo.waitForTorrentStatus('completed', 60_000)
+ expect(connected, 'Plexo connected to the other client').toBe(true)
+ expect(fromPlexo, 'what the other client received from Plexo').toBeGreaterThan(0)
+ // What Plexo shows it sent: at least what arrived (a little may still be in flight at the end).
+ const sentOverB = done.networks.find((network) => network.id === 'b')?.bytesUploaded ?? 0
+ expect(sentOverB).toBeGreaterThanOrEqual(fromPlexo)
+ expect(done.bytesUploaded).toBe(sentOverB)
+ // Nothing is moving once it's done.
+ expect(done.uploadSpeedBytesPerSec ?? 0).toBe(0)
+ })
+})
diff --git a/e2e/torrentFiles.spec.ts b/e2e/torrentFiles.spec.ts
new file mode 100644
index 0000000..c010ac5
--- /dev/null
+++ b/e2e/torrentFiles.spec.ts
@@ -0,0 +1,48 @@
+import { expect, test } from '@playwright/test'
+import fc from 'fast-check'
+import { chosenFiles, wantedPieces } from '../src/main/download/torrent/files'
+
+test.describe('choosing a torrent’s files', () => {
+ test('a piece is wanted exactly when a byte of a chosen file is in it', () => {
+ fc.assert(
+ fc.property(
+ fc.array(fc.nat({ max: 3000 }), { minLength: 1, maxLength: 6 }),
+ fc.integer({ min: 16, max: 2048 }),
+ fc.array(fc.boolean(), { minLength: 6, maxLength: 6 }),
+ (lengths, pieceLength, picks) => {
+ const files = lengths.map((length) => ({ length }))
+ const chosen = new Set(lengths.flatMap((_, index) => (picks[index] ? [index] : [])))
+ const wanted = wantedPieces(files, pieceLength, chosen)
+
+ const total = lengths.reduce((sum, length) => sum + length, 0)
+ expect(wanted).toHaveLength(Math.ceil(total / pieceLength))
+ // The plain definition: some byte of the piece belongs to a chosen file.
+ wanted.forEach((isWanted, piece) => {
+ let offset = 0
+ const needed = lengths.some((length, index) => {
+ const start = offset
+ offset += length
+ // An empty file has no byte, so it needs no piece.
+ return (
+ chosen.has(index) &&
+ length > 0 &&
+ start < (piece + 1) * pieceLength &&
+ start + length > piece * pieceLength
+ )
+ })
+ expect(isWanted, `piece ${piece}`).toBe(needed)
+ })
+ }
+ )
+ )
+ })
+
+ test('what the window asks for: all, some, none, or something that isn’t there', () => {
+ expect(chosenFiles(undefined, 3)).toBeNull()
+ expect(chosenFiles([0, 1, 2], 3)).toBeNull()
+ expect(chosenFiles([2, 0, 0], 3)).toEqual(new Set([0, 2]))
+ expect(() => chosenFiles([], 3)).toThrow(/at least one/)
+ expect(() => chosenFiles([3], 3)).toThrow(/isn’t in it/)
+ expect(() => chosenFiles([1.5], 3)).toThrow(/isn’t in it/)
+ })
+})
diff --git a/e2e/torrentPaths.spec.ts b/e2e/torrentPaths.spec.ts
new file mode 100644
index 0000000..cb20e67
--- /dev/null
+++ b/e2e/torrentPaths.spec.ts
@@ -0,0 +1,98 @@
+import { expect, test } from '@playwright/test'
+import fc from 'fast-check'
+import { posix, win32 } from 'node:path'
+import {
+ safeTorrentPaths,
+ STRIPPED_FROM_NAMES,
+ UnsafeTorrentError
+} from '../src/main/download/torrent/paths'
+
+// What a torrent can put in a path: anything, including what tries to climb out of the folder,
+// what Windows can't save, and names too long for any file system.
+const segment = fc.oneof(
+ fc.constantFrom('..', '.', '', 'CON', 'con.txt', 'a:b', 'x\u0000y', 'A', 'a', 'dir', 'name. '),
+ fc.string({ maxLength: 8 }),
+ fc.string({ minLength: 250, maxLength: 300 })
+)
+const torrentPath = fc
+ .tuple(fc.array(segment, { minLength: 1, maxLength: 4 }), fc.constantFrom('/', '\\'))
+ .map(([segments, separator]) => segments.join(separator))
+const torrentFiles = fc.array(
+ torrentPath.map((path) => ({ path, length: 1 })),
+ { minLength: 1, maxLength: 5 }
+)
+
+test.describe('torrent paths', () => {
+ for (const platform of ['darwin', 'linux', 'win32'] as const) {
+ test(`on ${platform}, a path either stays inside the folder or the torrent is refused`, () => {
+ const path = platform === 'win32' ? win32 : posix
+ const base = path.resolve(path.sep, 'staging')
+ fc.assert(
+ fc.property(torrentFiles, (files) => {
+ let checked: { path: string }[]
+ try {
+ checked = safeTorrentPaths(files, platform)
+ } catch (error) {
+ expect(error).toBeInstanceOf(UnsafeTorrentError)
+ return
+ }
+ for (const file of checked) {
+ expect(path.isAbsolute(file.path)).toBe(false)
+ expect(path.resolve(base, file.path).startsWith(base + path.sep)).toBe(true)
+ for (const part of file.path.split(path.sep)) {
+ expect(['', '.', '..']).not.toContain(part)
+ expect(Buffer.byteLength(part)).toBeLessThanOrEqual(255)
+ }
+ }
+ const lowered = checked.map((file) => file.path.toLowerCase())
+ expect(new Set(lowered).size).toBe(lowered.length)
+ }),
+ { numRuns: 500 }
+ )
+ })
+ }
+
+ test('an ordinary multi-file torrent keeps its layout', () => {
+ const files = [
+ { path: 'Album/01 - Intro.flac', length: 10 },
+ { path: 'Album/Art/cover.jpg', length: 5 }
+ ]
+ expect(safeTorrentPaths(files, 'darwin')).toEqual(files)
+ expect(safeTorrentPaths(files, 'win32').map((file) => file.path)).toEqual([
+ 'Album\\01 - Intro.flac',
+ 'Album\\Art\\cover.jpg'
+ ])
+ })
+
+ test('what climbs out of the folder, collides, or Windows reserves is refused', () => {
+ const refused = (paths: string[], platform: NodeJS.Platform = 'darwin'): void => {
+ const files = paths.map((path) => ({ path, length: 1 }))
+ expect(() => safeTorrentPaths(files, platform)).toThrow(UnsafeTorrentError)
+ }
+ refused(['../evil'])
+ refused(['Name/../../evil'])
+ refused(['Name/A.txt', 'Name/a.txt'])
+ refused(['Name/x', 'Name/x/y'])
+ refused(['Name/::'])
+ refused(['Name/CON.txt'], 'win32')
+ refused(['Name/a:b/file'], 'win32')
+ refused([])
+ // The same names are fine where nothing reserves them, as are names that only start with dots.
+ expect(safeTorrentPaths([{ path: 'Name/CON.txt', length: 1 }], 'darwin')).toHaveLength(1)
+ expect(safeTorrentPaths([{ path: '..notes.txt', length: 1 }], 'darwin')).toEqual([
+ { path: '..notes.txt', length: 1 }
+ ])
+ })
+
+ test('names are cleaned the way webtorrent’s storage cleans them', async () => {
+ // fs-chunk-store's own regex, as installed: an upgrade that changes it fails here. (ESM-only,
+ // so through import(), as specs load such packages.)
+ const { default: filenameReservedRegex } = (await import(
+ 'filename-reserved-regex' as string
+ )) as { default: () => RegExp }
+ expect(STRIPPED_FROM_NAMES.source).toBe(filenameReservedRegex().source)
+ expect(safeTorrentPaths([{ path: 'Name/a:b?.txt', length: 1 }], 'darwin')).toEqual([
+ { path: 'Name/ab.txt', length: 1 }
+ ])
+ })
+})
diff --git a/e2e/torrentPeers.spec.ts b/e2e/torrentPeers.spec.ts
new file mode 100644
index 0000000..576731d
--- /dev/null
+++ b/e2e/torrentPeers.spec.ts
@@ -0,0 +1,52 @@
+import { expect, test } from '@playwright/test'
+import fc from 'fast-check'
+import { bitfieldOf, creditPiece, pickNetwork } from '../src/main/download/torrent/peers'
+
+test.describe('torrent peers across networks', () => {
+ test('a new peer goes to the network with the fewest, the first on a tie', () => {
+ expect(pickNetwork([])).toBeNull()
+ expect(
+ pickNetwork([
+ { id: 'wifi', peers: 3 },
+ { id: 'usb', peers: 1 },
+ { id: 'eth', peers: 1 }
+ ])
+ ).toBe('usb')
+ })
+
+ test('peers spread evenly when each new one takes the least loaded network', () => {
+ const peers: Record<string, number> = { a: 0, b: 0, c: 0 }
+ for (let added = 0; added < 30; added++) {
+ const id = pickNetwork(Object.entries(peers).map(([id, count]) => ({ id, peers: count })))!
+ peers[id]++
+ }
+ expect(peers).toEqual({ a: 10, b: 10, c: 10 })
+ })
+
+ test('a verified piece is credited in whole bytes that add up to its length', () => {
+ fc.assert(
+ fc.property(
+ fc.dictionary(fc.constantFrom('a', 'b', 'c'), fc.nat({ max: 1 << 20 })),
+ fc.integer({ min: 1, max: 1 << 22 }),
+ (received, length) => {
+ const shares = creditPiece(received, length, 'a')
+ const values = Object.values(shares)
+ expect(values.every((bytes) => Number.isInteger(bytes) && bytes >= 0)).toBe(true)
+ expect(values.reduce((sum, bytes) => sum + bytes, 0)).toBe(length)
+ // Only networks that delivered something are credited, unless nobody did.
+ const delivered = Object.keys(received).filter((id) => received[id] > 0)
+ expect(Object.keys(shares).sort()).toEqual(delivered.length ? delivered.sort() : ['a'])
+ }
+ )
+ )
+ expect(creditPiece({ a: 3, b: 1 }, 100, 'a')).toEqual({ a: 75, b: 25 })
+ expect(creditPiece({}, 64, 'eth')).toEqual({ eth: 64 })
+ })
+
+ test('the starting bitfield has one bit per piece, the first piece highest', () => {
+ expect([...bitfieldOf([true, false, false, false, false, false, false, true, true])]).toEqual([
+ 0b10000001, 0b10000000
+ ])
+ expect(bitfieldOf([])).toHaveLength(0)
+ })
+})
diff --git a/e2e/torrentProbe.spec.ts b/e2e/torrentProbe.spec.ts
new file mode 100644
index 0000000..61f4d6d
--- /dev/null
+++ b/e2e/torrentProbe.spec.ts
@@ -0,0 +1,143 @@
+import { mkdtemp, writeFile } from 'node:fs/promises'
+import { createServer, type Server } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import type WebTorrent from 'webtorrent'
+import type { Torrent } from 'webtorrent'
+import { expect, test } from './fixtures'
+import { seededBytes } from './origin'
+
+// Getting a torrent in: every way in gives the same answer, and a torrent Plexo can't save
+// safely is refused before anything is written. Peers come from the link itself (x.pe), so no
+// tracker or DHT is involved.
+
+// ESM-only: specs are compiled to CommonJS, so these come in through import().
+const loadWebTorrent = (): Promise<typeof WebTorrent> =>
+ import('webtorrent').then((module) => module.default)
+const loadBencode = (): Promise<{ encode: (value: unknown) => Uint8Array }> =>
+ import('bencode' as string).then((module) => module.default)
+
+const quiet = { dht: false, lsd: false, tracker: false, natUpnp: false, natPmp: false, utp: false }
+
+function named(data: Buffer, name: string): Buffer {
+ return Object.assign(data, { name })
+}
+
+/** A client seeding `files` (one file, or a folder of them when `folder` is given). */
+async function seed(
+ files: Buffer[],
+ folder?: string
+): Promise<{ client: WebTorrent; torrent: Torrent }> {
+ const client = new (await loadWebTorrent())(quiet)
+ const torrent = await new Promise<Torrent>((resolve) =>
+ client.seed(files.length === 1 ? files[0] : files, { name: folder, announce: [] }, resolve)
+ )
+ return { client, torrent }
+}
+
+/** Serves `body` at /file.torrent as a torrent. */
+async function serveTorrent(body: Uint8Array): Promise<{ url: string; server: Server }> {
+ const server = createServer((_req, res) => {
+ res.writeHead(200, { 'Content-Type': 'application/x-bittorrent' })
+ res.end(body)
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ return { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/file.torrent`, server }
+}
+
+const clients: WebTorrent[] = []
+const servers: Server[] = []
+test.afterEach(async () => {
+ await Promise.all(clients.splice(0).map((client) => new Promise((done) => client.destroy(done))))
+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))))
+})
+
+test.describe('getting a torrent in', () => {
+ test('a link to a .torrent', async ({ plexo }) => {
+ const { client, torrent } = await seed([named(seededBytes(300_000, 1), 'movie.mkv')])
+ clients.push(client)
+ const { url, server } = await serveTorrent(torrent.torrentFile)
+ servers.push(server)
+
+ const probe = await plexo.api.probeUrl(url)
+ expect(probe.kind).toBe('torrent')
+ if (probe.kind !== 'torrent') throw new Error('Expected torrent metadata')
+ expect(probe.torrent.infoHash).toBe(torrent.infoHash)
+ expect(probe.suggestedFileName).toBe('movie.mkv')
+ expect(probe.totalBytes).toBe(300_000)
+ expect(probe.torrent.files).toEqual([{ path: 'movie.mkv', length: 300_000 }])
+ })
+
+ test('a .torrent file on this computer, with a folder of files', async ({ plexo }) => {
+ const { client, torrent } = await seed(
+ [named(seededBytes(1000, 2), 'a.bin'), named(seededBytes(2000, 3), 'b.bin')],
+ 'Album'
+ )
+ clients.push(client)
+ const path = join(await mkdtemp(join(tmpdir(), 'plexo-torrent-')), 'album.torrent')
+ await writeFile(path, torrent.torrentFile)
+
+ const probe = await plexo.api.probeUrl(path)
+ expect(probe.kind).toBe('torrent')
+ if (probe.kind !== 'torrent') throw new Error('Expected torrent metadata')
+ expect(probe.suggestedFileName).toBe('Album')
+ expect(probe.totalBytes).toBe(3000)
+ expect(probe.torrent.files.map((file) => file.path.replace(/\\/g, '/')).sort()).toEqual([
+ 'Album/a.bin',
+ 'Album/b.bin'
+ ])
+ })
+
+ test('a magnet link, its details fetched from a peer', async ({ plexo }) => {
+ const { client, torrent } = await seed([named(seededBytes(500_000, 4), 'show.mp4')])
+ clients.push(client)
+ const magnet = `${torrent.magnetURI}&x.pe=127.0.0.1:${client.address().port}`
+
+ const probe = await plexo.api.probeUrl(magnet)
+ expect(probe.kind).toBe('torrent')
+ if (probe.kind !== 'torrent') throw new Error('Expected torrent metadata')
+ expect(probe.torrent.infoHash).toBe(torrent.infoHash)
+ expect(probe.suggestedFileName).toBe('show.mp4')
+ expect(probe.totalBytes).toBe(500_000)
+ })
+
+ test('two files that would be saved as one are refused', async ({ plexo }) => {
+ const { client, torrent } = await seed(
+ [named(seededBytes(10, 5), 'Read.txt'), named(seededBytes(10, 6), 'read.txt')],
+ 'Docs'
+ )
+ clients.push(client)
+ const { url, server } = await serveTorrent(torrent.torrentFile)
+ servers.push(server)
+
+ await expect(plexo.api.probeUrl(url)).rejects.toThrow(/saved as the same file/)
+ })
+
+ test('a v2-only torrent is refused', async ({ plexo }) => {
+ // BEP 52: a file tree and per-file piece roots, but none of the v1 piece hashes.
+ const v2Only = (await loadBencode()).encode({
+ info: {
+ name: 'new.bin',
+ 'piece length': 16384,
+ 'meta version': 2,
+ 'file tree': { 'new.bin': { '': { length: 1, 'pieces root': Buffer.alloc(32) } } }
+ }
+ })
+ const { url, server } = await serveTorrent(v2Only)
+ servers.push(server)
+
+ await expect(plexo.api.probeUrl(url)).rejects.toThrow(/BitTorrent v2 only/)
+ })
+
+ test.describe('with nobody to ask', () => {
+ test.use({ appEnv: { PLEXO_E2E_MAGNET_MS: '1500' } })
+
+ test('a magnet link nobody answers gives up', async ({ plexo }) => {
+ const magnet = `magnet:?xt=urn:btih:${'ab'.repeat(20)}&dn=nothing`
+ await expect(plexo.api.probeUrl(magnet)).rejects.toThrow(
+ /No peers responded to this magnet link/
+ )
+ })
+ })
+})
diff --git a/e2e/torrentSwarm.ts b/e2e/torrentSwarm.ts
new file mode 100644
index 0000000..25bcb56
--- /dev/null
+++ b/e2e/torrentSwarm.ts
@@ -0,0 +1,105 @@
+import { mkdtemp, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import type WebTorrent from 'webtorrent'
+import type { ClientOptions, Torrent } from 'webtorrent'
+
+// A small BitTorrent swarm in the test process: a tracker on 127.0.0.1, and webtorrent clients
+// seeding (or fetching) through it. The app finds the peers by announcing to the tracker, as it
+// would on the internet; no DHT is involved anywhere.
+
+// ESM-only: specs are compiled to CommonJS, so these come in through import().
+export const loadWebTorrent = (): Promise<typeof WebTorrent> =>
+ import('webtorrent').then((module) => module.default)
+
+interface TrackerServer {
+ listen(port: number, hostname: string, onListening: () => void): void
+ close(onClose?: () => void): void
+ http: { address(): { port: number } }
+}
+const loadTracker = (): Promise<new (options: object) => TrackerServer> =>
+ import('bittorrent-tracker/server' as string).then((module) => module.default)
+
+/** Nothing beyond the swarm: no DHT, local discovery, port mapping or uTP. */
+export const QUIET: ClientOptions = {
+ dht: false,
+ lsd: false,
+ natUpnp: false,
+ natPmp: false,
+ utp: false
+}
+
+/** A file to seed: its bytes, named as it appears in the torrent. */
+export function named(data: Buffer, name: string): Buffer {
+ return Object.assign(data, { name })
+}
+
+export class Swarm {
+ private clients: WebTorrent[] = []
+ private tracker: TrackerServer | null = null
+ private announce: string[] = []
+
+ async start(): Promise<this> {
+ const Server = await loadTracker()
+ const tracker = new Server({ udp: false, ws: false, stats: false })
+ await new Promise<void>((resolve) => tracker.listen(0, '127.0.0.1', resolve))
+ this.tracker = tracker
+ this.announce = [`http://127.0.0.1:${tracker.http.address().port}/announce`]
+ return this
+ }
+
+ /** A client of the swarm, gone at stop(). */
+ async client(options: ClientOptions = {}): Promise<WebTorrent> {
+ const client = new (await loadWebTorrent())({ ...QUIET, ...options })
+ this.clients.push(client)
+ return client
+ }
+
+ /** A client seeding `files`: one file, or a folder of them named `folder`. The same files,
+ * name and piece length make the same torrent, so seed() again for another seeder of it. */
+ async seed(
+ files: Buffer[],
+ options: { folder?: string; pieceLength?: number; uploadLimit?: number } = {}
+ ): Promise<Torrent> {
+ const client = await this.client({ uploadLimit: options.uploadLimit })
+ // A folder of its own, as leech() has: left to webtorrent, every seeder shares /tmp/webtorrent,
+ // and two tests seeding different files under one name in parallel overwrite each other's —
+ // the seeder then serves pieces that fail verification, forever.
+ const path = await mkdtemp(join(tmpdir(), 'plexo-seed-'))
+ return new Promise((resolve) =>
+ client.seed(
+ files.length === 1 ? files[0] : files,
+ { name: options.folder, pieceLength: options.pieceLength, announce: this.announce, path },
+ resolve
+ )
+ )
+ }
+
+ /** A client fetching `torrent` from the swarm, into a folder of its own. */
+ async leech(torrent: Torrent): Promise<Torrent> {
+ const client = await this.client()
+ const path = await mkdtemp(join(tmpdir(), 'plexo-leech-'))
+ return client.add(torrent.torrentFile, { path })
+ }
+
+ /** What every client has uploaded, all together. */
+ uploaded(): number {
+ return this.clients
+ .flatMap((client) => client.torrents)
+ .reduce((sum, torrent) => sum + torrent.uploaded, 0)
+ }
+
+ async stop(): Promise<void> {
+ await Promise.all(
+ this.clients.splice(0).map((client) => new Promise((done) => client.destroy(done)))
+ )
+ await new Promise<void>((resolve) => (this.tracker ? this.tracker.close(resolve) : resolve()))
+ }
+}
+
+/** `torrent`'s .torrent, written to a file for the app to open. */
+export async function torrentFileOnDisk(torrent: Torrent): Promise<string> {
+ const path = join(await mkdtemp(join(tmpdir(), 'plexo-torrent-')), `${torrent.name}.torrent`)
+ await writeFile(path, torrent.torrentFile)
+ return path
+}
diff --git a/e2e/ui.spec.ts b/e2e/ui.spec.ts
index 22fc6d9..c987c15 100644
--- a/e2e/ui.spec.ts
+++ b/e2e/ui.spec.ts
@@ -1,7 +1,9 @@
-import { writeFile } from 'node:fs/promises'
+import { readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
-import type { Page } from '@playwright/test'
-import { BLOCK, expect, interfacesEnv, NETWORKS, test } from './fixtures'
+import type { Locator, Page } from '@playwright/test'
+import { BLOCK, expect, interfacesEnv, NETWORKS, test, treeSha } from './fixtures'
+import { seededBytes } from './origin'
+import { named, Swarm, torrentFileOnDisk } from './torrentSwarm'
// G. A handful of journeys through the real UI, to prove the screens are wired to the main
// process. Download correctness is covered far more thoroughly by the API-level specs; these
@@ -22,6 +24,95 @@ async function stubNativeUi(
}, destination)
}
+test.describe('a torrent through the UI', () => {
+ test('choose its files, watch its peers, finish', async ({ plexo, dirs }) => {
+ const swarm = await new Swarm().start()
+ try {
+ const files = ['a.bin', 'b.bin', 'c.bin'].map((name, index) =>
+ named(seededBytes(1024 * 1024, 81 + index), name)
+ )
+ // Two seeders, slow enough to look at the download while it runs.
+ const options = { folder: 'Trio', pieceLength: 64 * 1024, uploadLimit: 200 * 1024 }
+ await swarm.seed(files, options)
+ const torrent = await swarm.seed(files, options)
+ await stubNativeUi(plexo, dirs.dest)
+ const page = plexo.page
+
+ const link = await plexo.newDownload()
+ await page.getByRole('button', { name: 'Change…' }).click()
+ await link.fill(await torrentFileOnDisk(torrent))
+ await page.getByRole('checkbox', { name: /b\.bin/ }).click()
+ await plexo.expectNextDownload(
+ treeSha(
+ [files[0], files[2]].map((data) => ({ path: (data as { name?: string }).name!, data }))
+ )
+ )
+ // Started: its own screen opens.
+ await page.getByRole('button', { name: 'Download' }).click()
+
+ // Running: its connections are peers, and its blocks pieces.
+ const peers = page.getByRole('button', { name: /^\d+ peers?/ }).first()
+ await expect(peers).toBeVisible()
+ await peers.click()
+ // Numbered by connection, so whichever peers are connected now.
+ const peerRow = page
+ .getByRole('row')
+ .filter({ hasText: /Peer #\d+/ })
+ .first()
+ await expect(peerRow).toBeVisible()
+ // Only what isn't the usual gets a word: no badge for a peer that's sending.
+ await expect(peerRow).not.toContainText(/RECEIVING|CONNECTED|ACTIVE/)
+ await expect(peerRow).not.toContainText('Peer connection')
+ // Its share of what its network's peers have sent.
+ await expect(peerRow).toContainText(/\d+%/)
+ // Read out in words, not only shown as an arrow; upload only once something was sent.
+ await expect(peerRow).toContainText('Receiving at')
+ await expect(peerRow).not.toContainText('Sending at')
+ await expect(peerRow.getByRole('cell')).toHaveCount(6)
+ // What it runs. A peer has no progress of its own: a dash, not a bar.
+ await expect(peerRow).toContainText('WebTorrent')
+ await expect(peerRow.getByRole('progressbar')).toHaveCount(0)
+ // Each peer's number is its own across the download: no two rows share one, whichever
+ // networks they're on.
+ for (const button of await page.getByRole('button', { name: /^\d+ peers?/ }).all()) {
+ if ((await button.getAttribute('aria-expanded')) !== 'true') await button.click()
+ }
+ const numbers = (await page.getByText(/^Peer #\d+$/).allTextContents()).map((text) =>
+ text.trim()
+ )
+ expect(numbers.length).toBeGreaterThan(0)
+ expect(new Set(numbers).size).toBe(numbers.length)
+ const networks = page.getByRole('table', { name: 'Networks' })
+ await expect(networks.getByRole('columnheader', { name: 'Verified' })).toHaveCount(0)
+ await expect(
+ networks.getByRole('columnheader', { name: 'Progress', exact: true })
+ ).toBeVisible()
+ await expect(networks.getByRole('progressbar').first()).toBeVisible()
+ await expect(
+ page.getByRole('progressbar', { name: 'Download progress', exact: true })
+ ).toHaveCount(0)
+ await expect(peerRow).not.toContainText(/Piece #/)
+ await expect(page.getByText(/^\d+ pieces · /)).toBeVisible()
+ // Each network's upload, even before anything is sent; nothing at the top. A peer that has
+ // sent nothing carries no upload line, and no arrows: a lone download figure needs none.
+ await expect(page.getByText(/^UP \d/)).toHaveCount(0)
+ await expect(networks.getByText(/Uploading at/).first()).toBeAttached()
+ await expect(peerRow).not.toContainText('↑')
+ await expect(peerRow).not.toContainText('↓')
+
+ // Done: two of its three files, with what fetched them.
+ await expect(page.getByRole('button', { name: /Show in (Finder|folder)/ })).toBeVisible({
+ timeout: 60_000
+ })
+ await expect(page.getByText(/^2 of 3 files · /)).toBeVisible()
+ await expect(page.getByText('Peers', { exact: true })).toBeVisible()
+ await expect(page.getByText(/^written in \d+ pieces · uploaded /)).toBeVisible()
+ } finally {
+ await swarm.stop()
+ }
+ })
+})
+
test.describe('UI journeys @smoke', () => {
test('paste a link, start, pause, resume, finish, reveal the file', async ({
plexo,
@@ -32,23 +123,37 @@ test.describe('UI journeys @smoke', () => {
await stubNativeUi(plexo, dirs.dest)
const page = plexo.page
- await page.getByRole('button', { name: 'Browse…' }).click()
- await page.getByRole('textbox', { name: 'LINK' }).fill(origin.url())
- const start = page.getByRole('button', { name: 'Start' })
+ const link = await plexo.newDownload()
+ await page.getByRole('button', { name: 'Change…' }).click()
+ await link.fill(origin.url())
+ const start = page.getByRole('button', { name: 'Download' })
await expect(start).toBeEnabled()
+ await page.getByRole('group', { name: 'Streams' }).getByRole('button', { name: '8' }).click()
const reached = origin.hold(6 * BLOCK)
await plexo.expectNextDownload(origin.sha256)
await start.click()
await reached
-
+ // The streams picked in the dialog reach the download.
+ const { id } = (await plexo.current())!
+ const manifestPath = join(dirs.userData, 'downloads', id, 'manifest.json')
+ await expect
+ .poll(async () => JSON.parse(await readFile(manifestPath, 'utf-8')).requestPayload)
+ .toMatchObject({ streamsPerNetwork: 8 })
+ // Started: its own screen opens.
await page.getByRole('button', { name: 'Pause' }).click()
await expect(page.getByRole('button', { name: 'Resume' })).toBeVisible()
+ await expect(page.getByRole('columnheader', { name: 'Progress', exact: true })).toBeVisible()
+ // An HTTP download's connections are streams, and its blocks chunks.
+ await expect(page.getByRole('button', { name: /^\d+ streams?/ }).first()).toBeVisible()
+ await expect(page.getByText(/^\d+ chunks · /)).toBeVisible()
origin.release()
await page.getByRole('button', { name: 'Resume' }).click()
- const reveal = page.getByRole('button', { name: /Reveal in Finder|Show in folder/ })
+ const reveal = page.getByRole('button', { name: /Show in (Finder|folder)/ })
await expect(reveal).toBeVisible()
+ await expect(page.getByText('Streams', { exact: true })).toBeVisible()
+ await expect(page.getByText(/^written in \d+ chunks/)).toBeVisible()
await reveal.click()
const { destinationPath } = (await plexo.current())!
await expect
@@ -58,7 +163,7 @@ test.describe('UI journeys @smoke', () => {
.toEqual([destinationPath])
})
- test('cancel through the confirmation dialog, then "Download Again"', async ({
+ test('delete through the confirmation dialog, then download it again', async ({
plexo,
serve,
dirs
@@ -66,44 +171,46 @@ test.describe('UI journeys @smoke', () => {
const origin = await serve({ size: SIZE })
await stubNativeUi(plexo, dirs.dest)
const page = plexo.page
- await page.getByRole('button', { name: 'Browse…' }).click()
- await page.getByRole('textbox', { name: 'LINK' }).fill(origin.url())
+ let link = await plexo.newDownload()
+ await page.getByRole('button', { name: 'Change…' }).click()
+ await link.fill(origin.url())
const reached = origin.hold(6 * BLOCK)
- await page.getByRole('button', { name: 'Start' }).click()
+ await page.getByRole('button', { name: 'Download' }).click()
await reached
- await page.getByRole('button', { name: 'Cancel', exact: true }).click()
- await page.getByRole('button', { name: 'Cancel download' }).click()
+ await page.getByRole('button', { name: 'Cancel download…' }).click()
+ await page.getByRole('button', { name: 'Cancel download', exact: true }).click()
origin.release()
+ // Gone, with what it had downloaded.
+ await expect(page.getByText('No downloads yet')).toBeVisible()
- await page.getByRole('button', { name: 'Download Again' }).click()
+ link = await plexo.newDownload()
+ await link.fill(origin.url())
await plexo.expectNextDownload(origin.sha256)
- await page.getByRole('button', { name: 'Start' }).click({ timeout: 5000 })
- await expect(
- page.getByRole('button', { name: /Reveal in Finder|Show in folder/ })
- ).toBeVisible()
+ await page.getByRole('button', { name: 'Download' }).click({ timeout: 5000 })
+ await plexo.waitForStatus('completed')
})
- test('a link the server rejects shows the error and keeps Start disabled', async ({
+ test('a link the server rejects shows the error and keeps Download disabled', async ({
plexo,
serve
}) => {
const origin = await serve({ size: SIZE })
origin.setRule(() => ({ status: 404 }))
const page = plexo.page
- await page.getByRole('textbox', { name: 'LINK' }).fill(origin.url())
- await expect(page.getByText(/could not be found/)).toBeVisible()
- await expect(page.getByRole('button', { name: 'Start' })).toBeDisabled()
+ await (await plexo.newDownload()).fill(origin.url())
+ await expect(page.getByText(/couldn’t be found/)).toBeVisible()
+ await expect(page.getByRole('button', { name: 'Download' })).toBeDisabled()
})
test('a completed download is shown again after a restart', async ({ plexo, serve }) => {
const origin = await serve({ size: SIZE })
await plexo.start(origin.url(), origin.sha256)
- await plexo.waitForStatus('completed')
+ const { fileName } = await plexo.waitForStatus('completed')
await plexo.relaunch()
- await expect(
- plexo.page.getByRole('button', { name: /Reveal in Finder|Show in folder/ })
- ).toBeVisible()
+ // Listed under Finished; opened, it shows as it did when it finished.
+ await plexo.page.getByRole('button', { name: `Open ${fileName}` }).click()
+ await expect(plexo.page.getByRole('button', { name: /Show in (Finder|folder)/ })).toBeVisible()
})
})
@@ -127,20 +234,32 @@ test.describe('settings @smoke', () => {
await themeToggle.click()
await stubNativeUi(plexo, dirs.dest)
- await page().getByRole('button', { name: 'Browse…' }).click()
-
+ await plexo.newDownload()
+ await page().getByRole('button', { name: 'Change…' }).click()
+ await page().keyboard.press('Escape')
+ // A function: the window, and so the page, is a new one after a relaunch.
+ const networksMenu = (): Locator =>
+ page()
+ .getByRole('button', { name: /network/ })
+ .first()
+ .first()
+ await networksMenu().click()
await page().getByRole('button', { name: 'Edit network' }).first().click()
await page().getByRole('textbox', { name: 'Name' }).fill('Office fibre')
await page().getByRole('button', { name: 'Violet' }).click()
await page().getByRole('button', { name: 'Done' }).click()
+ await page().keyboard.press('Escape')
const expectAllKept = async (): Promise<void> => {
- // Waiting on the titlebar indicator first means the update check has answered, so the
- // dialog's absence below is a real "stayed dismissed", not "not checked yet".
+ // Waiting on the status bar's indicator first means the update check has answered, so
+ // the dialog's absence below is a real "stayed dismissed", not "not checked yet".
await expect(page().getByRole('link', { name: 'Update available: 9.9.9' })).toBeVisible()
await expect(page().getByRole('alertdialog')).toBeHidden()
await expect(page().getByRole('button', { name: labelAfterSwitch })).toBeVisible()
+ await plexo.newDownload()
await expect(page().getByText(dirs.dest)).toBeVisible()
+ await page().keyboard.press('Escape')
+ await networksMenu().click()
await expect(page().getByText('Office fibre')).toBeVisible()
await page().getByRole('button', { name: 'Edit network' }).first().click()
await expect(page().getByRole('button', { name: 'Violet' })).toHaveAttribute(
@@ -148,6 +267,7 @@ test.describe('settings @smoke', () => {
'true'
)
await page().keyboard.press('Escape')
+ await page().keyboard.press('Escape')
}
// No waiting for saves: a user doesn't either.
@@ -163,10 +283,14 @@ test.describe('settings @smoke', () => {
dirs
}) => {
const settingsPath = join(dirs.userData, 'app-settings.json')
- // The TO row, as the user sees it — compared whole, so no platform's idea of the default
- // folder is baked into the test.
- const choices = (): Promise<string> =>
- plexo.page.getByText('TO', { exact: true }).locator('..').innerText()
+ // New download's "Save to" row, as the user sees it — compared whole, so no platform's idea
+ // of the default folder is baked into the test.
+ const choices = async (): Promise<string> => {
+ await plexo.newDownload()
+ const row = await plexo.page.getByText('Save to', { exact: true }).locator('..').innerText()
+ await plexo.page.keyboard.press('Escape')
+ return row
+ }
const fresh = await choices()
await plexo.quit()
@@ -184,15 +308,15 @@ test.describe('settings @smoke', () => {
test.describe('no networks', () => {
test.use({ appEnv: { PLEXO_E2E_INTERFACES: '' } })
- test('a network appearing takes you back to the start screen @smoke', async ({ plexo }) => {
- await expect(plexo.page.getByText('No networks to combine')).toBeVisible()
+ test('a network appearing makes the list ready for downloads @smoke', async ({ plexo }) => {
+ await expect(plexo.page.getByText('No networks connected')).toBeVisible()
await plexo.evaluateMain(
(_electron, value) => {
process.env['PLEXO_E2E_INTERFACES'] = value
},
interfacesEnv({ a: NETWORKS['a'] })
)
- await plexo.page.getByRole('button', { name: 'Scan Again' }).click()
- await expect(plexo.page.getByRole('textbox', { name: 'LINK' })).toBeVisible()
+ await plexo.page.getByRole('button', { name: 'Scan again' }).click()
+ await expect(plexo.page.getByText('No downloads yet')).toBeVisible()
})
})
diff --git a/electron-builder.yml b/electron-builder.yml
index 7c70b9b..c41d887 100644
--- a/electron-builder.yml
+++ b/electron-builder.yml
@@ -15,6 +15,9 @@ files:
asarUnpack:
- resources/**
win:
+ # No protocols or fileAssociations: the NSIS installer would register Plexo as *the* handler for
+ # magnet links and .torrent files, taking them from a torrent client the user already has.
+ # A .torrent can still be opened with Plexo through "Open with".
executableName: plexo
target:
- target: nsis
@@ -37,6 +40,17 @@ mac:
entitlementsInherit: build/entitlements.mac.plist
extendInfo:
- NSDownloadsFolderUsageDescription: Plexo saves downloaded files to your Downloads folder.
+ # Magnet links and .torrent files can be opened with Plexo, as one choice among others: it's
+ # never made the default over a torrent client the user already has (LSHandlerRank).
+ - CFBundleURLTypes:
+ - CFBundleURLName: Magnet link
+ CFBundleURLSchemes: [magnet]
+ CFBundleDocumentTypes:
+ - CFBundleTypeName: Torrent
+ CFBundleTypeRole: Viewer
+ LSHandlerRank: Alternate
+ CFBundleTypeExtensions: [torrent]
+ LSItemContentTypes: [org.bittorrent.torrent]
notarize: false
dmg:
artifactName: ${name}-${version}-${arch}.${ext}
@@ -48,6 +62,8 @@ linux:
arch: [x64, arm64]
maintainer: electronjs.org
category: Utility
+ # Offered for magnet links and .torrent files ("Open with"), not made their default.
+ mimeTypes: [x-scheme-handler/magnet, application/x-bittorrent]
appImage:
artifactName: ${name}-${version}-${arch}.${ext}
npmRebuild: false
diff --git a/package-lock.json b/package-lock.json
index 4e06862..532d422 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,21 +1,25 @@
{
"name": "plexo",
- "version": "1.0.0-rc.11",
+ "version": "1.0.0-rc.12",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "plexo",
- "version": "1.0.0-rc.11",
+ "version": "1.0.0-rc.12",
"hasInstallScript": true,
"dependencies": {
"@base-ui/react": "^1.8.0",
"@electron-toolkit/preload": "^3.0.2",
"@electron-toolkit/utils": "^4.0.0",
+ "bittorrent-peerid": "2.0.2",
"class-variance-authority": "^0.7.1",
"cn": "^0.3.0",
+ "fs-chunk-store": "5.0.1",
"koffi": "^2.16.3",
"lucide-react": "^1.47.0",
+ "parse-torrent": "11.0.24",
+ "webtorrent": "3.0.21",
"zustand": "^5.0.15"
},
"devDependencies": {
@@ -36,6 +40,7 @@
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"fast-check": "^4.10.1",
+ "patch-package": "8.0.1",
"prettier": "^3.7.4",
"react": "^19.2.1",
"react-dom": "^19.2.1",
@@ -717,21 +722,6 @@
"node": ">=12.0.0"
}
},
- "node_modules/@electron/osx-sign/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
"node_modules/@electron/osx-sign/node_modules/isbinaryfile": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.10.tgz",
@@ -745,29 +735,6 @@
"url": "https://github.com/sponsors/gjtorikian/"
}
},
- "node_modules/@electron/osx-sign/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "universalify": "^2.0.0"
- },
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
- }
- },
- "node_modules/@electron/osx-sign/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 10.0.0"
- }
- },
"node_modules/@electron/rebuild": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.2.0.tgz",
@@ -2346,6 +2313,23 @@
"win32"
]
},
+ "node_modules/@silentbot1/nat-api": {
+ "version": "0.4.9",
+ "resolved": "https://registry.npmjs.org/@silentbot1/nat-api/-/nat-api-0.4.9.tgz",
+ "integrity": "sha512-Bm2Fr0sJyGr4B/XgKjQxjGe7Rzs/OlK91OIHsghObxhP3Y4j2y8o7Xjlledu/pxzFEIWaTbZIBSl8ABqoP/WhQ==",
+ "license": "MIT",
+ "dependencies": {
+ "chrome-dgram": "^3.0.6",
+ "cross-fetch-ponyfill": "^1.0.3",
+ "debug": "^4.4.0",
+ "default-gateway": "^7.2.2",
+ "unordered-array-remove": "^1.0.2",
+ "xml2js": "^0.6.2"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
"node_modules/@sindresorhus/is": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz",
@@ -2710,6 +2694,50 @@
"vite": "^5.2.0 || ^6 || ^7 || ^8"
}
},
+ "node_modules/@thaunknown/simple-peer": {
+ "version": "10.1.2",
+ "resolved": "https://registry.npmjs.org/@thaunknown/simple-peer/-/simple-peer-10.1.2.tgz",
+ "integrity": "sha512-pcG35e815X43Crr/HVmOWlbsx9Jz3KD27HOhy/BwIjQkDlafzJFl0NKb8B+bf+bsnfQL/BB6Z44cMZPQaYHLYQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "err-code": "^3.0.1",
+ "streamx": "^2.28.0",
+ "uint8-util": "^2.3.2",
+ "webrtc-polyfill": "^1.2.2"
+ }
+ },
+ "node_modules/@thaunknown/simple-peer/node_modules/err-code": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/err-code/-/err-code-3.0.1.tgz",
+ "integrity": "sha512-GiaH0KJUewYok+eeY05IIgjtAe4Yltygk9Wqp1V5yVWLdhf0hYZchRjNIT9bb0mSwRcIusT3cx7PJUf3zEIfUA==",
+ "license": "MIT"
+ },
+ "node_modules/@thaunknown/simple-websocket": {
+ "version": "9.1.5",
+ "resolved": "https://registry.npmjs.org/@thaunknown/simple-websocket/-/simple-websocket-9.1.5.tgz",
+ "integrity": "sha512-FTrycAOMeJIHxHxH4iiq0EHMlmITvim04FGpwRcrytykg4jCFPaRYJqjo8wvBVx88TYfxrtQCaHhzaKLDKS71w==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "queue-microtask": "^1.2.3",
+ "streamx": "^2.28.0",
+ "uint8-util": "^2.3.2",
+ "ws": "^8.21.1"
+ }
+ },
+ "node_modules/@thaunknown/thirty-two": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/@thaunknown/thirty-two/-/thirty-two-1.0.6.tgz",
+ "integrity": "sha512-Uz2kFb0cNeHg7hds8BtI/umcwzaSMUdbkeQgZrIZQbp3gWRFjrvrvBHNEB6SQYChVxC3rWHovKx1Ya/vSRRMYA==",
+ "license": "MIT",
+ "dependencies": {
+ "uint8-util": "^2.3.2"
+ },
+ "engines": {
+ "node": ">=0.2.6"
+ }
+ },
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -3143,6 +3171,16 @@
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
+ "node_modules/@webtorrent/http-node": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/@webtorrent/http-node/-/http-node-1.3.0.tgz",
+ "integrity": "sha512-GWZQKroPES4z91Ijx6zsOsb7+USOxjy66s8AoTWg0HiBBdfnbtf9aeh3Uav0MgYn4BL8Q7tVSUpd0gGpngKGEQ==",
+ "license": "MIT",
+ "dependencies": {
+ "freelist": "^1.0.3",
+ "http-parser-js": "^0.4.3"
+ }
+ },
"node_modules/@xmldom/xmldom": {
"version": "0.8.15",
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.15.tgz",
@@ -3153,6 +3191,13 @@
"node": ">=10.0.0"
}
},
+ "node_modules/@yarnpkg/lockfile": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz",
+ "integrity": "sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ==",
+ "dev": true,
+ "license": "BSD-2-Clause"
+ },
"node_modules/abbrev": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz",
@@ -3163,6 +3208,18 @@
"node": "^20.17.0 || >=22.9.0"
}
},
+ "node_modules/abort-controller": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
+ "license": "MIT",
+ "dependencies": {
+ "event-target-shim": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=6.5"
+ }
+ },
"node_modules/acorn": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
@@ -3186,6 +3243,15 @@
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
+ "node_modules/addr-to-ip-port": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/addr-to-ip-port/-/addr-to-ip-port-2.0.0.tgz",
+ "integrity": "sha512-9bYbtjamtdLHZSqVIUXhilOryNPiL+x+Q5J/Unpg4VY3ZIkK3fT52UoErj1NdUeVm3J1t2iBEAur4Ywbl/bahw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
"node_modules/agent-base": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
@@ -3359,44 +3425,6 @@
"node": ">=8"
}
},
- "node_modules/app-builder-lib/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/app-builder-lib/node_modules/fs-extra/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "universalify": "^2.0.0"
- },
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
- }
- },
- "node_modules/app-builder-lib/node_modules/fs-extra/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 10.0.0"
- }
- },
"node_modules/app-builder-lib/node_modules/semver": {
"version": "7.7.4",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
@@ -3637,6 +3665,20 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/b4a": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.9.0.tgz",
+ "integrity": "sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "react-native-b4a": "*"
+ },
+ "peerDependenciesMeta": {
+ "react-native-b4a": {
+ "optional": true
+ }
+ }
+ },
"node_modules/balanced-match": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
@@ -3647,11 +3689,134 @@
"node": "18 || 20 || >=22"
}
},
+ "node_modules/bare-addon-resolve": {
+ "version": "1.10.1",
+ "resolved": "https://registry.npmjs.org/bare-addon-resolve/-/bare-addon-resolve-1.10.1.tgz",
+ "integrity": "sha512-F/SD2du8keuYSb4xipnGz5j2E6yhNdHA8ZVxtHae6h2uOrpBIjjbhXvjzKZbr5XUOzqBzh/i8GVFycj2DlFQIA==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "bare-module-resolve": "^1.10.0",
+ "bare-semver": "^1.0.0"
+ },
+ "peerDependencies": {
+ "bare-url": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-url": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-events": {
+ "version": "2.9.2",
+ "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.2.tgz",
+ "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "bare-abort-controller": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-fs": {
+ "version": "4.8.2",
+ "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.2.tgz",
+ "integrity": "sha512-+ZI68KHMUvosXfKbg/UOHK0tbCdRnegbvPEdEcZ3Nd6TetieQsJPRXBRXPdLyy8+3VSEbPXtsumTpEtt78xv9w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.5.4",
+ "bare-path": "^3.0.0",
+ "bare-stream": "^2.6.4",
+ "bare-url": "^2.2.2",
+ "fast-fifo": "^1.3.2"
+ },
+ "engines": {
+ "bare": ">=1.28.0"
+ },
+ "peerDependencies": {
+ "bare-buffer": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-buffer": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-module-resolve": {
+ "version": "1.12.5",
+ "resolved": "https://registry.npmjs.org/bare-module-resolve/-/bare-module-resolve-1.12.5.tgz",
+ "integrity": "sha512-VOncxVvVk8SQVw9vhcBnoTJD/74aR5DgdRPCm0gQ7uB5MsWpBJnoCeJrwEHKiz09O83ndf3NTjsz3LEuFxAq5A==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "bare-semver": "^1.0.0"
+ },
+ "peerDependencies": {
+ "bare-url": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-url": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-path": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.2.tgz",
+ "integrity": "sha512-ZyKbsuuqK6Ag0K8pX6V5Txq6XeJRvY+wXucnFGRjiyVYP9YWDpIQugk/b+enRYrEYBJaqLzghRQpXPMR7341Nw==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/bare-semver": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/bare-semver/-/bare-semver-1.1.0.tgz",
+ "integrity": "sha512-1Hw5qJ7hXdVt3uPUqjeFTuxyvBUJauvz5A1I2jk8gzjZMHp04n//6nV9MDbG9CMw78JHY2lGV0w6s//LrASm2w==",
+ "license": "Apache-2.0",
+ "optional": true
+ },
+ "node_modules/bare-stream": {
+ "version": "2.13.4",
+ "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.4.tgz",
+ "integrity": "sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.8.1",
+ "streamx": "^2.25.0",
+ "teex": "^1.0.1"
+ },
+ "peerDependencies": {
+ "bare-abort-controller": "*",
+ "bare-buffer": "*",
+ "bare-events": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ },
+ "bare-buffer": {
+ "optional": true
+ },
+ "bare-events": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-url": {
+ "version": "2.5.4",
+ "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.4.tgz",
+ "integrity": "sha512-Gxa7UVWBr0/edU1b+TJhn/AZvMQUj9OGspvYsaTYQrAbZA4BOTZGL3LiZxvD+CeMlDH4juwD84+eTAp/bLYW5g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-path": "^3.0.0"
+ }
+ },
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
- "dev": true,
"funding": [
{
"type": "github",
@@ -3681,69 +3846,339 @@
"node": ">=6.0.0"
}
},
- "node_modules/bluebird": {
- "version": "3.7.2",
- "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
- "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==",
- "dev": true,
- "license": "MIT"
+ "node_modules/bencode": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/bencode/-/bencode-4.0.1.tgz",
+ "integrity": "sha512-/bCR3FvgfB8AZk4LlowShU+nfaTNRM2vruJ9aejDa5LpgkCoRjFyEauFiZFxbpxVxQbBFapYCN42Er2dkE/Qgw==",
+ "license": "MIT",
+ "dependencies": {
+ "uint8-util": "^2.2.2"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
},
- "node_modules/boolean": {
- "version": "3.2.0",
- "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",
- "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==",
- "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",
- "dev": true,
+ "node_modules/bep53-range": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/bep53-range/-/bep53-range-2.0.1.tgz",
+ "integrity": "sha512-VWN7j7sqUssWD6ROZe2m709YL3u5A1IAx1qvAbH3DAhszHt4WPvCzJLRJ+mzmZn1qWIb4mpflwdn95qezz3n8g==",
"license": "MIT",
- "optional": true
+ "engines": {
+ "node": ">=12.20.0"
+ }
},
- "node_modules/brace-expansion": {
- "version": "5.0.9",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
- "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
- "dev": true,
+ "node_modules/bitfield": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/bitfield/-/bitfield-5.0.1.tgz",
+ "integrity": "sha512-81mvFHCa0L1HsDdKVCTkPKZZ6KFdyXgfQNoneFT7Qk5/PZeBWdPkTFa4KttbR8uHszfjiqOJbeahLOPfCqw4cw==",
"license": "MIT",
- "dependencies": {
- "balanced-match": "^4.0.2"
- },
"engines": {
- "node": "20 || >=22"
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
}
},
- "node_modules/browserslist": {
- "version": "4.28.9",
- "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.9.tgz",
- "integrity": "sha512-EWazOblFYUvlGZcfGhPUPmYh3nikUxBVb+y9MJun5f3hBi812X+8MSQTujLBtgK3cf51fJWbWfOjyeO954d+Eg==",
- "dev": true,
+ "node_modules/bittorrent-dht": {
+ "version": "11.0.12",
+ "resolved": "https://registry.npmjs.org/bittorrent-dht/-/bittorrent-dht-11.0.12.tgz",
+ "integrity": "sha512-bFmQq874HMIBon/6KNMf/U1OG+UxJ0UzI9oPra2IRlZLuPA7VwBiA7uEpWaO2ww8G76OFjxB1p1XCOS94FuCPQ==",
"funding": [
{
- "type": "opencollective",
- "url": "https://opencollective.com/browserslist"
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
},
{
- "type": "tidelift",
- "url": "https://tidelift.com/funding/github/npm/browserslist"
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
},
{
- "type": "github",
- "url": "https://github.com/sponsors/ai"
+ "type": "consulting",
+ "url": "https://feross.org/support"
}
],
"license": "MIT",
"dependencies": {
- "baseline-browser-mapping": "^2.11.20",
- "caniuse-lite": "^1.0.30001810",
- "electron-to-chromium": "^1.5.420",
- "node-releases": "^2.0.54",
- "update-browserslist-db": "^1.3.2"
+ "bencode": "^4.0.1",
+ "debug": "^4.4.3",
+ "k-bucket": "^5.1.0",
+ "k-rpc": "^5.1.0",
+ "last-one-wins": "^1.0.4",
+ "lru": "^3.1.0",
+ "randombytes": "^2.1.0",
+ "record-cache": "^1.2.0"
},
- "bin": {
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/bittorrent-lsd": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/bittorrent-lsd/-/bittorrent-lsd-2.0.3.tgz",
+ "integrity": "sha512-FE4ImhpJZo8ahzDS/Qk1Ol+3Ea1sIhCPWE2WSjiv1s8YoCSEf7JBL3bbCJW5hdVNK5ohtZ3vH5xGjZ9QWFiatQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "chrome-dgram": "^3.0.6",
+ "debug": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/bittorrent-peerid": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/bittorrent-peerid/-/bittorrent-peerid-2.0.2.tgz",
+ "integrity": "sha512-V2iUvbtv31uLA8XFxbhB3f/fKTxWGaa6FI/3wSm93YAS/DS8IkeRWCyYGQ13Xbc9ajR40nsxNjGtVt7OHB3VOQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/bittorrent-protocol": {
+ "version": "5.0.9",
+ "resolved": "https://registry.npmjs.org/bittorrent-protocol/-/bittorrent-protocol-5.0.9.tgz",
+ "integrity": "sha512-GIRHD1W9tFIkLbJP6OYZs6sWFJbfxaRnx4FYX1hvig/9+Ui691ZvJcQ+y6oSUmV7fh7/ehKT1lICh1/UEYsAcw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "bencode": "^4.0.1",
+ "bitfield": "^5.0.1",
+ "debug": "^4.4.3",
+ "streamx": "^2.28.0",
+ "throughput": "^1.0.2",
+ "uint8-util": "^2.3.2",
+ "unordered-array-remove": "^1.0.2"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/bittorrent-tracker": {
+ "version": "11.2.3",
+ "resolved": "https://registry.npmjs.org/bittorrent-tracker/-/bittorrent-tracker-11.2.3.tgz",
+ "integrity": "sha512-i9pWOf1YAQWyTjDnpWwcTfEYDi5XwqD6f48pKmIHByb7x2XU86CqK+IsyMy1buKkDZ3rDKht2jIeKCZf1Dmd8g==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@thaunknown/simple-peer": "^10.0.8",
+ "@thaunknown/simple-websocket": "^9.1.3",
+ "bencode": "^4.0.0",
+ "bittorrent-peerid": "^2.0.0",
+ "chrome-dgram": "^3.0.6",
+ "compact2string": "^1.4.1",
+ "cross-fetch-ponyfill": "^1.0.3",
+ "debug": "^4.3.4",
+ "ip": "^2.0.1",
+ "lru": "^3.1.0",
+ "minimist": "^1.2.8",
+ "once": "^1.4.0",
+ "queue-microtask": "^1.2.3",
+ "random-iterate": "^1.0.1",
+ "run-parallel": "^1.2.0",
+ "run-series": "^1.1.9",
+ "socks": "^2.8.3",
+ "string2compact": "^2.0.1",
+ "uint8-util": "^2.2.5",
+ "unordered-array-remove": "^1.0.2",
+ "ws": "^8.17.0"
+ },
+ "bin": {
+ "bittorrent-tracker": "bin/cmd.js"
+ },
+ "engines": {
+ "node": ">=16.0.0"
+ },
+ "optionalDependencies": {
+ "bufferutil": "^4.0.8",
+ "utf-8-validate": "^6.0.4"
+ }
+ },
+ "node_modules/bl": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer": "^5.5.0",
+ "inherits": "^2.0.4",
+ "readable-stream": "^3.4.0"
+ }
+ },
+ "node_modules/bl/node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/block-iterator": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/block-iterator/-/block-iterator-1.1.2.tgz",
+ "integrity": "sha512-yAHUP44v2K25xLPdrgVTgwtuQctlullzjczu9CoUZom5AP3g4p1R1+aWHjS1GHG9JtcSUVUnbEPiuXiW5YZ24w==",
+ "license": "MIT"
+ },
+ "node_modules/bluebird": {
+ "version": "3.7.2",
+ "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
+ "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/boolean": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",
+ "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==",
+ "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",
+ "dev": true,
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/brace-expansion": {
+ "version": "5.0.9",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
+ "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^4.0.2"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
+ "node_modules/braces": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
+ "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fill-range": "^7.1.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/browserslist": {
+ "version": "4.28.9",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.9.tgz",
+ "integrity": "sha512-EWazOblFYUvlGZcfGhPUPmYh3nikUxBVb+y9MJun5f3hBi812X+8MSQTujLBtgK3cf51fJWbWfOjyeO954d+Eg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "baseline-browser-mapping": "^2.11.20",
+ "caniuse-lite": "^1.0.30001810",
+ "electron-to-chromium": "^1.5.420",
+ "node-releases": "^2.0.54",
+ "update-browserslist-db": "^1.3.2"
+ },
+ "bin": {
"browserslist": "cli.js"
},
"engines": {
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
+ "node_modules/buffer": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.1.13"
+ }
+ },
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -3751,6 +4186,20 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/bufferutil": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.1.0.tgz",
+ "integrity": "sha512-ZMANVnAixE6AWWnPzlW2KpUrxhm9woycYvPOo67jWHyFowASTEd9s+QN1EIMsSDtwhIxN4sWE1jotpuDUIgyIw==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "node-gyp-build": "^4.3.0"
+ },
+ "engines": {
+ "node": ">=6.14.2"
+ }
+ },
"node_modules/builder-util": {
"version": "26.15.3",
"resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.15.3.tgz",
@@ -3791,44 +4240,6 @@
"node": ">=12.0.0"
}
},
- "node_modules/builder-util/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/builder-util/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "universalify": "^2.0.0"
- },
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
- }
- },
- "node_modules/builder-util/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 10.0.0"
- }
- },
"node_modules/bytestreamjs": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/bytestreamjs/-/bytestreamjs-2.0.1.tgz",
@@ -3849,6 +4260,30 @@
"node": ">=8"
}
},
+ "node_modules/cache-chunk-store": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/cache-chunk-store/-/cache-chunk-store-3.2.2.tgz",
+ "integrity": "sha512-2lJdWbgHFFxcSth9s2wpId3CR3v1YC63KjP4T9WhpW7LWlY7Hiiei3QwwqzkWqlJTfR8lSy9F5kRQECeyj+yQA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "lru": "^3.1.0",
+ "queue-microtask": "^1.2.3"
+ }
+ },
"node_modules/cacheable-lookup": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz",
@@ -3986,6 +4421,62 @@
"node": ">=18"
}
},
+ "node_modules/chrome-dgram": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/chrome-dgram/-/chrome-dgram-3.0.6.tgz",
+ "integrity": "sha512-bqBsUuaOiXiqxXt/zA/jukNJJ4oaOtc7ciwqJpZVEaaXwwxqgI2/ZdG02vXYWUhHGziDlvGMQWk0qObgJwVYKA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.4",
+ "run-series": "^1.1.9"
+ }
+ },
+ "node_modules/chrome-dns": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/chrome-dns/-/chrome-dns-1.0.1.tgz",
+ "integrity": "sha512-HqsYJgIc8ljJJOqOzLphjAs79EUuWSX3nzZi2LNkzlw3GIzAeZbaSektC8iT/tKvLqZq8yl1GJu5o6doA4TRbg==",
+ "license": "MIT",
+ "dependencies": {
+ "chrome-net": "^3.3.2"
+ }
+ },
+ "node_modules/chrome-net": {
+ "version": "3.3.4",
+ "resolved": "https://registry.npmjs.org/chrome-net/-/chrome-net-3.3.4.tgz",
+ "integrity": "sha512-Jzy2EnzmE+ligqIZUsmWnck9RBXLuUy6CaKyuNMtowFG3ZvLt8d+WBJCTPEludV0DHpIKjAOlwjFmTaEdfdWCw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.1"
+ }
+ },
"node_modules/chromium-pickle-js": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/chromium-pickle-js/-/chromium-pickle-js-0.2.0.tgz",
@@ -3993,6 +4484,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/chunk-store-iterator": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/chunk-store-iterator/-/chunk-store-iterator-1.0.4.tgz",
+ "integrity": "sha512-LGjzJNmk7W1mrdaBoJNztPumT2ACmgjHmI1AMm8aeGYOl4+LKaYC/yfnx27i++LiAtoe/dR+3jC8HRzb6gW4/A==",
+ "license": "MIT",
+ "dependencies": {
+ "block-iterator": "^1.1.1"
+ }
+ },
"node_modules/ci-info": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz",
@@ -4113,6 +4613,15 @@
"node": ">= 6"
}
},
+ "node_modules/compact2string": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/compact2string/-/compact2string-1.4.1.tgz",
+ "integrity": "sha512-3D+EY5nsRhqnOwDxveBv5T8wGo4DEvYxjDtPGmdOX+gfr5gE92c2RC0w2wa+xEefm07QuVqqcF3nZJUZ92l/og==",
+ "license": "BSD",
+ "dependencies": {
+ "ipaddr.js": ">= 0.1.5"
+ }
+ },
"node_modules/compare-version": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/compare-version/-/compare-version-0.1.2.tgz",
@@ -4144,6 +4653,66 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/cpus": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/cpus/-/cpus-1.0.3.tgz",
+ "integrity": "sha512-PXHBvGLuL69u55IkLa5e5838fLhIMHxmkV4ge42a8alGyn7BtawYgI0hQ849EedvtHIOLNNH3i6eQU1BiE9SUA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/create-torrent": {
+ "version": "6.1.3",
+ "resolved": "https://registry.npmjs.org/create-torrent/-/create-torrent-6.1.3.tgz",
+ "integrity": "sha512-/XARuf6/TmOLICFkUU7pf4KPL/vlIFyk2xOJjQ4np8Xzl8xLt9W7KJps1EVnZyUCMHbAm5xYfCoDrgVw3F4FxA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "bencode": "^4.0.1",
+ "block-iterator": "^1.1.2",
+ "fast-readable-async-iterator": "^2.0.0",
+ "is-file": "^1.0.0",
+ "join-async-iterator": "^1.1.1",
+ "junk": "^4.0.1",
+ "minimist": "^1.2.8",
+ "once": "^1.4.0",
+ "piece-length": "^2.0.1",
+ "queue-microtask": "^1.2.3",
+ "run-parallel": "^1.2.0",
+ "uint8-util": "^2.3.2"
+ },
+ "bin": {
+ "create-torrent": "bin/cmd.js"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/cross-dirname": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz",
@@ -4153,11 +4722,20 @@
"optional": true,
"peer": true
},
+ "node_modules/cross-fetch-ponyfill": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/cross-fetch-ponyfill/-/cross-fetch-ponyfill-1.0.3.tgz",
+ "integrity": "sha512-uOBkDhUAGAbx/FEzNKkOfx3w57H8xReBBXoZvUnOKTI0FW0Xvrj3GrYv2iZXUqlffC1LMGfQzhmBM/ke+6eTDA==",
+ "license": "MIT",
+ "dependencies": {
+ "abort-controller": "^3.0.0",
+ "node-fetch": "^3.3.0"
+ }
+ },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
@@ -4172,14 +4750,12 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
- "dev": true,
"license": "ISC"
},
"node_modules/cross-spawn/node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
- "dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
@@ -4198,6 +4774,15 @@
"devOptional": true,
"license": "MIT"
},
+ "node_modules/data-uri-to-buffer": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
+ "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
"node_modules/data-view-buffer": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",
@@ -4273,7 +4858,6 @@
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
"integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"mimic-response": "^3.1.0"
@@ -4289,7 +4873,6 @@
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
"integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=10"
@@ -4298,6 +4881,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/deep-extend": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
+ "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
"node_modules/deep-is": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@@ -4305,6 +4897,18 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/default-gateway": {
+ "version": "7.2.2",
+ "resolved": "https://registry.npmjs.org/default-gateway/-/default-gateway-7.2.2.tgz",
+ "integrity": "sha512-AD7TrdNNPXRZIGw63dw+lnGmT4v7ggZC5NHNJgAYWm5njrwoze1q5JSAW9YuLy2tjnoLUG/r8FEB93MCh9QJPg==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "execa": "^7.1.1"
+ },
+ "engines": {
+ "node": ">= 16"
+ }
+ },
"node_modules/defer-to-connect": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz",
@@ -4365,7 +4969,6 @@
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
- "dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=8"
@@ -4428,48 +5031,10 @@
"dev": true,
"license": "MIT",
"dependencies": {
- "app-builder-lib": "26.15.3",
- "builder-util": "26.15.3",
- "fs-extra": "^10.1.0",
- "js-yaml": "^4.1.0"
- }
- },
- "node_modules/dmg-builder/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/dmg-builder/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "universalify": "^2.0.0"
- },
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
- }
- },
- "node_modules/dmg-builder/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 10.0.0"
+ "app-builder-lib": "26.15.3",
+ "builder-util": "26.15.3",
+ "fs-extra": "^10.1.0",
+ "js-yaml": "^4.1.0"
}
},
"node_modules/doctrine": {
@@ -4612,44 +5177,6 @@
"electron-winstaller": "5.4.0"
}
},
- "node_modules/electron-builder/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/electron-builder/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "universalify": "^2.0.0"
- },
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
- }
- },
- "node_modules/electron-builder/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 10.0.0"
- }
- },
"node_modules/electron-publish": {
"version": "26.15.3",
"resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.15.3.tgz",
@@ -4668,44 +5195,6 @@
"mime": "^2.5.2"
}
},
- "node_modules/electron-publish/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/electron-publish/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "universalify": "^2.0.0"
- },
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
- }
- },
- "node_modules/electron-publish/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 10.0.0"
- }
- },
"node_modules/electron-to-chromium": {
"version": "1.5.427",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.427.tgz",
@@ -4807,7 +5296,6 @@
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
"integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"once": "^1.4.0"
@@ -5103,6 +5591,12 @@
"node": ">=6"
}
},
+ "node_modules/escape-html": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+ "license": "MIT"
+ },
"node_modules/escape-string-regexp": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
@@ -5467,6 +5961,68 @@
"node": ">=0.10.0"
}
},
+ "node_modules/event-target-shim": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/events-universal": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
+ "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.7.0"
+ }
+ },
+ "node_modules/execa": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/execa/-/execa-7.2.0.tgz",
+ "integrity": "sha512-UduyVP7TLB5IcAQl+OzLyLcS/l32W/GLg+AhHJ+ow40FOk2U3SAllPwR44v4vmdFwIWqpdwxxpQbF1n5ta9seA==",
+ "license": "MIT",
+ "dependencies": {
+ "cross-spawn": "^7.0.3",
+ "get-stream": "^6.0.1",
+ "human-signals": "^4.3.0",
+ "is-stream": "^3.0.0",
+ "merge-stream": "^2.0.0",
+ "npm-run-path": "^5.1.0",
+ "onetime": "^6.0.0",
+ "signal-exit": "^3.0.7",
+ "strip-final-newline": "^3.0.0"
+ },
+ "engines": {
+ "node": "^14.18.0 || ^16.14.0 || >=18.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sindresorhus/execa?sponsor=1"
+ }
+ },
+ "node_modules/execa/node_modules/get-stream": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
+ "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/expand-template": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
+ "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
+ "license": "(MIT OR WTFPL)",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/exponential-backoff": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz",
@@ -5511,6 +6067,12 @@
"dev": true,
"license": "Apache-2.0"
},
+ "node_modules/fast-fifo": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
+ "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",
+ "license": "MIT"
+ },
"node_modules/fast-json-stable-stringify": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
@@ -5525,6 +6087,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/fast-readable-async-iterator": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/fast-readable-async-iterator/-/fast-readable-async-iterator-2.0.0.tgz",
+ "integrity": "sha512-8Sld+DuyWRIftl86ZguJxR2oXCBccOiJxrY/Rj9/7ZBynW8pYMWzIcqxFL1da+25jaWJZVa+HHX/8SsA21JdTA==",
+ "license": "MIT"
+ },
"node_modules/fast-uri": {
"version": "3.1.7",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz",
@@ -5560,6 +6128,29 @@
}
}
},
+ "node_modules/fetch-blob": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
+ "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/jimmywarting"
+ },
+ {
+ "type": "paypal",
+ "url": "https://paypal.me/jimmywarting"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "node-domexception": "^1.0.0",
+ "web-streams-polyfill": "^3.0.3"
+ },
+ "engines": {
+ "node": "^12.20 || >= 14.13"
+ }
+ },
"node_modules/file-entry-cache": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
@@ -5613,6 +6204,31 @@
"node": ">=10"
}
},
+ "node_modules/filename-reserved-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/filename-reserved-regex/-/filename-reserved-regex-3.0.0.tgz",
+ "integrity": "sha512-hn4cQfU6GOT/7cFHXBqeBg2TbrMBgdD0kcjLhvSQYYwm3s4B6cjvBfb7nBALJLAXqmU5xajSa7X2NnUud/VCdw==",
+ "license": "MIT",
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/fill-range": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
+ "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "to-regex-range": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/find-up": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",
@@ -5630,6 +6246,16 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/find-yarn-workspace-root": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/find-yarn-workspace-root/-/find-yarn-workspace-root-2.0.0.tgz",
+ "integrity": "sha512-1IMnbjt4KzsQfnhnzNd8wUEgXZ44IzZaZmnLYx7D5FZlaHt2gW20Cri8Q+E/t5tIj4+epTBub+2Zxu/vNILzqQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "micromatch": "^4.0.2"
+ }
+ },
"node_modules/flat-cache": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz",
@@ -5684,6 +6310,110 @@
"node": ">= 6"
}
},
+ "node_modules/formdata-polyfill": {
+ "version": "4.0.10",
+ "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
+ "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
+ "license": "MIT",
+ "dependencies": {
+ "fetch-blob": "^3.1.2"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/freelist": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/freelist/-/freelist-1.0.3.tgz",
+ "integrity": "sha512-Ji7fEnMdZDGbS5oXElpRJsn9jPvBR8h/037D3bzreNmS8809cISq/2D9//JbA/TaZmkkN8cmecXwmQHmM+NHhg==",
+ "license": "MIT"
+ },
+ "node_modules/fs-chunk-store": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/fs-chunk-store/-/fs-chunk-store-5.0.1.tgz",
+ "integrity": "sha512-bhD1YfAzdOugxu4VepYjxvzZwik9Qunn69Ogj47DZmogD6h/VkD/4vArNRoQ+kPYYOFqex3c9Ob2iAOkNYdkgw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "filename-reserved-regex": "^3.0.0",
+ "queue-microtask": "^1.2.2",
+ "random-access-file": "^4.0.0",
+ "run-parallel": "^1.1.2",
+ "thunky": "^1.0.1",
+ "uint8-util": "^2.2.5"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/fs-constants": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
+ "license": "MIT"
+ },
+ "node_modules/fs-extra": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
+ "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^6.0.1",
+ "universalify": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/fs-extra/node_modules/jsonfile": {
+ "version": "6.2.1",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
+ "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "universalify": "^2.0.0"
+ },
+ "optionalDependencies": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "node_modules/fs-extra/node_modules/universalify": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
+ "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10.0.0"
+ }
+ },
+ "node_modules/fs-native-extensions": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/fs-native-extensions/-/fs-native-extensions-1.5.1.tgz",
+ "integrity": "sha512-abjiHKkYdcH5M9ikBEJb0MKb/fEpPtZx/yfLHzTptvUAoiFayX0tIe0BTLBU4SAoRyjZLzA0dP1Rn2p0+QRyVg==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "require-addon": "^1.1.0",
+ "which-runtime": "^1.2.0"
+ }
+ },
"node_modules/fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
@@ -5691,6 +6421,15 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/fsa-chunk-store": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/fsa-chunk-store/-/fsa-chunk-store-1.3.0.tgz",
+ "integrity": "sha512-0WCfuxqqSB6Tz/g7Ar/nwAxMoigXaIXuvfrnLIEFYIA9uc6w9eNaHuBGzU1X3lyM4cpLKCOTUmKAA/gCiTvzMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "filename-reserved-regex": "^3.0.0"
+ }
+ },
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
@@ -5819,6 +6558,18 @@
"node": ">= 0.4"
}
},
+ "node_modules/get-stdin": {
+ "version": "10.0.0",
+ "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-10.0.0.tgz",
+ "integrity": "sha512-eWSePJ4zXFdqz+/Lyfopob4rIcoF/U2XfE8nJc7iZV6lnebWc9k7DoQQpX+2a9jc0AOvBsXvbe5YkjXl/MHbpg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/get-stream": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
@@ -5853,6 +6604,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/github-from-package": {
+ "version": "0.0.0",
+ "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
+ "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",
+ "license": "MIT"
+ },
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
@@ -6178,6 +6935,12 @@
"dev": true,
"license": "BSD-2-Clause"
},
+ "node_modules/http-parser-js": {
+ "version": "0.4.13",
+ "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.4.13.tgz",
+ "integrity": "sha512-u8u5ZaG0Tr/VvHlucK2ufMuOp4/5bvwgneXle+y228K5rMbJOlVjThONcaAw3ikAy8b2OO9RfEucdMHFz3UWMA==",
+ "license": "MIT"
+ },
"node_modules/http-proxy-agent": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
@@ -6220,6 +6983,35 @@
"node": ">= 14"
}
},
+ "node_modules/human-signals": {
+ "version": "4.3.1",
+ "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-4.3.1.tgz",
+ "integrity": "sha512-nZXjEF2nbo7lIw3mgYjItAfgQXog3OjJogSbKa2CQIIvSGWcKgeJnQlNXip6NglNzYH45nSRiEVimMvYL8DDqQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=14.18.0"
+ }
+ },
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
"node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
@@ -6230,6 +7022,29 @@
"node": ">= 4"
}
},
+ "node_modules/immediate-chunk-store": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/immediate-chunk-store/-/immediate-chunk-store-2.2.0.tgz",
+ "integrity": "sha512-1bHBna0hCa6arRXicu91IiL9RvvkbNYLVq+mzWdaLGZC3hXvX4doh8e1dLhMKez5siu63CYgO5NrGJbRX5lbPA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "queue-microtask": "^1.2.3"
+ }
+ },
"node_modules/import-fresh": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
@@ -6273,7 +7088,12 @@
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
- "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/ini": {
+ "version": "1.3.8",
+ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
+ "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
"license": "ISC"
},
"node_modules/internal-slot": {
@@ -6291,6 +7111,43 @@
"node": ">= 0.4"
}
},
+ "node_modules/ip": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/ip/-/ip-2.0.1.tgz",
+ "integrity": "sha512-lJUL9imLTNi1ZfXT+DU6rBBdbiKGBuay9B6xGSPVjUeQwaH1RIGqef8RZkUtHioLmSNpPR5M4HVKJGm1j8FWVQ==",
+ "license": "MIT"
+ },
+ "node_modules/ip-address": {
+ "version": "10.7.3",
+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.3.tgz",
+ "integrity": "sha512-A1kdq/tSb5QjvKvAMgIoEvDBIgL7qaqVP/jkvSwYYRZ9iEzvPpopxp2wQfu3SuZRHtpHNxMn8Fs0bS+gf5Xmwg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/ip-set": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/ip-set/-/ip-set-3.0.0.tgz",
+ "integrity": "sha512-EkKzllMFYKMHOoeNxM8v10IJM2n9K6L3ruaQx4A/5RrkOInV8cjp9IwkVU0/cpzwwkq1zGNudrAdCjSR97Rf5w==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "ip-address": "^10.0.1"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/ipaddr.js": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.5.0.tgz",
+ "integrity": "sha512-aq+t5NAc+cS6rZQQVWC2x98CPqGtKKTMDd4Gaodv0wShnItdKg/51djkGJ1hqH+Oy0ivDftCbSLCQob8zso01w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10"
+ }
+ },
"node_modules/is-array-buffer": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
@@ -6426,6 +7283,22 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/is-docker": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
+ "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "is-docker": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/is-document.all": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-document.all/-/is-document.all-1.0.0.tgz",
@@ -6452,6 +7325,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/is-file": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-file/-/is-file-1.0.0.tgz",
+ "integrity": "sha512-ZGMuc+xA8mRnrXtmtf2l/EkIW2zaD2LSBWlaOVEF6yH4RTndHob65V4SwWWdtGKVthQfXPVKsXqw4TDUjbVxVQ==",
+ "license": "MIT"
+ },
"node_modules/is-finalizationregistry": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz",
@@ -6537,6 +7416,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/is-number": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.12.0"
+ }
+ },
"node_modules/is-number-object": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz",
@@ -6602,6 +7491,18 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/is-stream": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz",
+ "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==",
+ "license": "MIT",
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/is-string": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz",
@@ -6699,6 +7600,19 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/is-wsl": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
+ "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-docker": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/isarray": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",
@@ -6775,6 +7689,12 @@
"jiti": "lib/jiti-cli.mjs"
}
},
+ "node_modules/join-async-iterator": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/join-async-iterator/-/join-async-iterator-1.1.1.tgz",
+ "integrity": "sha512-ATse+nuNeKZ9K1y27LKdvPe/GCe9R/u9dw9vI248e+vILeRK3IcJP4JUPAlSmKRCDK0cKhEwfmiw4Skqx7UnGQ==",
+ "license": "MIT"
+ },
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -6832,6 +7752,26 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/json-stable-stringify": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.3.0.tgz",
+ "integrity": "sha512-qtYiSSFlwot9XHtF9bD9c7rwKjr+RecWT//ZnPvSmEjpV5mmPOCN4j8UjY5hbjNkOwZ/jQv3J6R1/pL7RwgMsg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.4",
+ "isarray": "^2.0.5",
+ "jsonify": "^0.0.1",
+ "object-keys": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/json-stable-stringify-without-jsonify": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",
@@ -6870,6 +7810,16 @@
"graceful-fs": "^4.1.6"
}
},
+ "node_modules/jsonify": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.1.tgz",
+ "integrity": "sha512-2/Ki0GcmuqSrgFyelQq9M05y7PS0mEwuIzrf3f1fPqkVDVRvZrPZtVSMHxdgo8Aq0sxAOb/cr2aqqA3LeWHVPg==",
+ "dev": true,
+ "license": "Public Domain",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/jsx-ast-utils": {
"version": "3.3.5",
"resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",
@@ -6886,6 +7836,56 @@
"node": ">=4.0"
}
},
+ "node_modules/junk": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/junk/-/junk-4.0.1.tgz",
+ "integrity": "sha512-Qush0uP+G8ZScpGMZvHUiRfI0YBWuB3gVBYlI0v0vvOJt5FLicco+IkP0a50LqTTQhmts/m6tP5SWE+USyIvcQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/k-bucket": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/k-bucket/-/k-bucket-5.1.0.tgz",
+ "integrity": "sha512-Fac7iINEovXIWU20GPnOMLUbjctiS+cnmyjC4zAUgvs3XPf1vo9akfCHkigftSic/jiKqKl+KA3a/vFcJbHyCg==",
+ "license": "MIT",
+ "dependencies": {
+ "randombytes": "^2.1.0"
+ }
+ },
+ "node_modules/k-rpc": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/k-rpc/-/k-rpc-5.1.0.tgz",
+ "integrity": "sha512-FGc+n70Hcjoa/X2JTwP+jMIOpBz+pkRffHnSl9yrYiwUxg3FIgD50+u1ePfJUOnRCnx6pbjmVk5aAeB1wIijuQ==",
+ "license": "MIT",
+ "dependencies": {
+ "k-bucket": "^5.0.0",
+ "k-rpc-socket": "^1.7.2",
+ "randombytes": "^2.0.5"
+ }
+ },
+ "node_modules/k-rpc-socket": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/k-rpc-socket/-/k-rpc-socket-1.11.1.tgz",
+ "integrity": "sha512-8xtA8oqbZ6v1Niryp2/g4GxW16EQh5MvrUylQoOG+zcrDff5CKttON2XUXvMwlIHq4/2zfPVFiinAccJ+WhxoA==",
+ "license": "MIT",
+ "dependencies": {
+ "bencode": "^2.0.0",
+ "chrome-dgram": "^3.0.2",
+ "chrome-dns": "^1.0.0",
+ "chrome-net": "^3.3.2"
+ }
+ },
+ "node_modules/k-rpc-socket/node_modules/bencode": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/bencode/-/bencode-2.0.3.tgz",
+ "integrity": "sha512-D/vrAD4dLVX23NalHwb8dSvsUsxeRPO8Y7ToKA015JQYq69MLDOMkC0uGZYA/MPpltLO8rt8eqFC2j8DxjTZ/w==",
+ "license": "MIT"
+ },
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -6896,6 +7896,16 @@
"json-buffer": "3.0.1"
}
},
+ "node_modules/klaw-sync": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/klaw-sync/-/klaw-sync-6.0.0.tgz",
+ "integrity": "sha512-nIeuVSzdCCs6TDPTqI8w1Yre34sSq7AkZ4B3sfOBbI2CgVSB4Du4aLQijFU2+lhAFCwt9+42Hel6lQNIv6AntQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.1.11"
+ }
+ },
"node_modules/koffi": {
"version": "2.16.3",
"resolved": "https://registry.npmjs.org/koffi/-/koffi-2.16.3.tgz",
@@ -6906,6 +7916,12 @@
"url": "https://liberapay.com/Koromix"
}
},
+ "node_modules/last-one-wins": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/last-one-wins/-/last-one-wins-1.0.4.tgz",
+ "integrity": "sha512-t+KLJFkHPQk8lfN6WBOiGkiUXoub+gnb2XTYI2P3aiISL+94xgZ1vgz1SXN/N4hthuOoLXarXfBZPUruyjQtfA==",
+ "license": "MIT"
+ },
"node_modules/lazy-val": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/lazy-val/-/lazy-val-1.0.5.tgz",
@@ -7188,6 +8204,42 @@
"url": "https://opencollective.com/parcel"
}
},
+ "node_modules/limiter": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/limiter/-/limiter-1.1.5.tgz",
+ "integrity": "sha512-FWWMIEOxz3GwUI4Ts/IvgVy6LPvoMPgjMdQ185nN6psJyBJ4yOpzqm695/h5umdLJg2vW3GR5iG11MAkR2AzJA=="
+ },
+ "node_modules/load-ip-set": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/load-ip-set/-/load-ip-set-3.0.2.tgz",
+ "integrity": "sha512-UD1GM3CLlkC3b0gAKIxd+6SFJb1WQttWyYhwvjdWjGpJKzu32HnaSMfWtUtVgRtFY+K5vgrvecuVQLRxx5Ojag==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "cross-fetch-ponyfill": "^1.0.1",
+ "ip-set": "^3.0.0",
+ "netmask": "^2.0.1",
+ "once": "^1.4.0",
+ "queue-microtask": "^1.2.3",
+ "split": "^1.0.1"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
"node_modules/locate-path": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
@@ -7241,6 +8293,18 @@
"node": ">=8"
}
},
+ "node_modules/lru": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/lru/-/lru-3.1.0.tgz",
+ "integrity": "sha512-5OUtoiVIGU4VXBOshidmtOsvBIvcQR6FD/RzWSvaeHyxCGB+PCUCu+52lqMfdc0h/2CLvHhZS4TwUmMQrrMbBQ==",
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
@@ -7251,6 +8315,33 @@
"yallist": "^3.0.2"
}
},
+ "node_modules/lt_donthave": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/lt_donthave/-/lt_donthave-2.0.7.tgz",
+ "integrity": "sha512-FdfetmgzUr0IC2ZXHaOhAMEsvw8BFo7kDM7JzfYsJ5pO5+xzjfZIPdLSQWE4+/UTlQA7D8IU5ZJ0LTuLE4BRBQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.2.0",
+ "unordered-array-remove": "^1.0.2"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
"node_modules/lucide-react": {
"version": "1.47.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.47.0.tgz",
@@ -7270,6 +8361,34 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
+ "node_modules/magnet-uri": {
+ "version": "7.0.10",
+ "resolved": "https://registry.npmjs.org/magnet-uri/-/magnet-uri-7.0.10.tgz",
+ "integrity": "sha512-PjS/xWnvq9RK6P/8+dWG7ka3mFGGt/R9xiq5A+P8a8MpE40Dw6yNyTdjCFuJHS3apn6p5bJUCzMSceW3VxezRA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@thaunknown/thirty-two": "^1.0.6",
+ "bep53-range": "^2.0.0",
+ "uint8-util": "^2.3.2"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
"node_modules/matcher": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",
@@ -7294,6 +8413,48 @@
"node": ">= 0.4"
}
},
+ "node_modules/memory-chunk-store": {
+ "version": "1.3.5",
+ "resolved": "https://registry.npmjs.org/memory-chunk-store/-/memory-chunk-store-1.3.5.tgz",
+ "integrity": "sha512-E1Xc1U4ifk/FkC2ZsWhCaW1xg9HbE/OBmQTLe2Tr9c27YPSLbW7kw1cnb3kQWD1rDtErFJHa7mB9EVrs7aTx9g==",
+ "license": "MIT",
+ "dependencies": {
+ "queue-microtask": "^1.2.3"
+ }
+ },
+ "node_modules/merge-stream": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
+ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
+ "license": "MIT"
+ },
+ "node_modules/micromatch": {
+ "version": "4.0.8",
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "braces": "^3.0.3",
+ "picomatch": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=8.6"
+ }
+ },
+ "node_modules/micromatch/node_modules/picomatch": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
"node_modules/mime": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz",
@@ -7327,7 +8488,19 @@
"mime-db": "1.52.0"
},
"engines": {
- "node": ">= 0.6"
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mimic-fn": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz",
+ "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/mimic-response": {
@@ -7360,7 +8533,6 @@
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
- "dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
@@ -7403,6 +8575,12 @@
"mkdirp": "bin/cmd.js"
}
},
+ "node_modules/mkdirp-classic": {
+ "version": "0.5.3",
+ "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
+ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
+ "license": "MIT"
+ },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -7428,6 +8606,19 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/napi-build-utils": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
+ "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",
+ "license": "MIT"
+ },
+ "node_modules/napi-macros": {
+ "version": "2.2.2",
+ "resolved": "https://registry.npmjs.org/napi-macros/-/napi-macros-2.2.2.tgz",
+ "integrity": "sha512-hmEVtAGYzVQpCKdbQea4skABsdXW4RUh5t5mJ2zzqowJS2OyXZTU1KhDVFhx+NlWZ4ap9mqR9TcDO3LTTttd+g==",
+ "license": "MIT",
+ "optional": true
+ },
"node_modules/natural-compare": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
@@ -7435,6 +8626,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/netmask": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.1.1.tgz",
+ "integrity": "sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
"node_modules/node-abi": {
"version": "4.35.0",
"resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.35.0.tgz",
@@ -7484,6 +8684,39 @@
"node": ">=10"
}
},
+ "node_modules/node-datachannel": {
+ "version": "0.32.3",
+ "resolved": "https://registry.npmjs.org/node-datachannel/-/node-datachannel-0.32.3.tgz",
+ "integrity": "sha512-Aok1ZhLsll472lRefgWYuWJ0070jh0ecHravTdRyZEmoESumebMEQV8Y+poBwSW2ZbEwAokAOGsK5Cu8pDDT2g==",
+ "hasInstallScript": true,
+ "license": "MPL 2.0",
+ "dependencies": {
+ "prebuild-install": "^7.1.3"
+ },
+ "engines": {
+ "node": ">=18.20.0"
+ }
+ },
+ "node_modules/node-domexception": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
+ "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
+ "deprecated": "Use your platform's native DOMException instead",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/jimmywarting"
+ },
+ {
+ "type": "github",
+ "url": "https://paypal.me/jimmywarting"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.5.0"
+ }
+ },
"node_modules/node-exports-info": {
"version": "1.6.2",
"resolved": "https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.2.tgz",
@@ -7503,6 +8736,24 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/node-fetch": {
+ "version": "3.3.2",
+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
+ "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
+ "license": "MIT",
+ "dependencies": {
+ "data-uri-to-buffer": "^4.0.0",
+ "fetch-blob": "^3.1.4",
+ "formdata-polyfill": "^4.0.10"
+ },
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/node-fetch"
+ }
+ },
"node_modules/node-gyp": {
"version": "12.4.0",
"resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.4.0.tgz",
@@ -7528,6 +8779,18 @@
"node": "^20.17.0 || >=22.9.0"
}
},
+ "node_modules/node-gyp-build": {
+ "version": "4.8.4",
+ "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",
+ "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",
+ "license": "MIT",
+ "optional": true,
+ "bin": {
+ "node-gyp-build": "bin.js",
+ "node-gyp-build-optional": "optional.js",
+ "node-gyp-build-test": "build-test.js"
+ }
+ },
"node_modules/node-gyp/node_modules/isexe": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz",
@@ -7613,6 +8876,33 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/npm-run-path": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz",
+ "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==",
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^4.0.0"
+ },
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/npm-run-path/node_modules/path-key": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz",
+ "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@@ -7725,12 +9015,43 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
- "dev": true,
"license": "ISC",
"dependencies": {
"wrappy": "1"
}
},
+ "node_modules/onetime": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz",
+ "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==",
+ "license": "MIT",
+ "dependencies": {
+ "mimic-fn": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/open": {
+ "version": "7.4.2",
+ "resolved": "https://registry.npmjs.org/open/-/open-7.4.2.tgz",
+ "integrity": "sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-docker": "^2.0.0",
+ "is-wsl": "^2.1.1"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/optionator": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
@@ -7823,6 +9144,99 @@
"node": ">=6"
}
},
+ "node_modules/parse-torrent": {
+ "version": "11.0.24",
+ "resolved": "https://registry.npmjs.org/parse-torrent/-/parse-torrent-11.0.24.tgz",
+ "integrity": "sha512-6nNWYiJq6egD8pMqZYL1mfnAly9ZH32DHkAYgZuAfwWij52ce7e3BtrWGVw2q1Bpb5Us8YQVGN7ML/47z/bVIA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "bencode": "^4.0.1",
+ "cross-fetch-ponyfill": "^1.0.3",
+ "get-stdin": "^10.0.0",
+ "magnet-uri": "^7.0.10",
+ "queue-microtask": "^1.2.3",
+ "uint8-util": "^2.3.2"
+ },
+ "bin": {
+ "parse-torrent": "bin/cmd.js"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/patch-package": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/patch-package/-/patch-package-8.0.1.tgz",
+ "integrity": "sha512-VsKRIA8f5uqHQ7NGhwIna6Bx6D9s/1iXlA1hthBVBEbkq+t4kXD0HHt+rJhf/Z+Ci0F/HCB2hvn0qLdLG+Qxlw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@yarnpkg/lockfile": "^1.1.0",
+ "chalk": "^4.1.2",
+ "ci-info": "^3.7.0",
+ "cross-spawn": "^7.0.3",
+ "find-yarn-workspace-root": "^2.0.0",
+ "fs-extra": "^10.0.0",
+ "json-stable-stringify": "^1.0.2",
+ "klaw-sync": "^6.0.0",
+ "minimist": "^1.2.6",
+ "open": "^7.4.2",
+ "semver": "^7.5.3",
+ "slash": "^2.0.0",
+ "tmp": "^0.2.4",
+ "yaml": "^2.2.2"
+ },
+ "bin": {
+ "patch-package": "index.js"
+ },
+ "engines": {
+ "node": ">=14",
+ "npm": ">5"
+ }
+ },
+ "node_modules/patch-package/node_modules/ci-info": {
+ "version": "3.9.0",
+ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz",
+ "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/sibiraj-s"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/patch-package/node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/path-exists": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
@@ -7847,7 +9261,6 @@
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -7895,6 +9308,12 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/piece-length": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/piece-length/-/piece-length-2.0.1.tgz",
+ "integrity": "sha512-dBILiDmm43y0JPISWEmVGKBETQjwJe6mSU9GND+P9KW0SJGUwoU/odyH1nbalOP9i8WSYuqf1lQnaj92Bhw+Ug==",
+ "license": "MIT"
+ },
"node_modules/pkijs": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.0.tgz",
@@ -8039,6 +9458,57 @@
"node": "^12.20.0 || >=14"
}
},
+ "node_modules/prebuild-install": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
+ "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
+ "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
+ "license": "MIT",
+ "dependencies": {
+ "detect-libc": "^2.0.0",
+ "expand-template": "^2.0.3",
+ "github-from-package": "0.0.0",
+ "minimist": "^1.2.3",
+ "mkdirp-classic": "^0.5.3",
+ "napi-build-utils": "^2.0.0",
+ "node-abi": "^3.3.0",
+ "pump": "^3.0.0",
+ "rc": "^1.2.7",
+ "simple-get": "^4.0.0",
+ "tar-fs": "^2.0.0",
+ "tunnel-agent": "^0.6.0"
+ },
+ "bin": {
+ "prebuild-install": "bin.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/prebuild-install/node_modules/node-abi": {
+ "version": "3.96.0",
+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.96.0.tgz",
+ "integrity": "sha512-rebQ/lz7i0EkoLzUVSrKRzA69zMkwLp95kKMWoMDkkM00Suxz0D7zEQPwRml5fQum24mj7bPvmlgLAmu2JCiYg==",
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^7.3.5"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/prebuild-install/node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
@@ -8146,7 +9616,6 @@
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
"integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"end-of-stream": "^1.1.0",
@@ -8180,37 +9649,139 @@
],
"license": "MIT"
},
- "node_modules/pvtsutils": {
- "version": "1.3.6",
- "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
- "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
- "dev": true,
+ "node_modules/pvtsutils": {
+ "version": "1.3.6",
+ "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
+ "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.8.1"
+ }
+ },
+ "node_modules/pvutils": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
+ "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.0.0"
+ }
+ },
+ "node_modules/queue-microtask": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
+ "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/queue-tick": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz",
+ "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==",
+ "license": "MIT"
+ },
+ "node_modules/quick-lru": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",
+ "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/random-access-file": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/random-access-file/-/random-access-file-4.1.2.tgz",
+ "integrity": "sha512-GQM6R78DceZDcQod8KxlDFwXIiUvlvuy1EOzxTDsjuDjW5NlnlZi0MOk6iI4itAj/2vcvdqcEExYbVpC/dJcEw==",
+ "license": "MIT",
+ "dependencies": {
+ "bare-fs": "^4.0.1",
+ "bare-path": "^3.0.0",
+ "random-access-storage": "^3.0.0"
+ },
+ "optionalDependencies": {
+ "fs-native-extensions": "^1.3.1"
+ }
+ },
+ "node_modules/random-access-storage": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/random-access-storage/-/random-access-storage-3.0.2.tgz",
+ "integrity": "sha512-Es9maUyWdJXWKckKy9s1+vT+DEgAt+PBb9lxPaake/0EDUsHehloKGv9v1zimS2V3gpFAcQXubvc1Rgci2sDPQ==",
+ "license": "MIT",
+ "dependencies": {
+ "bare-events": "^2.2.0",
+ "queue-tick": "^1.0.0"
+ }
+ },
+ "node_modules/random-iterate": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/random-iterate/-/random-iterate-1.0.1.tgz",
+ "integrity": "sha512-Jdsdnezu913Ot8qgKgSgs63XkAjEsnMcS1z+cC6D6TNXsUXsMxy0RpclF2pzGZTEiTXL9BiArdGTEexcv4nqcA==",
+ "license": "MIT"
+ },
+ "node_modules/randombytes": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz",
+ "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==",
"license": "MIT",
"dependencies": {
- "tslib": "^2.8.1"
+ "safe-buffer": "^5.1.0"
}
},
- "node_modules/pvutils": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
- "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
- "dev": true,
+ "node_modules/range-parser": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz",
+ "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==",
"license": "MIT",
"engines": {
- "node": ">=16.0.0"
+ "node": ">= 0.6"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
}
},
- "node_modules/quick-lru": {
- "version": "5.1.1",
- "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",
- "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==",
- "dev": true,
+ "node_modules/rc": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
+ "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
+ "license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
+ "dependencies": {
+ "deep-extend": "^0.6.0",
+ "ini": "~1.3.0",
+ "minimist": "^1.2.0",
+ "strip-json-comments": "~2.0.1"
+ },
+ "bin": {
+ "rc": "cli.js"
+ }
+ },
+ "node_modules/rc/node_modules/strip-json-comments": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
+ "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
"license": "MIT",
"engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
+ "node": ">=0.10.0"
}
},
"node_modules/react": {
@@ -8287,6 +9858,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/record-cache": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/record-cache/-/record-cache-1.2.0.tgz",
+ "integrity": "sha512-kyy3HWCez2WrotaL3O4fTn0rsIdfRKOdQQcEJ9KpvmKmbffKVvwsloX063EgRUlpJIXHiDQFhJcTbZequ2uTZw==",
+ "license": "MIT",
+ "dependencies": {
+ "b4a": "^1.3.1"
+ }
+ },
"node_modules/reflect.getprototypeof": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
@@ -8331,6 +9911,19 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/require-addon": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/require-addon/-/require-addon-1.3.0.tgz",
+ "integrity": "sha512-j8pifaPNZI7ShKY3ihXZwF0qaEjua8zmlqPvDil0a8SBnyRvjCbAiEQuzO0UcoXH1sqU5U/ilXSjYd1W5NYwAA==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "bare-addon-resolve": "^1.3.0"
+ },
+ "engines": {
+ "bare": ">=1.10.0"
+ }
+ },
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
@@ -8519,6 +10112,72 @@
"fsevents": "~2.3.2"
}
},
+ "node_modules/run-parallel": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
+ "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "queue-microtask": "^1.2.2"
+ }
+ },
+ "node_modules/run-parallel-limit": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/run-parallel-limit/-/run-parallel-limit-1.1.0.tgz",
+ "integrity": "sha512-jJA7irRNM91jaKc3Hcl1npHsFLOXOoTkPCUL1JEa1R82O2miplXXRaGdjW/KM/98YQWDhJLiSs793CnXfblJUw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "queue-microtask": "^1.2.2"
+ }
+ },
+ "node_modules/run-series": {
+ "version": "1.1.9",
+ "resolved": "https://registry.npmjs.org/run-series/-/run-series-1.1.9.tgz",
+ "integrity": "sha512-Arc4hUN896vjkqCYrUXquBFtRZdv1PfLbTYP71efP6butxyQ0kWpiNJyAgsxscmQg1cqvHY32/UCBzXedTpU2g==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/safe-array-concat": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.4.tgz",
@@ -8543,7 +10202,6 @@
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
- "dev": true,
"license": "MIT"
},
"node_modules/safe-push-apply": {
@@ -8595,7 +10253,6 @@
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
- "dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
@@ -8695,7 +10352,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
@@ -8708,7 +10364,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -8794,9 +10449,53 @@
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
- "dev": true,
"license": "ISC"
},
+ "node_modules/simple-concat": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
+ "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/simple-get": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
+ "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decompress-response": "^6.0.0",
+ "once": "^1.3.1",
+ "simple-concat": "^1.0.0"
+ }
+ },
"node_modules/simple-update-notifier": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",
@@ -8823,6 +10522,40 @@
"node": ">=10"
}
},
+ "node_modules/slash": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz",
+ "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/smart-buffer": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
+ "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6.0.0",
+ "npm": ">= 3.0.0"
+ }
+ },
+ "node_modules/socks": {
+ "version": "2.8.10",
+ "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.10.tgz",
+ "integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ip-address": "^10.1.1",
+ "smart-buffer": "^4.2.0"
+ },
+ "engines": {
+ "node": ">= 10.0.0",
+ "npm": ">= 3.0.0"
+ }
+ },
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
@@ -8854,6 +10587,28 @@
"source-map": "^0.6.0"
}
},
+ "node_modules/speed-limiter": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/speed-limiter/-/speed-limiter-1.0.2.tgz",
+ "integrity": "sha512-Ax+TbUOho84bWUc3AKqWtkIvAIVws7d6QI4oJkgH4yQ5Yil+lR3vjd/7qd51dHKGzS5bFxg0++QwyNRN7s6rZA==",
+ "license": "MIT",
+ "dependencies": {
+ "limiter": "^1.1.5",
+ "streamx": "^2.10.3"
+ }
+ },
+ "node_modules/split": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz",
+ "integrity": "sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==",
+ "license": "MIT",
+ "dependencies": {
+ "through": "2"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/sprintf-js": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
@@ -8886,11 +10641,21 @@
"node": ">= 0.4"
}
},
+ "node_modules/streamx": {
+ "version": "2.28.0",
+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.0.tgz",
+ "integrity": "sha512-1Yowhzjf0ivGMrTIkY9hav5TxobO9qIVqUE41fiCGMGgc3CLlf4MY+9AHmZqBWgDTue0fY9zWjYFVyf6Diuobw==",
+ "license": "MIT",
+ "dependencies": {
+ "events-universal": "^1.0.0",
+ "fast-fifo": "^1.3.2",
+ "text-decoder": "^1.1.0"
+ }
+ },
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.1.0"
@@ -9010,6 +10775,28 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/string2compact": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/string2compact/-/string2compact-2.0.2.tgz",
+ "integrity": "sha512-ZUUIyrS+sSj84gR6fFoz/boiqCptyw37/hMxIehReuf6ekpJOlwSXhTfEasqc5t3QucBXi2ghwLlHOSC8hjEaw==",
+ "license": "MIT",
+ "dependencies": {
+ "addr-to-ip-port": "^2.0.0",
+ "ipaddr.js": "2.0.1"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/string2compact/node_modules/ipaddr.js": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.0.1.tgz",
+ "integrity": "sha512-1qTgH9NG+IIJ4yfKs2e6Pp1bZg8wbDbKHT21HrLIeYBTRLgMYKnMTPAuI3Lcs61nfx5h1xlXnbJtH1kX5/d/ng==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10"
+ }
+ },
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
@@ -9023,6 +10810,18 @@
"node": ">=8"
}
},
+ "node_modules/strip-final-newline": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz",
+ "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/strip-json-comments": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
@@ -9128,6 +10927,54 @@
"node": ">=18"
}
},
+ "node_modules/tar-fs": {
+ "version": "2.1.5",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz",
+ "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==",
+ "license": "MIT",
+ "dependencies": {
+ "chownr": "^1.1.1",
+ "mkdirp-classic": "^0.5.2",
+ "pump": "^3.0.0",
+ "tar-stream": "^2.1.4"
+ }
+ },
+ "node_modules/tar-fs/node_modules/chownr": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
+ "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
+ "license": "ISC"
+ },
+ "node_modules/tar-stream": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
+ "license": "MIT",
+ "dependencies": {
+ "bl": "^4.0.3",
+ "end-of-stream": "^1.4.1",
+ "fs-constants": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.1.1"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/tar-stream/node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/tar/node_modules/yallist": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
@@ -9138,6 +10985,15 @@
"node": ">=18"
}
},
+ "node_modules/teex": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",
+ "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==",
+ "license": "MIT",
+ "dependencies": {
+ "streamx": "^2.12.5"
+ }
+ },
"node_modules/temp": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/temp/-/temp-0.9.4.tgz",
@@ -9153,55 +11009,51 @@
"node": ">=6.0.0"
}
},
- "node_modules/temp-file": {
- "version": "3.4.0",
- "resolved": "https://registry.npmjs.org/temp-file/-/temp-file-3.4.0.tgz",
- "integrity": "sha512-C5tjlC/HCtVUOi3KWVokd4vHVViOmGjtLwIh4MuzPo/nMYTV/p1urt3RnMz2IWXDdKEGJH3k5+KPxtqRsUYGtg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "async-exit-hook": "^2.0.1",
- "fs-extra": "^10.0.0"
- }
- },
- "node_modules/temp-file/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/temp-file/node_modules/jsonfile": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
- "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
+ "node_modules/temp-file": {
+ "version": "3.4.0",
+ "resolved": "https://registry.npmjs.org/temp-file/-/temp-file-3.4.0.tgz",
+ "integrity": "sha512-C5tjlC/HCtVUOi3KWVokd4vHVViOmGjtLwIh4MuzPo/nMYTV/p1urt3RnMz2IWXDdKEGJH3k5+KPxtqRsUYGtg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "universalify": "^2.0.0"
- },
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
+ "async-exit-hook": "^2.0.1",
+ "fs-extra": "^10.0.0"
}
},
- "node_modules/temp-file/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 10.0.0"
+ "node_modules/text-decoder": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz",
+ "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.6.4"
}
},
+ "node_modules/through": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz",
+ "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==",
+ "license": "MIT"
+ },
+ "node_modules/throughput": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/throughput/-/throughput-1.0.2.tgz",
+ "integrity": "sha512-jvK1ZXuhsggjb3qYQjMiU/AVYYiTeqT5thWvYR2yuy2LGM84P5MSSyAinwHahGsdBYKR9m9HncVR/3f3nFKkxg==",
+ "license": "MIT"
+ },
+ "node_modules/thunky": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz",
+ "integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==",
+ "license": "MIT"
+ },
+ "node_modules/timeout-refresh": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/timeout-refresh/-/timeout-refresh-1.0.3.tgz",
+ "integrity": "sha512-Mz0CX4vBGM5lj8ttbIFt7o4ZMxk/9rgudJRh76EvB7xXZMur7T/cjRiH2w4Fmkq0zxf2QpM8IFvOSRn8FEu3gA==",
+ "license": "MIT",
+ "optional": true
+ },
"node_modules/tiny-async-pool": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz",
@@ -9259,6 +11111,75 @@
"tmp": "^0.2.0"
}
},
+ "node_modules/to-regex-range": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-number": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
+ "node_modules/torrent-discovery": {
+ "version": "11.0.21",
+ "resolved": "https://registry.npmjs.org/torrent-discovery/-/torrent-discovery-11.0.21.tgz",
+ "integrity": "sha512-x+RGu60qJp2u4S7B7XglyYCrfDJWKB0RIexODlA5dpBpMh94q4MbmRjusdbvxN+XD4NHhpwEfub/CRA9pUXjEQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "bittorrent-dht": "^11.0.12",
+ "bittorrent-lsd": "^2.0.3",
+ "bittorrent-tracker": "^11.2.3",
+ "debug": "^4.4.3",
+ "run-parallel": "^1.2.0"
+ },
+ "engines": {
+ "node": ">=16.0.0"
+ }
+ },
+ "node_modules/torrent-piece": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/torrent-piece/-/torrent-piece-4.0.1.tgz",
+ "integrity": "sha512-bL5lLm0CknuXMJ3c8Xw+27etPTH7P1vLXwEASQ3bktZlWV2ZEkCW1l0ssV6Y9EHpcUlf0aqB9x49bkgMA4JrHw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "uint8-util": "^2.1.9"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
"node_modules/truncate-utf8-bytes": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/truncate-utf8-bytes/-/truncate-utf8-bytes-1.0.2.tgz",
@@ -9289,6 +11210,18 @@
"dev": true,
"license": "0BSD"
},
+ "node_modules/tunnel-agent": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
+ "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "safe-buffer": "^5.0.1"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/type-check": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
@@ -9432,6 +11365,12 @@
"typescript": ">=4.8.4 <6.1.0"
}
},
+ "node_modules/uint8-util": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/uint8-util/-/uint8-util-2.3.2.tgz",
+ "integrity": "sha512-u1c0/eiT1IW+c5+ogbmE2Fu2hmtJQPkuzDmXD/4crMU4FPMjkTkFnjJ2NN/9AsZ9YWcc7yE869uc3WB8wIZEEA==",
+ "license": "MIT"
+ },
"node_modules/unbox-primitive": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz",
@@ -9478,6 +11417,19 @@
"node": ">= 4.0.0"
}
},
+ "node_modules/unordered-array-remove": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/unordered-array-remove/-/unordered-array-remove-1.0.2.tgz",
+ "integrity": "sha512-45YsfD6svkgaCBNyvD+dFHm4qFX9g3wRSIVgWVPtm2OCnphvPxzJoe20ATsiNpNJrmzHifnxm+BN5F7gFT/4gw==",
+ "license": "MIT"
+ },
+ "node_modules/unordered-set": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/unordered-set/-/unordered-set-2.0.1.tgz",
+ "integrity": "sha512-eUmNTPzdx+q/WvOHW0bgGYLWvWHNT3PTKEQLg0MAQhc0AHASHVHoP/9YytYd4RBVariqno/mEUhVZN98CmD7bg==",
+ "license": "MIT",
+ "optional": true
+ },
"node_modules/unzipper": {
"version": "0.12.5",
"resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.5.tgz",
@@ -9580,6 +11532,77 @@
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
+ "node_modules/ut_metadata": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ut_metadata/-/ut_metadata-5.0.1.tgz",
+ "integrity": "sha512-V+6jKXXvkH8YQDFeSpvjSkn7Yiz7Juz3LhIkA1QhxuvOjhrqwlZKJfRMOjVSEW/mPa9Bpk4hvFOCim98tzR04w==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "bencode": "^4.0.0",
+ "bitfield": "^5.0.0",
+ "debug": "^4.2.0",
+ "uint8-util": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+ },
+ "node_modules/ut_pex": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/ut_pex/-/ut_pex-5.0.2.tgz",
+ "integrity": "sha512-tPWnEmFIpn47IgZ3CyMzA4onr6zGtBrR+DVtRGoyCpC59OgqELvj9jkzLuisCwIH5FdUQiwqtXtsiAWwpUfrKw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "bencode": "^4.0.1",
+ "compact2string": "^1.4.1",
+ "string2compact": "^2.0.2"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/utf-8-validate": {
+ "version": "6.0.6",
+ "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-6.0.6.tgz",
+ "integrity": "sha512-q3l3P9UtEEiAHcsgsqTgf9PPjctrDWoIXW3NpOHFdRDbLvu4DLIcxHangJ4RLrWkBcKjmcs/6NkerI8T/rE4LA==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "node-gyp-build": "^4.3.0"
+ },
+ "engines": {
+ "node": ">=6.14.2"
+ }
+ },
"node_modules/utf8-byte-length": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/utf8-byte-length/-/utf8-byte-length-1.0.5.tgz",
@@ -9591,9 +11614,44 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
- "dev": true,
"license": "MIT"
},
+ "node_modules/utp-native": {
+ "version": "2.5.3",
+ "resolved": "https://registry.npmjs.org/utp-native/-/utp-native-2.5.3.tgz",
+ "integrity": "sha512-sWTrWYXPhhWJh+cS2baPzhaZc89zwlWCfwSthUjGhLkZztyPhcQllo+XVVCbNGi7dhyRlxkWxN4NKU6FbA9Y8w==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "napi-macros": "^2.0.0",
+ "node-gyp-build": "^4.2.0",
+ "readable-stream": "^3.0.2",
+ "timeout-refresh": "^1.0.0",
+ "unordered-set": "^2.0.1"
+ },
+ "bin": {
+ "ucat": "ucat.js"
+ },
+ "engines": {
+ "node": ">=8.12"
+ }
+ },
+ "node_modules/utp-native/node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/vite": {
"version": "7.3.6",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz",
@@ -10153,6 +12211,15 @@
"@esbuild/win32-x64": "0.28.2"
}
},
+ "node_modules/web-streams-polyfill": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
+ "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 8"
+ }
+ },
"node_modules/webcrypto-core": {
"version": "1.9.2",
"resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz",
@@ -10167,6 +12234,97 @@
"tslib": "^2.8.1"
}
},
+ "node_modules/webrtc-polyfill": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/webrtc-polyfill/-/webrtc-polyfill-1.2.2.tgz",
+ "integrity": "sha512-t/H2OySa7lZSq2f5j4whmr+IWCl5TqF4daGotE8VhPP7U+E4x5x8MK1wqOkqlb4xxRlag4kBB9enU4oxNk//+g==",
+ "license": "MIT",
+ "dependencies": {
+ "node-datachannel": "^0.32.3"
+ },
+ "engines": {
+ "node": ">=16.0.0"
+ }
+ },
+ "node_modules/webtorrent": {
+ "version": "3.0.21",
+ "resolved": "https://registry.npmjs.org/webtorrent/-/webtorrent-3.0.21.tgz",
+ "integrity": "sha512-PFgLphma0dsUWmbWrZ016Cja+j+3D3DXuhk09A5u9qVAzH1T4Vj1VZd8j+zb8sDwPv7NA7+qgPtDEN4iFd6wdw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@silentbot1/nat-api": "^0.4.9",
+ "@thaunknown/simple-peer": "^10.1.2",
+ "@webtorrent/http-node": "^1.3.0",
+ "addr-to-ip-port": "^2.0.0",
+ "bitfield": "^5.0.1",
+ "bittorrent-dht": "^11.0.12",
+ "bittorrent-protocol": "^5.0.9",
+ "cache-chunk-store": "^3.2.2",
+ "chunk-store-iterator": "^1.0.4",
+ "cpus": "^1.0.3",
+ "create-torrent": "^6.1.3",
+ "cross-fetch-ponyfill": "^1.0.3",
+ "debug": "^4.4.3",
+ "escape-html": "^1.0.3",
+ "fs-chunk-store": "^5.0.1",
+ "fsa-chunk-store": "^1.3.0",
+ "immediate-chunk-store": "^2.2.0",
+ "join-async-iterator": "^1.1.1",
+ "load-ip-set": "^3.0.2",
+ "lt_donthave": "^2.0.7",
+ "memory-chunk-store": "^1.3.5",
+ "mime": "^3.0.0",
+ "once": "^1.4.0",
+ "parse-torrent": "^11.0.24",
+ "pump": "^3.0.4",
+ "queue-microtask": "^1.2.3",
+ "random-iterate": "^1.0.1",
+ "range-parser": "^1.3.0",
+ "run-parallel": "^1.2.0",
+ "run-parallel-limit": "^1.1.0",
+ "speed-limiter": "^1.0.2",
+ "streamx": "2.28.0",
+ "throughput": "^1.0.2",
+ "torrent-discovery": "^11.0.21",
+ "torrent-piece": "^4.0.1",
+ "uint8-util": "^2.3.2",
+ "unordered-array-remove": "^1.0.2",
+ "ut_metadata": "^5.0.1",
+ "ut_pex": "^5.0.2"
+ },
+ "engines": {
+ "node": ">=22"
+ },
+ "optionalDependencies": {
+ "utp-native": "^2.5.3"
+ }
+ },
+ "node_modules/webtorrent/node_modules/mime": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",
+ "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==",
+ "license": "MIT",
+ "bin": {
+ "mime": "cli.js"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
"node_modules/which": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz",
@@ -10250,6 +12408,13 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/which-runtime": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/which-runtime/-/which-runtime-1.4.0.tgz",
+ "integrity": "sha512-0ugbP4CJW4e2D20jvEcC4973dCgIaHI4Rw1PT+26U9zEve7FyYdWAIwUnoeOYvoCfn+wXHoHTKb1KhkYlb60Pw==",
+ "license": "Apache-2.0",
+ "optional": true
+ },
"node_modules/which-typed-array": {
"version": "1.1.22",
"resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.22.tgz",
@@ -10304,9 +12469,51 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
- "dev": true,
"license": "ISC"
},
+ "node_modules/ws": {
+ "version": "8.22.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/xml2js": {
+ "version": "0.6.2",
+ "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz",
+ "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==",
+ "license": "MIT",
+ "dependencies": {
+ "sax": ">=0.6.0",
+ "xmlbuilder": "~11.0.0"
+ },
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/xml2js/node_modules/xmlbuilder": {
+ "version": "11.0.1",
+ "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz",
+ "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
"node_modules/xmlbuilder": {
"version": "15.1.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
@@ -10334,6 +12541,22 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/yaml": {
+ "version": "2.9.1",
+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz",
+ "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "yaml": "bin.mjs"
+ },
+ "engines": {
+ "node": ">= 14.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/eemeli"
+ }
+ },
"node_modules/yargs": {
"version": "17.7.3",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz",
diff --git a/package.json b/package.json
index 1d95a04..b72638c 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "plexo",
- "version": "1.0.0-rc.11",
+ "version": "1.0.0-rc.12",
"description": "Speed up downloads by combining multiple network connections in parallel",
"main": "./out/main/index.js",
"author": "Anmol Kapil",
@@ -18,7 +18,7 @@
"predev": "install-electron",
"dev": "electron-vite dev",
"build": "npm run typecheck && electron-vite build",
- "postinstall": "install-electron && electron-builder install-app-deps",
+ "postinstall": "patch-package && install-electron && electron-builder install-app-deps",
"build:unpack": "npm run build && electron-builder --dir",
"build:win": "npm run build && electron-builder --win",
"build:mac": "electron-vite build && electron-builder --mac",
@@ -30,10 +30,14 @@
"@base-ui/react": "^1.8.0",
"@electron-toolkit/preload": "^3.0.2",
"@electron-toolkit/utils": "^4.0.0",
+ "bittorrent-peerid": "2.0.2",
+ "fs-chunk-store": "5.0.1",
"class-variance-authority": "^0.7.1",
"cn": "^0.3.0",
"koffi": "^2.16.3",
"lucide-react": "^1.47.0",
+ "parse-torrent": "11.0.24",
+ "webtorrent": "3.0.21",
"zustand": "^5.0.15"
},
"devDependencies": {
@@ -54,6 +58,7 @@
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"fast-check": "^4.10.1",
+ "patch-package": "8.0.1",
"prettier": "^3.7.4",
"react": "^19.2.1",
"react-dom": "^19.2.1",
@@ -66,6 +71,7 @@
}
}
diff --git a/patches/webtorrent+3.0.21.patch b/patches/webtorrent+3.0.21.patch
new file mode 100644
index 0000000..21f5ec3
--- /dev/null
+++ b/patches/webtorrent+3.0.21.patch
@@ -0,0 +1,25 @@
+diff --git a/node_modules/webtorrent/index.js b/node_modules/webtorrent/index.js
+index 8d3d156..08e8cf7 100644
+--- a/node_modules/webtorrent/index.js
++++ b/node_modules/webtorrent/index.js
+@@ -82,6 +82,7 @@ export default class WebTorrent extends EventEmitter {
+ this.natPmp = opts.natPmp ?? true
+ this.torrents = []
+ this.maxConns = Number(opts.maxConns) || 55
++ this._connect = typeof opts.connect === 'function' ? opts.connect : null
+ this.utp = WebTorrent.UTP_SUPPORT && opts.utp !== false
+ this.seedOutgoingConnections = opts.seedOutgoingConnections ?? true
+
+diff --git a/node_modules/webtorrent/lib/torrent.js b/node_modules/webtorrent/lib/torrent.js
+index 771a87f..1eafb73 100644
+--- a/node_modules/webtorrent/lib/torrent.js
++++ b/node_modules/webtorrent/lib/torrent.js
+@@ -2122,7 +2122,7 @@ export default class Torrent extends EventEmitter {
+ const utpServer = this.client._utpServer
+ peer.conn = utpServer ? utpServer.connect(opts.port, opts.host) : utp.connect(opts.port, opts.host)
+ } else {
+- peer.conn = net.connect(opts)
++ peer.conn = this.client._connect ? this.client._connect(opts) : net.connect(opts)
+ }
+
+ const conn = peer.conn
diff --git a/src/main/download/blockProgress.ts b/src/main/download/blockProgress.ts
index f04479b..819fa3a 100644
--- a/src/main/download/blockProgress.ts
+++ b/src/main/download/blockProgress.ts
@@ -1,4 +1,4 @@
-import type { BlockState } from '../../shared/types'
+import type { HttpBlockState } from '../../shared/types'
// A block's `bytesDownloaded` is its frontier: how much of it, from its first byte, is secured.
// Near the end of a download two attempts can race for one block, so the frontier is the furthest
@@ -6,14 +6,14 @@ import type { BlockState } from '../../shared/types'
// and always adds up to it — these three functions are the only ways either changes.
/** Records that `networkId` delivered `bytes` more of this block. */
-function credit(block: BlockState, networkId: string, bytes: number): void {
+function credit(block: HttpBlockState, networkId: string, bytes: number): void {
block.bytesByInterface[networkId] = (block.bytesByInterface[networkId] ?? 0) + bytes
}
/** Drops attribution for bytes that turned out not to be secured, so the per-network tallies
* keep summing to the block's real byte count. The lost bytes are always at the tail, so they
* come off `blamed` first (the network that wrote last) before spilling over to the rest. */
-function trim(block: BlockState, keepBytes: number, blamed?: string): void {
+function trim(block: HttpBlockState, keepBytes: number, blamed?: string): void {
let attributed = 0
for (const bytes of Object.values(block.bytesByInterface)) attributed += bytes
@@ -36,7 +36,7 @@ function trim(block: BlockState, keepBytes: number, blamed?: string): void {
/** Moves the frontier forward to `position` (a byte offset into the block), crediting the bytes
* it gains to `networkId`. Does nothing if something already got further. Returns the gain. */
-export function advanceBlock(block: BlockState, networkId: string, position: number): number {
+export function advanceBlock(block: HttpBlockState, networkId: string, position: number): number {
const length = block.rangeEnd === null ? Infinity : block.rangeEnd - block.rangeStart + 1
const next = Math.min(position, length)
const gained = next - block.bytesDownloaded
@@ -49,7 +49,7 @@ export function advanceBlock(block: BlockState, networkId: string, position: num
/** Pulls the frontier back to `position`, for bytes that turned out not to be there or a racing
* attempt that lost. `blamed` is the network they came from.
* Returns how much it removed. */
-export function retractBlock(block: BlockState, position: number, blamed?: string): number {
+export function retractBlock(block: HttpBlockState, position: number, blamed?: string): number {
const removed = block.bytesDownloaded - position
if (removed <= 0) return 0
trim(block, position, blamed)
diff --git a/src/main/download/chunkDownloader.ts b/src/main/download/chunkDownloader.ts
index 486c5e7..6979816 100644
--- a/src/main/download/chunkDownloader.ts
+++ b/src/main/download/chunkDownloader.ts
@@ -23,6 +23,8 @@ export interface ChunkDownloadOptions {
/** Called once the server has answered with usable headers: how long that took, and whether
* the request went out on a connection an earlier one had already warmed up. */
onResponse?: (info: { ttfbMs: number; reusedSocket: boolean }) => void
+ /** Told of every body byte received; answers how many ms to stop reading for (see Limits). */
+ throttle?: (bytes: number) => number
}
/** A response whose version doesn't match the download's. Nothing from it was written; the
@@ -129,7 +131,8 @@ export function downloadChunk(options: ChunkDownloadOptions): Promise<void> {
onProgress,
signal,
acceptedVersions,
- onResponse
+ onResponse,
+ throttle
} = options
return new Promise((resolve, reject) => {
@@ -283,6 +286,22 @@ export function downloadChunk(options: ChunkDownloadOptions): Promise<void> {
// headers then freezes, or goes silent mid-stream.
resetWatchdog()
+ // Reading stops while the disk catches up or a speed limit says to wait, and goes on
+ // once neither holds it. Neither says anything about the network: the watchdog stops
+ // until then.
+ let holds = 0
+ const hold = (): void => {
+ if (holds++ === 0) {
+ clearWatchdog()
+ res.pause()
+ }
+ }
+ const release = (): void => {
+ if (--holds > 0 || settled) return
+ resetWatchdog()
+ res.resume()
+ }
+
// Written by hand rather than piped so an overlong body can be cut off
// at the range boundary: an overlong response could overwrite the next block.
res.on('data', (chunk: Buffer) => {
@@ -304,14 +323,13 @@ export function downloadChunk(options: ChunkDownloadOptions): Promise<void> {
else if (!settled) onProgress(progress)
})
) {
- // Waiting on the disk says nothing about the network: the watchdog stops until
- // the writer has caught up.
- clearWatchdog()
- res.pause()
- fileStream.once('drain', () => {
- resetWatchdog()
- res.resume()
- })
+ hold()
+ fileStream.once('drain', release)
+ }
+ const wait = throttle?.(usable.length) ?? 0
+ if (wait > 0) {
+ hold()
+ setTimeout(release, wait)
}
}
diff --git a/src/main/download/downloadFile.ts b/src/main/download/downloadFile.ts
index 2cbaef1..b5c8f8c 100644
--- a/src/main/download/downloadFile.ts
+++ b/src/main/download/downloadFile.ts
@@ -98,4 +98,10 @@ export class DownloadFile {
async discard(): Promise<void> {
await rm(this.path, { force: true })
}
+
+ /** Clears what's left once the download is published (or was found to be). A file published by
+ * rename leaves nothing, bar the partial of a publish interrupted after it. */
+ async discardLeftover(): Promise<void> {
+ await this.discard()
+ }
}
diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.ts
index b65ac7c..43d3ca6 100644
--- a/src/main/download/downloadManager.ts
+++ b/src/main/download/downloadManager.ts
@@ -1,215 +1,125 @@
+import { trashDownload } from './trashDownload'
+import { describeError } from '../../shared/errors'
import { randomUUID } from 'node:crypto'
-import { readFile, readdir, rename, rm, stat, statfs, writeFile } from 'node:fs/promises'
-import { basename, join } from 'node:path'
+import { lstat, readFile, readdir, rename, rm, stat, statfs, writeFile } from 'node:fs/promises'
+import { basename, dirname, isAbsolute, join, sep } from 'node:path'
import type { BrowserWindow } from 'electron'
-import { app, Notification, powerSaveBlocker } from 'electron'
+import { app, Notification, powerSaveBlocker, shell } from 'electron'
import { IpcChannels } from '../../shared/ipc-channels'
-import type {
- BlockState,
- ChunkState,
- DownloadNetwork,
- DownloadState,
- DownloadStatus,
- DownloadUpdate,
- NetworkInterfaceInfo,
- NetworkStatus,
- StartDownloadRequest
+import {
+ DOWNLOADS_AT_ONCE,
+ type AppSettings,
+ type DownloadNetwork,
+ type DownloadState,
+ type DownloadStatus,
+ type DownloadUnitState,
+ type DownloadUpdate,
+ type FinishedDownload,
+ type HttpBlockState,
+ type HttpDownloadNetwork,
+ type HttpDownloadState,
+ type NetworkInterfaceInfo,
+ type NetworkStatus,
+ type StartDownloadRequest,
+ type StartHttpDownloadRequest,
+ type StartTorrentDownloadRequest,
+ type TorrentDownloadNetwork,
+ type TorrentDownloadState,
+ type TorrentFileEntry,
+ type TorrentInfo,
+ type TorrentPieceState
} from '../../shared/types'
-import { testKnobs, testStreamsPerNetwork } from '../testKnobs'
-import { advanceBlock, retractBlock } from './blockProgress'
-import { ConcurrencyController, type Action, type Snapshot } from './concurrency'
-import { downloadChunk, fetchRange, HttpStatusError, RemoteChangedError } from './chunkDownloader'
+import { Limits } from '../network/limits'
+import { loadSettings } from '../settings'
+import { addToHistory, findInHistory, removeFromHistory } from './history'
+import { testKnobs } from '../testKnobs'
import { DownloadFile } from './downloadFile'
-import { compareVersion, type FileVersion } from './fileVersion'
-import { ensureDirectory, reserveDestinationPath } from './paths'
+import { HttpTransfer, splittable } from './httpTransfer'
+import { ensureDirectory, pathExists, reserveDestinationPath } from './paths'
+import { planBlocks, planDownload, planPieces } from './plan'
+import { restoreBlocks, restorePieces, saveBlocks, type SavedBlocks } from './savedProgress'
+import { chosenFiles, finishedFiles, wantedPieces } from './torrent/files'
+import { probeUrl } from './probe'
+import { describeTorrent, probedTorrentFile } from './torrent/metadata'
+import { TorrentDestination } from './torrent/torrentDestination'
+import { TorrentTransfer } from './torrent/torrentTransfer'
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'
+ clearSpeeds,
+ delay,
+ Meters,
+ recomputeAggregates,
+ updateSpeeds,
+ updateTimeLeft,
+ type Transfer,
+ type TransferHost,
+ type HttpTransferTarget,
+ type TorrentTransferTarget
+} from './transfer'
import type { NetworkMonitor } from '../network/interfaces'
import {
compatibleInterfaces,
- ConnectionError,
NoCompatibleRouteError,
resolveTargetWithin,
- StreamConnection,
targetHost
} from '../network/routes'
-/** Why an attempt was called off by the manager rather than by a pause or a failure. */
-type AbortReason = 'refresh' | 'lost'
-
-/**
- * One request for one block, by one stream. A block normally has a single (primary) attempt.
- * Near the end of a download a second (hedge) one may race it — see scheduler.ts — and then the
- * block is finished by whichever gets there first.
- *
- * Both write straight into the staging file at the block's own offsets. Every response is checked
- * to be the download's version before any of it is written, so racing attempts write identical
- * bytes and it doesn't matter which lands last: whatever either has written stays secured.
- */
-interface Attempt {
- kind: 'primary' | 'hedge'
- block: BlockState
- streamId: number
- networkId: string
- /** Where the request begins, as an offset into the block. Null until it is known. */
- startOffset: number | null
- /** Bytes the destination writer has accepted; safe to resume from this prefix. */
- received: number
- /** Bytes the network has delivered, independently of disk backpressure. */
- networkReceived: number
- lastNetworkAt: number
- /** When the request was sent. */
- startedAt: number
- /** The network previously credited for this block's prefix. */
- previousWriter: string | undefined
- /** Aborts this request alone; ChunkRuntime.controller aborts the whole stream. */
- abort: AbortController
- abortReason: AbortReason | null
- /** What the server's answer cost, for diagnosing slow connections (see PLEXO_DEBUG). */
- response: { ttfbMs: number; reusedSocket: boolean } | null
-}
-
-/** What became of an attempt's request. */
-type AttemptOutcome =
- | { type: 'completed' }
- /** The download was paused or cancelled underneath it. */
- | { type: 'stopped' }
- /** Called off by the manager (see AbortReason). */
- | { type: 'aborted'; reason: AbortReason }
- | { type: 'failed'; error: unknown }
-
-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
- /** Cuts a backoff short without stopping the stream: what it was waiting out has changed (see
- * wake). Replaced once used. */
- nudge: AbortController
- /** Its one connection to the server, reused from block to block. */
- connection: StreamConnection
- /** What the stream is fetching right now, if anything. */
- attempt: Attempt | null
- /** When this connection last (re)connected; it isn't judged until SLOW_WARMUP_MS after. */
- warmSince: number
- slowSince: number | null
- /** Speed of its last finished block, start to end — 0 until it finishes one. */
- lastBlockSpeed: number
- /** Everything it has received, bytes another attempt already had included: what its speed is
- * measured from. (`ChunkState.bytesDownloaded` counts only bytes that were new.) */
- 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
- /** When the server first answered busy (see HttpStatusError.transient) since this stream last
- * made progress: a busy server is waited out for SERVER_BUSY_FOR_MS, not MAX_CHUNK_RETRIES. */
- busySince: number | null
- /** Since the stream count last looked: whether the server turned one of its requests away
- * (403, 429, 503, or left it unanswered), and whether it received anything. What a connection
- * limit is judged by (see concurrency.ts). */
- refused: boolean
- served: boolean
- /** Stopped for good, and to leave the list once its worker has (see retireStreams). */
- retiring: boolean
-}
-
-interface SpeedSample {
- bytes: number
- time: number
-}
-
-interface DownloadRuntime {
- state: DownloadState
+interface RuntimeFields {
publicationPath?: string
publicationIdentity?: { dev: number; ino: number }
- requestPayload: StartDownloadRequest
- 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: DownloadFile
runPromise?: Promise<void>
+ cancelPromise?: Promise<void>
publishing: boolean
- speedSamplesByChunk: Map<number, SpeedSample[]>
pushScheduled: boolean
- blocks: BlockState[]
- totalBlocks: number
persistenceTimer?: NodeJS.Timeout
persistenceChain: Promise<void>
removed: boolean
- /** The version this download started on, plus any since confirmed to serve identical bytes
- * (see confirmSameBytes). Not persisted: after a restart, a confirmation is simply redone. */
- acceptedVersions: FileVersion[]
- /** Slow-connection refreshes per block index, capped at MAX_REFRESHES_PER_BLOCK. */
- refreshesByBlock: Map<number, number>
- /** For a block whose last attempt delivered nothing, the network that made it. That network
- * leaves the block to another one while another is free to take it (see scheduler.ts). Not
- * persisted: it only steers the next hand-out. */
- avoidNetworkByBlock: Map<number, string>
- /** Attempts in flight, by block index. */
- attempts: Map<number, Attempt[]>
- /** Hedges started per block index, capped at SCHEDULER_POLICY.maxHedgesPerBlock. */
- hedgesByBlock: Map<number, number>
- /** By network id: everything its streams have received, and when it last showed it was alive —
- * received something, or came into use. */
- traffic: Map<string, { received: number; aliveAt: number }>
- /** By network id: until when the server asked (Retry-After) not to be sent new requests over
- * it. */
- holdUntil: Map<string, 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
/** Updates sent to the window so far (see DownloadUpdate). */
sentUpdates: number
/** Each block as the window was last sent it, by index — what tells a changed block apart. */
- sentBlocks: Pick<BlockState, 'status' | 'interfaceId' | 'bytesDownloaded'>[]
+ sentUnits: (Pick<DownloadUnitState, 'status' | 'interfaceId' | 'bytesDownloaded'> & {
+ provisionalBytes?: number
+ })[]
/** The network most recently switched off: what a resume switches back on if it finds none on.
* Not persisted: after a restart, the first network present is used instead. */
lastSwitchedOff?: string
/** Paused by switching off its last network, rather than by Pause: switching one back on
* resumes it. */
pausedForNoNetwork?: boolean
+ /** When the speeds last went into the history (see sampleSpeeds). */
+ speedSampledAt: number
+ /** The best combined speed this run has shown: the peak of one done before it held one. */
+ bestSpeedSeen: number
+ /** Changes asked of a torrent's choice of files, counted: only the latest applies. */
+ fileChoices: number
+}
+
+interface HttpDownloadRuntime extends RuntimeFields, HttpTransferTarget {
+ kind: 'http'
+ transfer: Transfer
+}
+
+interface TorrentDownloadRuntime extends RuntimeFields, TorrentTransferTarget {
+ kind: 'torrent'
+ transfer: TorrentTransfer
}
+type DownloadRuntime = HttpDownloadRuntime | TorrentDownloadRuntime
+
interface PersistedDownloadBase {
savedAt: number
partialPath: string
publicationPath?: string
publicationIdentity?: { dev: number; ino: number }
requestPayload: StartDownloadRequest
- /** 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 &
- (
- | ({ version: 5; state: Omit<DownloadState, 'blocks'> } & SavedBlocks)
- /** Written before version 5, with every block saved whole; still read, so an update doesn't
- * lose the progress of a download it finds paused. */
- | { version: 4; state: DownloadState }
- )
+type PersistedState =
+ Omit<HttpDownloadState, 'blocks' | 'streams'> | Omit<TorrentDownloadState, 'pieces' | 'peers'>
-// Set PLEXO_DEBUG=1 to log every request's outcome, how long the server took to answer and
-// whether it reused a warm connection — what it takes to tell one slow connection from a slow path.
-const debug: (...args: unknown[]) => void = process.env['PLEXO_DEBUG']
- ? (...args) => console.debug('[plexo]', ...args)
- : () => {}
+type PersistedDownload = PersistedDownloadBase & {
+ version: 7
+ state: PersistedState
+} & SavedBlocks
const UI_UPDATE_MS = 200
/** How often a running download takes stock (see run). */
@@ -218,176 +128,34 @@ const TICK_MS = 500
// checkpoints independent of UI updates; pause and publication still force an immediate sync.
const CHECKPOINT_INTERVAL_MS = 15_000
-// Raw per-event deltas are too noisy to display (socket buffers flush in
-// irregular bursts a few ms apart). Averaging over a few seconds instead
-// gives a speed/ETA reading that tracks reality without jumping around.
-const SPEED_WINDOW_MS = 3000
-
-// Appends a sample and returns the average byte rate over SPEED_WINDOW_MS.
-function pushSpeedSample(samples: SpeedSample[], bytes: number, time: number): number {
- if (samples.length > 0 && time - samples[samples.length - 1].time > SPEED_WINDOW_MS) {
- samples.length = 0
- }
- samples.push({ bytes, time })
-
- return calculateCurrentSpeed(samples, time)
-}
-
-function calculateCurrentSpeed(samples: SpeedSample[] | undefined, time: number): number {
- if (!samples || samples.length === 0) return 0
-
- const latest = samples[samples.length - 1]
- if (time - latest.time > SPEED_WINDOW_MS) {
- return 0
- }
-
- const cutoff = time - SPEED_WINDOW_MS
- while (samples.length > 2 && samples[1].time <= cutoff) {
- samples.shift()
- }
-
- // At least a second: a fresh window can hold two samples ms apart, and one socket burst over a
- // few ms reads as a speed the connection never had (and sticks as the UI's peak).
- const oldest = samples[0]
- const deltaSeconds = Math.max((time - oldest.time) / 1000, 1)
- return (latest.bytes - oldest.bytes) / deltaSeconds
-}
-
-const MAX_CHUNK_RETRIES = 5
-const RETRY_BASE_DELAY_MS = testKnobs.retryBaseDelayMs
-const RETRY_MAX_DELAY_MS = 15_000
-// A network that can't reach the server keeps one stream asking (see reconcile). That is one
-// cheap connection, so it asks often enough to find out soon after the network gets through.
-const UNREACHABLE_RETRY_MS = 5_000
-// A server that answers busy (429, 503, …) is waited out this long before a stream gives up on
-// it, however many retries that takes; what it asks for in Retry-After is waited, up to
-// RETRY_AFTER_MAX_MS.
-const SERVER_BUSY_FOR_MS = testKnobs.serverBusyForMs
-const RETRY_AFTER_MAX_MS = 120_000
-
-/** Doubling from RETRY_BASE_DELAY_MS, with ±20% jitter as gRPC's backoff has: a network that
- * drops fails all its streams at once, and they shouldn't all come back at the same instant. */
-function retryDelayMs(attempt: number): number {
- const exact = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), RETRY_MAX_DELAY_MS)
- return exact * (0.8 + 0.4 * Math.random())
-}
-
-// A single TCP stream can get stuck at a crawl (loss-collapsed congestion window, a bad CDN node
-// or route) while its siblings on the same network run fine. It never goes silent, so the stall
-// watchdog can't catch it; a fresh connection usually lands somewhere healthy. Only relative
-// thresholds — nothing here knows how fast the network ought to be.
-const SLOW_RATIO = 0.1
-const SLOW_WARMUP_MS = testKnobs.slowWarmupMs
-const 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). 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.
-const MAX_REFRESHES_PER_BLOCK = 2
-const SCHEDULER_POLICY: SchedulerPolicy = {
- hedgeAfterMs: testKnobs.hedgeAfterMs,
- maxHedgesPerBlock: 2,
- startupMs: 1000
-}
-
-/** 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 {
- if (!splittable(request) || testStreamsPerNetwork() !== null) return null
- const picked = pickedStreams(request)
- return picked === undefined
- ? new ConcurrencyController(MAX_STREAMS_PER_NETWORK)
- : new ConcurrencyController(picked, false)
-}
-
-/** The streams per network the user picked for this download, if they didn't leave it on Auto. */
-function pickedStreams(request: StartDownloadRequest): number | undefined {
- const picked = request.streamsPerNetwork
- return Number.isInteger(picked) && picked! >= 1 && picked! <= MAX_STREAMS_PER_NETWORK
- ? picked
- : undefined
-}
-/** How often a stream with nothing to do looks for work again. */
-const IDLE_POLL_MS = 250
-// Just longer than an idle stream takes to look for work, so a refreshed block goes to a
-// connection that is already proven fast, if there is one.
-const REFRESH_HANDOFF_MS = IDLE_POLL_MS + 50
-
-function median(values: number[]): number {
- const sorted = [...values].sort((a, b) => a - b)
- const mid = sorted.length >> 1
- return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2
+const SPEED_HISTORY_LENGTH = 60
+// The peak is the best speed held this many samples (seconds): longer than a start's burst (an
+// ISP's burst allowance, every connection ramping up at once), which isn't the line's speed.
+const PEAK_SAMPLES = 5
+
+/** Adds each network's speed to the download's history, and 0 for one no longer listed. A
+ * network seen for the first time starts at 0 too, so every series is as long as the others and
+ * lines up with them. Then raises the peak, once the last PEAK_SAMPLES are in. */
+function sampleSpeeds(state: DownloadState): void {
+ const history = (state.speedHistory ??= {})
+ const length = Object.values(history)[0]?.length ?? 0
+ for (const network of state.networks) {
+ history[network.id] ??= new Array<number>(length).fill(0)
+ }
+ for (const [id, series] of Object.entries(history)) {
+ series.push(state.networks.find((network) => network.id === id)?.speedBytesPerSec ?? 0)
+ if (series.length > SPEED_HISTORY_LENGTH) series.shift()
+ }
+ const series = Object.values(history)
+ if (series[0].length < PEAK_SAMPLES) return
+ let held = 0
+ for (const values of series) for (const value of values.slice(-PEAK_SAMPLES)) held += value
+ state.peakSpeedBytesPerSec = Math.max(state.peakSpeedBytesPerSec ?? 0, held / PEAK_SAMPLES)
}
-/** 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
- }
- 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). */
-function delay(ms: number, signal: AbortSignal): Promise<void> {
- return new Promise((resolve) => {
- if (signal.aborted) {
- resolve()
- return
- }
- const onAbort = (): void => {
- clearTimeout(timer)
- resolve()
- }
- const timer = setTimeout(() => {
- signal.removeEventListener('abort', onAbort)
- resolve()
- }, ms)
- signal.addEventListener('abort', onAbort, { once: true })
- })
-}
-
-function newStream(id: number, networkId: string): ChunkState {
- return {
- id,
- interfaceId: networkId,
- rangeStart: 0,
- rangeEnd: null,
- bytesDownloaded: 0,
- speedBytesPerSec: 0,
- status: 'pending'
- }
-}
-
-function newNetwork(iface: NetworkInterfaceInfo, enabled: boolean): DownloadNetwork {
+function newHttpNetwork(iface: NetworkInterfaceInfo, enabled: boolean): HttpDownloadNetwork {
return {
+ transfer: 'http',
id: iface.id,
label: iface.displayName,
kind: iface.kind,
@@ -399,52 +167,99 @@ function newNetwork(iface: NetworkInterfaceInfo, enabled: boolean): DownloadNetw
}
}
-/** A runtime for `state`, with nothing running. */
-function newRuntime(
- state: DownloadState,
- requestPayload: StartDownloadRequest,
- file: DownloadFile,
- blocks: BlockState[]
-): DownloadRuntime {
+function newTorrentNetwork(iface: NetworkInterfaceInfo, enabled: boolean): TorrentDownloadNetwork {
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(),
- holdUntil: new Map(),
- concurrency: concurrencyFor(requestPayload),
- sentUpdates: 0,
- sentBlocks: []
+ ...newHttpNetwork(iface, enabled),
+ transfer: 'torrent',
+ bytesUploaded: 0,
+ uploadSpeedBytesPerSec: 0
}
}
-function requestedVersion(request: StartDownloadRequest): FileVersion {
- return { etag: request.etag, lastModified: request.lastModified, totalBytes: request.totalBytes }
+/** A block that needs nothing more: in, or skipped (see BlockStatus). */
+const isDone = (unit: DownloadUnitState): boolean =>
+ unit.status === 'completed' || unit.status === 'skipped'
+
+const unitsOf = (runtime: DownloadRuntime): DownloadUnitState[] =>
+ runtime.kind === 'http' ? runtime.blocks : runtime.pieces
+
+/** A torrent download's files as its state shows them, given those `chosen` (null: every one). */
+function choiceOf(chosen: Set<number> | null, total: number): TorrentDownloadState['files'] {
+ const selected = chosen ? [...chosen].sort((a, b) => a - b) : undefined
+ return { chosen: selected?.length ?? total, total, selected }
}
-// How much of the already-downloaded file to re-fetch and compare when a server labels a
-// response with an ETag or Last-Modified this download hasn't seen before.
-const SAMPLE_BYTES = 16 * 1024
-const MAX_SAMPLES = 8
-/** A sample must come from a server presenting the new label; behind a load balancer the next
- * request may land on another one, so take a few tries at reaching it. */
-const SAMPLE_TRIES = 4
+/** Sets each piece of `torrent` by whether a `chosen` file (null: every one) needs it: skipped
+ * when none does, waiting again when one does. A piece that's in stays in, needed or not. The
+ * skipped pieces' bytes, all together. As a download starts, comes back, or its choice changes. */
+function choosePieces(
+ pieces: TorrentPieceState[],
+ torrent: TorrentInfo,
+ chosen: Set<number> | null
+): number {
+ const wanted = chosen && wantedPieces(torrent.files, torrent.pieceLength, chosen)
+ let skipped = 0
+ for (const piece of pieces) {
+ if (piece.status === 'completed' || piece.rangeEnd === null) continue
+ if (!wanted || wanted[piece.index]) {
+ if (piece.status === 'skipped') piece.status = 'pending'
+ continue
+ }
+ piece.status = 'skipped'
+ piece.provisionalBytes = 0
+ skipped += piece.rangeEnd - piece.rangeStart + 1
+ }
+ return skipped
+}
+
+/** The files not `chosen`, as the torrent names them. */
+function unchosenPaths(torrent: TorrentInfo, chosen: Set<number> | null): string[] {
+ return chosen
+ ? torrent.files.filter((_, index) => !chosen.has(index)).map((file) => file.path)
+ : []
+}
+
+const isNotFound = (error: unknown): boolean =>
+ (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'
+
+/** A manifest this version writes, for the download in folder `id`. */
+function isCurrentManifest(value: unknown, id: string): value is PersistedDownload {
+ const manifest = value as Partial<PersistedDownload> | null
+ return manifest?.version === 7 && manifest.state?.id === id
+}
+
+/**
+ * Where a saved download that can't be restored kept its partial data beside its destination:
+ * only what is unmistakably Plexo's, so that a damaged manifest can never point it at a real file.
+ * - A `<name>.plexo` staging file, or a torrent's `<name>.plexo/` staging folder.
+ * - rc.1–rc.9 (manifest version 2) claimed the final name itself as an empty file, until the
+ * download's parts were joined into it: taken while it is still empty and the download
+ * unfinished, never once it holds anything.
+ */
+async function partialLeftovers(persisted: unknown): Promise<string[]> {
+ const manifest = persisted as {
+ version?: unknown
+ partialPath?: unknown
+ state?: { status?: unknown; destinationPath?: unknown }
+ } | null
+ const leftovers: string[] = []
+ const partial = manifest?.partialPath
+ if (typeof partial === 'string' && isAbsolute(partial)) {
+ if (partial.endsWith('.plexo')) leftovers.push(partial)
+ else if (dirname(partial).endsWith('.plexo')) leftovers.push(dirname(partial))
+ }
+ const placeholder = manifest?.state?.destinationPath
+ if (
+ manifest?.version === 2 &&
+ manifest.state?.status !== 'completed' &&
+ typeof placeholder === 'string' &&
+ isAbsolute(placeholder)
+ ) {
+ const found = await lstat(placeholder).catch(() => null)
+ if (found?.isFile() && found.size === 0) leftovers.push(placeholder)
+ }
+ return leftovers
+}
function formatGigabytes(bytes: number): string {
return `${(bytes / 1024 ** 3).toFixed(2)} GB`
@@ -470,12 +285,79 @@ export class DownloadManager {
private seenAddresses = new Map<string, string[]>()
/** The powerSaveBlocker keeping the computer awake while a download runs (see keepAwake). */
private awakeBlocker: number | null = null
+ /** How many downloads may run at once; the rest wait, queued (see pump). */
+ private downloadsAtOnce = DOWNLOADS_AT_ONCE.default
+ /** Speed and data limits, for every download together. */
+ readonly limits = new Limits(() => this.limitsChanged())
constructor(
private getWindow: () => BrowserWindow | null,
private networks: NetworkMonitor
) {
- this.initialization = this.restorePersistedDownloads()
+ this.initialization = Promise.all([
+ this.restorePersistedDownloads(),
+ this.limits.loaded,
+ loadSettings().then((settings) => this.applySettings(settings))
+ ]).then(() => {})
+ }
+
+ /** Takes up what the user set: how many run at once, and the limits. One running past a
+ * lowered count is left to finish; a raised one starts the next ones in the queue. */
+ applySettings(settings: AppSettings): void {
+ this.downloadsAtOnce = settings.downloadsAtOnce ?? DOWNLOADS_AT_ONCE.default
+ this.limits.configure(settings)
+ this.limitsChanged()
+ this.pump()
+ }
+
+ /** A network ran out of data, or a limit changed: each download's networks are looked at
+ * again, so one at its limit stops being used, and one no longer at it is used again. */
+ async resetNetworkUsage(id: string): Promise<void> {
+ await this.limits.resetUsage(id)
+ this.limitsChanged()
+ }
+
+ private limitsChanged(): void {
+ for (const runtime of this.runtimes.values()) {
+ const { status } = runtime.state
+ if (status !== 'downloading' && status !== 'paused' && status !== 'queued') continue
+ this.reconcile(runtime)
+ this.scheduleUpdate(runtime)
+ }
+ }
+
+ private runningCount(): number {
+ let running = 0
+ for (const runtime of this.runtimes.values()) {
+ if (runtime.state.status === 'downloading') running++
+ }
+ return running
+ }
+
+ /** Starts queued downloads, first queued first, while fewer than downloadsAtOnce run. Called
+ * whenever one might have room: a run ended, a queued one went, the count went up. */
+ private pump(): void {
+ if (this.suspending) return
+ const queued = [...this.runtimes.values()]
+ .filter((runtime) => runtime.state.status === 'queued')
+ .sort((a, b) => (a.state.queuedAt ?? 0) - (b.state.queuedAt ?? 0))
+ for (const runtime of queued) {
+ if (this.runningCount() >= this.downloadsAtOnce) return
+ this.begin(runtime)
+ }
+ }
+
+ /** Puts a download in the queue: at its end, or at its front when the user asked for it. */
+ private enqueue(runtime: DownloadRuntime, front: boolean): void {
+ const places = [...this.runtimes.values()]
+ .filter((other) => other !== runtime && other.state.status === 'queued')
+ .map((other) => other.state.queuedAt ?? 0)
+ runtime.state.status = 'queued'
+ // Time spent waiting isn't time spent downloading (begin adds it to totalPausedMs).
+ runtime.state.pausedAt ??= Date.now()
+ runtime.state.queuedAt = front
+ ? Math.min(Date.now(), ...places) - 1
+ : Math.max(Date.now(), ...places.map((place) => place + 1))
}
private downloadsRoot(): string {
@@ -490,6 +372,85 @@ export class DownloadManager {
return join(this.downloadDir(id), 'manifest.json')
}
+ /** Where a torrent download keeps its .torrent, beside its manifest. */
+ private torrentFilePath(id: string): string {
+ return join(this.downloadDir(id), 'metadata.torrent')
+ }
+
+ private runtimeFields(): RuntimeFields {
+ return {
+ publishing: false,
+ pushScheduled: false,
+ persistenceChain: Promise.resolve(),
+ removed: false,
+ sentUpdates: 0,
+ sentUnits: [],
+ speedSampledAt: 0,
+ bestSpeedSeen: 0,
+ fileChoices: 0
+ }
+ }
+
+ private newHttpRuntime(
+ state: HttpDownloadState,
+ requestPayload: StartHttpDownloadRequest,
+ file: DownloadFile,
+ blocks: HttpBlockState[]
+ ): HttpDownloadRuntime {
+ const target: HttpTransferTarget = {
+ state,
+ requestPayload,
+ stop: new AbortController(),
+ file,
+ blocks,
+ meters: new Meters()
+ }
+ const host: TransferHost = {
+ networks: this.networks,
+ limits: this.limits,
+ reconcile: () => this.reconcile(runtime),
+ failDownload: (message, discard) => this.failDownload(runtime, message, discard),
+ failNetwork: (network, message) => this.failNetwork(runtime, network, message),
+ scheduleUpdate: () => this.scheduleUpdate(runtime)
+ }
+ const runtime: HttpDownloadRuntime = Object.assign(target, this.runtimeFields(), {
+ kind: 'http' as const,
+ transfer: new HttpTransfer(target, host)
+ })
+ return runtime
+ }
+
+ private newTorrentRuntime(
+ state: TorrentDownloadState,
+ requestPayload: StartTorrentDownloadRequest,
+ file: TorrentDestination,
+ pieces: TorrentDownloadState['pieces'],
+ torrentFile: Uint8Array
+ ): TorrentDownloadRuntime {
+ const target: TorrentTransferTarget = {
+ state,
+ requestPayload,
+ stop: new AbortController(),
+ file,
+ pieces,
+ meters: new Meters(),
+ uploadMeters: new Meters()
+ }
+ const host: TransferHost = {
+ networks: this.networks,
+ limits: this.limits,
+ reconcile: () => this.reconcile(runtime),
+ failDownload: (message, discard) => this.failDownload(runtime, message, discard),
+ failNetwork: (network, message) => this.failNetwork(runtime, network, message),
+ scheduleUpdate: () => this.scheduleUpdate(runtime)
+ }
+ const runtime: TorrentDownloadRuntime = Object.assign(target, this.runtimeFields(), {
+ kind: 'torrent' as const,
+ transfer: new TorrentTransfer(target, host, torrentFile, file.path)
+ })
+ return runtime
+ }
+
private async restorePersistedDownloads(): Promise<void> {
let entries: string[]
try {
@@ -501,260 +462,462 @@ export class DownloadManager {
const restored: DownloadRuntime[] = []
await Promise.all(
entries.map(async (id) => {
+ await rm(`${this.manifestPath(id)}.tmp`, { force: true }).catch(() => {})
+ let persisted: unknown
try {
- await rm(`${this.manifestPath(id)}.tmp`, { force: true })
- const persisted = JSON.parse(
- await readFile(this.manifestPath(id), 'utf-8')
- ) as PersistedDownload
- if (persisted.state.id !== id) return
- const blocks =
- persisted.version === 5
- ? restoreBlocks(persisted.state, persisted)
- : persisted.version === 4
- ? persisted.state.blocks
- : undefined
- if (!blocks) return
- 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()
+ persisted = JSON.parse(await readFile(this.manifestPath(id), 'utf-8'))
+ } catch (error) {
+ // No manifest, or a garbled one: nothing can bring it back. Any other read error (a
+ // drive not mounted, a permission) may pass, and is left for the next launch.
+ if (error instanceof SyntaxError || isNotFound(error)) {
+ await this.discardUnrestorable(id, undefined)
}
- clearSpeeds(state)
- for (const block of blocks) {
- if (block.status === 'downloading') block.status = 'pending'
- }
-
- const file = new DownloadFile(persisted.partialPath)
- if (state.status === 'paused') {
- const size = await file.size().catch(() => -1)
- const publishedPath = persisted.publicationPath ?? state.destinationPath
- const published = await stat(publishedPath).catch(() => null)
- const publishedSize = published?.size ?? -1
- const expected = state.totalBytes || state.bytesDownloaded
- const sameFile =
- !!published &&
- (size >= 0
- ? await stat(file.path)
- .then(
- (partial) => partial.dev === published.dev && partial.ino === published.ino
- )
- .catch(() => false)
- : persisted.publicationIdentity?.dev === published.dev &&
- persisted.publicationIdentity?.ino === published.ino)
- if (
- blocks.every((block) => block.status === 'completed') &&
- publishedSize === expected &&
- sameFile
- ) {
- state.status = 'completed'
- state.destinationPath = publishedPath
- state.fileName = basename(publishedPath)
- state.error = undefined
- state.completedAt ??= persisted.savedAt
- if (size >= 0) await file.discard()
- } else if (size < 0) {
- 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
- if (
- block.rangeStart + block.bytesDownloaded > size ||
- (block.status === 'completed' && block.bytesDownloaded !== length)
- ) {
- block.status = 'pending'
- block.bytesDownloaded = 0
- block.bytesByInterface = {}
- }
- }
- state.bytesDownloaded = blocks.reduce((sum, block) => sum + block.bytesDownloaded, 0)
- }
- }
-
- const runtime = newRuntime(state, persisted.requestPayload, file, blocks)
- runtime.publicationPath = persisted.publicationPath
- runtime.publicationIdentity = persisted.publicationIdentity
- this.recomputeAggregates(runtime)
- restored.push(runtime)
+ return
+ }
+ // Another version's, which this one doesn't read: rc.1–rc.9 kept parts in a folder of
+ // their own (manifest version 2), later ones a different layout. Cleared, not kept forever.
+ if (!isCurrentManifest(persisted, id)) return this.discardUnrestorable(id, persisted)
+ try {
+ const runtime = await this.restoreOne(id, persisted)
+ if (runtime) restored.push(runtime)
+ else await this.discardUnrestorable(id, persisted)
} catch {
- // Ignore incomplete or corrupt manifests; other downloads can still be restored.
+ // As above: left for a launch where it can be read.
}
})
)
- // Plexo only ever tracks one current download — getCurrentDownload() always returns
- // whichever restored runtime started most recently. Any other one restored alongside it is
- // an orphan (most likely left over from before concurrent starts were blocked): nothing
- // would ever look at it again, so left in `runtimes` it would sit there forever, invisibly
- // failing every future start() with "a download is already in progress".
+ // Two writing one partial file would scramble it: of any that share one, the newest is kept
+ // and the others go, the file left to it.
restored.sort((a, b) => b.state.startedAt - a.state.startedAt)
- const [current, ...orphans] = restored
-
+ const claimed = new Set<string>()
+ const kept = restored.filter((runtime) => {
+ if (claimed.has(runtime.file.path)) return false
+ claimed.add(runtime.file.path)
+ return true
+ })
await Promise.all(
- orphans.map((runtime) =>
- this.removePersistedDownload(runtime, runtime.file.path !== current?.file.path)
- )
+ restored
+ .filter((runtime) => !kept.includes(runtime))
+ .map((runtime) => this.removePersistedDownload(runtime, false))
)
- if (current) {
- if (current.state.status === 'completed' && current.publicationIdentity) {
- const published = await stat(current.state.destinationPath).catch(() => null)
- if (
- published?.dev === current.publicationIdentity.dev &&
- published.ino === current.publicationIdentity.ino
- ) {
- await current.file.discard().catch(() => {})
+ await Promise.all(
+ kept.map(async (runtime) => {
+ if (runtime.state.status === 'completed' && runtime.publicationIdentity) {
+ const published = await stat(runtime.state.destinationPath).catch(() => null)
+ if (
+ published?.dev === runtime.publicationIdentity.dev &&
+ published.ino === runtime.publicationIdentity.ino
+ ) {
+ await runtime.file.discardLeftover().catch(() => {})
+ }
}
+ this.runtimes.set(runtime.state.id, runtime)
+ // Finished before the relaunch (or found to be): history keeps it from here.
+ if (runtime.state.status === 'completed') await this.moveToHistory(runtime)
+ else await this.persistNow(runtime)
+ })
+ )
+ }
+
+ /** A finished download leaves the list of running ones for history, with its work units: a
+ * download that is done needs none of them. Its saved state goes only once history has it. */
+ private async moveToHistory(runtime: DownloadRuntime): Promise<void> {
+ let entry: FinishedDownload
+ if (runtime.kind === 'http') {
+ const { blocks: omittedBlocks, streams: omittedStreams, ...state } = runtime.state
+ void omittedBlocks
+ void omittedStreams
+ entry = { ...state, unitsWritten: state.totalBlocks }
+ } else {
+ const { pieces, peers: omittedPeers, ...state } = runtime.state
+ void omittedPeers
+ const written = pieces.filter((piece) => piece.status !== 'skipped').length
+ const files = await this.torrentFiles(state.id)
+ entry = {
+ ...state,
+ unitsWritten: written,
+ downloadedFiles: files
+ .filter((file) => file.chosen)
+ .map((file) =>
+ state.folder ? file.path.split(/[\\/]/).slice(1).join(sep) : basename(file.path)
+ )
}
- this.runtimes.set(current.state.id, current)
- await this.persistNow(current)
}
+ try {
+ await addToHistory(structuredClone(entry))
+ } catch {
+ // Kept as it is, to be moved on the next launch.
+ return
+ }
+ this.runtimes.delete(runtime.state.id)
+ await this.removePersistedDownload(runtime, false)
+ this.historyChanged()
}
- /** A snapshot of the current download: an update with every block in it. */
- async getCurrentDownload(): Promise<DownloadUpdate | null> {
- await this.initialization
- const latest = [...this.runtimes.values()].sort(
- (a, b) => b.state.startedAt - a.state.startedAt
- )[0]
- if (!latest) return null
- const { blocks, ...state } = latest.state
- return structuredClone({ seq: latest.sentUpdates, state, blocks: blocks ?? latest.blocks })
+ private historyChanged(): void {
+ const window = this.getWindow()
+ if (window && !window.isDestroyed()) window.webContents.send(IpcChannels.historyChanged)
}
- /** Plexo shows one download at a time (see useAppStore's currentDownload) — starting a second
- * one while one is already running or paused would silently race it for disk I/O and
- * scramble the renderer's single-download view as updates from both interleave. */
- private hasActiveDownload(): boolean {
- for (const runtime of this.runtimes.values()) {
- if (runtime.state.status === 'downloading' || runtime.state.status === 'paused') {
- return true
+ /** Forgets every finished download. Their files are the user's: they stay. */
+ async clearHistory(): Promise<void> {
+ await this.initialization
+ await Promise.allSettled(
+ [...this.runtimes.values()]
+ .filter((runtime) => runtime.state.status === 'completed')
+ .map((runtime) => runtime.runPromise)
+ )
+ await removeFromHistory()
+ this.historyChanged()
+ }
+
+ /** A saved download as this version writes it, restored paused — or null when it never can
+ * be: its progress doesn't fit its plan, or a torrent's .torrent is gone. */
+ private async restoreOne(
+ id: string,
+ persisted: PersistedDownload
+ ): Promise<DownloadRuntime | null> {
+ const { requestPayload } = persisted
+ const saved: SavedBlocks = { progress: persisted.progress, complete: persisted.complete }
+ let state: DownloadState
+ let runtime: DownloadRuntime
+ if (persisted.state.kind === 'torrent' && requestPayload.kind === 'torrent') {
+ const torrentFile = await readFile(this.torrentFilePath(id)).catch((error: unknown) => {
+ if (isNotFound(error)) return null
+ throw error
+ })
+ if (!torrentFile) return null
+ const probe = await describeTorrent(torrentFile, requestPayload.url)
+ if (probe.kind !== 'torrent') return null
+ const { torrent } = probe
+ const old = persisted.state
+ const pieces = restorePieces(old, saved)
+ if (!pieces) return null
+ const chosen = chosenFiles(requestPayload.selectedFiles, torrent.files.length)
+ state = {
+ ...old,
+ networks: old.networks.map((network) => ({ ...network, uploadSpeedBytesPerSec: 0 })),
+ peers: [],
+ pieces,
+ totalPieces: pieces.length,
+ pieceLength: torrent.pieceLength,
+ files: choiceOf(chosen, torrent.files.length),
+ // Its pieces no chosen file needs are skipped again.
+ skippedBytes: choosePieces(pieces, torrent, chosen),
+ uploadSpeedBytesPerSec: 0
+ }
+ runtime = this.newTorrentRuntime(
+ state,
+ requestPayload,
+ new TorrentDestination(
+ persisted.partialPath,
+ state.totalBytes,
+ unchosenPaths(torrent, chosen),
+ torrent.files.map((file) => file.path)
+ ),
+ pieces,
+ torrentFile
+ )
+ } else if (persisted.state.kind === 'http' && requestPayload.kind === 'http') {
+ const old = persisted.state
+ const blocks = restoreBlocks(old, saved)
+ if (!blocks) return null
+ state = { ...old, streams: [], blocks, totalBlocks: blocks.length }
+ runtime = this.newHttpRuntime(
+ state,
+ requestPayload,
+ new DownloadFile(persisted.partialPath),
+ blocks
+ )
+ } else {
+ return null
+ }
+ const units = unitsOf(runtime)
+ // Nothing starts by itself after a relaunch: running or waiting, it comes back paused.
+ if (state.status === 'downloading' || state.status === 'queued') {
+ state.status = 'paused'
+ state.pausedAt = persisted.savedAt || Date.now()
+ state.queuedAt = undefined
+ }
+ clearSpeeds(state)
+ for (const unit of units) {
+ if (unit.status === 'downloading') unit.status = 'pending'
+ if (unit.kind === 'torrent') unit.provisionalBytes = 0
+ }
+
+ const file = runtime.file
+ if (state.status === 'paused') {
+ const size = await file.size().catch(() => -1)
+ const publishedPath = persisted.publicationPath ?? state.destinationPath
+ const published = await stat(publishedPath).catch(() => null)
+ // A torrent's folder of files: its identity below is what tells it's this download's.
+ const publishedSize = published?.isDirectory() ? state.totalBytes : (published?.size ?? -1)
+ const expected = state.totalBytes || state.bytesDownloaded
+ const sameFile =
+ !!published &&
+ (size >= 0
+ ? await stat(file.path)
+ .then((partial) => partial.dev === published.dev && partial.ino === published.ino)
+ .catch(() => false)
+ : persisted.publicationIdentity?.dev === published.dev &&
+ persisted.publicationIdentity?.ino === published.ino)
+ if (units.every(isDone) && publishedSize === expected && sameFile) {
+ state.status = 'completed'
+ state.destinationPath = publishedPath
+ state.fileName = basename(publishedPath)
+ state.error = undefined
+ state.completedAt ??= persisted.savedAt
+ if (size >= 0) await file.discardLeftover()
+ } else if (size < 0) {
+ state.status = 'error'
+ state.error = 'The partial download file is missing. Remove this download and start again.'
+ state.resumable = false
+ } else {
+ for (const unit of units) {
+ const length = unit.rangeEnd === null ? 0 : unit.rangeEnd - unit.rangeStart + 1
+ if (
+ unit.rangeStart + unit.bytesDownloaded > size ||
+ (unit.status === 'completed' && unit.bytesDownloaded !== length)
+ ) {
+ unit.status = 'pending'
+ unit.bytesDownloaded = 0
+ unit.bytesByInterface = {}
+ }
+ }
+ state.bytesDownloaded = units.reduce((sum, unit) => sum + unit.bytesDownloaded, 0)
}
}
- return false
+
+ runtime.publicationPath = persisted.publicationPath
+ runtime.publicationIdentity = persisted.publicationIdentity
+ // A resumed download's last minute starts when it does, not where it stopped before the
+ // relaunch; a finished one keeps its chart.
+ if (state.status !== 'completed') state.speedHistory = undefined
+ recomputeAggregates(state, units)
+ return runtime
+ }
+
+ /**
+ * Clears a saved download that can't be restored, rather than keep it forever: its folder here
+ * (manifest, a saved .torrent, an old version's parts/ folder), and its partial data beside the
+ * destination when that is unmistakably Plexo's (see partialLeftovers).
+ */
+ private async discardUnrestorable(id: string, persisted: unknown): Promise<void> {
+ for (const path of await partialLeftovers(persisted)) {
+ await rm(path, { recursive: true, force: true }).catch(() => {})
+ }
+ await rm(this.downloadDir(id), { recursive: true, force: true }).catch(() => {})
+ }
+
+ /** A snapshot of every download: updates with every work unit in them, oldest first. */
+ async listDownloads(): Promise<DownloadUpdate[]> {
+ await this.initialization
+ return [...this.runtimes.values()]
+ .sort((a, b) => a.state.startedAt - b.state.startedAt)
+ .map((runtime) => {
+ if (runtime.kind === 'http') {
+ const { blocks, ...state } = runtime.state
+ return structuredClone({ seq: runtime.sentUpdates, state, blocks })
+ }
+ const { pieces, ...state } = runtime.state
+ return structuredClone({ seq: runtime.sentUpdates, state, pieces })
+ })
}
async start(requestPayload: StartDownloadRequest): Promise<string> {
await this.initialization
- if (this.hasActiveDownload()) {
- throw new Error('A download is already in progress — finish or remove it first.')
- }
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')
+ throw new Error('Select at least one network')
}
- const target = new URL(requestPayload.url)
- // 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 (usable.length === 0) throw new NoCompatibleRouteError(targetHost(target))
-
await ensureDirectory(requestPayload.destinationDir)
- await ensureDiskSpace(requestPayload.destinationDir, requestPayload.totalBytes)
-
- const plan = planDownload({
- totalBytes: requestPayload.totalBytes,
- splittable: requestPayload.supportsRanges,
- networkCount: usable.length,
- maxBlockBytes: testKnobs.blockBytes // 8 MB outside tests
- })
-
- // Claimed on disk, not just picked, so a second download of the same file
- // name can't pick it too and overwrite this one at publish time. Done
- // before anything else is created, so a destination we can't write to
- // leaves nothing behind.
- const destinationPath = await reserveDestinationPath(
- requestPayload.destinationDir,
- requestPayload.suggestedFileName
- )
-
const id = randomUUID()
- const file = new DownloadFile(`${destinationPath}.plexo`)
-
- // The UI caps how many cells it renders separately (see BlockGrid), by bucketing these
- // blocks rather than by shrinking their count here.
- const blocks = planBlocks(requestPayload.totalBytes, plan.blockSizeBytes)
-
- // 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,
- url: requestPayload.url,
- fileName: basename(destinationPath),
- destinationPath,
- totalBytes: requestPayload.totalBytes,
- bytesDownloaded: 0,
- speedBytesPerSec: 0,
- status: 'downloading',
- networks,
- chunks: [],
- peakStreams: 0,
- blocks,
- totalBlocks: blocks.length,
- blockSizeBytes: plan.blockSizeBytes,
- startedAt: Date.now()
+ let runtime: DownloadRuntime
+ if (requestPayload.kind === 'torrent') {
+ const torrentFile = probedTorrentFile(requestPayload.infoHash)
+ if (!torrentFile) throw new Error('Add the torrent again to start downloading.')
+ const torrentProbe = await describeTorrent(torrentFile, requestPayload.url)
+ if (torrentProbe.kind !== 'torrent') throw new Error('Invalid torrent metadata')
+ const torrent = torrentProbe.torrent
+ const totalBytes = torrent.files.reduce((sum, entry) => sum + entry.length, 0)
+ const chosen = chosenFiles(requestPayload.selectedFiles, torrent.files.length)
+ const pieces = planPieces(totalBytes, torrent.pieceLength)
+ const skippedBytes = choosePieces(pieces, torrent, chosen)
+ await ensureDiskSpace(requestPayload.destinationDir, totalBytes - skippedBytes)
+ const folder = torrent.files[0].path.includes(sep)
+ const file = await TorrentDestination.create(
+ requestPayload.destinationDir,
+ requestPayload.suggestedFileName,
+ folder,
+ totalBytes,
+ unchosenPaths(torrent, chosen),
+ torrent.files.map((file) => file.path)
+ )
+ const destinationPath = file.path
+ await ensureDirectory(this.downloadDir(id))
+ await writeFile(this.torrentFilePath(id), torrentFile)
+ const state: TorrentDownloadState = {
+ id,
+ kind: 'torrent',
+ files: choiceOf(chosen, torrent.files.length),
+ folder,
+ url: requestPayload.url,
+ fileName: basename(destinationPath),
+ destinationPath,
+ totalBytes,
+ skippedBytes,
+ bytesDownloaded: 0,
+ speedBytesPerSec: 0,
+ bytesUploaded: 0,
+ uploadSpeedBytesPerSec: 0,
+ status: 'downloading',
+ networks: available.map((iface) => newTorrentNetwork(iface, selected.includes(iface))),
+ peers: [],
+ peakPeers: 0,
+ pieces,
+ totalPieces: pieces.length,
+ pieceLength: torrent.pieceLength,
+ startedAt: Date.now()
+ }
+ runtime = this.newTorrentRuntime(state, requestPayload, file, pieces, torrentFile)
+ } else {
+ const target = new URL(requestPayload.url)
+ const usable = compatibleInterfaces(
+ selected,
+ await resolveTargetWithin(targetHost(target), testKnobs.stallTimeoutMs)
+ )
+ if (usable.length === 0) throw new NoCompatibleRouteError(targetHost(target))
+ const blockSizeBytes = planDownload({
+ totalBytes: requestPayload.totalBytes,
+ splittable: requestPayload.supportsRanges,
+ networkCount: usable.length,
+ maxBlockBytes: testKnobs.blockBytes
+ }).blockSizeBytes
+ const blocks = planBlocks(requestPayload.totalBytes, blockSizeBytes)
+ await ensureDiskSpace(requestPayload.destinationDir, requestPayload.totalBytes)
+ const destinationPath = await reserveDestinationPath(
+ requestPayload.destinationDir,
+ requestPayload.suggestedFileName
+ )
+ const networks = available.map((iface) => newHttpNetwork(iface, usable.includes(iface)))
+ 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: HttpDownloadState = {
+ id,
+ kind: 'http',
+ url: requestPayload.url,
+ fileName: basename(destinationPath),
+ destinationPath,
+ totalBytes: requestPayload.totalBytes,
+ bytesDownloaded: 0,
+ speedBytesPerSec: 0,
+ status: 'downloading',
+ networks,
+ streams: [],
+ peakStreams: 0,
+ blocks,
+ totalBlocks: blocks.length,
+ blockSizeBytes,
+ startedAt: Date.now()
+ }
+ runtime = this.newHttpRuntime(
+ state,
+ requestPayload,
+ new DownloadFile(`${destinationPath}.plexo`),
+ blocks
+ )
}
-
- const runtime = newRuntime(state, requestPayload, file, blocks)
+ // Decided only now: other starts may have taken the room while this one was set up.
+ const room = this.runningCount() < this.downloadsAtOnce
+ if (!room) this.enqueue(runtime, false)
this.runtimes.set(id, runtime)
await this.persistNow(runtime)
this.pushUpdate(runtime)
-
- runtime.runPromise = this.run(runtime)
+ if (room) this.launch(runtime)
return id
}
+ /** Runs the download, and once the run ends makes room for the next one queued. */
+ private launch(runtime: DownloadRuntime): void {
+ runtime.runPromise = this.run(runtime).finally(() => this.pump())
+ }
+
async pause(id: string): Promise<void> {
const runtime = this.runtimes.get(id)
+ if (runtime?.state.status === 'queued') {
+ runtime.state.status = 'paused'
+ runtime.state.queuedAt = undefined
+ runtime.state.pausedAt ??= Date.now()
+ this.pushUpdate(runtime)
+ await this.persistNow(runtime)
+ return
+ }
if (!runtime || runtime.state.status !== 'downloading' || runtime.publishing) return
runtime.state.status = 'paused'
runtime.state.pausedAt = Date.now()
clearSpeeds(runtime.state)
- for (const chunk of runtime.state.chunks) {
- if (chunk.status !== 'completed') {
- chunk.status = 'paused'
+ if (runtime.kind === 'http') {
+ for (const stream of runtime.state.streams) {
+ if (stream.status !== 'completed') {
+ stream.status = 'paused'
+ }
+ stream.currentBlockIndex = undefined
+ stream.hedge = undefined
}
- chunk.currentBlockIndex = undefined
- chunk.hedge = undefined
}
- for (const block of runtime.blocks) {
- if (block.status === 'downloading') {
- block.status = 'pending'
+ for (const unit of unitsOf(runtime)) {
+ if (unit.status === 'downloading') {
+ unit.status = 'pending'
}
+ if (unit.kind === 'torrent') unit.provisionalBytes = 0
}
- runtime.avoidNetworkByBlock.clear()
+ runtime.transfer.reset()
this.stopRun(runtime)
this.pushUpdate(runtime)
await runtime.runPromise
await this.persistNow(runtime)
}
+ /** Gives a download whose link stopped working (a signed link ran out, say) a fresh link to the
+ * same file, and resumes it from where it stopped. The file must be as big as before; whether
+ * its bytes are the same is checked as on any resume (see HttpTransfer's version check). */
+ async relink(id: string, url: string): Promise<void> {
+ const runtime = this.runtimes.get(id)
+ if (runtime?.kind !== 'http') throw new Error('Only web downloads support replacing a link.')
+ const { status, resumable, totalBytes } = runtime.state
+ if (status !== 'error' && status !== 'paused') {
+ throw new Error('Pause the download before replacing its link.')
+ }
+ if (resumable === false) throw new Error('This download can’t resume. Start it again.')
+ const probe = await probeUrl(url)
+ if (probe.kind !== 'http') throw new Error('That isn’t a link to a file')
+ if ((probe.totalBytes ?? 0) !== totalBytes) {
+ throw new Error(
+ `That link is to a different file: ${formatGigabytes(probe.totalBytes ?? 0)}, not ${formatGigabytes(totalBytes)}`
+ )
+ }
+ if (splittable(runtime.requestPayload) && !probe.supportsRanges) {
+ throw new Error(
+ 'This server doesn’t support resuming downloads. Try another link to the same file.'
+ )
+ }
+ runtime.requestPayload.url = probe.finalUrl
+ runtime.state.url = probe.finalUrl
+ await this.persistNow(runtime)
+ this.resume(id)
+ }
+
resume(id: string): void {
const runtime = this.runtimes.get(id)
- if (!runtime) return
+ if (!runtime || runtime.cancelPromise) return
const { status, resumable } = runtime.state
if (status !== 'paused' && !(status === 'error' && resumable !== false)) return
@@ -779,12 +942,32 @@ export class DownloadManager {
this.pushUpdate(runtime)
return
}
- if (runtime.state.status !== 'paused' && runtime.state.status !== 'error') return
+ if (
+ runtime.cancelPromise ||
+ (runtime.state.status !== 'paused' && runtime.state.status !== 'error')
+ )
+ return
const { networks } = runtime.state
// Switched back on, then off again while the paused run wound down: it stays paused.
if (byNetwork && !networks.some((network) => network.enabled)) return
+ if (this.runningCount() >= this.downloadsAtOnce) {
+ // Asked for by name, so it goes next.
+ this.enqueue(runtime, true)
+ runtime.state.error = undefined
+ runtime.state.resumable = undefined
+ runtime.pausedForNoNetwork = undefined
+ this.pushUpdate(runtime)
+ return
+ }
+ this.begin(runtime)
+ }
+
+ /** Starts a run of a paused, failed or queued download, from where it stopped. */
+ private begin(runtime: DownloadRuntime): void {
+ const { networks } = runtime.state
runtime.state.status = 'downloading'
+ runtime.state.queuedAt = undefined
runtime.state.error = undefined
runtime.state.resumable = undefined
runtime.pausedForNoNetwork = undefined
@@ -811,22 +994,26 @@ export class DownloadManager {
(runtime.state.totalPausedMs || 0) + (Date.now() - runtime.state.pausedAt)
runtime.state.pausedAt = undefined
}
- for (const block of runtime.blocks) {
- if (block.status !== 'completed') {
- block.status = 'pending'
+ for (const unit of unitsOf(runtime)) {
+ if (unit.status === 'downloading') {
+ unit.status = 'pending'
}
+ if (unit.kind === 'torrent') unit.provisionalBytes = 0
}
- for (const chunk of runtime.state.chunks) {
- if (chunk.status !== 'completed') {
- chunk.status = 'pending'
+ if (runtime.kind === 'http') {
+ for (const stream of runtime.state.streams) {
+ if (stream.status !== 'completed') {
+ stream.status = 'pending'
+ }
+ stream.speedBytesPerSec = 0
}
- runtime.speedSamplesByChunk.delete(chunk.id)
- chunk.speedBytesPerSec = 0
+ } else {
+ runtime.state.peers.length = 0
}
- runtime.avoidNetworkByBlock.clear()
+ runtime.transfer.reset()
this.pushUpdate(runtime)
- runtime.runPromise = this.run(runtime)
+ this.launch(runtime)
}
/** Switches one of a download's networks on or off, running or paused. Switching off the last
@@ -834,13 +1021,19 @@ export class DownloadManager {
async setNetworkEnabled(id: string, networkId: string, enabled: boolean): Promise<void> {
const runtime = this.runtimes.get(id)
const status = runtime?.state.status
- if (!runtime || (status !== 'downloading' && status !== 'paused')) return
+ if (
+ !runtime ||
+ runtime.cancelPromise ||
+ (status !== 'downloading' && status !== 'paused' && status !== 'queued')
+ ) {
+ return
+ }
const { networks } = runtime.state
const network = networks.find((entry) => entry.id === networkId)
if (!network || network.enabled === enabled) return
const wasLast = !enabled && !networks.some((other) => other !== network && other.enabled)
// A download that can't be split runs over one network: switching one on switches it over.
- if (enabled && !splittable(runtime.requestPayload)) {
+ if (enabled && runtime.kind === 'http' && !splittable(runtime.requestPayload)) {
for (const other of networks) other.enabled = false
}
network.enabled = enabled
@@ -882,10 +1075,9 @@ export class DownloadManager {
for (const runtime of this.runtimes.values()) {
const { status } = runtime.state
- if (status !== 'downloading' && status !== 'paused') continue
+ if (status !== 'downloading' && status !== 'paused' && status !== 'queued') continue
this.reconcile(runtime)
- this.wake(
- runtime,
+ runtime.transfer.wake(
(id) => changed.has(id),
(id) => moved.has(id)
)
@@ -900,47 +1092,10 @@ export class DownloadManager {
const now = Date.now()
for (const runtime of this.runtimes.values()) {
if (runtime.state.status !== 'downloading') continue
- for (const traffic of runtime.traffic.values()) traffic.aliveAt = now
- for (const self of runtime.chunkRuntimes.values()) {
- self.warmSince = now
- self.slowSince = null
- }
- this.wake(
- runtime,
- () => true,
- () => true
- )
+ runtime.transfer.systemResumed(now)
}
}
- /**
- * Gets streams going again now, rather than when their backoff runs out: what held them back
- * has changed. The ones `reconnect` picks also drop their sockets, and what they were fetching
- * is taken up again on a new one: a refresh, so nothing is lost and no retry is counted.
- */
- private wake(
- runtime: DownloadRuntime,
- pick: (networkId: string) => boolean,
- reconnect: (networkId: string) => boolean
- ): void {
- for (const chunk of runtime.state.chunks) {
- const self = runtime.chunkRuntimes.get(chunk.id)
- if (!self || self.retiring || !pick(chunk.interfaceId)) continue
- self.failures = 0
- if (reconnect(chunk.interfaceId)) {
- if (self.attempt) this.abortAttempt(self.attempt, 'refresh')
- self.connection.reconnect()
- }
- self.nudge.abort()
- }
- }
-
- /** Waits out a backoff; cut short when the stream stops, or is woken (see wake). */
- private async backOff(self: ChunkRuntime, ms: number): Promise<void> {
- await delay(ms, AbortSignal.any([self.wait, self.nudge.signal]))
- if (self.nudge.signal.aborted) self.nudge = new AbortController()
- }
-
/** Keeps the computer from sleeping while a download runs, which would stop it — as
* qBittorrent and Transmission offer to. The display can still sleep. */
private keepAwake(): void {
@@ -959,39 +1114,184 @@ export class DownloadManager {
}
}
+ /** A torrent download's own .torrent, read: its files never change, so they're read when
+ * needed rather than kept or sent with every update. */
+ private async torrentInfo(id: string): Promise<TorrentInfo | null> {
+ const request = this.runtimes.get(id)?.requestPayload
+ if (request?.kind !== 'torrent') return null
+ const probe = await describeTorrent(await readFile(this.torrentFilePath(id)), request.url)
+ return probe.kind === 'torrent' ? probe.torrent : null
+ }
+
+ /** A torrent download's files, each marked by whether it's chosen. */
+ async torrentFiles(id: string): Promise<TorrentFileEntry[]> {
+ const torrent = await this.torrentInfo(id)
+ const request = this.runtimes.get(id)?.requestPayload
+ if (!torrent || request?.kind !== 'torrent') return []
+ const chosen = chosenFiles(request.selectedFiles, torrent.files.length)
+ return torrent.files.map((file, index) => ({ ...file, chosen: !chosen || chosen.has(index) }))
+ }
+
+ /** Changes which of a torrent download's files it fetches, running or not, as its choice
+ * (requestPayload.selectedFiles) everything else follows from. What's in stays in: the pieces
+ * a newly chosen file needs are fetched, those no chosen file needs any more aren't. A file
+ * that's in can't be dropped: it's done, and dropping it would delete it once the download is. */
+ async chooseTorrentFiles(id: string, selected: number[]): Promise<void> {
+ const runtime = this.runtimes.get(id)
+ if (runtime?.kind !== 'torrent') throw new Error('This download has no files to choose')
+ // Ticks come quicker than the disk answers: one overtaken by a later one gives way to it.
+ const turn = ++runtime.fileChoices
+ const torrent = await this.torrentInfo(id)
+ if (!torrent) throw new Error('This download has no files to choose')
+ // Done or going: its files are what they are. Checked again after waiting on the disk.
+ const settled = (): boolean =>
+ runtime.publishing ||
+ runtime.state.status === 'completed' ||
+ runtime.state.status === 'cancelled' ||
+ this.runtimes.get(id) !== runtime
+ if (settled()) throw new Error('This download’s files can’t change now')
+
+ const chosen = chosenFiles(selected, torrent.files.length)
+ const completed = runtime.pieces.map((piece) => piece.status === 'completed')
+ const finished = finishedFiles(torrent.files, torrent.pieceLength, completed)
+ if (chosen && [...finished].some((index) => !chosen.has(index))) {
+ throw new Error('A file that’s already downloaded stays')
+ }
+ const wanted = chosen && wantedPieces(torrent.files, torrent.pieceLength, chosen)
+ let adding = 0
+ for (const piece of runtime.pieces) {
+ if (piece.status === 'skipped' && (!wanted || wanted[piece.index])) {
+ adding += piece.rangeEnd! - piece.rangeStart + 1
+ }
+ }
+ await ensureDiskSpace(runtime.requestPayload.destinationDir, adding)
+ if (settled()) throw new Error('This download’s files can’t change now')
+ if (turn !== runtime.fileChoices) return
+
+ runtime.state.files = choiceOf(chosen, torrent.files.length)
+ runtime.requestPayload.selectedFiles = runtime.state.files.selected
+ runtime.state.skippedBytes = choosePieces(runtime.pieces, torrent, chosen)
+ runtime.file.unwanted = unchosenPaths(torrent, chosen)
+ runtime.transfer.filesChosen()
+ // Sent now, ahead of the answer: the window shows the choice from the state it's sent.
+ this.pushUpdate(runtime)
+ }
+
async cancel(id: string): Promise<void> {
const runtime = this.runtimes.get(id)
+ if (runtime?.cancelPromise) return runtime.cancelPromise
if (
!runtime ||
runtime.publishing ||
(runtime.state.status !== 'downloading' &&
runtime.state.status !== 'paused' &&
+ runtime.state.status !== 'queued' &&
runtime.state.status !== 'error')
)
return
- runtime.state.status = 'cancelled'
- clearSpeeds(runtime.state)
- for (const chunk of runtime.state.chunks) chunk.status = 'cancelled'
- this.stopRun(runtime)
- this.pushUpdate(runtime, false)
- await runtime.runPromise
- await runtime.file.discard()
- await this.removePersistedDownload(runtime)
+ runtime.cancelPromise = this.cancelRuntime(runtime)
+ try {
+ await runtime.cancelPromise
+ } finally {
+ runtime.cancelPromise = undefined
+ }
}
- async remove(id: string): Promise<void> {
- const runtime = this.runtimes.get(id)
+ private async cancelRuntime(runtime: DownloadRuntime): Promise<void> {
+ try {
+ // Stop writing first, but keep the item visible until its files and manifest are gone.
+ await this.pause(runtime.state.id)
+ if (runtime.state.status !== 'error') {
+ runtime.state.status = 'paused'
+ runtime.state.queuedAt = undefined
+ runtime.state.pausedAt ??= Date.now()
+ }
+ clearSpeeds(runtime.state)
+ this.stopRun(runtime)
+ this.pushUpdate(runtime, false)
+ await runtime.runPromise?.catch(() => {})
+ await runtime.file.discard()
+ await this.removePersistedDownload(runtime, false)
+ runtime.state.status = 'cancelled'
+ if (runtime.kind === 'http') {
+ for (const stream of runtime.state.streams) stream.status = 'cancelled'
+ }
+ this.pushUpdate(runtime, false)
+ } catch (error) {
+ runtime.removed = false
+ runtime.state.status = 'error'
+ runtime.state.error = error instanceof Error ? error.message : String(error)
+ // Cleanup may have removed only some files: retry cancellation rather than resuming them.
+ runtime.state.resumable = false
+ this.pushUpdate(runtime, false)
+ await this.persistNow(runtime)
+ throw error
+ } finally {
+ // A queued one never ran, so no run's end makes room after it.
+ this.pump()
+ }
+ }
+
+ /** Removes a download, cancelling one under way. A finished one's file stays where it is,
+ * unless `trashFile`: then it goes to the Trash, where the user can still get it back. The
+ * path is the download's own, never one the window names. */
+ async remove(id: string, trashFile = false): Promise<void> {
+ await this.initialization
+ let runtime = this.runtimes.get(id)
+ if (runtime?.state.status === 'completed') {
+ // Completion is shown before history is saved. Let that move finish before choosing
+ // whether to remove a live runtime or a history entry, including for torrent file removal.
+ await runtime.runPromise?.catch(() => {})
+ runtime = this.runtimes.get(id)
+ }
if (
runtime &&
(runtime.state.status === 'downloading' ||
runtime.state.status === 'paused' ||
+ runtime.state.status === 'queued' ||
runtime.state.status === 'error')
) {
await this.cancel(id)
}
- this.runtimes.delete(id)
- if (runtime) await this.removePersistedDownload(runtime)
+ if (runtime) {
+ if (trashFile && runtime.state.status === 'completed') {
+ const owned =
+ runtime.kind === 'torrent'
+ ? (await this.torrentFiles(id))
+ .filter((file) => file.chosen)
+ .map((file) => file.path.split(/[\\/]/).slice(1).join(sep))
+ : undefined
+ await trashDownload(runtime.state, owned)
+ }
+ this.runtimes.delete(id)
+ await this.removePersistedDownload(runtime)
+ if (runtime.state.status === 'completed') {
+ await removeFromHistory([id])
+ this.historyChanged()
+ }
+ return
+ }
+ // A finished one, from history.
+ const entry = trashFile ? await findInHistory(id) : undefined
+ if (entry && !entry.missing) await trashDownload(entry)
+ await removeFromHistory([id])
+ this.historyChanged()
+ }
+
+ /** Shows a download's file in its folder: by the download's own path, never one the window
+ * names, and only once it's checked to be there — the window's view of that can be old (the
+ * file moved or deleted since). When it isn't, the window is told to look again, and the
+ * history it gets marks it missing. */
+ async reveal(id: string): Promise<boolean> {
+ const download = this.runtimes.get(id)?.state ?? (await findInHistory(id))
+ const path = download?.destinationPath
+ if (path && (await pathExists(path).catch(() => false))) {
+ shell.showItemInFolder(path)
+ return true
+ }
+ this.historyChanged()
+ return false
}
async suspendAll(): Promise<void> {
@@ -1003,6 +1303,7 @@ export class DownloadManager {
else await this.persistNow(runtime)
})
)
+ await this.limits.save()
}
/**
@@ -1012,32 +1313,54 @@ export class DownloadManager {
*/
private async run(runtime: DownloadRuntime): Promise<void> {
if (runtime.stop.signal.aborted) runtime.stop = new AbortController()
- runtime.reconciled.clear()
+ runtime.transfer.reset()
+ // Speeds are this run's: nothing carries over from the last one.
+ runtime.meters.clear()
+ if (runtime.kind === 'torrent') runtime.uploadMeters.clear()
const { signal } = runtime.stop
this.reconcile(runtime)
+ // One watcher per stream for its whole life. Racing every stream each tick would pile a
+ // handler per tick onto each one still running, held until it ends.
+ const watched = new WeakSet<Promise<void>>()
+ let wake: { resolve: () => void; reject: (error: unknown) => void } | null = null
+ let tickedAt = Date.now()
while (
runtime.state.status === 'downloading' &&
- runtime.blocks.some((block) => block.status !== 'completed')
+ unitsOf(runtime).some((unit) => !isDone(unit))
) {
- await Promise.race([delay(TICK_MS, signal), ...runtime.workers.values()])
+ await new Promise<void>((resolve, reject) => {
+ wake = { resolve, reject }
+ for (const worker of runtime.transfer.running()) {
+ if (watched.has(worker)) continue
+ watched.add(worker)
+ worker.then(
+ () => wake?.resolve(),
+ (error) => wake?.reject(error)
+ )
+ }
+ void delay(TICK_MS, signal).then(resolve)
+ })
if ((runtime.state.status as DownloadStatus) !== 'downloading') break
const now = Date.now()
- const speed = runtime.state.speedBytesPerSec
- updateSpeeds(runtime, now)
- if (runtime.state.speedBytesPerSec !== speed) this.scheduleUpdate(runtime)
- this.refreshStuckConnections(runtime, now)
- this.reconcile(runtime)
- this.adjustStreams(runtime, runtime.concurrency?.tick(this.concurrencySnapshot(runtime)))
- // Each refusal is counted once.
- for (const self of runtime.chunkRuntimes.values()) {
- self.refused = false
- self.served = false
+ // The only place speeds are read: on this clock, never as bytes arrive (see Meter).
+ const speedsChanged = updateSpeeds(runtime, now)
+ const timeLeftChanged = updateTimeLeft(runtime.state, (now - tickedAt) / 1000)
+ tickedAt = now
+ if (speedsChanged || timeLeftChanged) this.scheduleUpdate(runtime)
+ runtime.bestSpeedSeen = Math.max(runtime.bestSpeedSeen, runtime.state.speedBytesPerSec)
+ if (now - runtime.speedSampledAt >= 1000) {
+ runtime.speedSampledAt = now
+ sampleSpeeds(runtime.state)
+ this.scheduleUpdate(runtime)
}
+ runtime.transfer.tick(now)
}
// The last blocks are in, or the run was stopped: its streams wind down.
runtime.stop.abort()
- await Promise.all(runtime.workers.values())
+ await Promise.all(runtime.transfer.running())
+ // However it ended — paused, failed, cancelled, done — nothing is moving now.
+ clearSpeeds(runtime.state)
if (runtime.state.status !== 'downloading') {
// Paused, errored, or cancelled — nothing left to do right now. An error keeps what it has
@@ -1051,7 +1374,7 @@ export class DownloadManager {
runtime.publishing = true
try {
- if (runtime.blocks.some((block) => block.status !== 'completed')) {
+ if (unitsOf(runtime).some((unit) => !isDone(unit))) {
throw new Error('Download is incomplete — refusing to publish the file')
}
await this.persistNow(runtime)
@@ -1069,24 +1392,33 @@ export class DownloadManager {
runtime.state.fileName = basename(publishedPath)
runtime.state.status = 'completed'
runtime.state.completedAt = Date.now()
- runtime.state.bytesDownloaded = runtime.state.totalBytes || runtime.state.bytesDownloaded
+ // Done before it held a speed for long: the best it showed.
+ if (runtime.bestSpeedSeen > 0) runtime.state.peakSpeedBytesPerSec ??= runtime.bestSpeedSeen
+ runtime.state.bytesDownloaded =
+ runtime.state.totalBytes -
+ (runtime.state.kind === 'torrent' ? runtime.state.skippedBytes : 0) ||
+ runtime.state.bytesDownloaded
await this.persistNow(runtime)
- await runtime.file.discard().catch(() => {})
- this.notify('Download Complete', `${runtime.state.fileName} has finished downloading.`)
+ await runtime.file.discardLeftover().catch(() => {})
+ this.notify('Download complete', `${runtime.state.fileName} has finished downloading.`)
} catch (error) {
runtime.state.status = 'error'
runtime.state.error = error instanceof Error ? error.message : String(error)
- this.notify('Download Failed', `${runtime.state.fileName}: ${runtime.state.error}`)
+ this.notify(
+ 'Download failed',
+ `${runtime.state.fileName}: ${describeError(runtime.state.error)}`
+ )
}
runtime.publishing = false
this.pushUpdate(runtime)
+ if (runtime.state.status === 'completed') await this.moveToHistory(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()
+ runtime.transfer.abort()
}
/** Ends the download in an error. What it has downloaded stays for a resume, unless
@@ -1096,7 +1428,7 @@ export class DownloadManager {
runtime.state.status = 'error'
runtime.state.error = message
runtime.state.resumable = !discard
- this.notify('Download Failed', `${runtime.state.fileName}: ${message}`)
+ this.notify('Download failed', `${runtime.state.fileName}: ${describeError(message)}`)
this.stopRun(runtime)
}
@@ -1108,12 +1440,6 @@ export class DownloadManager {
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
@@ -1123,14 +1449,7 @@ export class DownloadManager {
* 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.
+ * Streams, while the download runs, are the transfer's (see HttpTransfer.reconcile).
*/
private reconcile(runtime: DownloadRuntime): void {
const { state } = runtime
@@ -1138,16 +1457,28 @@ export class DownloadManager {
// 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)
- )
+ if (state.kind === 'http') {
+ state.networks = state.networks.filter(
+ (network) =>
+ network.enabled ||
+ network.bytesDownloaded > 0 ||
+ present.some((iface) => iface.id === network.id) ||
+ state.streams.some((stream) => stream.interfaceId === network.id)
+ )
+ } else {
+ state.networks = state.networks.filter(
+ (network) =>
+ network.enabled ||
+ network.bytesDownloaded > 0 ||
+ network.bytesUploaded > 0 ||
+ present.some((iface) => iface.id === network.id) ||
+ state.peers.some((peer) => peer.interfaceId === network.id)
+ )
+ }
for (const iface of present) {
if (!state.networks.some((network) => network.id === iface.id)) {
- state.networks.push(newNetwork(iface, false))
+ if (state.kind === 'http') state.networks.push(newHttpNetwork(iface, false))
+ else state.networks.push(newTorrentNetwork(iface, false))
}
}
}
@@ -1162,9 +1493,11 @@ export class DownloadManager {
? 'off'
: !iface && known
? 'offline'
- : network.status === 'off' || network.status === 'offline'
- ? 'on'
- : network.status
+ : this.limits.limitReached(network.id)
+ ? 'limit'
+ : network.status === 'off' || network.status === 'offline' || network.status === 'limit'
+ ? 'on'
+ : network.status
if (status !== network.status) {
network.status = status
network.error = undefined
@@ -1178,197 +1511,7 @@ export class DownloadManager {
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() ?? pickedStreams(runtime.requestPayload)
- )
- : 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, actions: Action[] | undefined): void {
- for (const action of actions ?? []) {
- if (action.kind === 'add') {
- this.startStreams(runtime, this.addStreams(runtime, action.networkId, action.count))
- } else {
- 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.
- *
- * - Silent: nothing received for SILENT_AFTER_MS while the file is demonstrably being served
- * to others. Judged by the clock alone, so it also catches a network that has yet to
- * deliver a byte and therefore has no speed to be compared with.
- * - Crawling: under SLOW_RATIO of its network's reference speed for SLOW_FOR_MS. The reference
- * is the median of what connections on the same network are doing now and did on their last
- * finished block — its own included, which covers the tail (everyone else is done) and a
- * network with a single connection. Networks are never compared with each other: cellular
- * is expected to be slower than Wi-Fi.
- *
- * Reconnecting only swaps one connection for another, and stops after a couple of tries; what
- * can finish a block whose connections all crawl is a hedge (see scheduler.ts).
- */
- private refreshStuckConnections(runtime: DownloadRuntime, now: number): void {
- // Without ranges a reconnect restarts the whole file from byte 0.
- if (!runtime.requestPayload.supportsRanges) return
-
- let unreachable = false
- for (const chunk of runtime.state.chunks) {
- const self = runtime.chunkRuntimes.get(chunk.id)
- const attempt = self?.attempt
- if (!self || !attempt || attempt.abortReason) continue
-
- const silent = this.isSilent(runtime, attempt, now)
- // A refresh isn't a failure, so no failed request would say that the network can't get
- // through; a connection gone silent with the rest of its network says it instead, as soon
- // as SILENT_AFTER_MS rather than once a connect or stall timeout has run out.
- if (silent && this.markUnreachable(runtime, this.network(runtime, attempt.networkId), now)) {
- unreachable = true
- }
- // Silent while its network's other connections are served: the server took the connection
- // and left it waiting, which is how some turn away one too many (see concurrency.ts).
- if (silent) self.refused = true
-
- const index = attempt.block.index
- const refreshes = runtime.refreshesByBlock.get(index) ?? 0
- // A hedge is optional work: it is only ever dropped, never counted against its block.
- const isPrimary = attempt.kind === 'primary'
- if (isPrimary && refreshes >= MAX_REFRESHES_PER_BLOCK) continue
-
- if (silent || (isPrimary && this.isCrawling(runtime, chunk, self, now))) {
- if (isPrimary) runtime.refreshesByBlock.set(index, refreshes + 1)
- this.abortAttempt(attempt, 'refresh')
- }
- }
- if (unreachable) this.reconcile(runtime)
- }
-
- /** Marks a network in use that has received nothing for SILENT_AFTER_MS as unable to reach the
- * server. Whether it did. */
- private markUnreachable(
- runtime: DownloadRuntime,
- network: DownloadNetwork,
- now: number
- ): boolean {
- if (network.status !== 'on') return false
- if (now - this.traffic(runtime, network.id).aliveAt < SILENT_AFTER_MS) return false
- network.status = 'unreachable'
- return true
- }
-
- private isSilent(runtime: DownloadRuntime, attempt: Attempt, now: number): boolean {
- if (attempt.networkReceived > 0 || now - attempt.startedAt < SILENT_AFTER_MS) return false
- // Until something has arrived, a quiet origin is just a slow one — nothing to blame this
- // connection for.
- return runtime.blocks.some(
- (block) => block.index !== attempt.block.index && block.bytesDownloaded > 0
- )
- }
-
- private isCrawling(
- runtime: DownloadRuntime,
- chunk: ChunkState,
- self: ChunkRuntime,
- now: number
- ): boolean {
- const warm = (connection: ChunkRuntime): boolean => now - connection.warmSince >= SLOW_WARMUP_MS
- if (!warm(self)) return false
-
- const reference: number[] = []
- for (const other of runtime.state.chunks) {
- if (other.interfaceId !== chunk.interfaceId) continue
- const peer = runtime.chunkRuntimes.get(other.id)
- if (!peer) continue
- if (peer.lastBlockSpeed > 0) reference.push(peer.lastBlockSpeed)
- if (other !== chunk && peer.attempt && warm(peer)) reference.push(other.speedBytesPerSec)
- }
-
- if (reference.length === 0 || chunk.speedBytesPerSec >= median(reference) * SLOW_RATIO) {
- self.slowSince = null
- return false
- }
- self.slowSince ??= now
- return now - self.slowSince >= SLOW_FOR_MS
- }
-
- private abortAttempt(attempt: Attempt, reason: AbortReason): void {
- if (attempt.abortReason) return
- attempt.abortReason = reason
- attempt.abort.abort()
+ runtime.transfer.reconcile()
}
private notify(title: string, body: string): void {
@@ -1389,678 +1532,6 @@ export class DownloadManager {
}
}
- // --- attempts ---------------------------------------------------------------------------------
- //
- // A stream's life is a loop: ask the scheduler for work, run it as an attempt, then apply what
- // became of it. Everything that changes the download's state happens in the synchronous stretches
- // between awaits, so a stream never sees another's half-finished change.
-
- /** Where an attempt has got to in its block. */
- private attemptPosition(attempt: Attempt): number {
- return (attempt.startOffset ?? 0) + attempt.received
- }
-
- /** How far the block's other attempts have got: what is safe to keep counted when one lets go. */
- private otherAttemptsPosition(runtime: DownloadRuntime, attempt: Attempt): number {
- let furthest = 0
- for (const other of runtime.attempts.get(attempt.block.index) ?? []) {
- if (other !== attempt) furthest = Math.max(furthest, this.attemptPosition(other))
- }
- return furthest
- }
-
- /** The stream holds no block: it says so, rather than keeping the last one's numbers on show. */
- private goIdle(chunk: ChunkState): void {
- chunk.status = 'pending'
- chunk.currentBlockIndex = undefined
- chunk.hedge = undefined
- chunk.speedBytesPerSec = 0
- }
-
- private beginAttempt(
- runtime: DownloadRuntime,
- chunk: ChunkState,
- self: ChunkRuntime,
- work: Work
- ): Attempt {
- const { block } = work
- const attempt: Attempt = {
- kind: work.kind,
- block,
- streamId: chunk.id,
- networkId: chunk.interfaceId,
- startOffset: null,
- received: 0,
- networkReceived: 0,
- lastNetworkAt: 0,
- startedAt: Date.now(),
- // Whoever held this block before now is the one whose tail bytes a truncation would
- // discard — captured before the lease overwrites the field.
- previousWriter: block.interfaceId,
- abort: new AbortController(),
- abortReason: null,
- response: null
- }
-
- if (work.kind === 'primary') {
- block.status = 'downloading'
- block.interfaceId = chunk.interfaceId
- runtime.avoidNetworkByBlock.delete(block.index)
- } else {
- runtime.hedgesByBlock.set(block.index, (runtime.hedgesByBlock.get(block.index) ?? 0) + 1)
- }
- const inFlight = runtime.attempts.get(block.index)
- if (inFlight) inFlight.push(attempt)
- else runtime.attempts.set(block.index, [attempt])
- self.attempt = attempt
-
- chunk.status = 'downloading'
- chunk.hedge = work.kind === 'hedge' ? true : undefined
- chunk.rangeStart = block.rangeStart
- chunk.rangeEnd = block.rangeEnd
- chunk.currentBlockIndex = block.index
- return attempt
- }
-
- /** Takes the attempt off the books. Safe to repeat. */
- private endAttempt(runtime: DownloadRuntime, self: ChunkRuntime, attempt: Attempt): void {
- const inFlight = runtime.attempts.get(attempt.block.index)
- if (inFlight) {
- const position = inFlight.indexOf(attempt)
- if (position >= 0) inFlight.splice(position, 1)
- if (inFlight.length === 0) runtime.attempts.delete(attempt.block.index)
- }
- if (self.attempt === attempt) self.attempt = null
- }
-
- /** Sends the request and reports how it ended. Never throws. */
- private async executeAttempt(
- runtime: DownloadRuntime,
- chunk: ChunkState,
- self: ChunkRuntime,
- attempt: Attempt
- ): Promise<AttemptOutcome> {
- const { block } = attempt
- try {
- if (attempt.kind === 'primary') {
- // A failed range leaves its written prefix in the staging file. Without range support,
- // the server can only restart from byte zero.
- attempt.startOffset = runtime.requestPayload.supportsRanges ? block.bytesDownloaded : 0
- // What another attempt has already secured stays counted.
- const keep = Math.max(attempt.startOffset, this.otherAttemptsPosition(runtime, attempt))
- if (retractBlock(block, keep, attempt.previousWriter) > 0) this.recomputeAggregates(runtime)
- } else {
- attempt.startOffset = block.bytesDownloaded
- }
-
- const length = block.rangeEnd === null ? null : block.rangeEnd - block.rangeStart + 1
- if (length !== null && attempt.startOffset >= length) {
- // The staging file already holds the whole block.
- return attempt.kind === 'primary'
- ? { type: 'completed' }
- : { type: 'aborted', reason: 'lost' }
- }
-
- attempt.startedAt = Date.now()
- await downloadChunk({
- url: runtime.requestPayload.url,
- rangeStart: block.rangeStart + attempt.startOffset,
- rangeEnd: block.rangeEnd,
- connection: self.connection,
- createDestination: () => runtime.file.writer(block.rangeStart + (attempt.startOffset ?? 0)),
- signal: AbortSignal.any([self.controller.signal, attempt.abort.signal]),
- acceptedVersions: runtime.acceptedVersions,
- onResponse: (info) => (attempt.response = info),
- onNetworkProgress: (bytesThisRun) => {
- const delta = bytesThisRun - attempt.networkReceived
- if (delta > 0) {
- attempt.networkReceived = bytesThisRun
- attempt.lastNetworkAt = Date.now()
- this.onNetworkProgress(runtime, chunk, self, delta)
- }
- },
- onProgress: (bytesThisRun) => {
- const delta = bytesThisRun - attempt.received
- if (delta > 0) {
- attempt.received = bytesThisRun
- this.onAttemptProgress(runtime, chunk, attempt)
- }
- }
- })
- return { type: 'completed' }
- } catch (error) {
- const status = runtime.state.status as DownloadStatus
- if (self.controller.signal.aborted || status !== 'downloading') return { type: 'stopped' }
- if (attempt.abortReason) return { type: 'aborted', reason: attempt.abortReason }
- return { type: 'failed', error }
- }
- }
-
- private onNetworkProgress(
- runtime: DownloadRuntime,
- chunk: ChunkState,
- self: ChunkRuntime,
- deltaBytes: number
- ): void {
- const now = Date.now()
- self.receivedBytes += deltaBytes
- self.served = true
- 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)
- updateSpeeds(runtime, now)
- this.scheduleUpdate(runtime)
- }
-
- private onAttemptProgress(runtime: DownloadRuntime, chunk: ChunkState, attempt: Attempt): void {
- // Only what gets the block further than it already was counts as progress: a racing attempt
- // 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
- // callers of recomputeAggregates are rare enough to afford the full pass, and each one
- // re-derives the true total, so any drift here cannot accumulate.
- runtime.state.bytesDownloaded += gained
- this.scheduleUpdate(runtime)
- }
-
- /** Applies what became of an attempt to the download. 'stop' ends the stream. */
- private async finishAttempt(
- runtime: DownloadRuntime,
- chunk: ChunkState,
- self: ChunkRuntime,
- attempt: Attempt,
- outcome: AttemptOutcome
- ): Promise<'continue' | 'stop'> {
- debug('attempt', {
- block: attempt.block.index,
- stream: chunk.id,
- network: attempt.networkId,
- kind: attempt.kind,
- outcome: outcome.type === 'aborted' ? `aborted:${outcome.reason}` : outcome.type,
- networkBytes: attempt.networkReceived,
- writtenBytes: attempt.received,
- ms: Date.now() - attempt.startedAt,
- ...attempt.response
- })
-
- switch (outcome.type) {
- case 'completed':
- return this.finishCompleted(runtime, chunk, self, attempt)
- case 'stopped':
- return this.finishStopped(runtime, chunk, self, attempt)
- case 'aborted':
- return this.finishAborted(runtime, chunk, self, attempt, outcome.reason)
- case 'failed':
- return this.finishFailed(runtime, chunk, self, attempt, outcome.error)
- }
- }
-
- private finishCompleted(
- runtime: DownloadRuntime,
- chunk: ChunkState,
- self: ChunkRuntime,
- attempt: Attempt
- ): 'continue' {
- const { block } = attempt
-
- // Another attempt already finished this block: these bytes are surplus.
- if (block.status === 'completed') {
- this.letGo(runtime, chunk, self, attempt, false)
- return 'continue'
- }
-
- this.endAttempt(runtime, self, attempt)
- block.status = 'completed'
- block.interfaceId = attempt.networkId
- if (block.rangeEnd !== null) {
- // Progress events can lag the final write, so square the block up to its exact size and
- // credit the shortfall to the network that finished it.
- const blockBytes = block.rangeEnd - block.rangeStart + 1
- chunk.bytesDownloaded += advanceBlock(block, attempt.networkId, blockBytes)
- self.lastBlockSpeed =
- (attempt.networkReceived /
- Math.max(1, (attempt.lastNetworkAt || Date.now()) - attempt.startedAt)) *
- 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)
- this.scheduleUpdate(runtime)
- return 'continue'
- }
-
- /** The stream was stopped while its request was in flight. */
- private finishStopped(
- runtime: DownloadRuntime,
- chunk: ChunkState,
- self: ChunkRuntime,
- attempt: Attempt
- ): 'stop' {
- // Whatever stopped it — a pause, a cancel, retirement — the block goes back as any other
- // attempt's would, and one another attempt has finished stays finished.
- this.letGo(runtime, chunk, self, attempt, false)
- chunk.status = runtime.state.status === 'paused' ? 'paused' : 'cancelled'
- return 'stop'
- }
-
- private async finishAborted(
- runtime: DownloadRuntime,
- chunk: ChunkState,
- self: ChunkRuntime,
- attempt: Attempt,
- reason: AbortReason
- ): Promise<'continue'> {
- // 'lost': another attempt decided the block, so its state is no longer this one's to touch.
- // 'refresh': not a failure — no retry counted, no backoff. Whoever takes the block next
- // resumes it from the staging file on a new connection.
- this.letGo(runtime, chunk, self, attempt, reason === 'refresh' && attempt.networkReceived === 0)
- if (reason === 'refresh' && attempt.kind === 'primary') {
- // 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.wait)
- self.warmSince = Date.now()
- self.slowSince = null
- }
- return 'continue'
- }
-
- private async finishFailed(
- runtime: DownloadRuntime,
- chunk: ChunkState,
- self: ChunkRuntime,
- attempt: Attempt,
- error: unknown
- ): Promise<'continue' | 'stop'> {
- const message = error instanceof Error ? error.message : String(error)
- const network = this.network(runtime, attempt.networkId)
- const deliveredNothing = attempt.networkReceived === 0
-
- if (error instanceof RemoteChangedError) {
- const verdict =
- error.check.kind === 'size'
- ? 'different'
- : await this.confirmSameBytes(runtime, self.connection, error.seen)
- // The check takes a moment; the download may have been paused or stopped meanwhile.
- if ((runtime.state.status as DownloadStatus) !== 'downloading') {
- return this.finishStopped(runtime, chunk, self, attempt)
- }
- if (verdict === 'same') {
- // Same bytes under another label — accept it and fetch again straight away; nothing from
- // the rejected response was written.
- if (compareVersion(runtime.acceptedVersions, error.seen).kind !== 'same') {
- runtime.acceptedVersions.push(error.seen)
- }
- this.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. 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, 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)
- 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 && this.markUnreachable(runtime, network, Date.now())) {
- 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 += 1
- // What arrived before it failed shows the network works, and what was written shows the
- // server does: the count in a row starts over, and so does the backoff.
- if (attempt.networkReceived > 0) self.failures = 0
- if (attempt.received > 0) {
- self.strikes = 0
- self.busySince = null
- }
- self.failures += 1
- // Back to the queue, so any available worker can pick it up.
- this.letGo(runtime, chunk, self, attempt, deliveredNothing)
-
- // 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, and one
- // that answered busy is waited out for SERVER_BUSY_FOR_MS as well; then this stream gives up,
- // and once all its network's have, so does the network.
- const now = Date.now()
- // The server turning a request away: the stream count takes it as a limit (see
- // concurrency.ts).
- if (error instanceof HttpStatusError && [403, 429, 503].includes(error.status)) {
- self.refused = true
- }
- const busy = error instanceof HttpStatusError && error.transient
- if (busy) self.busySince ??= now
- const waitingOut = busy && now - (self.busySince ?? now) < SERVER_BUSY_FOR_MS
- if (!(error instanceof ConnectionError) && ++self.strikes > MAX_CHUNK_RETRIES && !waitingOut) {
- self.retiring = true
- if (this.liveStreams(runtime, network.id).length === 0) {
- this.failNetwork(runtime, network, message)
- }
- return 'stop'
- }
-
- let wait = retryDelayMs(self.failures)
- if (network.status === 'unreachable') wait = Math.min(wait, UNREACHABLE_RETRY_MS)
- if (error instanceof HttpStatusError && error.transient && error.retryAfterMs !== null) {
- // Asked of whoever sent it — this network's address, to the server — not of this one
- // request: none of the network's streams sends another until then.
- const asked = Math.min(error.retryAfterMs, RETRY_AFTER_MAX_MS)
- wait = Math.max(wait, asked)
- runtime.holdUntil.set(
- network.id,
- Math.max(runtime.holdUntil.get(network.id) ?? 0, now + asked)
- )
- }
-
- chunk.status = 'retrying'
- this.scheduleUpdate(runtime)
- await this.backOff(self, wait)
- const statusAfterDelay = runtime.state.status as DownloadStatus
- if (self.controller.signal.aborted || statusAfterDelay !== 'downloading') {
- chunk.status = statusAfterDelay === 'paused' ? 'paused' : 'cancelled'
- chunk.speedBytesPerSec = 0
- return 'stop'
- }
- this.goIdle(chunk)
- self.warmSince = Date.now()
- self.slowSince = null
- return 'continue'
- }
-
- /**
- * The stream stops working on the attempt's block without having finished it. A primary hands
- * the block back to the queue; a hedge just drops out. Either way what it wrote stays counted.
- * When the attempt delivered nothing, its network is remembered (see scheduler.ts).
- */
- private letGo(
- runtime: DownloadRuntime,
- chunk: ChunkState,
- self: ChunkRuntime,
- attempt: Attempt,
- deliveredNothing: boolean
- ): void {
- this.endAttempt(runtime, self, attempt)
- const { block } = attempt
- // A block another attempt has finished stays finished.
- if (attempt.kind === 'primary' && block.status === 'downloading') block.status = 'pending'
- if (deliveredNothing) runtime.avoidNetworkByBlock.set(block.index, attempt.networkId)
- this.goIdle(chunk)
- }
-
- private concurrencySnapshot(runtime: DownloadRuntime): Snapshot {
- const inUse = runtime.state.networks.filter((network) => network.status === 'on')
- const networks = inUse.map(({ id }) => {
- let streams = 0
- let answered = 0
- let refused = 0
- let served = 0
- for (const chunk of this.liveStreams(runtime, id)) {
- const self = runtime.chunkRuntimes.get(chunk.id)
- streams++
- if (self && self.receivedBytes > 0) answered++
- if (self?.refused) refused++
- if (self?.served) served++
- }
- return { id, streams, answered, refused, served }
- })
- // A new stream takes a waiting block the moment it starts.
- const waiting = runtime.blocks.filter((block) => block.status === 'pending').length
- return { now: Date.now(), networks, spareWork: waiting }
- }
-
- /** New streams on `networkId`, put on the download's list for the caller to start. */
- private addStreams(runtime: DownloadRuntime, networkId: string, count: number): ChunkState[] {
- let id = Math.max(-1, ...runtime.state.chunks.map((chunk) => chunk.id))
- 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: networkId, added: count })
- this.scheduleUpdate(runtime)
- return added
- }
-
- /** Stops `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): void {
- if (count < 1) return
- // Streams the server just refused go first (see concurrency.ts), then ones whose last
- // request failed, then the newest.
- const rank = (chunk: ChunkState): number => {
- const self = runtime.chunkRuntimes.get(chunk.id)
- return self?.refused ? 2 : (self?.failures ?? 0) > 0 ? 1 : 0
- }
- const order = this.liveStreams(runtime, networkId).sort(
- (a, b) => rank(b) - rank(a) || b.id - a.id
- )
- for (const chunk of order.slice(0, count)) {
- const self = runtime.chunkRuntimes.get(chunk.id)
- 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 })
- }
-
- /** 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) return
- runtime.state.chunks.splice(index, 1)
- this.scheduleUpdate(runtime)
- }
-
- private async runWorker(runtime: DownloadRuntime, chunk: ChunkState): Promise<void> {
- const controller = new AbortController()
- const self: ChunkRuntime = {
- controller,
- wait: AbortSignal.any([controller.signal, runtime.stop.signal]),
- nudge: new AbortController(),
- connection: new StreamConnection(() => this.networks.find(chunk.interfaceId), {
- timeoutMs: testKnobs.stallTimeoutMs,
- connectTimeoutMs: testKnobs.connectTimeoutMs
- }),
- attempt: null,
- warmSince: Date.now(),
- slowSince: null,
- lastBlockSpeed: 0,
- receivedBytes: 0,
- failures: 0,
- strikes: 0,
- busySince: null,
- refused: false,
- served: false,
- retiring: false
- }
- runtime.chunkRuntimes.set(chunk.id, self)
-
- try {
- while (runtime.state.status === 'downloading') {
- if (controller.signal.aborted || self.retiring) break
-
- // The server asked this network to hold off: no new request over it until then. Each
- // stream comes back a little apart from the others.
- const holdFor = (runtime.holdUntil.get(chunk.interfaceId) ?? 0) - Date.now()
- if (holdFor > 0) {
- this.goIdle(chunk)
- chunk.status = 'retrying'
- this.scheduleUpdate(runtime)
- await this.backOff(self, holdFor + Math.random() * Math.min(1000, holdFor / 10))
- continue
- }
-
- // Taken atomically: nothing between choosing the work and registering it can yield.
- const work = pickWork(
- {
- blocks: runtime.blocks,
- streams: runtime.state.chunks,
- attempts: runtime.attempts,
- avoid: runtime.avoidNetworkByBlock,
- hedgesUsed: runtime.hedgesByBlock
- },
- {
- id: chunk.id,
- networkId: chunk.interfaceId,
- speedBytesPerSec: self.lastBlockSpeed || undefined
- },
- Date.now(),
- SCHEDULER_POLICY
- )
- if (!work) {
- this.goIdle(chunk)
- // While blocks are still in flight, stay available in case one fails and is handed back,
- // 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(IDLE_POLL_MS, self.wait)
- continue
- }
- chunk.status = 'completed'
- this.scheduleUpdate(runtime)
- break
- }
-
- 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, attempt, outcome)
- } finally {
- this.endAttempt(runtime, self, attempt)
- }
- if (next === 'stop') break
- }
- } finally {
- // Its sockets would otherwise stay open, kept alive for requests that will never come.
- self.connection.close()
- }
-
- this.scheduleUpdate(runtime)
- }
-
- /**
- * Settles whether a server labelling the file differently (new ETag or Last-Modified, same
- * size) is serving the same bytes — load-balanced servers often disagree on labels for
- * identical files — or a new version. Re-fetches a spread of bytes this download already has
- * on disk, from a server presenting the new label, and compares them.
- *
- * 'unknown' when there's nothing on disk to compare yet or the samples couldn't be fetched;
- * the caller then treats the response as an ordinary failed request and retries.
- */
- private async confirmSameBytes(
- runtime: DownloadRuntime,
- connection: StreamConnection,
- seen: FileVersion
- ): Promise<'same' | 'different' | 'unknown'> {
- if (compareVersion(runtime.acceptedVersions, seen).kind === 'same') return 'same'
-
- // Every byte on disk came from an accepted version: mismatched responses are rejected
- // before anything is written.
- const withData = runtime.blocks.filter((block) => block.bytesDownloaded > 0)
- const step = Math.max(1, withData.length / MAX_SAMPLES)
- const picks = Array.from(
- { length: Math.min(MAX_SAMPLES, withData.length) },
- (_, i) => withData[Math.floor(i * step)]
- )
-
- let compared = 0
- for (const block of picks) {
- let local: Buffer
- try {
- local = await runtime.file.read(
- block.rangeStart,
- Math.min(SAMPLE_BYTES, block.bytesDownloaded)
- )
- } catch {
- continue
- }
- if (local.length === 0) continue
-
- for (let tries = 0; tries < SAMPLE_TRIES; tries++) {
- try {
- const remote = await fetchRange(
- runtime.requestPayload.url,
- block.rangeStart,
- block.rangeStart + local.length - 1,
- connection
- )
- // A reply from a server still presenting an accepted label proves nothing here.
- if (compareVersion([seen], remote.version).kind !== 'same') continue
- if (!remote.body.equals(local)) return 'different'
- compared += 1
- break
- } catch {
- return 'unknown'
- }
- }
- }
- 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 {
- 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 {
if (runtime.pushScheduled) return
runtime.pushScheduled = true
@@ -2084,29 +1555,42 @@ export class DownloadManager {
window.webContents.send(IpcChannels.downloadUpdated, this.takeUpdate(runtime))
}
- /** What the window hasn't been sent yet: the download's state, and the blocks that moved. */
+ /** What the window hasn't been sent yet: the download's state, and the work units that moved. */
private takeUpdate(runtime: DownloadRuntime): DownloadUpdate {
- const { blocks: all, ...state } = runtime.state
- const sent = runtime.sentBlocks
- const blocks: BlockState[] = []
- for (const block of all ?? runtime.blocks) {
- const last = sent[block.index]
- // bytesByInterface only ever changes along with bytesDownloaded (see blockProgress.ts).
+ if (runtime.kind === 'http') {
+ const changed = this.changedUnits(runtime, runtime.blocks)
+ const { blocks: omittedBlocks, ...state } = runtime.state
+ void omittedBlocks
+ return structuredClone({ seq: ++runtime.sentUpdates, state, blocks: changed })
+ }
+ const changed = this.changedUnits(runtime, runtime.pieces)
+ const { pieces: omittedPieces, ...state } = runtime.state
+ void omittedPieces
+ return structuredClone({ seq: ++runtime.sentUpdates, state, pieces: changed })
+ }
+
+ private changedUnits<T extends DownloadUnitState>(runtime: DownloadRuntime, units: T[]): T[] {
+ const sent = runtime.sentUnits
+ const changed: T[] = []
+ for (const unit of units) {
+ const last = sent[unit.index]
if (
- last?.status === block.status &&
- last.interfaceId === block.interfaceId &&
- last.bytesDownloaded === block.bytesDownloaded
+ last?.status === unit.status &&
+ last.interfaceId === unit.interfaceId &&
+ last.bytesDownloaded === unit.bytesDownloaded &&
+ last.provisionalBytes === (unit.kind === 'torrent' ? unit.provisionalBytes : undefined)
) {
continue
}
- sent[block.index] = {
- status: block.status,
- interfaceId: block.interfaceId,
- bytesDownloaded: block.bytesDownloaded
+ sent[unit.index] = {
+ status: unit.status,
+ interfaceId: unit.interfaceId,
+ bytesDownloaded: unit.bytesDownloaded,
+ provisionalBytes: unit.kind === 'torrent' ? unit.provisionalBytes : undefined
}
- blocks.push(block)
+ changed.push(unit)
}
- return structuredClone({ seq: ++runtime.sentUpdates, state, blocks })
+ return changed
}
private schedulePersistence(runtime: DownloadRuntime): void {
@@ -2131,12 +1615,23 @@ export class DownloadManager {
const dir = this.downloadDir(runtime.state.id)
const path = this.manifestPath(runtime.state.id)
const temporaryPath = `${path}.tmp`
- const { blocks, ...state } = runtime.state
+ let state: PersistedState
+ if (runtime.kind === 'http') {
+ const { blocks: omittedBlocks, streams: omittedStreams, ...rest } = runtime.state
+ void omittedBlocks
+ void omittedStreams
+ state = rest
+ } else {
+ const { pieces: omittedPieces, peers: omittedPeers, ...rest } = runtime.state
+ void omittedPieces
+ void omittedPeers
+ state = rest
+ }
const persisted: PersistedDownload = {
- version: 5,
+ version: 7,
savedAt: Date.now(),
state: structuredClone(state),
- ...saveBlocks(blocks ?? runtime.blocks),
+ ...saveBlocks(unitsOf(runtime)),
partialPath: runtime.file.path,
publicationPath: runtime.publicationPath,
publicationIdentity: runtime.publicationIdentity,
@@ -2162,7 +1657,13 @@ export class DownloadManager {
runtime.removed = true
if (runtime.persistenceTimer) clearTimeout(runtime.persistenceTimer)
await runtime.persistenceChain.catch(() => {})
- if (discardPartial) await runtime.file.discard().catch(() => {})
+ // A finished download is the user's now: only what's left of it goes.
+ if (discardPartial) {
+ const file = runtime.file
+ await (runtime.state.status === 'completed' ? file.discardLeftover() : file.discard()).catch(
+ () => {}
+ )
+ }
await rm(this.downloadDir(runtime.state.id), { recursive: true, force: true })
}
}
diff --git a/src/main/download/history.ts b/src/main/download/history.ts
new file mode 100644
index 0000000..a179a2a
--- /dev/null
+++ b/src/main/download/history.ts
@@ -0,0 +1,85 @@
+import { stat } from 'node:fs/promises'
+import { join } from 'node:path'
+import { app } from 'electron'
+import type { FinishedDownload } from '../../shared/types'
+import { readJson, updateJson } from '../jsonFile'
+
+// Finished downloads, newest first: what the window lists under Finished. A download moves here
+// once it completes, leaving its work units behind (tens of thousands of them for a large file,
+// none of any use once it's done), so a long history costs launch nothing.
+
+// ponytail: a fixed cap, oldest dropped; a setting if anyone wants more than this kept.
+const MAX_ENTRIES = 500
+
+function historyPath(): string {
+ return join(app.getPath('userData'), 'history.json')
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value)
+
+/** The file may be hand-edited or from another version: an entry is kept only if it has what the
+ * window reads off every entry, and anything else malformed is dropped rather than shown. */
+function isEntry(value: unknown): value is FinishedDownload {
+ if (!isRecord(value)) return false
+ return (
+ typeof value.id === 'string' &&
+ (value.kind === 'http' || value.kind === 'torrent') &&
+ typeof value.url === 'string' &&
+ typeof value.fileName === 'string' &&
+ typeof value.destinationPath === 'string' &&
+ typeof value.totalBytes === 'number' &&
+ typeof value.bytesDownloaded === 'number' &&
+ typeof value.startedAt === 'number' &&
+ typeof value.completedAt === 'number' &&
+ typeof value.unitsWritten === 'number' &&
+ Array.isArray(value.networks) &&
+ value.networks.every(isRecord)
+ )
+}
+
+function entriesOf(parsed: unknown): FinishedDownload[] {
+ return Array.isArray(parsed) ? parsed.filter(isEntry) : []
+}
+
+/** Every finished download, newest first, each marked `missing` when its file is gone. */
+export async function listHistory(): Promise<FinishedDownload[]> {
+ const entries = entriesOf(await readJson(historyPath()).catch(() => undefined))
+ return Promise.all(
+ entries.map(async (entry) => ({
+ ...entry,
+ missing: !(await stat(entry.destinationPath).then(
+ () => true,
+ () => false
+ ))
+ }))
+ )
+}
+
+/** One finished download, its file checked alone rather than every entry's. */
+export async function findInHistory(id: string): Promise<FinishedDownload | undefined> {
+ const entry = entriesOf(await readJson(historyPath()).catch(() => undefined)).find(
+ (other) => other.id === id
+ )
+ if (!entry) return undefined
+ const missing = !(await stat(entry.destinationPath).then(
+ () => true,
+ () => false
+ ))
+ return { ...entry, missing }
+}
+
+export function addToHistory(entry: FinishedDownload): Promise<void> {
+ const { missing: omitted, ...kept } = entry
+ void omitted
+ return updateJson(historyPath(), (current) =>
+ [kept, ...entriesOf(current).filter((other) => other.id !== entry.id)].slice(0, MAX_ENTRIES)
+ )
+}
+
+/** Forgets the entries with these ids; none given, every one. The files themselves stay. */
+export function removeFromHistory(ids?: string[]): Promise<void> {
+ return updateJson(historyPath(), (current) =>
+ ids ? entriesOf(current).filter((entry) => !ids.includes(entry.id)) : []
+ )
+}
diff --git a/src/main/download/httpTransfer.ts b/src/main/download/httpTransfer.ts
new file mode 100644
index 0000000..2ab372a
--- /dev/null
+++ b/src/main/download/httpTransfer.ts
@@ -0,0 +1,1136 @@
+import type {
+ HttpBlockState,
+ HttpStreamState,
+ DownloadNetwork,
+ DownloadStatus,
+ NetworkStatus,
+ StartHttpDownloadRequest
+} from '../../shared/types'
+import { testKnobs, testStreamsPerNetwork } from '../testKnobs'
+import { advanceBlock, retractBlock } from './blockProgress'
+import { ConcurrencyController, type Action, type Snapshot } from './concurrency'
+import { downloadChunk, fetchRange, HttpStatusError, RemoteChangedError } from './chunkDownloader'
+import { compareVersion, type FileVersion } from './fileVersion'
+import { interleave, MAX_STREAMS_PER_NETWORK, startingStreams } from './plan'
+import { pickWork, type SchedulerPolicy, type Work } from './scheduler'
+import {
+ delay,
+ recomputeAggregates,
+ type Transfer,
+ type TransferHost,
+ type HttpTransferTarget
+} from './transfer'
+import { ConnectionError, NoCompatibleRouteError, StreamConnection } from '../network/routes'
+
+/** Why an attempt was called off by the manager rather than by a pause or a failure. */
+type AbortReason = 'refresh' | 'lost'
+
+/**
+ * One request for one block, by one stream. A block normally has a single (primary) attempt.
+ * Near the end of a download a second (hedge) one may race it — see scheduler.ts — and then the
+ * block is finished by whichever gets there first.
+ *
+ * Both write straight into the staging file at the block's own offsets. Every response is checked
+ * to be the download's version before any of it is written, so racing attempts write identical
+ * bytes and it doesn't matter which lands last: whatever either has written stays secured.
+ */
+interface Attempt {
+ kind: 'primary' | 'hedge'
+ block: HttpBlockState
+ streamId: number
+ networkId: string
+ /** Where the request begins, as an offset into the block. Null until it is known. */
+ startOffset: number | null
+ /** Bytes the destination writer has accepted; safe to resume from this prefix. */
+ received: number
+ /** Bytes the network has delivered, independently of disk backpressure. */
+ networkReceived: number
+ lastNetworkAt: number
+ /** When the request was sent. */
+ startedAt: number
+ /** The network previously credited for this block's prefix. */
+ previousWriter: string | undefined
+ /** Aborts this request alone; ChunkRuntime.controller aborts the whole stream. */
+ abort: AbortController
+ abortReason: AbortReason | null
+ /** What the server's answer cost, for diagnosing slow connections (see PLEXO_DEBUG). */
+ response: { ttfbMs: number; reusedSocket: boolean } | null
+}
+
+/** What became of an attempt's request. */
+type AttemptOutcome =
+ | { type: 'completed' }
+ /** The download was paused or cancelled underneath it. */
+ | { type: 'stopped' }
+ /** Called off by the manager (see AbortReason). */
+ | { type: 'aborted'; reason: AbortReason }
+ | { type: 'failed'; error: unknown }
+
+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
+ /** Cuts a backoff short without stopping the stream: what it was waiting out has changed (see
+ * wake). Replaced once used. */
+ nudge: AbortController
+ /** Its one connection to the server, reused from block to block. */
+ connection: StreamConnection
+ /** What the stream is fetching right now, if anything. */
+ attempt: Attempt | null
+ /** When this connection last (re)connected; it isn't judged until SLOW_WARMUP_MS after. */
+ warmSince: number
+ slowSince: number | null
+ /** Speed of its last finished block, start to end — 0 until it finishes one. */
+ lastBlockSpeed: number
+ /** Everything it has received, bytes another attempt already had included: what its speed is
+ * measured from. (`HttpStreamState.bytesDownloaded` counts only bytes that were new.) */
+ 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
+ /** When the server first answered busy (see HttpStatusError.transient) since this stream last
+ * made progress: a busy server is waited out for SERVER_BUSY_FOR_MS, not MAX_CHUNK_RETRIES. */
+ busySince: number | null
+ /** Since the stream count last looked: whether the server turned one of its requests away
+ * (403, 429, 503, or left it unanswered), and whether it received anything. What a connection
+ * limit is judged by (see concurrency.ts). */
+ refused: boolean
+ served: boolean
+ /** Stopped for good, and to leave the list once its worker has (see retireStreams). */
+ retiring: boolean
+}
+
+// Set PLEXO_DEBUG=1 to log every request's outcome, how long the server took to answer and
+// whether it reused a warm connection — what it takes to tell one slow connection from a slow path.
+const debug: (...args: unknown[]) => void = process.env['PLEXO_DEBUG']
+ ? (...args) => console.debug('[plexo]', ...args)
+ : () => {}
+
+const MAX_CHUNK_RETRIES = 5
+const RETRY_BASE_DELAY_MS = testKnobs.retryBaseDelayMs
+const RETRY_MAX_DELAY_MS = 15_000
+// A network that can't reach the server keeps one stream asking (see reconcile). That is one
+// cheap connection, so it asks often enough to find out soon after the network gets through.
+const UNREACHABLE_RETRY_MS = 5_000
+// A server that answers busy (429, 503, …) is waited out this long before a stream gives up on
+// it, however many retries that takes; what it asks for in Retry-After is waited, up to
+// RETRY_AFTER_MAX_MS.
+const SERVER_BUSY_FOR_MS = testKnobs.serverBusyForMs
+const RETRY_AFTER_MAX_MS = 120_000
+
+/** Doubling from RETRY_BASE_DELAY_MS, with ±20% jitter as gRPC's backoff has: a network that
+ * drops fails all its streams at once, and they shouldn't all come back at the same instant. */
+function retryDelayMs(attempt: number): number {
+ const exact = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), RETRY_MAX_DELAY_MS)
+ return exact * (0.8 + 0.4 * Math.random())
+}
+
+// A single TCP stream can get stuck at a crawl (loss-collapsed congestion window, a bad CDN node
+// or route) while its siblings on the same network run fine. It never goes silent, so the stall
+// watchdog can't catch it; a fresh connection usually lands somewhere healthy. Only relative
+// thresholds — nothing here knows how fast the network ought to be.
+const SLOW_RATIO = 0.1
+const SLOW_WARMUP_MS = testKnobs.slowWarmupMs
+const 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). 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.
+const MAX_REFRESHES_PER_BLOCK = 2
+const SCHEDULER_POLICY: SchedulerPolicy = {
+ hedgeAfterMs: testKnobs.hedgeAfterMs,
+ maxHedgesPerBlock: 2,
+ startupMs: 1000
+}
+
+/** Whether the file can be fetched in parts. Otherwise one request has to carry all of it: one
+ * stream, on one network. */
+export function splittable(request: StartHttpDownloadRequest): 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: StartHttpDownloadRequest): ConcurrencyController | null {
+ if (!splittable(request) || testStreamsPerNetwork() !== null) return null
+ const picked = pickedStreams(request)
+ return picked === undefined
+ ? new ConcurrencyController(MAX_STREAMS_PER_NETWORK)
+ : new ConcurrencyController(picked, false)
+}
+
+/** The streams per network the user picked for this download, if they didn't leave it on Auto. */
+export function pickedStreams(request: StartHttpDownloadRequest): number | undefined {
+ const picked = request.streamsPerNetwork
+ return Number.isInteger(picked) && picked! >= 1 && picked! <= MAX_STREAMS_PER_NETWORK
+ ? picked
+ : undefined
+}
+/** How often a stream with nothing to do looks for work again. */
+const IDLE_POLL_MS = 250
+// Just longer than an idle stream takes to look for work, so a refreshed block goes to a
+// connection that is already proven fast, if there is one.
+const REFRESH_HANDOFF_MS = IDLE_POLL_MS + 50
+
+function median(values: number[]): number {
+ const sorted = [...values].sort((a, b) => a - b)
+ const mid = sorted.length >> 1
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2
+}
+
+function newStream(id: number, networkId: string): HttpStreamState {
+ return {
+ id,
+ interfaceId: networkId,
+ rangeStart: 0,
+ rangeEnd: null,
+ bytesDownloaded: 0,
+ speedBytesPerSec: 0,
+ status: 'pending'
+ }
+}
+
+function requestedVersion(request: StartHttpDownloadRequest): FileVersion {
+ return { etag: request.etag, lastModified: request.lastModified, totalBytes: request.totalBytes }
+}
+
+// How much of the already-downloaded file to re-fetch and compare when a server labels a
+// response with an ETag or Last-Modified this download hasn't seen before.
+const SAMPLE_BYTES = 16 * 1024
+const MAX_SAMPLES = 8
+/** A sample must come from a server presenting the new label; behind a load balancer the next
+ * request may land on another one, so take a few tries at reaching it. */
+const SAMPLE_TRIES = 4
+
+/**
+ * Fetches a download over HTTP: streams, each one connection to the server through one network,
+ * taking blocks from the scheduler and writing them into the staging file at their own offsets.
+ */
+export class HttpTransfer implements Transfer {
+ private chunkRuntimes = new Map<number, ChunkRuntime>()
+ /** The running streams' workers, by stream id. Empty unless the download is running. */
+ private workers = new Map<number, Promise<void>>()
+ /** 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. */
+ private reconciled = new Map<string, NetworkStatus>()
+ /** The version this download started on, plus any since confirmed to serve identical bytes
+ * (see confirmSameBytes). Not persisted: after a restart, a confirmation is simply redone. */
+ private acceptedVersions: FileVersion[]
+ /** Slow-connection refreshes per block index, capped at MAX_REFRESHES_PER_BLOCK. */
+ private refreshesByBlock = new Map<number, number>()
+ /** For a block whose last attempt delivered nothing, the network that made it. That network
+ * leaves the block to another one while another is free to take it (see scheduler.ts). Not
+ * persisted: it only steers the next hand-out. */
+ private avoidNetworkByBlock = new Map<number, string>()
+ /** Attempts in flight, by block index. */
+ private attempts = new Map<number, Attempt[]>()
+ /** Hedges started per block index, capped at SCHEDULER_POLICY.maxHedgesPerBlock. */
+ private hedgesByBlock = new Map<number, number>()
+ /** By network id: everything its streams have received, and when it last showed it was alive —
+ * received something, or came into use. */
+ private traffic = new Map<string, { received: number; aliveAt: number }>()
+ /** By network id: until when the server asked (Retry-After) not to be sent new requests over
+ * it. */
+ private holdUntil = new Map<string, 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. */
+ private concurrency: ConcurrencyController | null
+
+ constructor(
+ private readonly runtime: HttpTransferTarget,
+ private readonly host: TransferHost
+ ) {
+ this.acceptedVersions = [requestedVersion(runtime.requestPayload)]
+ this.concurrency = concurrencyFor(runtime.requestPayload)
+ }
+
+ /**
+ * Each network's streams in line with what it can do now:
+ * - 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.
+ */
+ reconcile(): void {
+ const { state } = this.runtime
+ const canSplit = splittable(this.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' &&
+ (this.reconciled.get(network.id) !== 'on' || this.liveStreams(network.id).length === 0)
+ )
+ const starting = canSplit
+ ? startingStreams(
+ this.runtime.blocks.filter((block) => block.status === 'pending').length,
+ joining.length,
+ testStreamsPerNetwork() ?? pickedStreams(this.runtime.requestPayload)
+ )
+ : 1
+
+ const now = Date.now()
+ const toStart: HttpStreamState[] = []
+ for (const network of state.networks) {
+ const live = this.liveStreams(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.trafficOf(network.id).aliveAt = now
+ if (live.length > target) this.retireStreams(network.id, live.length - target)
+ // Streams kept from before a pause start again.
+ for (const chunk of live.slice(0, target)) {
+ if (!this.workers.has(chunk.id)) toStart.push(chunk)
+ }
+ if (target > live.length) {
+ toStart.push(...this.addStreams(network.id, target - live.length))
+ }
+ this.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(interleave(toStart, (chunk) => chunk.interfaceId))
+ }
+
+ tick(now: number): void {
+ this.refreshStuckConnections(now)
+ this.host.reconcile()
+ this.adjustStreams(this.concurrency?.tick(this.concurrencySnapshot()))
+ // Each refusal is counted once.
+ for (const self of this.chunkRuntimes.values()) {
+ self.refused = false
+ self.served = false
+ }
+ }
+
+ running(): Iterable<Promise<void>> {
+ return this.workers.values()
+ }
+
+ abort(): void {
+ for (const self of this.chunkRuntimes.values()) self.controller.abort()
+ }
+
+ reset(): void {
+ this.avoidNetworkByBlock.clear()
+ this.reconciled.clear()
+ }
+
+ systemResumed(now: number): void {
+ for (const traffic of this.traffic.values()) traffic.aliveAt = now
+ for (const self of this.chunkRuntimes.values()) {
+ self.warmSince = now
+ self.slowSince = null
+ }
+ this.wake(
+ () => true,
+ () => true
+ )
+ }
+
+ /**
+ * Gets streams going again now, rather than when their backoff runs out: what held them back
+ * has changed. The ones `reconnect` picks also drop their sockets, and what they were fetching
+ * is taken up again on a new one: a refresh, so nothing is lost and no retry is counted.
+ */
+ wake(pick: (networkId: string) => boolean, reconnect: (networkId: string) => boolean): void {
+ for (const chunk of this.runtime.state.streams) {
+ const self = this.chunkRuntimes.get(chunk.id)
+ if (!self || self.retiring || !pick(chunk.interfaceId)) continue
+ self.failures = 0
+ if (reconnect(chunk.interfaceId)) {
+ if (self.attempt) this.abortAttempt(self.attempt, 'refresh')
+ self.connection.reconnect()
+ }
+ self.nudge.abort()
+ }
+ }
+
+ /** Waits out a backoff; cut short when the stream stops, or is woken (see wake). */
+ private async backOff(self: ChunkRuntime, ms: number): Promise<void> {
+ await delay(ms, AbortSignal.any([self.wait, self.nudge.signal]))
+ if (self.nudge.signal.aborted) self.nudge = new AbortController()
+ }
+
+ private network(id: string): DownloadNetwork {
+ const network = this.runtime.state.networks.find((entry) => entry.id === id)
+ if (!network) throw new Error(`Unknown network ${id}`)
+ return network
+ }
+
+ /** A network's streams that aren't on their way out. */
+ private liveStreams(networkId: string): HttpStreamState[] {
+ return this.runtime.state.streams.filter(
+ (chunk) => chunk.interfaceId === networkId && !this.chunkRuntimes.get(chunk.id)?.retiring
+ )
+ }
+
+ private trafficOf(networkId: string): { received: number; aliveAt: number } {
+ let traffic = this.traffic.get(networkId)
+ if (!traffic) this.traffic.set(networkId, (traffic = { received: 0, aliveAt: 0 }))
+ return traffic
+ }
+
+ private startStreams(chunks: HttpStreamState[]): void {
+ for (const chunk of chunks) {
+ this.workers.set(
+ chunk.id,
+ this.runWorker(chunk).finally(() => {
+ this.workers.delete(chunk.id)
+ if (this.chunkRuntimes.get(chunk.id)?.retiring) this.removeStream(chunk)
+ })
+ )
+ }
+ if (chunks.length > 0) this.host.scheduleUpdate()
+ }
+
+ private adjustStreams(actions: Action[] | undefined): void {
+ for (const action of actions ?? []) {
+ if (action.kind === 'add') {
+ this.startStreams(this.addStreams(action.networkId, action.count))
+ } else {
+ this.retireStreams(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.
+ *
+ * - Silent: nothing received for SILENT_AFTER_MS while the file is demonstrably being served
+ * to others. Judged by the clock alone, so it also catches a network that has yet to
+ * deliver a byte and therefore has no speed to be compared with.
+ * - Crawling: under SLOW_RATIO of its network's reference speed for SLOW_FOR_MS. The reference
+ * is the median of what connections on the same network are doing now and did on their last
+ * finished block — its own included, which covers the tail (everyone else is done) and a
+ * network with a single connection. Networks are never compared with each other: cellular
+ * is expected to be slower than Wi-Fi.
+ *
+ * Reconnecting only swaps one connection for another, and stops after a couple of tries; what
+ * can finish a block whose connections all crawl is a hedge (see scheduler.ts).
+ */
+ private refreshStuckConnections(now: number): void {
+ // Without ranges a reconnect restarts the whole file from byte 0.
+ if (!this.runtime.requestPayload.supportsRanges) return
+
+ let unreachable = false
+ for (const chunk of this.runtime.state.streams) {
+ const self = this.chunkRuntimes.get(chunk.id)
+ const attempt = self?.attempt
+ if (!self || !attempt || attempt.abortReason) continue
+
+ const silent = this.isSilent(attempt, now)
+ // A refresh isn't a failure, so no failed request would say that the network can't get
+ // through; a connection gone silent with the rest of its network says it instead, as soon
+ // as SILENT_AFTER_MS rather than once a connect or stall timeout has run out.
+ if (silent && this.markUnreachable(this.network(attempt.networkId), now)) {
+ unreachable = true
+ }
+ // Silent while its network's other connections are served: the server took the connection
+ // and left it waiting, which is how some turn away one too many (see concurrency.ts).
+ if (silent) self.refused = true
+
+ const index = attempt.block.index
+ const refreshes = this.refreshesByBlock.get(index) ?? 0
+ // A hedge is optional work: it is only ever dropped, never counted against its block.
+ const isPrimary = attempt.kind === 'primary'
+ if (isPrimary && refreshes >= MAX_REFRESHES_PER_BLOCK) continue
+
+ if (silent || (isPrimary && this.isCrawling(chunk, self, now))) {
+ if (isPrimary) this.refreshesByBlock.set(index, refreshes + 1)
+ this.abortAttempt(attempt, 'refresh')
+ }
+ }
+ if (unreachable) this.host.reconcile()
+ }
+
+ /** Marks a network in use that has received nothing for SILENT_AFTER_MS as unable to reach the
+ * server. Whether it did. */
+ private markUnreachable(network: DownloadNetwork, now: number): boolean {
+ if (network.status !== 'on') return false
+ if (now - this.trafficOf(network.id).aliveAt < SILENT_AFTER_MS) return false
+ network.status = 'unreachable'
+ return true
+ }
+
+ private isSilent(attempt: Attempt, now: number): boolean {
+ if (attempt.networkReceived > 0 || now - attempt.startedAt < SILENT_AFTER_MS) return false
+ // Until something has arrived, a quiet origin is just a slow one — nothing to blame this
+ // connection for.
+ return this.runtime.blocks.some(
+ (block) => block.index !== attempt.block.index && block.bytesDownloaded > 0
+ )
+ }
+
+ private isCrawling(chunk: HttpStreamState, self: ChunkRuntime, now: number): boolean {
+ const warm = (connection: ChunkRuntime): boolean => now - connection.warmSince >= SLOW_WARMUP_MS
+ if (!warm(self)) return false
+
+ const reference: number[] = []
+ for (const other of this.runtime.state.streams) {
+ if (other.interfaceId !== chunk.interfaceId) continue
+ const peer = this.chunkRuntimes.get(other.id)
+ if (!peer) continue
+ if (peer.lastBlockSpeed > 0) reference.push(peer.lastBlockSpeed)
+ if (other !== chunk && peer.attempt && warm(peer)) reference.push(other.speedBytesPerSec)
+ }
+
+ if (reference.length === 0 || chunk.speedBytesPerSec >= median(reference) * SLOW_RATIO) {
+ self.slowSince = null
+ return false
+ }
+ self.slowSince ??= now
+ return now - self.slowSince >= SLOW_FOR_MS
+ }
+
+ private abortAttempt(attempt: Attempt, reason: AbortReason): void {
+ if (attempt.abortReason) return
+ attempt.abortReason = reason
+ attempt.abort.abort()
+ }
+
+ // --- attempts ---------------------------------------------------------------------------------
+ //
+ // A stream's life is a loop: ask the scheduler for work, run it as an attempt, then apply what
+ // became of it. Everything that changes the download's state happens in the synchronous stretches
+ // between awaits, so a stream never sees another's half-finished change.
+
+ /** Where an attempt has got to in its block. */
+ private attemptPosition(attempt: Attempt): number {
+ return (attempt.startOffset ?? 0) + attempt.received
+ }
+
+ /** How far the block's other attempts have got: what is safe to keep counted when one lets go. */
+ private otherAttemptsPosition(attempt: Attempt): number {
+ let furthest = 0
+ for (const other of this.attempts.get(attempt.block.index) ?? []) {
+ if (other !== attempt) furthest = Math.max(furthest, this.attemptPosition(other))
+ }
+ return furthest
+ }
+
+ /** The stream holds no block: it says so, rather than keeping the last one's numbers on show. */
+ private goIdle(chunk: HttpStreamState): void {
+ chunk.status = 'pending'
+ chunk.currentBlockIndex = undefined
+ chunk.hedge = undefined
+ chunk.speedBytesPerSec = 0
+ }
+
+ private beginAttempt(chunk: HttpStreamState, self: ChunkRuntime, work: Work): Attempt {
+ const { block } = work
+ const attempt: Attempt = {
+ kind: work.kind,
+ block,
+ streamId: chunk.id,
+ networkId: chunk.interfaceId,
+ startOffset: null,
+ received: 0,
+ networkReceived: 0,
+ lastNetworkAt: 0,
+ startedAt: Date.now(),
+ // Whoever held this block before now is the one whose tail bytes a truncation would
+ // discard — captured before the lease overwrites the field.
+ previousWriter: block.interfaceId,
+ abort: new AbortController(),
+ abortReason: null,
+ response: null
+ }
+
+ if (work.kind === 'primary') {
+ block.status = 'downloading'
+ block.interfaceId = chunk.interfaceId
+ this.avoidNetworkByBlock.delete(block.index)
+ } else {
+ this.hedgesByBlock.set(block.index, (this.hedgesByBlock.get(block.index) ?? 0) + 1)
+ }
+ const inFlight = this.attempts.get(block.index)
+ if (inFlight) inFlight.push(attempt)
+ else this.attempts.set(block.index, [attempt])
+ self.attempt = attempt
+
+ chunk.status = 'downloading'
+ chunk.hedge = work.kind === 'hedge' ? true : undefined
+ chunk.rangeStart = block.rangeStart
+ chunk.rangeEnd = block.rangeEnd
+ chunk.currentBlockIndex = block.index
+ return attempt
+ }
+
+ /** Takes the attempt off the books. Safe to repeat. */
+ private endAttempt(self: ChunkRuntime, attempt: Attempt): void {
+ const inFlight = this.attempts.get(attempt.block.index)
+ if (inFlight) {
+ const position = inFlight.indexOf(attempt)
+ if (position >= 0) inFlight.splice(position, 1)
+ if (inFlight.length === 0) this.attempts.delete(attempt.block.index)
+ }
+ if (self.attempt === attempt) self.attempt = null
+ }
+
+ /** Sends the request and reports how it ended. Never throws. */
+ private async executeAttempt(
+ chunk: HttpStreamState,
+ self: ChunkRuntime,
+ attempt: Attempt
+ ): Promise<AttemptOutcome> {
+ const { block } = attempt
+ try {
+ if (attempt.kind === 'primary') {
+ // A failed range leaves its written prefix in the staging file. Without range support,
+ // the server can only restart from byte zero.
+ attempt.startOffset = this.runtime.requestPayload.supportsRanges ? block.bytesDownloaded : 0
+ // What another attempt has already secured stays counted.
+ const keep = Math.max(attempt.startOffset, this.otherAttemptsPosition(attempt))
+ if (retractBlock(block, keep, attempt.previousWriter) > 0) {
+ recomputeAggregates(this.runtime.state, this.runtime.blocks)
+ }
+ } else {
+ attempt.startOffset = block.bytesDownloaded
+ }
+
+ const length = block.rangeEnd === null ? null : block.rangeEnd - block.rangeStart + 1
+ if (length !== null && attempt.startOffset >= length) {
+ // The staging file already holds the whole block.
+ return attempt.kind === 'primary'
+ ? { type: 'completed' }
+ : { type: 'aborted', reason: 'lost' }
+ }
+
+ attempt.startedAt = Date.now()
+ await downloadChunk({
+ url: this.runtime.requestPayload.url,
+ rangeStart: block.rangeStart + attempt.startOffset,
+ rangeEnd: block.rangeEnd,
+ connection: self.connection,
+ createDestination: () =>
+ this.runtime.file.writer(block.rangeStart + (attempt.startOffset ?? 0)),
+ signal: AbortSignal.any([self.controller.signal, attempt.abort.signal]),
+ acceptedVersions: this.acceptedVersions,
+ onResponse: (info) => (attempt.response = info),
+ throttle: (bytes) => this.host.limits.take(attempt.networkId, bytes),
+ onNetworkProgress: (bytesThisRun) => {
+ const delta = bytesThisRun - attempt.networkReceived
+ if (delta > 0) {
+ attempt.networkReceived = bytesThisRun
+ attempt.lastNetworkAt = Date.now()
+ this.onNetworkProgress(chunk, self, delta)
+ }
+ },
+ onProgress: (bytesThisRun) => {
+ const delta = bytesThisRun - attempt.received
+ if (delta > 0) {
+ attempt.received = bytesThisRun
+ this.onAttemptProgress(chunk, attempt)
+ }
+ }
+ })
+ return { type: 'completed' }
+ } catch (error) {
+ const status = this.runtime.state.status as DownloadStatus
+ if (self.controller.signal.aborted || status !== 'downloading') return { type: 'stopped' }
+ if (attempt.abortReason) return { type: 'aborted', reason: attempt.abortReason }
+ return { type: 'failed', error }
+ }
+ }
+
+ private onNetworkProgress(chunk: HttpStreamState, self: ChunkRuntime, deltaBytes: number): void {
+ const now = Date.now()
+ self.receivedBytes += deltaBytes
+ self.served = true
+ const traffic = this.trafficOf(chunk.interfaceId)
+ traffic.received += deltaBytes
+ traffic.aliveAt = now
+ const network = this.network(chunk.interfaceId)
+ if (network.status === 'unreachable') {
+ // Through again: the next reconcile gives it back its streams.
+ network.status = 'on'
+ self.failures = 0
+ }
+ // Read as speeds on the download's clock (see updateSpeeds).
+ this.runtime.meters.add(chunk.id, chunk.interfaceId, deltaBytes)
+ this.host.scheduleUpdate()
+ }
+
+ private onAttemptProgress(chunk: HttpStreamState, attempt: Attempt): void {
+ // Only what gets the block further than it already was counts as progress: a racing attempt
+ // re-fetches bytes the other already has.
+ const gained = advanceBlock(attempt.block, attempt.networkId, this.attemptPosition(attempt))
+ chunk.bytesDownloaded += gained
+ this.network(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
+ // callers of recomputeAggregates are rare enough to afford the full pass, and each one
+ // re-derives the true total, so any drift here cannot accumulate.
+ this.runtime.state.bytesDownloaded += gained
+ this.host.scheduleUpdate()
+ }
+
+ /** Applies what became of an attempt to the download. 'stop' ends the stream. */
+ private async finishAttempt(
+ chunk: HttpStreamState,
+ self: ChunkRuntime,
+ attempt: Attempt,
+ outcome: AttemptOutcome
+ ): Promise<'continue' | 'stop'> {
+ debug('attempt', {
+ block: attempt.block.index,
+ stream: chunk.id,
+ network: attempt.networkId,
+ kind: attempt.kind,
+ outcome: outcome.type === 'aborted' ? `aborted:${outcome.reason}` : outcome.type,
+ networkBytes: attempt.networkReceived,
+ writtenBytes: attempt.received,
+ ms: Date.now() - attempt.startedAt,
+ ...attempt.response
+ })
+
+ switch (outcome.type) {
+ case 'completed':
+ return this.finishCompleted(chunk, self, attempt)
+ case 'stopped':
+ return this.finishStopped(chunk, self, attempt)
+ case 'aborted':
+ return this.finishAborted(chunk, self, attempt, outcome.reason)
+ case 'failed':
+ return this.finishFailed(chunk, self, attempt, outcome.error)
+ }
+ }
+
+ private finishCompleted(
+ chunk: HttpStreamState,
+ self: ChunkRuntime,
+ attempt: Attempt
+ ): 'continue' {
+ const { block } = attempt
+
+ // Another attempt already finished this block: these bytes are surplus.
+ if (block.status === 'completed') {
+ this.letGo(chunk, self, attempt, false)
+ return 'continue'
+ }
+
+ this.endAttempt(self, attempt)
+ block.status = 'completed'
+ block.interfaceId = attempt.networkId
+ if (block.rangeEnd !== null) {
+ // Progress events can lag the final write, so square the block up to its exact size and
+ // credit the shortfall to the network that finished it.
+ const blockBytes = block.rangeEnd - block.rangeStart + 1
+ chunk.bytesDownloaded += advanceBlock(block, attempt.networkId, blockBytes)
+ self.lastBlockSpeed =
+ (attempt.networkReceived /
+ Math.max(1, (attempt.lastNetworkAt || Date.now()) - attempt.startedAt)) *
+ 1000
+ }
+ self.failures = 0
+ self.strikes = 0
+ // Whoever is still racing for the block has lost.
+ for (const rival of this.attempts.get(block.index) ?? []) this.abortAttempt(rival, 'lost')
+ recomputeAggregates(this.runtime.state, this.runtime.blocks)
+ this.host.scheduleUpdate()
+ return 'continue'
+ }
+
+ /** The stream was stopped while its request was in flight. */
+ private finishStopped(chunk: HttpStreamState, self: ChunkRuntime, attempt: Attempt): 'stop' {
+ // Whatever stopped it — a pause, a cancel, retirement — the block goes back as any other
+ // attempt's would, and one another attempt has finished stays finished.
+ this.letGo(chunk, self, attempt, false)
+ chunk.status = this.runtime.state.status === 'paused' ? 'paused' : 'cancelled'
+ return 'stop'
+ }
+
+ private async finishAborted(
+ chunk: HttpStreamState,
+ self: ChunkRuntime,
+ attempt: Attempt,
+ reason: AbortReason
+ ): Promise<'continue'> {
+ // 'lost': another attempt decided the block, so its state is no longer this one's to touch.
+ // 'refresh': not a failure — no retry counted, no backoff. Whoever takes the block next
+ // resumes it from the staging file on a new connection.
+ this.letGo(chunk, self, attempt, reason === 'refresh' && attempt.networkReceived === 0)
+ if (reason === 'refresh' && attempt.kind === 'primary') {
+ // 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.host.scheduleUpdate()
+ await delay(REFRESH_HANDOFF_MS, self.wait)
+ self.warmSince = Date.now()
+ self.slowSince = null
+ }
+ return 'continue'
+ }
+
+ private async finishFailed(
+ chunk: HttpStreamState,
+ self: ChunkRuntime,
+ attempt: Attempt,
+ error: unknown
+ ): Promise<'continue' | 'stop'> {
+ const message = error instanceof Error ? error.message : String(error)
+ const network = this.network(attempt.networkId)
+ const deliveredNothing = attempt.networkReceived === 0
+
+ if (error instanceof RemoteChangedError) {
+ const verdict =
+ error.check.kind === 'size'
+ ? 'different'
+ : await this.confirmSameBytes(self.connection, error.seen)
+ // The check takes a moment; the download may have been paused or stopped meanwhile.
+ if ((this.runtime.state.status as DownloadStatus) !== 'downloading') {
+ return this.finishStopped(chunk, self, attempt)
+ }
+ if (verdict === 'same') {
+ // Same bytes under another label — accept it and fetch again straight away; nothing from
+ // the rejected response was written.
+ if (compareVersion(this.acceptedVersions, error.seen).kind !== 'same') {
+ this.acceptedVersions.push(error.seen)
+ }
+ this.letGo(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. What's on disk is of the old version: no use.
+ this.host.failDownload(message, true)
+ return this.finishStopped(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, and no retry over
+ // it will change that. Its block goes back to the queue for another network.
+ this.letGo(chunk, self, attempt, deliveredNothing)
+ this.host.failNetwork(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 && this.markUnreachable(network, Date.now())) {
+ this.host.reconcile()
+ }
+
+ // A hedge is optional work: its failure isn't retried, and what it did write stays.
+ if (attempt.kind === 'hedge') {
+ this.letGo(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 += 1
+ // What arrived before it failed shows the network works, and what was written shows the
+ // server does: the count in a row starts over, and so does the backoff.
+ if (attempt.networkReceived > 0) self.failures = 0
+ if (attempt.received > 0) {
+ self.strikes = 0
+ self.busySince = null
+ }
+ self.failures += 1
+ // Back to the queue, so any available worker can pick it up.
+ this.letGo(chunk, self, attempt, deliveredNothing)
+
+ // 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, and one
+ // that answered busy is waited out for SERVER_BUSY_FOR_MS as well; then this stream gives up,
+ // and once all its network's have, so does the network.
+ const now = Date.now()
+ // The server turning a request away: the stream count takes it as a limit (see
+ // concurrency.ts).
+ if (error instanceof HttpStatusError && [403, 429, 503].includes(error.status)) {
+ self.refused = true
+ }
+ const busy = error instanceof HttpStatusError && error.transient
+ if (busy) self.busySince ??= now
+ const waitingOut = busy && now - (self.busySince ?? now) < SERVER_BUSY_FOR_MS
+ if (!(error instanceof ConnectionError) && ++self.strikes > MAX_CHUNK_RETRIES && !waitingOut) {
+ self.retiring = true
+ if (this.liveStreams(network.id).length === 0) {
+ this.host.failNetwork(network, message)
+ }
+ return 'stop'
+ }
+
+ let wait = retryDelayMs(self.failures)
+ if (network.status === 'unreachable') wait = Math.min(wait, UNREACHABLE_RETRY_MS)
+ if (error instanceof HttpStatusError && error.transient && error.retryAfterMs !== null) {
+ // Asked of whoever sent it — this network's address, to the server — not of this one
+ // request: none of the network's streams sends another until then.
+ const asked = Math.min(error.retryAfterMs, RETRY_AFTER_MAX_MS)
+ wait = Math.max(wait, asked)
+ this.holdUntil.set(network.id, Math.max(this.holdUntil.get(network.id) ?? 0, now + asked))
+ }
+
+ chunk.status = 'retrying'
+ this.host.scheduleUpdate()
+ await this.backOff(self, wait)
+ const statusAfterDelay = this.runtime.state.status as DownloadStatus
+ if (self.controller.signal.aborted || statusAfterDelay !== 'downloading') {
+ chunk.status = statusAfterDelay === 'paused' ? 'paused' : 'cancelled'
+ chunk.speedBytesPerSec = 0
+ return 'stop'
+ }
+ this.goIdle(chunk)
+ self.warmSince = Date.now()
+ self.slowSince = null
+ return 'continue'
+ }
+
+ /**
+ * The stream stops working on the attempt's block without having finished it. A primary hands
+ * the block back to the queue; a hedge just drops out. Either way what it wrote stays counted.
+ * When the attempt delivered nothing, its network is remembered (see scheduler.ts).
+ */
+ private letGo(
+ chunk: HttpStreamState,
+ self: ChunkRuntime,
+ attempt: Attempt,
+ deliveredNothing: boolean
+ ): void {
+ this.endAttempt(self, attempt)
+ const { block } = attempt
+ // A block another attempt has finished stays finished.
+ if (attempt.kind === 'primary' && block.status === 'downloading') block.status = 'pending'
+ if (deliveredNothing) this.avoidNetworkByBlock.set(block.index, attempt.networkId)
+ this.goIdle(chunk)
+ }
+
+ private concurrencySnapshot(): Snapshot {
+ const inUse = this.runtime.state.networks.filter((network) => network.status === 'on')
+ const networks = inUse.map(({ id }) => {
+ let streams = 0
+ let answered = 0
+ let refused = 0
+ let served = 0
+ for (const chunk of this.liveStreams(id)) {
+ const self = this.chunkRuntimes.get(chunk.id)
+ streams++
+ if (self && self.receivedBytes > 0) answered++
+ if (self?.refused) refused++
+ if (self?.served) served++
+ }
+ return { id, streams, answered, refused, served }
+ })
+ // A new stream takes a waiting block the moment it starts.
+ const waiting = this.runtime.blocks.filter((block) => block.status === 'pending').length
+ return { now: Date.now(), networks, spareWork: waiting }
+ }
+
+ /** New streams on `networkId`, put on the download's list for the caller to start. */
+ private addStreams(networkId: string, count: number): HttpStreamState[] {
+ let id = Math.max(-1, ...this.runtime.state.streams.map((chunk) => chunk.id))
+ const added = Array.from({ length: count }, () => newStream(++id, networkId))
+ this.runtime.state.streams.push(...added)
+ this.runtime.state.peakStreams = Math.max(
+ this.runtime.state.peakStreams ?? 0,
+ this.runtime.state.streams.length
+ )
+ debug('streams', { network: networkId, added: count })
+ this.host.scheduleUpdate()
+ return added
+ }
+
+ /** Stops `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(networkId: string, count: number): void {
+ if (count < 1) return
+ // Streams the server just refused go first (see concurrency.ts), then ones whose last
+ // request failed, then the newest.
+ const rank = (chunk: HttpStreamState): number => {
+ const self = this.chunkRuntimes.get(chunk.id)
+ return self?.refused ? 2 : (self?.failures ?? 0) > 0 ? 1 : 0
+ }
+ const order = this.liveStreams(networkId).sort((a, b) => rank(b) - rank(a) || b.id - a.id)
+ for (const chunk of order.slice(0, count)) {
+ const self = this.chunkRuntimes.get(chunk.id)
+ if (self && this.workers.has(chunk.id)) {
+ // Its worker takes it off the list once it has stopped.
+ self.retiring = true
+ self.controller.abort()
+ } else {
+ this.removeStream(chunk)
+ }
+ }
+ debug('streams', { network: networkId, retired: count })
+ }
+
+ /** Takes a retired stream off the list. */
+ private removeStream(chunk: HttpStreamState): void {
+ this.chunkRuntimes.delete(chunk.id)
+ this.runtime.meters.connections.delete(chunk.id)
+ const index = this.runtime.state.streams.indexOf(chunk)
+ if (index < 0) return
+ this.runtime.state.streams.splice(index, 1)
+ this.host.scheduleUpdate()
+ }
+
+ private async runWorker(chunk: HttpStreamState): Promise<void> {
+ const controller = new AbortController()
+ const self: ChunkRuntime = {
+ controller,
+ wait: AbortSignal.any([controller.signal, this.runtime.stop.signal]),
+ nudge: new AbortController(),
+ connection: new StreamConnection(() => this.host.networks.find(chunk.interfaceId), {
+ timeoutMs: testKnobs.stallTimeoutMs,
+ connectTimeoutMs: testKnobs.connectTimeoutMs
+ }),
+ attempt: null,
+ warmSince: Date.now(),
+ slowSince: null,
+ lastBlockSpeed: 0,
+ receivedBytes: 0,
+ failures: 0,
+ strikes: 0,
+ busySince: null,
+ refused: false,
+ served: false,
+ retiring: false
+ }
+ this.chunkRuntimes.set(chunk.id, self)
+
+ try {
+ while (this.runtime.state.status === 'downloading') {
+ if (controller.signal.aborted || self.retiring) break
+
+ // The server asked this network to hold off: no new request over it until then. Each
+ // stream comes back a little apart from the others.
+ const holdFor = (this.holdUntil.get(chunk.interfaceId) ?? 0) - Date.now()
+ if (holdFor > 0) {
+ this.goIdle(chunk)
+ chunk.status = 'retrying'
+ this.host.scheduleUpdate()
+ await this.backOff(self, holdFor + Math.random() * Math.min(1000, holdFor / 10))
+ continue
+ }
+
+ // Taken atomically: nothing between choosing the work and registering it can yield.
+ const work = pickWork(
+ {
+ blocks: this.runtime.blocks,
+ streams: this.runtime.state.streams,
+ attempts: this.attempts,
+ avoid: this.avoidNetworkByBlock,
+ hedgesUsed: this.hedgesByBlock
+ },
+ {
+ id: chunk.id,
+ networkId: chunk.interfaceId,
+ speedBytesPerSec: self.lastBlockSpeed || undefined
+ },
+ Date.now(),
+ SCHEDULER_POLICY
+ )
+ if (!work) {
+ this.goIdle(chunk)
+ // While blocks are still in flight, stay available in case one fails and is handed back,
+ // or turns out to be slow enough to be worth racing.
+ if (
+ this.runtime.blocks.some((b) => b.status === 'pending' || b.status === 'downloading')
+ ) {
+ this.host.scheduleUpdate()
+ await delay(IDLE_POLL_MS, self.wait)
+ continue
+ }
+ chunk.status = 'completed'
+ this.host.scheduleUpdate()
+ break
+ }
+
+ const attempt = this.beginAttempt(chunk, self, work)
+ this.host.scheduleUpdate()
+ const outcome = await this.executeAttempt(chunk, self, attempt)
+ let next: 'continue' | 'stop'
+ try {
+ next = await this.finishAttempt(chunk, self, attempt, outcome)
+ } finally {
+ this.endAttempt(self, attempt)
+ }
+ if (next === 'stop') break
+ }
+ } finally {
+ // Its sockets would otherwise stay open, kept alive for requests that will never come.
+ self.connection.close()
+ }
+
+ this.host.scheduleUpdate()
+ }
+
+ /**
+ * Settles whether a server labelling the file differently (new ETag or Last-Modified, same
+ * size) is serving the same bytes — load-balanced servers often disagree on labels for
+ * identical files — or a new version. Re-fetches a spread of bytes this download already has
+ * on disk, from a server presenting the new label, and compares them.
+ *
+ * 'unknown' when there's nothing on disk to compare yet or the samples couldn't be fetched;
+ * the caller then treats the response as an ordinary failed request and retries.
+ */
+ private async confirmSameBytes(
+ connection: StreamConnection,
+ seen: FileVersion
+ ): Promise<'same' | 'different' | 'unknown'> {
+ if (compareVersion(this.acceptedVersions, seen).kind === 'same') return 'same'
+
+ // Every byte on disk came from an accepted version: mismatched responses are rejected
+ // before anything is written.
+ const withData = this.runtime.blocks.filter((block) => block.bytesDownloaded > 0)
+ const step = Math.max(1, withData.length / MAX_SAMPLES)
+ const picks = Array.from(
+ { length: Math.min(MAX_SAMPLES, withData.length) },
+ (_, i) => withData[Math.floor(i * step)]
+ )
+
+ let compared = 0
+ for (const block of picks) {
+ let local: Buffer
+ try {
+ local = await this.runtime.file.read(
+ block.rangeStart,
+ Math.min(SAMPLE_BYTES, block.bytesDownloaded)
+ )
+ } catch {
+ continue
+ }
+ if (local.length === 0) continue
+
+ for (let tries = 0; tries < SAMPLE_TRIES; tries++) {
+ try {
+ const remote = await fetchRange(
+ this.runtime.requestPayload.url,
+ block.rangeStart,
+ block.rangeStart + local.length - 1,
+ connection
+ )
+ // A reply from a server still presenting an accepted label proves nothing here.
+ if (compareVersion([seen], remote.version).kind !== 'same') continue
+ if (!remote.body.equals(local)) return 'different'
+ compared += 1
+ break
+ } catch {
+ return 'unknown'
+ }
+ }
+ }
+ return compared > 0 ? 'same' : 'unknown'
+ }
+}
diff --git a/src/main/download/paths.ts b/src/main/download/paths.ts
index 6628e0d..0cced9b 100644
--- a/src/main/download/paths.ts
+++ b/src/main/download/paths.ts
@@ -14,7 +14,7 @@ export function getHomeDir(): string {
// (or if something outside the app is creating them as fast as we try).
const MAX_NAME_ATTEMPTS = 10_000
-async function pathExists(path: string): Promise<boolean> {
+export async function pathExists(path: string): Promise<boolean> {
try {
await lstat(path)
return true
@@ -48,19 +48,22 @@ export async function ensureDirectory(directory: string): Promise<void> {
}
/**
- * Claims a download by exclusively creating <final name>.plexo. The final name
- * itself does not appear until the file is complete. An existing partial file
- * also claims its corresponding final name, including after a restart.
+ * The first of `name`, `name (1)`, `name (2)`… in `directory` that is free and that `claim` takes
+ * for this download: `claim` returns false to pass on a name, and an EEXIST it throws does too.
+ * `suffix` is what claiming adds to a name, room left for it within the 255-byte component limit.
*/
-export async function reserveDestinationPath(directory: string, fileName: string): Promise<string> {
+async function claimName(
+ directory: string,
+ name: string,
+ { suffix, extension }: { suffix: string; extension: boolean },
+ claim: (candidate: string) => Promise<boolean>
+): Promise<string> {
await ensureDirectory(directory)
- fileName = sanitizeFileName(fileName)
- const ext = extname(fileName)
- // Leave room for " (9999).plexo" within the usual 255-byte component limit.
- const suffixRoom = Buffer.byteLength(' (9999).plexo')
- const maxBaseBytes = 255 - suffixRoom - Buffer.byteLength(ext)
+ name = sanitizeFileName(name)
+ const ext = extension ? extname(name) : ''
+ const maxBaseBytes = 255 - Buffer.byteLength(` (9999)${suffix}`) - Buffer.byteLength(ext)
if (maxBaseBytes <= 0) throw new Error('The file extension is too long')
- const baseCharacters = Array.from(basename(fileName, ext))
+ const baseCharacters = Array.from(ext ? basename(name, ext) : name)
while (Buffer.byteLength(baseCharacters.join('')) > maxBaseBytes) baseCharacters.pop()
const base = baseCharacters.join('')
@@ -71,17 +74,49 @@ export async function reserveDestinationPath(directory: string, fileName: string
: join(directory, `${base} (${counter})${ext}`)
if (await pathExists(candidate)) continue
try {
- const handle = await open(`${candidate}.plexo`, 'wx+')
- await handle.close()
- if (await pathExists(candidate)) {
- await rm(`${candidate}.plexo`)
- continue
- }
- return candidate
+ if (await claim(candidate)) return candidate
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
}
}
- throw new Error(`Could not find an unused file name for "${fileName}" in ${directory}`)
+ throw new Error(`Could not find an unused file name for "${name}" in ${directory}`)
+}
+
+/**
+ * Claims a download by exclusively creating <final name>.plexo. The final name
+ * itself does not appear until the file is complete. An existing partial file
+ * also claims its corresponding final name, including after a restart.
+ */
+export async function reserveDestinationPath(directory: string, fileName: string): Promise<string> {
+ return claimName(
+ directory,
+ fileName,
+ { suffix: '.plexo', extension: true },
+ async (candidate) => {
+ const handle = await open(`${candidate}.plexo`, 'wx+')
+ await handle.close()
+ if (!(await pathExists(candidate))) return true
+ await rm(`${candidate}.plexo`)
+ return false
+ }
+ )
+}
+
+/**
+ * Claims the final name itself, by exclusively creating it empty: a torrent is written in place,
+ * as torrent clients do, so what's there from the start is its folder (or its one file). Being
+ * new, it's this download's alone, never something already in the destination.
+ */
+export async function claimDestinationPath(
+ directory: string,
+ name: string,
+ folder: boolean
+): Promise<string> {
+ // A folder's name has no extension to keep last: "Show.S01" goes to "Show.S01 (1)".
+ return claimName(directory, name, { suffix: '', extension: !folder }, async (candidate) => {
+ if (folder) await mkdir(candidate)
+ else await (await open(candidate, 'wx')).close()
+ return true
+ })
}
diff --git a/src/main/download/plan.ts b/src/main/download/plan.ts
index 39c1cbe..6787f74 100644
--- a/src/main/download/plan.ts
+++ b/src/main/download/plan.ts
@@ -1,4 +1,4 @@
-import type { BlockState } from '../../shared/types'
+import type { HttpBlockState, TorrentPieceState } from '../../shared/types'
// 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
@@ -101,8 +101,9 @@ export function startingStreams(
/** The blocks a file of `totalBytes` is cut into, none of them started. An unknown size is one
* block, open-ended to the end of the file. */
-export function planBlocks(totalBytes: number, blockSizeBytes: number): BlockState[] {
- const fresh = (index: number, rangeStart: number, rangeEnd: number | null): BlockState => ({
+export function planBlocks(totalBytes: number, blockSizeBytes: number): HttpBlockState[] {
+ const fresh = (index: number, rangeStart: number, rangeEnd: number | null): HttpBlockState => ({
+ kind: 'http',
index,
rangeStart,
rangeEnd,
@@ -116,3 +117,22 @@ export function planBlocks(totalBytes: number, blockSizeBytes: number): BlockSta
return fresh(index, rangeStart, Math.min(rangeStart + blockSizeBytes, totalBytes) - 1)
})
}
+
+/** A torrent's pieces. Unlike HTTP blocks, received bytes are provisional until the piece's hash
+ * verifies, so the live count is kept separately from durable progress. */
+export function planPieces(totalBytes: number, pieceLength: number): TorrentPieceState[] {
+ if (totalBytes <= 0 || pieceLength <= 0) return []
+ return Array.from({ length: Math.ceil(totalBytes / pieceLength) }, (_, index) => {
+ const rangeStart = index * pieceLength
+ return {
+ kind: 'torrent',
+ index,
+ rangeStart,
+ rangeEnd: Math.min(rangeStart + pieceLength, totalBytes) - 1,
+ status: 'pending',
+ bytesDownloaded: 0,
+ bytesByInterface: {},
+ provisionalBytes: 0
+ }
+ })
+}
diff --git a/src/main/download/probe.ts b/src/main/download/probe.ts
index 713624e..e5e13a9 100644
--- a/src/main/download/probe.ts
+++ b/src/main/download/probe.ts
@@ -1,8 +1,15 @@
import { request as httpRequest } from 'node:http'
import { request as httpsRequest } from 'node:https'
+import { isAbsolute } from 'node:path'
import { URL } from 'node:url'
import type { ProbeResult } from '../../shared/types'
import { testKnobs } from '../testKnobs'
+import {
+ describeTorrent,
+ downloadTorrentFile,
+ fetchMagnetMetadata,
+ readTorrentFile
+} from './torrent/metadata'
const MAX_REDIRECTS = 5
const USER_AGENT = 'Plexo/1.0'
@@ -128,7 +135,20 @@ async function requestFollowingRedirects(
return { current, response }
}
+/** A link the server says is a torrent, or that is named like one. */
+function isTorrentLink(headers: Headers, url: URL): boolean {
+ const contentType = headerValue(headers, 'content-type') ?? ''
+ return /^application\/x-bittorrent\b/i.test(contentType) || /\.torrent$/i.test(url.pathname)
+}
+
+/** What a link would download: a file over HTTP(S), or a torrent — a magnet link, a link to a
+ * .torrent, or the path of a .torrent on this computer (opened or dropped on the window). */
export async function probeUrl(rawUrl: string): Promise<ProbeResult> {
+ if (/^magnet:/i.test(rawUrl)) return describeTorrent(await fetchMagnetMetadata(rawUrl), rawUrl)
+ if (isAbsolute(rawUrl) && /\.torrent$/i.test(rawUrl)) {
+ return describeTorrent(await readTorrentFile(rawUrl), rawUrl)
+ }
+
const { current, response } = await requestFollowingRedirects(rawUrl)
// An empty file can't satisfy a request for its first byte: the server answers 416 and gives
@@ -138,6 +158,7 @@ export async function probeUrl(rawUrl: string): Promise<ProbeResult> {
/^\s*bytes\s+\*\/0\s*$/i.test(headerValue(response.headers, 'content-range') ?? '')
) {
return {
+ kind: 'http',
requestedUrl: rawUrl,
finalUrl: current.toString(),
supportsRanges: false,
@@ -153,6 +174,11 @@ export async function probeUrl(rawUrl: string): Promise<ProbeResult> {
throw new Error(`Server responded with status ${response?.statusCode || 'unknown'}`)
}
+ if (isTorrentLink(response.headers, current)) {
+ const finalUrl = current.toString()
+ return describeTorrent(await downloadTorrentFile(finalUrl, PROBE_TIMEOUT_MS), finalUrl)
+ }
+
const contentRange = headerValue(response.headers, 'content-range')
// A server that supports range requests must answer our 1-byte range GET with 206 Partial Content.
// If it returned 200 OK, it ignored the Range header and sent the whole file — even if its headers
@@ -172,6 +198,7 @@ export async function probeUrl(rawUrl: string): Promise<ProbeResult> {
}
return {
+ kind: 'http',
requestedUrl: rawUrl,
finalUrl: current.toString(),
supportsRanges,
diff --git a/src/main/download/savedProgress.ts b/src/main/download/savedProgress.ts
index 61aa6a5..ac991b5 100644
--- a/src/main/download/savedProgress.ts
+++ b/src/main/download/savedProgress.ts
@@ -1,8 +1,8 @@
-import type { BlockState, DownloadState } from '../../shared/types'
-import { planBlocks } from './plan'
+import type { DownloadUnitState, HttpBlockState, TorrentPieceState } from '../../shared/types'
+import { planBlocks, planPieces } from './plan'
-/** How a download's blocks are saved (manifest version 5). Everything about a block but its
- * progress follows from the plan — its range from the block size — so only the progress is. */
+/** How a download's HTTP blocks or torrent pieces are checkpointed. Their ranges follow from the
+ * transport plan, so only verified progress is durable; live, unverified piece bytes are not. */
export interface SavedBlocks {
/** Per network id, the bytes it delivered of each block, by block index. A block is complete
* when they add up to its length. */
@@ -12,7 +12,7 @@ export interface SavedBlocks {
complete: boolean
}
-export function saveBlocks(blocks: readonly BlockState[]): SavedBlocks {
+export function saveBlocks(blocks: readonly DownloadUnitState[]): SavedBlocks {
const progress: Record<string, number[]> = {}
for (const block of blocks) {
for (const [networkId, bytes] of Object.entries(block.bytesByInterface)) {
@@ -30,15 +30,15 @@ const isCount = (value: unknown): value is number =>
* is allocated for it, and progress that doesn't fit the plan is dropped — the download starts
* its blocks over rather than trusting bytes it can't account for. */
export function restoreBlocks(
- state: Pick<DownloadState, 'totalBytes' | 'blockSizeBytes' | 'totalBlocks'>,
+ state: { totalBytes: number; blockSizeBytes: number; totalBlocks: number },
saved: SavedBlocks
-): BlockState[] | undefined {
+): HttpBlockState[] | undefined {
const { totalBytes, blockSizeBytes, totalBlocks } = state
if (!isCount(totalBytes) || !isCount(blockSizeBytes) || !isCount(totalBlocks)) return undefined
if ((totalBytes > 0 ? Math.ceil(totalBytes / blockSizeBytes) : 1) !== totalBlocks)
return undefined
- const fresh = (): BlockState[] => planBlocks(totalBytes, blockSizeBytes)
+ const fresh = (): HttpBlockState[] => planBlocks(totalBytes, blockSizeBytes)
const blocks = fresh()
const columns =
typeof saved.progress === 'object' && saved.progress !== null
@@ -61,3 +61,37 @@ export function restoreBlocks(
}
return blocks
}
+
+export function restorePieces(
+ state: { totalBytes: number; pieceLength: number; totalPieces: number },
+ saved: SavedBlocks
+): TorrentPieceState[] | undefined {
+ const { totalBytes, pieceLength, totalPieces } = state
+ if (!isCount(totalBytes) || !isCount(pieceLength) || !isCount(totalPieces) || pieceLength === 0) {
+ return undefined
+ }
+ if (Math.ceil(totalBytes / pieceLength) !== totalPieces) return undefined
+
+ const fresh = (): TorrentPieceState[] => planPieces(totalBytes, pieceLength)
+ const pieces = fresh()
+ const columns =
+ typeof saved.progress === 'object' && saved.progress !== null
+ ? Object.entries(saved.progress)
+ : []
+ for (const [networkId, column] of columns) {
+ if (!Array.isArray(column) || column.length !== pieces.length || !column.every(isCount)) {
+ return fresh()
+ }
+ column.forEach((bytes, index) => {
+ if (bytes === 0) return
+ pieces[index].bytesByInterface[networkId] = bytes
+ pieces[index].bytesDownloaded += bytes
+ })
+ }
+ for (const piece of pieces) {
+ const length = piece.rangeEnd! - piece.rangeStart + 1
+ if (piece.bytesDownloaded > length) return fresh()
+ if (saved.complete === true || piece.bytesDownloaded === length) piece.status = 'completed'
+ }
+ return pieces
+}
diff --git a/src/main/download/scheduler.ts b/src/main/download/scheduler.ts
index 55b5d7e..bb5c461 100644
--- a/src/main/download/scheduler.ts
+++ b/src/main/download/scheduler.ts
@@ -1,4 +1,4 @@
-import type { BlockState, ChunkState } from '../../shared/types'
+import type { HttpBlockState, HttpStreamState } from '../../shared/types'
// Who should fetch what, decided from a snapshot of the download and nothing else — no I/O, no
// clock of its own — so every rule here can be checked against exact situations.
@@ -22,8 +22,8 @@ export interface AttemptView {
}
export interface SchedulerState {
- blocks: readonly BlockState[]
- streams: readonly Pick<ChunkState, 'id' | 'interfaceId' | 'status' | 'speedBytesPerSec'>[]
+ blocks: readonly HttpBlockState[]
+ streams: readonly Pick<HttpStreamState, 'id' | 'interfaceId' | 'status' | 'speedBytesPerSec'>[]
/** Attempts in flight, by block index. */
attempts: ReadonlyMap<number, readonly AttemptView[]>
/** For a block whose last attempt on some network delivered nothing, that network. */
@@ -53,7 +53,7 @@ export interface Requester {
export interface Work {
kind: 'primary' | 'hedge'
- block: BlockState
+ block: HttpBlockState
}
/** The first waiting block — except that one whose last attempt on this network delivered
@@ -61,7 +61,7 @@ export interface Work {
* Otherwise a network that isn't answering would be handed the same block again and again, by
* whichever of its streams asked first, while healthy networks sat idle beside it. With no other
* network free the block is taken anyway, so it can never be stranded. */
-function nextWaitingBlock(state: SchedulerState, networkId: string): BlockState | undefined {
+function nextWaitingBlock(state: SchedulerState, networkId: string): HttpBlockState | undefined {
// A pending stream is one waiting for work (see ChunkStatus).
const otherNetworkFree = state.streams.some(
(stream) => stream.interfaceId !== networkId && stream.status === 'pending'
@@ -80,14 +80,14 @@ function nextHedgeTarget(
who: Requester,
now: number,
policy: SchedulerPolicy
-): BlockState | undefined {
+): HttpBlockState | undefined {
// Only when everything left is already being fetched.
if (state.blocks.some((block) => block.status === 'pending')) return undefined
const speedOf = (streamId: number): number =>
state.streams.find((stream) => stream.id === streamId)?.speedBytesPerSec ?? 0
- let target: BlockState | undefined
+ let target: HttpBlockState | undefined
let latest = 0
for (const [index, attempts] of state.attempts) {
const block = state.blocks[index]
diff --git a/src/main/download/torrent/engine.ts b/src/main/download/torrent/engine.ts
new file mode 100644
index 0000000..4ed2e87
--- /dev/null
+++ b/src/main/download/torrent/engine.ts
@@ -0,0 +1,77 @@
+import { join } from 'node:path'
+import type WebTorrent from 'webtorrent'
+import type { ClientOptions, Store, StoreOptions } from 'webtorrent'
+import { testKnobs } from '../../testKnobs'
+
+// The only file that loads webtorrent. It's ESM-only and main is bundled as CommonJS, so it comes
+// in through import(), once, and only when a torrent is first looked at.
+let loaded: Promise<typeof WebTorrent> | null = null
+
+function loadWebTorrent(): Promise<typeof WebTorrent> {
+ loaded ??= import('webtorrent').then((module) => module.default)
+ return loaded
+}
+
+let peerIdParser: Promise<(peerId: string) => string | null> | null = null
+
+/** Names the client a peer runs from its peer id ("qBittorrent 4.6.2"), or null when unknown. */
+export function loadClientNamer(): Promise<(peerId: string) => string | null> {
+ peerIdParser ??= import('bittorrent-peerid').then(({ default: peerid }) => (peerId) => {
+ try {
+ const { client, version } = peerid(peerId)
+ return client === 'unknown' ? null : [client, version].filter(Boolean).join(' ')
+ } catch {
+ return null
+ }
+ })
+ return peerIdParser
+}
+
+/**
+ * webtorrent's own file store, writing the torrent's top entry (its folder, or its one file) under
+ * `name` rather than the torrent's: a download claims a free name, "Name (1)" when the torrent's
+ * is taken. `onWritten` hears each file a piece landed in, once it's written.
+ */
+export async function storeNamed(name: string, onWritten: (path: string) => void): Promise<Store> {
+ const { default: FsChunkStore } = await import('fs-chunk-store')
+ return class extends FsChunkStore {
+ constructor(chunkLength: number, options: StoreOptions) {
+ super(chunkLength, {
+ ...options,
+ files: options.files.map((file) => ({
+ path: join(name, ...file.path.split(/[\\/]/).slice(1)),
+ length: file.length,
+ offset: file.offset
+ }))
+ })
+ }
+
+ put(index: number, buf: Uint8Array, cb?: (error?: Error | null) => void): void {
+ super.put(index, buf, (error) => {
+ if (!error) for (const target of this.chunkMap[index] ?? []) onWritten(target.file.path)
+ cb?.(error)
+ })
+ }
+ }
+}
+
+/**
+ * A webtorrent client set up for Plexo:
+ * - uTP is off: its UDP sockets can't be pinned to a network the way `connect` pins TCP ones.
+ * - Web seeds are off: webtorrent fetches them over HTTP itself, again past `connect`.
+ * - No port mapping (UPnP, NAT-PMP) and no local peer discovery: nothing beyond the peers.
+ */
+export async function createClient(
+ options: Pick<ClientOptions, 'connect' | 'maxConns'> = {}
+): Promise<WebTorrent> {
+ const Client = await loadWebTorrent()
+ return new Client({
+ utp: false,
+ webSeeds: false,
+ natUpnp: false,
+ natPmp: false,
+ lsd: false,
+ dht: testKnobs.torrentDht,
+ ...options
+ })
+}
diff --git a/src/main/download/torrent/files.ts b/src/main/download/torrent/files.ts
new file mode 100644
index 0000000..ba37d59
--- /dev/null
+++ b/src/main/download/torrent/files.ts
@@ -0,0 +1,66 @@
+// Choosing which of a torrent's files to download. Pure.
+
+/**
+ * The files to download, from what the window asked for: null for all of them. Indexes that don't
+ * name a file, or none at all, are refused.
+ */
+export function chosenFiles(
+ requested: readonly number[] | undefined,
+ count: number
+): Set<number> | null {
+ if (requested === undefined) return null
+ const chosen = new Set(requested)
+ if ([...chosen].some((index) => !Number.isInteger(index) || index < 0 || index >= count)) {
+ throw new Error('A file chosen for this torrent isn’t in it')
+ }
+ if (chosen.size === 0) throw new Error('Choose at least one file to download')
+ return chosen.size === count ? null : chosen
+}
+
+/** The first and last piece each file has bytes in; null for an empty file, which has none. */
+function fileSpans(
+ files: readonly { length: number }[],
+ pieceLength: number
+): ([number, number] | null)[] {
+ let offset = 0
+ return files.map((file) => {
+ const span: [number, number] | null =
+ file.length > 0
+ ? [Math.floor(offset / pieceLength), Math.floor((offset + file.length - 1) / pieceLength)]
+ : null
+ offset += file.length
+ return span
+ })
+}
+
+/**
+ * Which pieces the chosen files need: a piece is needed when any byte of it belongs to one. The
+ * pieces at a chosen file's edges hold bytes of its neighbours too; those are fetched with them
+ * (a piece is only ever verified whole), then removed when the download is published.
+ */
+export function wantedPieces(
+ files: readonly { length: number }[],
+ pieceLength: number,
+ chosen: ReadonlySet<number>
+): boolean[] {
+ const total = files.reduce((sum, file) => sum + file.length, 0)
+ const wanted = new Array<boolean>(Math.ceil(total / pieceLength)).fill(false)
+ fileSpans(files, pieceLength).forEach((span, index) => {
+ if (!span || !chosen.has(index)) return
+ for (let piece = span[0]; piece <= span[1]; piece++) wanted[piece] = true
+ })
+ return wanted
+}
+
+/** The files every piece of which is in: downloaded, whatever is chosen. An empty file is. */
+export function finishedFiles(
+ files: readonly { length: number }[],
+ pieceLength: number,
+ completed: readonly boolean[]
+): Set<number> {
+ const finished = new Set<number>()
+ fileSpans(files, pieceLength).forEach((span, index) => {
+ if (!span || completed.slice(span[0], span[1] + 1).every(Boolean)) finished.add(index)
+ })
+ return finished
+}
diff --git a/src/main/download/torrent/metadata.ts b/src/main/download/torrent/metadata.ts
new file mode 100644
index 0000000..5bf3a0d
--- /dev/null
+++ b/src/main/download/torrent/metadata.ts
@@ -0,0 +1,124 @@
+import { open } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import type WebTorrent from 'webtorrent'
+import type { ProbeResult } from '../../../shared/types'
+import { testKnobs } from '../../testKnobs'
+import { createClient } from './engine'
+import { safeTorrentPaths } from './paths'
+
+/** A .torrent file is metadata only; a link answering with more than this isn't one. */
+const MAX_TORRENT_FILE_BYTES = 10 * 1024 * 1024
+const TOO_LARGE = 'Plexo supports .torrent files up to 10 MB.'
+const V2_ONLY = 'This torrent uses BitTorrent v2 only, which Plexo doesn’t support yet'
+const NO_PEERS = 'No peers responded to this magnet link. Try again later or open a .torrent file.'
+
+/** The .torrent of each torrent probed lately, by info hash: what a download of it starts from,
+ * so the window never has to hold or send it. */
+const recent = new Map<string, Uint8Array>()
+const RECENT_LIMIT = 8
+
+export function probedTorrentFile(infoHash: string): Uint8Array | undefined {
+ return recent.get(infoHash)
+}
+
+function remember(infoHash: string, torrentFile: Uint8Array): void {
+ recent.delete(infoHash)
+ recent.set(infoHash, torrentFile)
+ if (recent.size > RECENT_LIMIT) recent.delete(recent.keys().next().value!)
+}
+
+/** What a .torrent holds, as a probe result — once its paths are known to be safe to write. */
+export async function describeTorrent(torrentFile: Uint8Array, link: string): Promise<ProbeResult> {
+ const { default: parseTorrent } = await import('parse-torrent')
+ const parsed = await parseTorrent(torrentFile).catch((error: unknown) => {
+ // parse-torrent's check for the v1 piece hashes, which a v2-only torrent doesn't have.
+ if (error instanceof Error && error.message.endsWith('info.pieces')) throw new Error(V2_ONLY)
+ throw new Error('This isn’t a torrent Plexo can read')
+ })
+ const files = safeTorrentPaths(parsed.files ?? [])
+ remember(parsed.infoHash, torrentFile)
+ return {
+ kind: 'torrent',
+ requestedUrl: link,
+ finalUrl: link,
+ supportsRanges: true,
+ totalBytes: parsed.length ?? 0,
+ suggestedFileName: parsed.name ?? parsed.infoHash,
+ contentType: 'application/x-bittorrent',
+ etag: null,
+ lastModified: null,
+ torrent: { infoHash: parsed.infoHash, pieceLength: parsed.pieceLength ?? 0, files }
+ }
+}
+
+/** A .torrent file on this computer. */
+export async function readTorrentFile(path: string): Promise<Uint8Array> {
+ const handle = await open(path, 'r')
+ try {
+ if ((await handle.stat()).size > MAX_TORRENT_FILE_BYTES) throw new Error(TOO_LARGE)
+ return await handle.readFile()
+ } finally {
+ await handle.close()
+ }
+}
+
+/** A .torrent file a link points at. */
+export async function downloadTorrentFile(url: string, timeoutMs: number): Promise<Uint8Array> {
+ const response = await fetch(url, {
+ headers: { 'User-Agent': 'Plexo/1.0' },
+ signal: AbortSignal.timeout(timeoutMs)
+ })
+ if (!response.ok || !response.body) {
+ throw new Error(`Server responded with status ${response.status}`)
+ }
+ const chunks: Uint8Array[] = []
+ let total = 0
+ for await (const chunk of response.body) {
+ total += chunk.length
+ if (total > MAX_TORRENT_FILE_BYTES) throw new Error(TOO_LARGE)
+ chunks.push(chunk)
+ }
+ return Buffer.concat(chunks)
+}
+
+/** Fetches magnet links' metadata from their peers, over the default route: only a download's
+ * own client pins peers to networks. Kept for the app's life, so its DHT stays warm. */
+let probeClient: Promise<WebTorrent> | null = null
+/** The magnet link being looked up. A newer one replaces it: the window only shows the latest. */
+let current: { infoHash: string; metadata: Promise<Uint8Array>; cancel: () => void } | null = null
+
+/** A magnet link's .torrent, from whichever of its peers answers first. */
+export async function fetchMagnetMetadata(magnet: string): Promise<Uint8Array> {
+ const { default: parseTorrent } = await import('parse-torrent')
+ const { infoHash } = await parseTorrent(magnet).catch(() => {
+ throw new Error('This magnet link isn’t valid')
+ })
+ if (current?.infoHash === infoHash) return current.metadata
+ current?.cancel()
+
+ probeClient ??= createClient()
+ const client = await probeClient
+ const lookup = { infoHash } as NonNullable<typeof current>
+ // Set first: a lookup that ends at once must still be able to clear itself.
+ current = lookup
+ lookup.metadata = new Promise<Uint8Array>((resolve, reject) => {
+ // Deselected: only the metadata is wanted, none of the files.
+ const torrent = client.add(magnet, { path: join(tmpdir(), 'plexo-magnet'), deselect: true })
+ let done = false
+ const finish = (error: Error | null, torrentFile?: Uint8Array): void => {
+ if (done) return
+ done = true
+ clearTimeout(timer)
+ if (current === lookup) current = null
+ torrent.destroy({ destroyStore: true })
+ if (error) reject(error)
+ else resolve(torrentFile!)
+ }
+ const timer = setTimeout(() => finish(new Error(NO_PEERS)), testKnobs.magnetTimeoutMs)
+ torrent.once('metadata', () => finish(null, torrent.torrentFile))
+ torrent.once('error', (error: Error) => finish(error))
+ lookup.cancel = () => finish(new Error('Replaced by a newer link'))
+ })
+ return lookup.metadata
+}
diff --git a/src/main/download/torrent/modules.d.ts b/src/main/download/torrent/modules.d.ts
new file mode 100644
index 0000000..27f944a
--- /dev/null
+++ b/src/main/download/torrent/modules.d.ts
@@ -0,0 +1,122 @@
+// webtorrent and parse-torrent ship no types. These cover only what Plexo (and its e2e tests) use.
+
+declare module 'webtorrent' {
+ import type { EventEmitter } from 'node:events'
+ import type { Socket } from 'node:net'
+
+ export interface ClientOptions {
+ dht?: boolean
+ lsd?: boolean
+ utp?: boolean
+ natUpnp?: boolean
+ natPmp?: boolean
+ webSeeds?: boolean
+ tracker?: boolean | object
+ maxConns?: number
+ /** Bytes per second this client uploads at most. */
+ uploadLimit?: number
+ /** Added by Plexo's patch (patches/webtorrent+3.0.21.patch): opens every outgoing TCP peer
+ * connection. */
+ connect?: (options: { host: string; port: number }) => Socket
+ }
+
+ /** What webtorrent hands a store: the torrent's files, paths relative to `path`. */
+ export interface StoreOptions {
+ path: string
+ files: { path: string; length: number; offset: number }[]
+ [option: string]: unknown
+ }
+
+ export type Store = new (chunkLength: number, options: StoreOptions) => object
+
+ export interface AddOptions {
+ path?: string
+ /** Builds the torrent's storage; webtorrent's own is fs-chunk-store. */
+ store?: Store
+ deselect?: boolean
+ announce?: string[]
+ skipVerify?: boolean
+ bitfield?: Uint8Array
+ }
+
+ export interface SeedOptions {
+ name?: string
+ pieceLength?: number
+ announce?: string[]
+ /** Where it keeps the seeded files; webtorrent's default is a shared /tmp/webtorrent. */
+ path?: string
+ }
+
+ /** One peer connection (bittorrent-protocol). Emits 'piece' (index, offset, buffer) for each
+ * block it receives, and 'close'. */
+ export interface Wire extends EventEmitter {
+ destroy(): void
+ unchoke(): void
+ /** The remote peer's id, hex: set once it has shaken hands. */
+ peerId: string | null
+ }
+
+ export interface Torrent extends EventEmitter {
+ infoHash: string
+ magnetURI: string
+ torrentFile: Uint8Array
+ name: string
+ length: number
+ /** Bytes sent to peers. */
+ uploaded: number
+ /** In the torrent's order; a deselected file's pieces aren't fetched for it. */
+ files: { select(): void; deselect(): void }[]
+ pieces: unknown[]
+ /** Takes pieces `start` to `end` out of every selection, trimming or splitting those that
+ * reach further. */
+ deselect(start: number, end: number): void
+ /** Which pieces are verified and on disk. */
+ bitfield: { get(index: number): boolean }
+ destroy(options?: { destroyStore?: boolean }, callback?: (error?: Error) => void): void
+ addPeer(address: string): boolean
+ }
+
+ export default class WebTorrent extends EventEmitter {
+ constructor(options?: ClientOptions)
+ maxConns: number
+ destroyed: boolean
+ torrents: Torrent[]
+ add(torrentId: string | Uint8Array, options?: AddOptions): Torrent
+ seed(
+ input: Buffer | string | (Buffer | string)[],
+ options: SeedOptions,
+ onSeed: (torrent: Torrent) => void
+ ): Torrent
+ address(): { address: string; family: string; port: number }
+ destroy(callback?: (error?: Error) => void): void
+ /** Private: its listening server, where peers dial in. */
+ _connPool: { tcpServer: import('node:net').Server } | null
+ }
+}
+
+declare module 'fs-chunk-store' {
+ import type { StoreOptions } from 'webtorrent'
+ /** webtorrent's default store: a torrent's files on disk, at `path` + each file's path. */
+ export default class FsChunkStore {
+ constructor(chunkLength: number, options: StoreOptions)
+ /** By piece: the stretches of the torrent's files it covers. */
+ chunkMap: { file: { path: string } }[][]
+ put(index: number, buf: Uint8Array, cb?: (error?: Error | null) => void): void
+ }
+}
+
+declare module 'bittorrent-peerid' {
+ /** The client a peer id names, e.g. { client: 'qBittorrent', version: '4.6.2' }. */
+ export default function peerid(peerId: string | Buffer): { client: string; version?: string }
+}
+
+declare module 'parse-torrent' {
+ export interface ParsedTorrent {
+ infoHash: string
+ name?: string
+ length?: number
+ pieceLength?: number
+ files?: { path: string; name: string; length: number; offset: number }[]
+ }
+ export default function parseTorrent(torrentId: string | Uint8Array): Promise<ParsedTorrent>
+}
diff --git a/src/main/download/torrent/ownedFiles.ts b/src/main/download/torrent/ownedFiles.ts
new file mode 100644
index 0000000..206ee5c
--- /dev/null
+++ b/src/main/download/torrent/ownedFiles.ts
@@ -0,0 +1,48 @@
+import { lstat } from 'node:fs/promises'
+import { dirname, isAbsolute, join, relative, sep } from 'node:path'
+
+/** Validate all owned paths before removing any. User-added files and symlink targets are never followed. */
+export async function ownedTorrentFiles(
+ root: string,
+ files: readonly string[]
+): Promise<{
+ targets: string[]
+ folders: string[]
+}> {
+ const targets: string[] = []
+ const folders = new Set<string>([root])
+ const inspect = async (path: string): Promise<Awaited<ReturnType<typeof lstat>> | null> =>
+ lstat(path).catch((error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT') return null
+ throw error
+ })
+ for (const file of files) {
+ const target = join(root, file)
+ const within = relative(root, target)
+ if (
+ !within ||
+ isAbsolute(file) ||
+ isAbsolute(within) ||
+ within === '..' ||
+ within.startsWith(`..${sep}`)
+ ) {
+ throw new Error('Plexo can’t safely remove this torrent’s files.')
+ }
+ let parent = dirname(target)
+ while (true) {
+ const info = await inspect(parent)
+ if (info?.isSymbolicLink())
+ throw new Error('A torrent folder is now a link. Manage its files in your file browser.')
+ folders.add(parent)
+ if (parent === root) break
+ parent = dirname(parent)
+ }
+ const info = await inspect(target)
+ if (info) {
+ if (info.isDirectory())
+ throw new Error('A torrent file is now a folder. Manage it in your file browser.')
+ targets.push(target)
+ }
+ }
+ return { targets, folders: [...folders].sort((a, b) => b.length - a.length) }
+}
diff --git a/src/main/download/torrent/paths.ts b/src/main/download/torrent/paths.ts
new file mode 100644
index 0000000..2f47fbc
--- /dev/null
+++ b/src/main/download/torrent/paths.ts
@@ -0,0 +1,67 @@
+import { posix, win32 } from 'node:path'
+
+/** What fs-chunk-store (webtorrent's storage) strips from each file's own name before writing it:
+ * filename-reserved-regex 3.0.0. Its folders are written as they are. */
+// eslint-disable-next-line no-control-regex -- control characters are exactly what it strips
+export const STRIPPED_FROM_NAMES = /[<>:"/\\|?*\u0000-\u001F]/g
+// Unlike filename-reserved-regex's own check, this also catches the name with an extension:
+// Windows reserves CON.txt as well as CON.
+const WINDOWS_RESERVED = /^(con|prn|aux|nul|com\d|lpt\d)(\..*)?$/i
+// eslint-disable-next-line no-control-regex -- Windows can't save control characters either
+const WINDOWS_INVALID = /[<>:"|?*\u0000-\u001F]|[. ]$/
+const MAX_NAME_BYTES = 255
+
+export class UnsafeTorrentError extends Error {}
+
+/**
+ * Where webtorrent will write each of a torrent's files, relative to the folder it's handed —
+ * worked out exactly as fs-chunk-store does it — or an UnsafeTorrentError when any file could
+ * land outside that folder, collide with another, or can't be written on this system. A
+ * torrent's paths come from whoever made it: every torrent is checked before anything is written.
+ */
+export function safeTorrentPaths(
+ files: readonly { path: string; length: number }[],
+ platform: NodeJS.Platform = process.platform
+): { path: string; length: number }[] {
+ if (files.length === 0) throw new UnsafeTorrentError('This torrent has no files')
+ const path = platform === 'win32' ? win32 : posix
+ const base = path.resolve(path.sep, 'staging')
+ const checked = files.map((file) => {
+ const name = path.basename(file.path).replace(STRIPPED_FROM_NAMES, '')
+ // fs-chunk-store: resolve(join(folder, dirname(path))), then the cleaned name.
+ const target = path.join(path.resolve(path.join(base, path.dirname(file.path))), name)
+ const relative = path.relative(base, target)
+ const climbsOut = relative === '..' || relative.startsWith(`..${path.sep}`)
+ if (!name || !relative || climbsOut || path.isAbsolute(relative)) {
+ throw new UnsafeTorrentError(`This torrent has a file Plexo can't save safely: ${file.path}`)
+ }
+ for (const segment of relative.split(path.sep)) {
+ if (Buffer.byteLength(segment) > MAX_NAME_BYTES) {
+ throw new UnsafeTorrentError(`A name in this torrent is too long to save: ${segment}`)
+ }
+ if (
+ platform === 'win32' &&
+ (WINDOWS_RESERVED.test(segment) || WINDOWS_INVALID.test(segment))
+ ) {
+ throw new UnsafeTorrentError(`Windows can't save a file named ${segment}`)
+ }
+ }
+ return { path: relative, length: file.length }
+ })
+
+ // Compared without case: macOS and Windows treat "A.txt" and "a.txt" as one file. A file can't
+ // also be a folder another file sits in.
+ const taken = new Set(checked.map((file) => file.path.toLowerCase()))
+ if (taken.size !== checked.length) {
+ throw new UnsafeTorrentError('Two files in this torrent would be saved as the same file')
+ }
+ for (const file of checked) {
+ const segments = file.path.toLowerCase().split(path.sep)
+ for (let end = 1; end < segments.length; end++) {
+ if (taken.has(segments.slice(0, end).join(path.sep))) {
+ throw new UnsafeTorrentError('A file in this torrent has the same name as a folder in it')
+ }
+ }
+ }
+ return checked
+}
diff --git a/src/main/download/torrent/peers.ts b/src/main/download/torrent/peers.ts
new file mode 100644
index 0000000..4f49b6a
--- /dev/null
+++ b/src/main/download/torrent/peers.ts
@@ -0,0 +1,57 @@
+// How a torrent's peers are spread over the networks, and how their bytes are credited back.
+// Pure: torrentTransfer.ts feeds these what webtorrent reports.
+
+/** A network that can carry a connection to the peer at hand (one of its addresses has the peer's
+ * IP family), with its peers: connected, and being dialled. */
+export interface NetworkLoad {
+ id: string
+ peers: number
+}
+
+/**
+ * The network a new peer connects through: the one carrying the fewest peers, the first on a tie.
+ * A faster network then gets more of the torrent on its own, because each of its peers keeps a
+ * full queue of requests answered sooner.
+ */
+// ponytail: fewest-peers-first; weight by measured speed per network if one is seen starving.
+export function pickNetwork(networks: readonly NetworkLoad[]): string | null {
+ let best: NetworkLoad | null = null
+ for (const network of networks) if (!best || network.peers < best.peers) best = network
+ return best?.id ?? null
+}
+
+/**
+ * Splits a verified piece's length between the networks that delivered it, in proportion to what
+ * each received for it (a piece can arrive partly over each). Whole bytes that add up to `length`
+ * exactly; what rounding leaves goes to the largest share. Bytes nobody is known to have
+ * delivered — a piece found already on disk — go to `fallback`.
+ */
+export function creditPiece(
+ received: Readonly<Record<string, number>>,
+ length: number,
+ fallback: string
+): Record<string, number> {
+ const entries = Object.entries(received).filter(([, bytes]) => bytes > 0)
+ const total = entries.reduce((sum, [, bytes]) => sum + bytes, 0)
+ if (total === 0) return { [fallback]: length }
+ const shares: Record<string, number> = {}
+ let given = 0
+ let largest = entries[0][0]
+ for (const [id, bytes] of entries) {
+ shares[id] = Math.floor((length * bytes) / total)
+ given += shares[id]
+ if (bytes > received[largest]) largest = id
+ }
+ shares[largest] += length - given
+ return shares
+}
+
+/** The pieces in `done`, as webtorrent takes a starting bitfield: one bit each, first piece in
+ * the first byte's highest bit. */
+export function bitfieldOf(done: readonly boolean[]): Uint8Array {
+ const bits = new Uint8Array(Math.ceil(done.length / 8))
+ done.forEach((isDone, index) => {
+ if (isDone) bits[index >> 3] |= 0x80 >> (index & 7)
+ })
+ return bits
+}
diff --git a/src/main/download/torrent/torrentDestination.ts b/src/main/download/torrent/torrentDestination.ts
new file mode 100644
index 0000000..bb61260
--- /dev/null
+++ b/src/main/download/torrent/torrentDestination.ts
@@ -0,0 +1,123 @@
+import { open, readdir, rm, rmdir, stat } from 'node:fs/promises'
+import { join, sep } from 'node:path'
+import { DownloadFile } from '../downloadFile'
+import { ownedTorrentFiles } from './ownedFiles'
+import { claimDestinationPath } from '../paths'
+
+/**
+ * Where a torrent downloads: in place, under its own name, as torrent clients do. `path` is its
+ * folder of files (or its one file) at the destination from the start; publishing leaves it
+ * there, only dropping the files not chosen.
+ */
+export class TorrentDestination extends DownloadFile {
+ /** `path` as claimed (see create). `unwanted`: the torrent's files not chosen for download, as
+ * the torrent names them, its own folder first; changed when the choice is. */
+ constructor(
+ path: string,
+ private readonly totalBytes: number,
+ public unwanted: readonly string[] = [],
+ private readonly owned: readonly string[] = []
+ ) {
+ super(path)
+ }
+
+ /** Claims `name` in `directory`, or the first free `name (N)`, for a torrent's folder or file. */
+ static async create(
+ directory: string,
+ name: string,
+ folder: boolean,
+ totalBytes: number,
+ unwanted: readonly string[] = [],
+ owned: readonly string[] = []
+ ): Promise<TorrentDestination> {
+ const path = await claimDestinationPath(directory, name, folder)
+ return new TorrentDestination(path, totalBytes, unwanted, owned)
+ }
+
+ /** Already in place: it drops the files not chosen, and stays where it is. */
+ async publish(
+ _destinationPath: string,
+ _expectedBytes: number,
+ beforeAttempt: (candidate: string) => Promise<void>
+ ): Promise<string> {
+ await this.removeUnwanted()
+ await this.sync()
+ await beforeAttempt(this.path)
+ return this.path
+ }
+
+ /** It is what was published: nothing is left over. */
+ discardLeftover(): Promise<void> {
+ return Promise.resolve()
+ }
+
+ /** The files not chosen — the pieces at a chosen file's edges wrote part of them — and any
+ * folder that leaves empty. Only what was chosen stays. */
+ private async removeUnwanted(): Promise<void> {
+ if (this.unwanted.length === 0) return
+ // Under this download's name for the torrent's folder, which may be "Name (1)".
+ const inPlace = (path: string): string => join(this.path, ...path.split(sep).slice(1))
+ await Promise.all(this.unwanted.map((path) => rm(inPlace(path), { force: true })))
+ const folders = (await readdir(this.path, { recursive: true, withFileTypes: true }))
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => join(entry.parentPath, entry.name))
+ // Deepest first, so a folder emptied by removing its subfolders goes too.
+ .sort((a, b) => b.length - a.length)
+ for (const folder of folders) await rmdir(folder).catch(() => {}) // only empty ones go
+ }
+
+ /** Its files are sparse: once it's there, every byte of the torrent has its place. Throws, like
+ * DownloadFile's, when it's gone. */
+ async size(): Promise<number> {
+ await stat(this.path)
+ return this.totalBytes
+ }
+
+ /** The files written to since the last sync (the store adds them): only they need one. A
+ * torrent of thousands of files has a few in progress at a time. */
+ readonly written = new Set<string>()
+
+ async sync(): Promise<void> {
+ if (!(await stat(this.path)).isDirectory()) return super.sync()
+ const paths = [...this.written]
+ this.written.clear()
+ try {
+ for (const path of paths) {
+ const handle = await open(path, 'r+').catch((error: NodeJS.ErrnoException) => {
+ // A file not chosen, removed before publishing.
+ if (error.code === 'ENOENT') return null
+ throw error
+ })
+ if (!handle) continue
+ try {
+ await handle.sync()
+ } finally {
+ await handle.close()
+ }
+ }
+ } catch (error) {
+ // Synced at the next checkpoint instead.
+ for (const path of paths) this.written.add(path)
+ throw error
+ }
+ }
+
+ /** Remove owned partial files and empty folders, preserving unrelated files. */
+ async discard(): Promise<void> {
+ const info = await stat(this.path).catch((error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT') return null
+ throw error
+ })
+ if (!info) return
+ if (!info.isDirectory()) {
+ await rm(this.path, { force: true })
+ return
+ }
+ if (!this.owned.length)
+ throw new Error('Plexo can’t identify this torrent’s files for removal.')
+ const files = this.owned.map((path) => path.split(/[\\/]/).slice(1).join(sep))
+ const { targets, folders } = await ownedTorrentFiles(this.path, files)
+ for (const target of targets) await rm(target, { force: true })
+ for (const folder of folders) await rmdir(folder).catch(() => {})
+ }
+}
diff --git a/src/main/download/torrent/torrentTransfer.ts b/src/main/download/torrent/torrentTransfer.ts
new file mode 100644
index 0000000..d5ca66b
--- /dev/null
+++ b/src/main/download/torrent/torrentTransfer.ts
@@ -0,0 +1,434 @@
+import { isIP, Socket } from 'node:net'
+import { basename, dirname } from 'node:path'
+import type WebTorrent from 'webtorrent'
+import type { Store, Torrent, Wire } from 'webtorrent'
+import type { TorrentDownloadNetwork, TorrentPeerState } from '../../../shared/types'
+import { connectRoute } from '../../network/deviceBinding'
+import { routesFor, type NetworkRoute } from '../../network/routes'
+import {
+ recomputeAggregates,
+ type Transfer,
+ type TransferHost,
+ type TorrentTransferTarget
+} from '../transfer'
+import { createClient, loadClientNamer, storeNamed } from './engine'
+import { bitfieldOf, creditPiece, pickNetwork } from './peers'
+
+/** Peers each network in use may have at once (webtorrent's maxConns is this times the networks). */
+const PEERS_PER_NETWORK = 30
+// A network that has dialled this many peers with none answering, for this long, while another
+// network has peers, can't reach the swarm. It keeps one dial going, to see when it can again.
+const UNREACHABLE_AFTER_ATTEMPTS = 5
+const UNREACHABLE_AFTER_MS = 60_000
+
+const message = (error: unknown): string => (error instanceof Error ? error.message : String(error))
+
+/** webtorrent's name for a peer: what it hands the hook as host and port, and the 'wire' event as
+ * an address. */
+const addressOf = (host: string, port: number): string =>
+ isIP(host) === 6 ? `[${host}]:${port}` : `${host}:${port}`
+
+interface Peer {
+ state: TorrentPeerState
+}
+
+/**
+ * Fetches a torrent with webtorrent, every peer pinned to one network. webtorrent finds the peers
+ * and runs the protocol; each time it dials one, its `connect` hook (see engine.ts and
+ * patches/webtorrent+3.0.21.patch) asks this transfer which network to use, and the socket comes
+ * from connectRoute, as HTTP's do. Peers expose connection telemetry only; a piece is credited to
+ * the networks that delivered it once webtorrent has verified it and written it to disk.
+ *
+ * One webtorrent client per run: a pause destroys it, files kept, and a resume starts a new one
+ * from the pieces already done.
+ */
+export class TorrentTransfer implements Transfer {
+ private client: WebTorrent | null = null
+ /** Destroys this run's client; safe to repeat. */
+ private closeClient: (() => void) | null = null
+ /** Settles once this run's client is gone. Null between runs. */
+ private ended: Promise<void> | null = null
+ private peers = new Map<Wire, Peer>()
+ private nextPeerId = 0
+ /** webtorrent's file store, writing under the download's name; loaded with the first run. */
+ private store: Store | null = null
+ /** The run's torrent, once ready for its files to be chosen. */
+ private torrent: Torrent | null = null
+ /** Names a peer's client from its peer id; loaded with the first run. */
+ private nameClient: ((peerId: string) => string | null) | null = null
+ /** The network each peer is on, by webtorrent's address for it: dialled through, or dialled in
+ * on. */
+ private chosen = new Map<string, string>()
+ /** Dials in flight, by network. */
+ private dialling = new Map<string, number>()
+ /** By network: dials since a peer last answered, and when one last did. */
+ private reach = new Map<string, { dials: number; answeredAt: number }>()
+ /** Bytes of each piece not verified yet, by network. */
+ private unverified = new Map<number, Record<string, number>>()
+
+ constructor(
+ private readonly runtime: TorrentTransferTarget,
+ private readonly host: TransferHost,
+ private readonly torrentFile: Uint8Array,
+ /** The download, in place: the torrent's folder or file (TorrentDestination.path). */
+ private readonly destination: string
+ ) {}
+
+ reconcile(): void {
+ const usable = this.usable()
+ if (!this.ended) this.ended = this.run()
+ if (this.client) this.client.maxConns = PEERS_PER_NETWORK * usable.length
+ // A network switched off, or gone, takes its peers with it.
+ for (const [wire, peer] of this.peers) {
+ if (!usable.some((network) => network.id === peer.state.interfaceId)) wire.destroy()
+ }
+ }
+
+ tick(now: number): void {
+ const withPeers = new Set([...this.peers.values()].map((peer) => peer.state.interfaceId))
+ for (const network of this.usable()) {
+ const reach = this.reachOf(network.id, now)
+ if (
+ network.status === 'on' &&
+ reach.dials >= UNREACHABLE_AFTER_ATTEMPTS &&
+ now - reach.answeredAt >= UNREACHABLE_AFTER_MS &&
+ !withPeers.has(network.id) &&
+ withPeers.size > 0
+ ) {
+ network.status = 'unreachable'
+ this.host.scheduleUpdate()
+ }
+ }
+ for (const peer of this.peers.values()) {
+ const status = peer.state.speedBytesPerSec > 0 ? 'receiving' : 'connected'
+ if (peer.state.status !== status) {
+ peer.state.status = status
+ this.host.scheduleUpdate()
+ }
+ }
+ this.host.reconcile()
+ }
+
+ running(): Iterable<Promise<void>> {
+ return this.ended ? [this.ended] : []
+ }
+
+ abort(): void {
+ this.closeClient?.()
+ }
+
+ reset(): void {
+ this.chosen.clear()
+ this.dialling.clear()
+ this.reach.clear()
+ // webtorrent drops what it had of unfinished pieces with its client.
+ this.unverified.clear()
+ for (const piece of this.runtime.pieces) {
+ piece.provisionalBytes = 0
+ if (piece.status === 'downloading') piece.status = 'pending'
+ }
+ }
+
+ wake(_pick: (networkId: string) => boolean, reconnect: (networkId: string) => boolean): void {
+ // Peers on a network whose address changed are on dead sockets; webtorrent dials new ones.
+ for (const [wire, peer] of this.peers) if (reconnect(peer.state.interfaceId)) wire.destroy()
+ }
+
+ systemResumed(now: number): void {
+ // Time asleep says nothing about whether a network can reach the swarm.
+ for (const reach of this.reach.values()) reach.answeredAt = now
+ }
+
+ /** One run: a client added to the torrent, until the run stops (pause, cancel, error, done).
+ * Settles once the client is destroyed and its files closed. */
+ private async run(): Promise<void> {
+ const stop = this.runtime.stop.signal
+ try {
+ this.nameClient ??= await loadClientNamer()
+ this.store ??= await storeNamed(basename(this.destination), (path) =>
+ this.runtime.file.written.add(path)
+ )
+ const client = await createClient({
+ connect: (options) => this.connect(options),
+ maxConns: PEERS_PER_NETWORK * Math.max(1, this.usable().length)
+ })
+ await new Promise<void>((resolve) => {
+ let closing = false
+ const close = (): void => {
+ if (closing) return
+ closing = true
+ this.client = null
+ this.closeClient = null
+ // After a fatal error webtorrent has already torn itself down.
+ if (client.destroyed) resolve()
+ else client.destroy(() => resolve())
+ }
+ if (stop.aborted) return close()
+ this.client = client
+ this.closeClient = close
+ stop.addEventListener('abort', close, { once: true })
+ client.on('error', (error: unknown) => {
+ this.host.failDownload(message(error))
+ close()
+ })
+ client._connPool?.tcpServer.on('connection', (socket: Socket) => this.onIncoming(socket))
+ this.add(client)
+ })
+ } catch (error) {
+ this.host.failDownload(message(error))
+ } finally {
+ for (const peer of this.peers.values()) this.removePeer(peer)
+ this.peers.clear()
+ this.torrent = null
+ this.ended = null
+ }
+ }
+
+ /** The choice of files changed (requestPayload.selectedFiles): the engine fetches for the new
+ * one now. Not running, the next run starts with it. */
+ filesChosen(): void {
+ if (this.torrent) this.selectFiles(this.torrent)
+ }
+
+ /** Asks the engine for the chosen files' pieces only, all of them with no choice made. What it
+ * fetched before stays: a deselected piece just isn't asked for. */
+ private selectFiles(torrent: Torrent): void {
+ const chosen = this.runtime.requestPayload.selectedFiles
+ if (torrent.pieces.length > 0) torrent.deselect(0, torrent.pieces.length - 1)
+ torrent.files.forEach((file, index) => {
+ if (!chosen || chosen.includes(index)) file.select()
+ })
+ }
+
+ /** A peer took `bytes` of a piece from this download, over `network`. */
+ private onUpload(network: TorrentDownloadNetwork, peer: Peer, bytes: number): void {
+ const { state } = this.runtime
+ network.bytesUploaded += bytes
+ state.bytesUploaded += bytes
+ peer.state.bytesUploaded += bytes
+ // Read as speeds on the download's clock (see updateSpeeds).
+ this.runtime.uploadMeters.add(peer.state.id, network.id, bytes)
+ this.host.scheduleUpdate()
+ }
+
+ private add(client: WebTorrent): void {
+ const torrent = client.add(this.torrentFile, {
+ path: dirname(this.destination),
+ store: this.store!,
+ // Trusted as done, bar a hash check of a piece or two per file (more if one fails).
+ bitfield: bitfieldOf(this.runtime.pieces.map((block) => block.status === 'completed')),
+ // Nothing until webtorrent is ready to be told which files (below), as on a change.
+ deselect: true
+ })
+ torrent.on('wire', (wire: Wire, address: string) => this.onWire(wire, address))
+ torrent.on('verified', (index: number) => this.onVerified(index))
+ torrent.once('ready', () => {
+ this.torrent = torrent
+ this.selectFiles(torrent)
+ this.followEngine(torrent)
+ })
+ torrent.on('error', (error: unknown) => this.host.failDownload(message(error)))
+ }
+
+ /** The networks peers may use now. One that can't reach the swarm stays, for its one dial. */
+ private usable(): TorrentDownloadNetwork[] {
+ return this.runtime.state.networks.filter(
+ (network) => network.status === 'on' || network.status === 'unreachable'
+ )
+ }
+
+ private reachOf(networkId: string, now = Date.now()): { dials: number; answeredAt: number } {
+ let reach = this.reach.get(networkId)
+ if (!reach) this.reach.set(networkId, (reach = { dials: 0, answeredAt: now }))
+ return reach
+ }
+
+ /** webtorrent's `connect` hook: every outgoing peer comes through here. */
+ private connect({ host: address, port }: { host: string; port: number }): Socket {
+ // A peer named by hostname (a magnet's x.pe can be) has no family: no network takes it.
+ const family = isIP(address) as 0 | 4 | 6
+ const peersOn = (id: string): number =>
+ (this.dialling.get(id) ?? 0) +
+ [...this.peers.values()].filter((peer) => peer.state.interfaceId === id).length
+ const routes = new Map<string, NetworkRoute>()
+ for (const network of this.usable()) {
+ const iface = this.host.networks.find(network.id)
+ const route = family ? iface && routesFor(iface, [{ address, family }])[0] : undefined
+ if (!route) continue
+ // An unreachable network gets one dial at a time, to find out when it's back.
+ if (network.status === 'unreachable' && peersOn(network.id) > 0) continue
+ routes.set(network.id, route)
+ }
+ const networkId = pickNetwork([...routes.keys()].map((id) => ({ id, peers: peersOn(id) })))
+ if (!networkId) {
+ const socket = new Socket()
+ process.nextTick(() => socket.destroy(new Error('No network in use can reach this peer')))
+ return socket
+ }
+
+ this.chosen.set(addressOf(address, port), networkId)
+ this.dialling.set(networkId, (this.dialling.get(networkId) ?? 0) + 1)
+ this.reachOf(networkId).dials += 1
+ const socket = connectRoute(routes.get(networkId)!, port)
+ let settled = false
+ const settle = (): void => {
+ if (settled) return
+ settled = true
+ this.dialling.set(networkId, (this.dialling.get(networkId) ?? 1) - 1)
+ }
+ socket.once('connect', settle)
+ socket.once('close', settle)
+ this.limit(socket, networkId)
+ return socket
+ }
+
+ /** Puts what a peer sends through the speed and data limits (see Limits). push() is where
+ * the socket's bytes come in, whoever is reading them: a 'data' listener here would set it
+ * flowing before webtorrent is ready to read. */
+ private limit(socket: Socket, networkId: string): void {
+ const push = socket.push.bind(socket)
+ socket.push = (chunk: Buffer | null, encoding?: BufferEncoding): boolean => {
+ const wait = chunk ? this.host.limits.take(networkId, chunk.length) : 0
+ if (wait > 0) {
+ // ponytail: webtorrent's pipe resumes the socket when its wire drains, which can cut a
+ // wait short; the debt it leaves only lengthens the next one, so the rate still holds.
+ socket.pause()
+ setTimeout(() => socket.resume(), wait)
+ }
+ return push(chunk, encoding)
+ }
+ }
+
+ /** A peer dialling in: it's on the network whose address it reached. One that reached no
+ * network in use isn't put on any, and onWire drops it. */
+ private onIncoming(socket: Socket): void {
+ // A dual-stack server sees IPv4 as IPv4-mapped IPv6.
+ const local = socket.localAddress?.replace(/^::ffff:/, '')
+ const network = this.usable().find((entry) =>
+ this.host.networks.find(entry.id)?.addresses.some((address) => address.address === local)
+ )
+ // As webtorrent names an incoming peer: the address as the socket gives it, no brackets.
+ if (!network) return
+ this.chosen.set(`${socket.remoteAddress}:${socket.remotePort}`, network.id)
+ this.limit(socket, network.id)
+ }
+
+ private onWire(wire: Wire, address: string): void {
+ const networkId = this.chosen.get(address)
+ const network = this.runtime.state.networks.find((entry) => entry.id === networkId)
+ if (!network) {
+ wire.destroy()
+ return
+ }
+ // Every network uploads, whatever its kind: each has an address of its own, and webtorrent's
+ // tit-for-tat gives a network's peers back what they send it.
+
+ const reach = this.reachOf(network.id)
+ reach.dials = 0
+ reach.answeredAt = Date.now()
+ if (network.status === 'unreachable') network.status = 'on'
+
+ const peerState: TorrentPeerState = {
+ id: this.nextPeerId++,
+ interfaceId: network.id,
+ status: 'connected',
+ bytesDownloaded: 0,
+ speedBytesPerSec: 0,
+ bytesUploaded: 0,
+ uploadSpeedBytesPerSec: 0,
+ client: wire.peerId ? (this.nameClient?.(wire.peerId) ?? null) : null
+ }
+ const peer: Peer = { state: peerState }
+ this.peers.set(wire, peer)
+ const { state } = this.runtime
+ state.peers.push(peerState)
+ state.peakPeers = Math.max(state.peakPeers, state.peers.length)
+
+ wire.on('piece', (index: number, _offset: number, buffer: Uint8Array) => {
+ peerState.bytesDownloaded += buffer.length
+ peerState.status = 'receiving'
+ const pending = this.unverified.get(index) ?? {}
+ pending[network.id] = (pending[network.id] ?? 0) + buffer.length
+ this.unverified.set(index, pending)
+ const piece = this.runtime.pieces[index]
+ if (piece) {
+ // In flight now; it counts once verified (onVerified).
+ if (piece.status === 'pending') {
+ piece.status = 'downloading'
+ piece.interfaceId = network.id
+ }
+ const provisional = Object.values(pending).reduce((sum, bytes) => sum + bytes, 0)
+ const length = piece.rangeEnd === null ? 0 : piece.rangeEnd - piece.rangeStart + 1
+ piece.provisionalBytes = Math.min(length, provisional)
+ }
+ this.runtime.meters.add(peerState.id, network.id, buffer.length)
+ this.host.scheduleUpdate()
+ })
+ wire.on('upload', (bytes: number) => this.onUpload(network, peer, bytes))
+ wire.once('close', () => {
+ if (this.peers.delete(wire)) this.removePeer(peer)
+ })
+ this.host.scheduleUpdate()
+ }
+
+ private removePeer(peer: Peer): void {
+ const { peers } = this.runtime.state
+ const index = peers.indexOf(peer.state)
+ if (index >= 0) peers.splice(index, 1)
+ this.runtime.meters.connections.delete(peer.state.id)
+ this.runtime.uploadMeters.connections.delete(peer.state.id)
+ this.host.scheduleUpdate()
+ }
+
+ /** A piece verified and written: it counts now, credited to the networks that delivered it. */
+ private onVerified(index: number): void {
+ const piece = this.runtime.pieces[index]
+ const received = this.unverified.get(index) ?? {}
+ this.unverified.delete(index)
+ // A skipped piece fetched anyway isn't this download's: nothing chosen needs it.
+ if (!piece || piece.status === 'completed' || piece.status === 'skipped') return
+ if (piece.rangeEnd === null) return
+ const { state } = this.runtime
+ const length = piece.rangeEnd - piece.rangeStart + 1
+ // Found on disk rather than received: whoever held it last, else the first network in use.
+ const fallback = piece.interfaceId ?? this.usable()[0]?.id ?? state.networks[0].id
+ const shares = creditPiece(received, length, fallback)
+ state.bytesDownloaded += length - piece.bytesDownloaded
+ for (const [id, bytes] of Object.entries(piece.bytesByInterface)) {
+ const network = state.networks.find((entry) => entry.id === id)
+ if (network) network.bytesDownloaded -= bytes
+ }
+ for (const [id, bytes] of Object.entries(shares)) {
+ const network = state.networks.find((entry) => entry.id === id)
+ if (network) network.bytesDownloaded += bytes
+ }
+ piece.bytesByInterface = shares
+ piece.bytesDownloaded = length
+ piece.provisionalBytes = 0
+ piece.interfaceId = Object.entries(shares).sort((a, b) => b[1] - a[1])[0][0]
+ piece.status = 'completed'
+ this.host.scheduleUpdate()
+ }
+
+ /**
+ * Once webtorrent has checked what is on disk: a piece it found wanting, though this download
+ * had it as done, is fetched again — and isn't done here either, or the download would be
+ * published without it.
+ */
+ private followEngine(torrent: Torrent): void {
+ let changed = false
+ for (const piece of this.runtime.pieces) {
+ if (piece.status === 'completed' && !torrent.bitfield.get(piece.index)) {
+ piece.status = 'pending'
+ piece.bytesDownloaded = 0
+ piece.provisionalBytes = 0
+ piece.bytesByInterface = {}
+ changed = true
+ }
+ }
+ if (changed) {
+ recomputeAggregates(this.runtime.state, this.runtime.pieces)
+ this.host.scheduleUpdate()
+ }
+ }
+}
diff --git a/src/main/download/transfer.ts b/src/main/download/transfer.ts
new file mode 100644
index 0000000..d91d7c6
--- /dev/null
+++ b/src/main/download/transfer.ts
@@ -0,0 +1,266 @@
+import type {
+ DownloadNetwork,
+ DownloadState,
+ DownloadUnitState,
+ HttpBlockState,
+ HttpDownloadState,
+ StartHttpDownloadRequest,
+ StartTorrentDownloadRequest,
+ TorrentDownloadState,
+ TorrentPieceState
+} from '../../shared/types'
+import type { NetworkMonitor } from '../network/interfaces'
+import type { Limits } from '../network/limits'
+import type { DownloadFile } from './downloadFile'
+import type { TorrentDestination } from './torrent/torrentDestination'
+
+/**
+ * How a download's bytes get fetched: HTTP streams today (see httpTransfer.ts). The manager runs
+ * everything a download does whatever fetches it — its networks, pause and resume, saving it,
+ * telling the window — and hands the fetching to its transfer.
+ */
+export interface Transfer {
+ /** Brings its connections in line with what each network can do now. The manager calls it at
+ * the end of its own reconcile, while the download runs. */
+ reconcile(): void
+ /** Runs every TICK_MS while the download does. */
+ tick(now: number): void
+ /** Its connections' work, each settling once that connection stops: the run waits on them. */
+ running(): Iterable<Promise<void>>
+ /** Stops every connection: a pause, a cancel, a failed download. */
+ abort(): void
+ /** Forgets what only steers the current run. Done on a pause, a resume and as a run starts. */
+ reset(): void
+ /** Gets connections going again now, rather than when their backoff runs out: what held them
+ * back has changed. The ones `reconnect` picks also drop their sockets. */
+ wake(pick: (networkId: string) => boolean, reconnect: (networkId: string) => boolean): void
+ /** The computer woke from sleep: every judgement made by the clock starts over. */
+ systemResumed(now: number): void
+}
+
+/** The parts of a download a transfer works on. The manager owns them; this is the same object. */
+interface TransferTargetBase {
+ file: DownloadFile
+ /** 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
+}
+
+export interface HttpTransferTarget extends TransferTargetBase {
+ state: HttpDownloadState
+ requestPayload: StartHttpDownloadRequest
+ blocks: HttpBlockState[]
+ /** What each stream, and each network, has received (see updateSpeeds). */
+ meters: Meters
+}
+
+export interface TorrentTransferTarget extends TransferTargetBase {
+ file: TorrentDestination
+ state: TorrentDownloadState
+ requestPayload: StartTorrentDownloadRequest
+ pieces: TorrentPieceState[]
+ /** What each peer, and each network, has received (see updateSpeeds). */
+ meters: Meters
+ /** What each peer, and each network, has sent. */
+ uploadMeters: Meters
+}
+
+export type TransferTarget = HttpTransferTarget | TorrentTransferTarget
+
+/** What a transfer asks of the manager. */
+export interface TransferHost {
+ networks: NetworkMonitor
+ /** Every byte received goes through it (see Limits.take). */
+ limits: Limits
+ /** The manager's reconcile: networks first, then the transfer's own. */
+ reconcile(): void
+ failDownload(message: string, discard?: boolean): void
+ failNetwork(network: DownloadNetwork, message: string): void
+ scheduleUpdate(): void
+}
+
+// Raw per-event deltas are too noisy to display (socket buffers flush in
+// irregular bursts a few ms apart). Averaging over a few seconds instead
+// gives a speed/ETA reading that tracks reality without jumping around.
+const SPEED_WINDOW_MS = 3000
+
+/**
+ * Bytes counted as they arrive, and read as a rate only on the download's clock (its tick).
+ * Arrivals come in bursts — socket flushes, and a speed limit pausing reads between them — so a
+ * window that starts or ends on one is off by up to a burst: sampled on arrival, a 7 MB/s limit
+ * read 6.9. Between two clock readings, where the bursts fall doesn't matter.
+ */
+export class Meter {
+ private total = 0
+ private readings: { bytes: number; time: number }[] = []
+
+ add(bytes: number): void {
+ this.total += bytes
+ }
+
+ /** The rate over the last SPEED_WINDOW_MS, as of `now`. Bytes before the first reading are
+ * the meter's starting point, not part of any rate. */
+ read(now: number): number {
+ const { readings } = this
+ readings.push({ bytes: this.total, time: now })
+ while (readings.length > 2 && readings[1].time <= now - SPEED_WINDOW_MS) readings.shift()
+ const oldest = readings[0]
+ // At least a second: the clock can come round again ms later (a stream ending wakes it), and
+ // one burst over a few ms reads as a speed the connection never had (and sticks as the peak).
+ return (this.total - oldest.bytes) / Math.max((now - oldest.time) / 1000, 1)
+ }
+}
+
+/** A download's meters in one direction: each connection's, and each network's. A network's is
+ * its own rather than its connections' added up, so its bytes stay counted when one ends. */
+export class Meters {
+ readonly connections = new Map<number, Meter>()
+ readonly networks = new Map<string, Meter>()
+
+ /** Counts `bytes` through connection `connectionId`, on network `networkId`. */
+ add(connectionId: number, networkId: string, bytes: number): void {
+ meterOf(this.connections, connectionId).add(bytes)
+ meterOf(this.networks, networkId).add(bytes)
+ }
+
+ clear(): void {
+ this.connections.clear()
+ this.networks.clear()
+ }
+}
+
+function meterOf<K>(meters: Map<K, Meter>, key: K): Meter {
+ let meter = meters.get(key)
+ if (!meter) meters.set(key, (meter = new Meter()))
+ return meter
+}
+
+/** Reads every meter as of `now` into the download's speeds: each connection's, each
+ * network's and the download's, uploads too for a torrent. Says whether any of them changed. */
+export function updateSpeeds(runtime: TransferTarget, now: number): boolean {
+ const { state } = runtime
+ let changed = false
+ const set = <T, K extends keyof T>(target: T, key: K, value: T[K]): void => {
+ if (target[key] !== value) changed = true
+ target[key] = value
+ }
+ const connections: Array<{ id: number; status: string; speedBytesPerSec: number }> =
+ state.kind === 'http' ? state.streams : state.peers
+ for (const connection of connections) {
+ // Read every tick, moving or not, so its window is never stale when it moves again.
+ const speed = runtime.meters.connections.get(connection.id)?.read(now) ?? 0
+ // Between blocks, waiting to retry, or a peer sending nothing: 0, not what it last did.
+ const moving = connection.status === 'downloading' || connection.status === 'receiving'
+ set(connection, 'speedBytesPerSec', moving ? speed : 0)
+ }
+ let total = 0
+ for (const network of state.networks) {
+ const speed = runtime.meters.networks.get(network.id)?.read(now) ?? 0
+ set(network, 'speedBytesPerSec', speed)
+ total += speed
+ }
+ set(state, 'speedBytesPerSec', total)
+
+ if ('uploadMeters' in runtime) {
+ const { uploadMeters, state } = runtime
+ for (const peer of state.peers) {
+ set(peer, 'uploadSpeedBytesPerSec', uploadMeters.connections.get(peer.id)?.read(now) ?? 0)
+ }
+ let uploaded = 0
+ for (const network of state.networks) {
+ const speed = uploadMeters.networks.get(network.id)?.read(now) ?? 0
+ set(network, 'uploadSpeedBytesPerSec', speed)
+ uploaded += speed
+ }
+ set(state, 'uploadSpeedBytesPerSec', uploaded)
+ }
+ return changed
+}
+
+// How far time left moves toward a new estimate in a second: further down than up, so a speed-up
+// shows at once while a wobble doesn't add minutes. Firefox's shares per update
+// (DownloadUtils.getTimeLeft), here per second so the tick's pace doesn't change them.
+const TIME_LEFT_DOWN = 0.3
+const TIME_LEFT_UP = 0.1
+
+/** Time left, `elapsedSeconds` after `previous`, given a fresh `estimate`. */
+export function smoothTimeLeft(
+ previous: number | undefined,
+ elapsedSeconds: number,
+ estimate: number
+): number {
+ // Between estimates it counts down on its own.
+ const expected = previous === undefined ? 0 : previous - elapsedSeconds
+ // The first estimate, or far under what's expected (a slow start or resume picking up): as is.
+ if (expected <= 0 || estimate <= expected / 2) return estimate
+ const share = estimate < expected ? TIME_LEFT_DOWN : TIME_LEFT_UP
+ return expected + (estimate - expected) * (1 - (1 - share) ** elapsedSeconds)
+}
+
+/** Brings time left up to date from the speed, `elapsedSeconds` after it last was. Read on the
+ * download's clock, with the speeds. Says whether it changed. */
+export function updateTimeLeft(state: DownloadState, elapsedSeconds: number): boolean {
+ const wanted = state.totalBytes - (state.kind === 'torrent' ? state.skippedBytes : 0)
+ const before = state.timeLeftSeconds
+ state.timeLeftSeconds =
+ state.totalBytes > 0 && state.speedBytesPerSec > 0
+ ? smoothTimeLeft(
+ before,
+ elapsedSeconds,
+ Math.max(0, wanted - state.bytesDownloaded) / state.speedBytesPerSec
+ )
+ : undefined
+ return state.timeLeftSeconds !== before
+}
+
+/** Nothing is moving: a paused or stopped download reads 0 everywhere. */
+export function clearSpeeds(state: DownloadState): void {
+ state.speedBytesPerSec = 0
+ state.timeLeftSeconds = undefined
+ const connections = state.kind === 'http' ? state.streams : state.peers
+ for (const connection of connections) connection.speedBytesPerSec = 0
+ for (const network of state.networks) network.speedBytesPerSec = 0
+ if (state.kind === 'torrent') {
+ state.uploadSpeedBytesPerSec = 0
+ for (const network of state.networks) network.uploadSpeedBytesPerSec = 0
+ for (const peer of state.peers) peer.uploadSpeedBytesPerSec = 0
+ }
+}
+
+/** Waits, but returns early if the signal aborts (pause/cancel shouldn't wait out a retry backoff). */
+export function delay(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (signal.aborted) {
+ resolve()
+ return
+ }
+ const onAbort = (): void => {
+ clearTimeout(timer)
+ resolve()
+ }
+ const timer = setTimeout(() => {
+ signal.removeEventListener('abort', onAbort)
+ resolve()
+ }, ms)
+ signal.addEventListener('abort', onAbort, { once: true })
+ })
+}
+
+/** Re-derives verified byte counts from HTTP blocks or torrent pieces. */
+export function recomputeAggregates(
+ state: DownloadState,
+ units: readonly DownloadUnitState[]
+): void {
+ let total = 0
+ const byNetwork = new Map<string, number>()
+ for (const block of units) {
+ total += block.bytesDownloaded
+ for (const [id, bytes] of Object.entries(block.bytesByInterface)) {
+ byNetwork.set(id, (byNetwork.get(id) ?? 0) + bytes)
+ }
+ }
+ state.bytesDownloaded = total
+ for (const network of state.networks) {
+ network.bytesDownloaded = byNetwork.get(network.id) ?? 0
+ }
+}
diff --git a/src/main/download/trashDownload.ts b/src/main/download/trashDownload.ts
new file mode 100644
index 0000000..93ffeeb
--- /dev/null
+++ b/src/main/download/trashDownload.ts
@@ -0,0 +1,24 @@
+import { rmdir } from 'node:fs/promises'
+import { shell } from 'electron'
+import type { DownloadState, FinishedDownload } from '../../shared/types'
+import { ownedTorrentFiles } from './torrent/ownedFiles'
+
+/** Trash only owned torrent files; never move unrelated files added to its folder. */
+export async function trashDownload(
+ download: DownloadState | FinishedDownload,
+ ownedFiles?: readonly string[]
+): Promise<void> {
+ if (download.kind !== 'torrent' || !download.folder) {
+ await shell.trashItem(download.destinationPath)
+ return
+ }
+ const files = ownedFiles ?? ('downloadedFiles' in download ? download.downloadedFiles : undefined)
+ if (!files?.length) {
+ throw new Error(
+ 'Plexo can’t identify the files in this older torrent. Remove it from the list or manage its files in your file browser.'
+ )
+ }
+ const { targets, folders } = await ownedTorrentFiles(download.destinationPath, files)
+ for (const target of targets) await shell.trashItem(target)
+ for (const folder of folders) await rmdir(folder).catch(() => {})
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 0d1fd8e..4ad0f2d 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -3,6 +3,7 @@ import { app, BrowserWindow, nativeTheme, shell } from 'electron'
import { join } from 'path'
import icon from '../../resources/icon-dark.png?asset'
import { registerIpcHandlers } from './ipc/handlers'
+import { acceptedLink, linkFromArgs, offerLink } from './openLinks'
import { loadThemeSource, migrateLegacyNetworkPreferences } from './settings'
import { testKnobs } from './testKnobs'
import type { DownloadManager } from './download/downloadManager'
@@ -15,16 +16,58 @@ app.setName('Plexo')
// Each e2e test runs against its own throwaway userData folder (downloads, manifests, settings).
if (testKnobs.userDataDir) app.setPath('userData', testKnobs.userDataDir)
+// One Plexo at a time (per userData folder, so parallel e2e runs each have their own): a second
+// launch — a magnet link clicked, a .torrent opened — hands its link to the first and exits.
+if (!app.requestSingleInstanceLock()) app.exit(0)
+
let mainWindow: BrowserWindow | null = null
let downloadManager: DownloadManager | null = null
let quitAfterSuspending = false
+/** A link the OS handed over goes to the window's link field (see openLinks.ts). */
+function offer(candidate: string): void {
+ const link = acceptedLink(candidate)
+ if (!link) return
+ offerLink(link, mainWindow)
+}
+
+app.on('second-instance', (_event, argv) => {
+ const link = linkFromArgs(argv)
+ if (link) return offer(link)
+ if (mainWindow?.isMinimized()) mainWindow.restore()
+ mainWindow?.focus()
+})
+// macOS hands links over as events, and may do so before the app is ready.
+app.on('open-url', (event, url) => {
+ event.preventDefault()
+ offer(url)
+})
+app.on('open-file', (event, path) => {
+ event.preventDefault()
+ offer(path)
+})
+// Windows and Linux put the first launch's link on its command line.
+const launchLink = linkFromArgs(process.argv)
+if (launchLink) offer(launchLink)
+
+/** The Windows/Linux window controls, in the title bar's colors (main.css's --bg-secondary and
+ * --text) for the theme in use, at its height. */
+function titleBarOverlay(): Electron.TitleBarOverlayOptions {
+ const dark = nativeTheme.shouldUseDarkColors
+ return {
+ color: dark ? '#202325' : '#fafafa',
+ symbolColor: dark ? '#eae7e2' : '#1d1d1f',
+ height: 44
+ }
+}
+
function createWindow(): void {
mainWindow = new BrowserWindow({
width: 760,
- height: 560,
+ height: 640,
minWidth: 720,
- minHeight: 520,
+ // Room under the download screen's pinned block grid for a network row and a few of its rows.
+ minHeight: 620,
show: false,
autoHideMenuBar: true,
title: 'Plexo',
@@ -32,12 +75,14 @@ function createWindow(): void {
// (which briefly exposes the raw window background) doesn't flash white.
backgroundColor: nativeTheme.shouldUseDarkColors ? '#1c1c1e' : '#ffffff',
...(process.platform !== 'darwin' ? { icon } : {}),
- // Design v2 draws its own logo + status readout where the title normally sits — on macOS,
- // keep the real traffic lights (still native, still draggable) but let the renderer's own
- // title bar occupy the rest of the strip instead of an OS-drawn title.
+ // One title bar on every OS: the renderer's own strip (see TitleBar.tsx), with the OS's
+ // window controls over it — macOS's traffic lights, or the minimize/maximize/close that
+ // Windows and Linux draw over the strip's right end.
+ titleBarStyle: 'hidden',
...(process.platform === 'darwin'
- ? { titleBarStyle: 'hiddenInset', trafficLightPosition: { x: 16, y: 16 } }
- : {}),
+ ? // Center the 14px native buttons in the renderer’s 32px macOS title bar.
+ { trafficLightPosition: { x: 16, y: 9 } }
+ : { titleBarOverlay: titleBarOverlay() }),
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
// A hidden e2e window would otherwise have its timers throttled.
@@ -88,6 +133,7 @@ app.whenReady().then(async () => {
nativeTheme.on('updated', () => {
mainWindow?.setBackgroundColor(nativeTheme.shouldUseDarkColors ? '#1c1c1e' : '#ffffff')
+ if (process.platform !== 'darwin') mainWindow?.setTitleBarOverlay(titleBarOverlay())
})
createWindow()
diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.ts
index d6ce336..6e0f0e6 100644
--- a/src/main/ipc/handlers.ts
+++ b/src/main/ipc/handlers.ts
@@ -1,4 +1,4 @@
-import { stat } from 'node:fs/promises'
+import { stat, statfs } from 'node:fs/promises'
import {
app,
clipboard,
@@ -12,11 +12,18 @@ import {
} from 'electron'
import { IpcChannels } from '../../shared/ipc-channels'
import type { IpcContract } from '../../shared/ipc-contract'
-import type { InitialState, ThemeSource } from '../../shared/types'
+import {
+ DEFAULT_SLOW_MODE_SPEED,
+ DOWNLOADS_AT_ONCE,
+ type InitialState,
+ type ThemeSource
+} from '../../shared/types'
import { DownloadManager } from '../download/downloadManager'
import { getDefaultDownloadsDir, getHomeDir } from '../download/paths'
+import { listHistory } from '../download/history'
import { probeUrl } from '../download/probe'
import { deviceBindingSupported } from '../network/deviceBinding'
+import { takePendingLink } from '../openLinks'
import { measureLatencies } from '../network/latency'
import { NetworkMonitor } from '../network/interfaces'
import { loadSettings, saveSettings } from '../settings'
@@ -56,6 +63,15 @@ function handle<K extends keyof IpcContract>(
const DESTINATION_CHECK_MS = 300
+async function freeSpace(dir: string): Promise<number | null> {
+ try {
+ const stats = await statfs(dir)
+ return stats.bavail * stats.bsize
+ } catch {
+ return null
+ }
+}
+
export function registerIpcHandlers(getWindow: () => BrowserWindow | null): DownloadManager {
// The main process keeps the network list, for downloads and the window alike.
const networks = new NetworkMonitor((list) => {
@@ -91,6 +107,8 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
nativeTheme.themeSource = patch.themeSource
}
await saveSettings(patch)
+ // Read back rather than taken from the patch: what was saved is what passed the checks.
+ manager.applySettings(await loadSettings())
})
// Answered via sendSync from the preload, which blocks the page until returnValue is set — so a
@@ -115,6 +133,10 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
downloadsDir: getDefaultDownloadsDir(),
themeSource: currentThemeSource(),
networkPreferences: settings.networkPreferences ?? {},
+ downloadsAtOnce: settings.downloadsAtOnce ?? DOWNLOADS_AT_ONCE.default,
+ speedLimit: settings.speedLimit,
+ slowMode: settings.slowMode ?? false,
+ slowModeSpeed: settings.slowModeSpeed ?? DEFAULT_SLOW_MODE_SPEED,
destinationDir: destinationExists ? destinationDir : undefined
} satisfies InitialState
} catch (error) {
@@ -124,7 +146,10 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
homeDir: '',
downloadsDir: '',
themeSource: currentThemeSource(),
- networkPreferences: {}
+ networkPreferences: {},
+ downloadsAtOnce: DOWNLOADS_AT_ONCE.default,
+ slowMode: false,
+ slowModeSpeed: DEFAULT_SLOW_MODE_SPEED
} satisfies InitialState
}
})
@@ -146,15 +171,40 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
return result.filePaths[0]
})
+ handle('chooseTorrentFile', async () => {
+ const window = getWindow()
+ if (!window) return null
+ const result = await dialog.showOpenDialog(window, {
+ properties: ['openFile'],
+ filters: [{ name: 'Torrent', extensions: ['torrent'] }]
+ })
+ if (result.canceled || result.filePaths.length === 0) return null
+ return result.filePaths[0]
+ })
+
+ handle('takePendingLink', async () => takePendingLink())
+
handle('readClipboardText', async () => clipboard.readText())
- handle('revealInFolder', async (_event, filePath) => {
- shell.showItemInFolder(filePath)
- })
+ handle('revealDownload', async (_event, id) => manager.reveal(id))
handle('startDownload', async (_event, request) => manager.start(request))
- handle('getCurrentDownload', async () => manager.getCurrentDownload())
+ handle('listDownloads', async () => manager.listDownloads())
+
+ handle('listHistory', async () => listHistory())
+
+ handle('clearHistory', async () => manager.clearHistory())
+
+ handle('networkUsage', async () => manager.limits.usedByPeriod())
+ handle('resetNetworkUsage', async (_event, id) => manager.resetNetworkUsage(id))
+
+ handle('freeSpace', async (_event, dir) => freeSpace(dir))
+
+ handle('torrentFiles', async (_event, id) => manager.torrentFiles(id))
+ handle('chooseTorrentFiles', async (_event, id, selected) =>
+ manager.chooseTorrentFiles(id, selected)
+ )
handle('pauseDownload', async (_event, id) => {
await manager.pause(id)
@@ -164,13 +214,17 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
manager.resume(id)
})
+ handle('relinkDownload', async (_event, id, url) => manager.relink(id, url))
+
handle('setDownloadNetwork', async (_event, id, networkId, enabled) => {
await manager.setNetworkEnabled(id, networkId, enabled)
})
handle('cancelDownload', async (_event, id) => manager.cancel(id))
- handle('removeDownload', async (_event, id) => manager.remove(id))
+ handle('removeDownload', async (_event, id, options) =>
+ manager.remove(id, options?.trashFile === true)
+ )
// Kicked off once at startup, not per-call — later renderer calls (e.g. a remount) just await
// the same in-flight/settled check instead of re-hitting the GitHub API.
diff --git a/src/main/network/limits.ts b/src/main/network/limits.ts
new file mode 100644
index 0000000..1c57d02
--- /dev/null
+++ b/src/main/network/limits.ts
@@ -0,0 +1,197 @@
+import { join } from 'node:path'
+import { app } from 'electron'
+import { dataPeriodKey } from '../../shared/dataLimits'
+import { DEFAULT_SLOW_MODE_SPEED, type AppSettings, type DataLimitPeriod } from '../../shared/types'
+import { readJson, updateJson } from '../jsonFile'
+
+// Speed and data limits, for every download together: what the user sets in Speed & data limits.
+// Every byte Plexo receives passes through take(), on the network it came in on — an HTTP
+// response's body and a torrent peer's socket alike — which says how long to stop reading for.
+// Stopping reading is what slows the sender: TCP's window fills, and it waits.
+
+/** A rate as a bucket of tokens (bytes) that refills at `rate` per second. Taking more than it
+ * holds leaves it in debt, and the debt is the wait. A second's worth is all it ever holds, so a
+ * quiet spell doesn't buy a burst over the limit. */
+class Bucket {
+ private tokens = 0
+ private at = Date.now()
+
+ constructor(public rate: number) {}
+
+ /** Takes `bytes`, and says how many ms to wait before taking more. */
+ take(bytes: number, now: number): number {
+ this.tokens = Math.min(this.rate, this.tokens + ((now - this.at) / 1000) * this.rate)
+ this.at = now
+ this.tokens -= bytes
+ return this.tokens >= 0 ? 0 : (-this.tokens / this.rate) * 1000
+ }
+}
+
+type Usage = { key: string; bytes: Record<string, number> }
+const PERIODS: DataLimitPeriod[] = ['day', 'week', 'month']
+function freshUsage(time: number): Record<DataLimitPeriod, Usage> {
+ return {
+ day: { key: dataPeriodKey('day', time), bytes: {} },
+ week: { key: dataPeriodKey('week', time), bytes: {} },
+ month: { key: dataPeriodKey('month', time), bytes: {} }
+ }
+}
+
+const USAGE_SAVE_MS = 10_000
+
+export class Limits {
+ private total: Bucket | null = null
+ private perNetwork = new Map<string, Bucket>()
+ /** Each network's data limit and selected calendar period. */
+ private dataLimits = new Map<string, number>()
+ private periods = new Map<string, DataLimitPeriod>()
+ private usage = freshUsage(Date.now())
+ private saveTimer: NodeJS.Timeout | null = null
+ readonly loaded: Promise<void>
+
+ /** `onLimitReached` is told when a network uses up its data for its selected period. */
+ constructor(private readonly onLimitReached: () => void) {
+ this.loaded = readJson(this.usagePath())
+ .then((saved) => {
+ if (!saved || typeof saved !== 'object') return
+ const record = saved as Record<string, unknown>
+ // Older releases saved only monthly usage. Preserve it without attributing it to a day or week.
+ const entries =
+ record.version === 2
+ ? record.periods
+ : {
+ month: { key: record.month, bytes: record.bytes }
+ }
+ if (!entries || typeof entries !== 'object') return
+ for (const period of PERIODS) {
+ const entry = (entries as Record<string, unknown>)[period]
+ if (!entry || typeof entry !== 'object') continue
+ const { key, bytes } = entry as { key?: unknown; bytes?: unknown }
+ if (
+ key !== this.usage[period].key ||
+ !bytes ||
+ typeof bytes !== 'object' ||
+ Array.isArray(bytes)
+ )
+ continue
+ for (const [id, used] of Object.entries(bytes)) {
+ if (Number.isSafeInteger(used) && used >= 0) this.usage[period].bytes[id] = used
+ }
+ }
+ })
+ .catch(() => {})
+ }
+
+ private usagePath(): string {
+ return join(app.getPath('userData'), 'network-usage.json')
+ }
+
+ /** Takes up the limits in `settings`. Slow mode, when on, stands in for the total limit. */
+ configure(settings: AppSettings): void {
+ // A slow mode speed never changed isn't saved: it's the default the window shows.
+ const total = settings.slowMode
+ ? (settings.slowModeSpeed ?? DEFAULT_SLOW_MODE_SPEED)
+ : settings.speedLimit
+ this.total = adjust(this.total, total)
+ const preferences = settings.networkPreferences ?? {}
+ for (const id of new Set([...this.perNetwork.keys(), ...Object.keys(preferences)])) {
+ const bucket = adjust(this.perNetwork.get(id) ?? null, preferences[id]?.speedLimit)
+ if (bucket) this.perNetwork.set(id, bucket)
+ else this.perNetwork.delete(id)
+ }
+ this.dataLimits.clear()
+ this.periods.clear()
+ for (const [id, preference] of Object.entries(preferences)) {
+ this.periods.set(id, preference.dataLimitPeriod ?? 'month')
+ if (preference.dataLimit !== undefined) this.dataLimits.set(id, preference.dataLimit)
+ }
+ }
+
+ /** Counts `bytes` just received on `networkId`, and says how many ms to stop reading for. */
+ take(networkId: string, bytes: number): number {
+ const now = Date.now()
+ this.rollPeriods(now)
+ const period = this.periods.get(networkId) ?? 'month'
+ const before = this.usage[period].bytes[networkId] ?? 0
+ for (const entry of Object.values(this.usage)) {
+ entry.bytes[networkId] = (entry.bytes[networkId] ?? 0) + bytes
+ }
+ this.saveTimer ??= setTimeout(() => void this.save(), USAGE_SAVE_MS)
+ const limit = this.dataLimits.get(networkId)
+ // Told once the caller is done with its bytes: what it does may stop the very connection
+ // they came in on.
+ if (limit !== undefined && before < limit && before + bytes >= limit) {
+ setImmediate(this.onLimitReached)
+ }
+ return Math.max(
+ this.total?.take(bytes, now) ?? 0,
+ this.perNetwork.get(networkId)?.take(bytes, now) ?? 0
+ )
+ }
+
+ /** Whether the network has used up its data for the selected period. */
+ limitReached(networkId: string): boolean {
+ this.rollPeriods(Date.now())
+ const limit = this.dataLimits.get(networkId)
+ return (
+ limit !== undefined &&
+ (this.usage[this.periods.get(networkId) ?? 'month'].bytes[networkId] ?? 0) >= limit
+ )
+ }
+
+ /** Each network's usage for its selected calendar period. */
+ usedByPeriod(): Record<string, number> {
+ this.rollPeriods(Date.now())
+ const ids = new Set(Object.values(this.usage).flatMap((entry) => Object.keys(entry.bytes)))
+ return Object.fromEntries(
+ [...ids].map((id) => [id, this.usage[this.periods.get(id) ?? 'month'].bytes[id] ?? 0])
+ )
+ }
+
+ /** Reset only the selected network's current period; other periods retain their usage. */
+ async resetUsage(networkId: string): Promise<void> {
+ await this.loaded
+ this.rollPeriods(Date.now())
+ const period = this.periods.get(networkId) ?? 'month'
+ const previous = this.usage[period].bytes[networkId] ?? 0
+ this.usage[period].bytes[networkId] = 0
+ try {
+ const snapshot = { version: 2, periods: structuredClone(this.usage) }
+ await updateJson(this.usagePath(), () => snapshot)
+ } catch (error) {
+ this.usage[period].bytes[networkId] += previous
+ throw error
+ }
+ }
+
+ /** Writes every period’s usage now (on quit; otherwise it's saved every USAGE_SAVE_MS). */
+ async save(): Promise<void> {
+ if (this.saveTimer) clearTimeout(this.saveTimer)
+ this.saveTimer = null
+ this.rollPeriods(Date.now(), false)
+ const usage = { version: 2, periods: structuredClone(this.usage) }
+ await updateJson(this.usagePath(), () => usage).catch(() => {})
+ }
+
+ private rollPeriods(now: number, scheduleSave = true): void {
+ let changed = false
+ for (const period of PERIODS) {
+ const key = dataPeriodKey(period, now)
+ if (key !== this.usage[period].key) {
+ this.usage[period] = { key, bytes: {} }
+ changed = true
+ }
+ }
+ if (changed && scheduleSave)
+ this.saveTimer ??= setTimeout(() => void this.save(), USAGE_SAVE_MS)
+ }
+}
+
+/** The bucket for `rate` bytes a second: `current` changed in place, so a debt carries over, or
+ * none for no limit. */
+function adjust(current: Bucket | null, rate: number | undefined): Bucket | null {
+ if (rate === undefined || !(rate > 0)) return null
+ if (!current) return new Bucket(rate)
+ current.rate = rate
+ return current
+}
diff --git a/src/main/openLinks.ts b/src/main/openLinks.ts
new file mode 100644
index 0000000..960b52b
--- /dev/null
+++ b/src/main/openLinks.ts
@@ -0,0 +1,51 @@
+import { statSync } from 'node:fs'
+import { isAbsolute } from 'node:path'
+import type { BrowserWindow } from 'electron'
+import { IpcChannels } from '../shared/ipc-channels'
+
+// Links the OS hands Plexo — a magnet link clicked in a browser, a .torrent opened from the file
+// manager — for the window's link field. They're never started on their own: the user still sees
+// what the link is and presses Start.
+
+/** The latest link handed over and not yet taken by the window. */
+let pending: string | null = null
+
+/** A magnet link, or the path of a .torrent file that exists; anything else isn't taken. */
+export function acceptedLink(candidate: string): string | null {
+ if (/^magnet:\?/i.test(candidate)) return candidate
+ if (!isAbsolute(candidate) || !/\.torrent$/i.test(candidate)) return null
+ try {
+ return statSync(candidate).isFile() ? candidate : null
+ } catch {
+ return null
+ }
+}
+
+/** The link in a command line (Windows and Linux hand one over as an argument). */
+export function linkFromArgs(argv: readonly string[]): string | null {
+ for (const argument of argv.slice(1)) {
+ const link = acceptedLink(argument)
+ if (link) return link
+ }
+ return null
+}
+
+/**
+ * Hands `link` to the window: it's kept until the window takes it (takePendingLink), so one that
+ * arrives before the window is ready isn't lost. The window is brought forward.
+ */
+export function offerLink(link: string, window: BrowserWindow | null): void {
+ pending = link
+ if (!window || window.isDestroyed()) return
+ if (window.isMinimized()) window.restore()
+ window.show()
+ window.focus()
+ window.webContents.send(IpcChannels.linkReceived)
+}
+
+/** The link handed over, once: whoever takes it puts it in the link field. */
+export function takePendingLink(): string | null {
+ const link = pending
+ pending = null
+ return link
+}
diff --git a/src/main/settings.ts b/src/main/settings.ts
index ec2534b..12d82c7 100644
--- a/src/main/settings.ts
+++ b/src/main/settings.ts
@@ -1,11 +1,12 @@
import { rm } from 'node:fs/promises'
import { isAbsolute, join } from 'node:path'
import { app, nativeTheme } from 'electron'
-import type {
- AppSettings,
- NetworkPreference,
- NetworkPreferences,
- ThemeSource
+import {
+ DOWNLOADS_AT_ONCE,
+ type AppSettings,
+ type NetworkPreference,
+ type NetworkPreferences,
+ type ThemeSource
} from '../shared/types'
import { readJson, updateJson } from './jsonFile'
@@ -17,10 +18,15 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
-/** Keeps only string customName/colorId fields (what every reader downstream assumes, e.g.
+/** A rate or an amount of bytes: a positive whole number, or nothing. */
+function byteCount(value: unknown): number | undefined {
+ return Number.isSafeInteger(value) && (value as number) > 0 ? (value as number) : undefined
+}
+
+/** Keeps only fields of the right type (what every reader downstream assumes, e.g.
* NetworkEditPopover's `customName?.trim()`), entry by entry, rather than discarding every
- * network over one bad entry. An entry left with neither field is dropped, so resetting a
- * network removes it from the file. */
+ * network over one bad entry. An entry left with no field is dropped, so resetting a network
+ * removes it from the file. */
function sanitizeNetworkPreferences(parsed: unknown): NetworkPreferences {
if (!isRecord(parsed)) return {}
@@ -30,7 +36,20 @@ function sanitizeNetworkPreferences(parsed: unknown): NetworkPreferences {
const preference: NetworkPreference = {}
if (typeof value.customName === 'string') preference.customName = value.customName
if (typeof value.colorId === 'string') preference.colorId = value.colorId
- if (preference.customName || preference.colorId) result[id] = preference
+ if (value.off === true) preference.off = true
+ preference.speedLimit = byteCount(value.speedLimit)
+ preference.dataLimit = byteCount(value.dataLimit)
+ if (
+ value.dataLimitPeriod === 'day' ||
+ value.dataLimitPeriod === 'week' ||
+ value.dataLimitPeriod === 'month'
+ ) {
+ preference.dataLimitPeriod = value.dataLimitPeriod
+ }
+ for (const key of Object.keys(preference) as (keyof NetworkPreference)[]) {
+ if (preference[key] === undefined) delete preference[key]
+ }
+ if (Object.keys(preference).length > 0) result[id] = preference
}
return result
}
@@ -41,7 +60,7 @@ function sanitizeNetworkPreferences(parsed: unknown): NetworkPreferences {
function sanitizeSettings(parsed: unknown): AppSettings {
if (!isRecord(parsed)) return {}
- const { themeSource, dismissedUpdateVersion, destinationDir } = parsed
+ const { themeSource, dismissedUpdateVersion, destinationDir, downloadsAtOnce } = parsed
const settings: AppSettings = {}
// 'system' was once an option — dropping it falls back to the OS appearance (loadThemeSource).
if (themeSource === 'light' || themeSource === 'dark') settings.themeSource = themeSource
@@ -51,9 +70,21 @@ function sanitizeSettings(parsed: unknown): AppSettings {
if (typeof destinationDir === 'string' && isAbsolute(destinationDir)) {
settings.destinationDir = destinationDir
}
+ if (
+ Number.isInteger(downloadsAtOnce) &&
+ (downloadsAtOnce as number) >= DOWNLOADS_AT_ONCE.min &&
+ (downloadsAtOnce as number) <= DOWNLOADS_AT_ONCE.max
+ ) {
+ settings.downloadsAtOnce = downloadsAtOnce as number
+ }
if (parsed.networkPreferences !== undefined) {
settings.networkPreferences = sanitizeNetworkPreferences(parsed.networkPreferences)
}
+ const speedLimit = byteCount(parsed.speedLimit)
+ if (speedLimit !== undefined) settings.speedLimit = speedLimit
+ const slowModeSpeed = byteCount(parsed.slowModeSpeed)
+ if (slowModeSpeed !== undefined) settings.slowModeSpeed = slowModeSpeed
+ if (parsed.slowMode === true) settings.slowMode = true
return settings
}
diff --git a/src/main/testKnobs.ts b/src/main/testKnobs.ts
index 33f28ce..579179b 100644
--- a/src/main/testKnobs.ts
+++ b/src/main/testKnobs.ts
@@ -26,6 +26,10 @@ export const testKnobs = {
slowForMs: positiveNumber('PLEXO_E2E_SLOW_FOR_MS', 10_000),
silentAfterMs: positiveNumber('PLEXO_E2E_SILENT_MS', 5_000),
hedgeAfterMs: positiveNumber('PLEXO_E2E_HEDGE_MS', 2_000),
+ /** How long a magnet link may take to find peers that send its metadata. */
+ magnetTimeoutMs: positiveNumber('PLEXO_E2E_MAGNET_MS', 3 * 60_000),
+ /** Tests turn the DHT off, so a run never reaches out to the internet's DHT nodes. */
+ torrentDht: env['PLEXO_E2E_DHT'] !== '0',
/** Skips the real GitHub check and pretends this version is available, for exercising the
* update banner without needing an actual newer release published. */
forceUpdateVersion: env['PLEXO_FORCE_UPDATE_VERSION']
@@ -53,9 +57,13 @@ export function testInterfaces(): NetworkInterfaceInfo[] | null {
.map((entry) => {
const [id, address, subnet, kind] = entry.split('=')
const inferredKind =
- kind === 'wifi' || id.toLowerCase().includes('wi-fi') || id.toLowerCase().includes('wifi')
- ? ('wifi' as const)
- : ('ethernet' as const)
+ kind === 'usb'
+ ? ('usb' as const)
+ : kind === 'wifi' ||
+ id.toLowerCase().includes('wi-fi') ||
+ id.toLowerCase().includes('wifi')
+ ? ('wifi' as const)
+ : ('ethernet' as const)
return {
id,
device: id,
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 583652c..609492e 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -1,4 +1,4 @@
-import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'
+import { contextBridge, ipcRenderer, webUtils, type IpcRendererEvent } from 'electron'
import { IpcChannels } from '../shared/ipc-channels'
import type { IpcContract } from '../shared/ipc-contract'
import type {
@@ -30,18 +30,39 @@ const plexoApi = {
updateSettings: (patch: AppSettings) => invoke('updateSettings', patch),
probeUrl: (url: string) => invoke('probeUrl', url),
chooseDestinationFolder: (defaultPath: string) => invoke('chooseDestinationFolder', defaultPath),
+ chooseTorrentFile: () => invoke('chooseTorrentFile'),
+ /** Where a file dropped on the window is on disk ('' for one that isn't a file). */
+ pathForFile: (file: File) => webUtils.getPathForFile(file),
readClipboardText: () => invoke('readClipboardText'),
- revealInFolder: (filePath: string) => invoke('revealInFolder', filePath),
+ revealDownload: (id: string) => invoke('revealDownload', id),
startDownload: (request: IpcContract['startDownload']['args'][0]) =>
invoke('startDownload', request),
- getCurrentDownload: () => invoke('getCurrentDownload'),
+ listDownloads: () => invoke('listDownloads'),
+ listHistory: () => invoke('listHistory'),
+ clearHistory: () => invoke('clearHistory'),
+ networkUsage: () => invoke('networkUsage'),
+ resetNetworkUsage: (id) => invoke('resetNetworkUsage', id),
+ freeSpace: (dir: string) => invoke('freeSpace', dir),
+ torrentFiles: (downloadId: string) => invoke('torrentFiles', downloadId),
+ chooseTorrentFiles: (downloadId: string, selected: number[]) =>
+ invoke('chooseTorrentFiles', downloadId, selected),
pauseDownload: (downloadId: string) => invoke('pauseDownload', downloadId),
resumeDownload: (downloadId: string) => invoke('resumeDownload', downloadId),
+ relinkDownload: (downloadId: string, url: string) => invoke('relinkDownload', downloadId, url),
setDownloadNetwork: (downloadId: string, networkId: string, enabled: boolean) =>
invoke('setDownloadNetwork', downloadId, networkId, enabled),
cancelDownload: (downloadId: string) => invoke('cancelDownload', downloadId),
- removeDownload: (downloadId: string) => invoke('removeDownload', downloadId),
+ removeDownload: (downloadId: string, options?: { trashFile?: boolean }) =>
+ invoke('removeDownload', downloadId, options),
checkForUpdate: () => invoke('checkForUpdate'),
+ takePendingLink: () => invoke('takePendingLink'),
+
+ /** The OS handed Plexo a link (a magnet link, a .torrent): takePendingLink() has it. */
+ onLinkReceived: (callback: () => void): (() => void) => {
+ const listener = (): void => callback()
+ ipcRenderer.on(IpcChannels.linkReceived, listener)
+ return () => ipcRenderer.removeListener(IpcChannels.linkReceived, listener)
+ },
onDownloadUpdated: (callback: (update: DownloadUpdate) => void): (() => void) => {
const listener = (_event: IpcRendererEvent, update: DownloadUpdate): void => callback(update)
@@ -49,6 +70,13 @@ const plexoApi = {
return () => ipcRenderer.removeListener(IpcChannels.downloadUpdated, listener)
},
+ /** A download was added to the finished ones or forgotten: listHistory() has them. */
+ onHistoryChanged: (callback: () => void): (() => void) => {
+ const listener = (): void => callback()
+ ipcRenderer.on(IpcChannels.historyChanged, listener)
+ return () => ipcRenderer.removeListener(IpcChannels.historyChanged, listener)
+ },
+
onNetworksChanged: (callback: (networks: NetworkInterfaceInfo[]) => void): (() => void) => {
const listener = (_event: IpcRendererEvent, networks: NetworkInterfaceInfo[]): void =>
callback(networks)
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index 27f3011..f5fe968 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -1,63 +1,39 @@
-import type { DownloadState } from '@shared/types'
+import type { DownloadState, FinishedDownload } from '@shared/types'
import { useEffect } from 'react'
-import { TitleBar, type TitleBarStatus } from './components/TitleBar'
import { NetworkBindingDialog } from './components/NetworkBindingDialog'
+import { NewDownloadDialog } from './components/NewDownloadDialog'
+import { StatusBar } from './components/StatusBar'
+import { TitleBar } from './components/TitleBar'
import { UpdateDialog } from './components/UpdateDialog'
import { TooltipProvider } from './components/ui/tooltip'
import { useDownloadEvents } from './hooks/useDownloadEvents'
import { useNetworkEvents } from './hooks/useNetworks'
+import { useNewDownloadShortcuts, useOpenedLinks } from './hooks/useOpenedLinks'
import { CompleteScreen } from './screens/CompleteScreen'
import { DownloadingScreen } from './screens/DownloadingScreen'
+import { DownloadsScreen } from './screens/DownloadsScreen'
import { ErrorScreen } from './screens/ErrorScreen'
-import { IdleScreen } from './screens/IdleScreen'
-import { NoConnectionsScreen } from './screens/NoConnectionsScreen'
import { useAppStore } from './store/useAppStore'
function assertNever(status: never): never {
throw new Error(`Unhandled download status: ${String(status)}`)
}
-/** One screen + title-bar status per download.status — a switch with an assertNever default so
- * a new DownloadStatus value is a compile error here instead of silently falling into whichever
- * branch happened to be last. */
-function renderDownload(
- download: DownloadState,
- handlers: { onNewDownload: () => void; onDownloadAgain: () => void }
-): { screen: React.JSX.Element; titleBarStatus: TitleBarStatus } {
+/** One screen per download.status — a switch with an assertNever default so a new
+ * DownloadStatus value is a compile error here instead of silently falling into whichever branch
+ * happened to be last. */
+function renderDownload(download: DownloadState | FinishedDownload): React.JSX.Element {
+ if ('unitsWritten' in download) return <CompleteScreen download={download} />
switch (download.status) {
+ case 'queued':
case 'downloading':
- return {
- screen: <DownloadingScreen download={download} />,
- titleBarStatus: {
- kind: 'combined',
- networkCount: download.networks.filter((network) => network.status === 'on').length
- }
- }
case 'paused':
- return {
- screen: <DownloadingScreen download={download} />,
- titleBarStatus: {
- kind: 'paused',
- networkCount: download.networks.filter((network) => network.enabled).length
- }
- }
+ return <DownloadingScreen download={download} />
case 'completed':
- return {
- screen: <CompleteScreen download={download} onNewDownload={handlers.onNewDownload} />,
- titleBarStatus: { kind: 'none' }
- }
+ return <CompleteScreen download={download} />
case 'error':
case 'cancelled':
- return {
- screen: (
- <ErrorScreen
- download={download}
- onNewDownload={handlers.onNewDownload}
- onDownloadAgain={handlers.onDownloadAgain}
- />
- ),
- titleBarStatus: { kind: 'none' }
- }
+ return <ErrorScreen download={download} />
default:
return assertNever(download.status)
}
@@ -65,54 +41,35 @@ function renderDownload(
function App(): React.JSX.Element {
useDownloadEvents()
+ useOpenedLinks()
+ useNewDownloadShortcuts()
useNetworkEvents()
- const interfaces = useAppStore((store) => store.interfaces)
- const interfacesStatus = useAppStore((store) => store.interfacesStatus)
- const currentDownload = useAppStore((store) => store.currentDownload)
- const clearCurrentDownload = useAppStore((store) => store.clearCurrentDownload)
+ const downloads = useAppStore((store) => store.downloads)
+ const history = useAppStore((store) => store.history)
+ const view = useAppStore((store) => store.view)
const checkForUpdate = useAppStore((store) => store.checkForUpdate)
useEffect(() => {
checkForUpdate()
}, [checkForUpdate])
- const handleNewDownload = (): void => {
- if (currentDownload) void window.plexo.removeDownload(currentDownload.id)
- clearCurrentDownload()
- }
-
- const handleDownloadAgain = (): void => {
- if (currentDownload) {
- const url = currentDownload.url
- void window.plexo.removeDownload(currentDownload.id)
- clearCurrentDownload()
- useAppStore.getState().setDraftUrl(url)
- }
- }
-
- const noConnections = interfacesStatus === 'ready' && interfaces.length === 0
-
- let screen: React.JSX.Element
- let titleBarStatus: TitleBarStatus = { kind: 'none' }
-
- if (currentDownload) {
- ;({ screen, titleBarStatus } = renderDownload(currentDownload, {
- onNewDownload: handleNewDownload,
- onDownloadAgain: handleDownloadAgain
- }))
- } else if (noConnections) {
- screen = <NoConnectionsScreen />
- titleBarStatus = { kind: 'offline' }
- } else {
- screen = <IdleScreen />
- }
+ // A download that's gone (removed, deleted) leaves the list showing.
+ const shown =
+ view.name === 'download'
+ ? (downloads[view.id] ?? history.find((entry) => entry.id === view.id) ?? null)
+ : null
+ const cancelled = shown && !('unitsWritten' in shown) && shown.status === 'cancelled'
return (
<TooltipProvider>
<div className="flex h-full flex-col">
- <TitleBar status={titleBarStatus} />
- <div className="min-h-0 flex-1">{screen}</div>
+ <TitleBar />
+ <div className="min-h-0 flex-1">
+ {shown && !cancelled ? renderDownload(shown) : <DownloadsScreen />}
+ </div>
+ <StatusBar />
+ <NewDownloadDialog />
<UpdateDialog />
<NetworkBindingDialog />
</div>
diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css
index 03d848c..276e223 100644
--- a/src/renderer/src/assets/main.css
+++ b/src/renderer/src/assets/main.css
@@ -72,6 +72,25 @@
--color-neutral-text: #4b5563;
--color-neutral-onsolid: #ffffff;
+ /* Network colors a user can pick (theme.ts NETWORK_COLOR_SWATCHES): deep enough on white for a
+ white glyph, as the kinds' are. Teal, amber and steel are the kinds' own. */
+ --swatch-teal: #1f8a70;
+ --swatch-teal-onsolid: #ffffff;
+ --swatch-amber: #d97706;
+ --swatch-amber-onsolid: #ffffff;
+ --swatch-steel: #4f64a5;
+ --swatch-steel-onsolid: #ffffff;
+ --swatch-rose: #b5525a;
+ --swatch-rose-onsolid: #ffffff;
+ --swatch-violet: #6c5ac4;
+ --swatch-violet-onsolid: #ffffff;
+ --swatch-lime: #5b8a1e;
+ --swatch-lime-onsolid: #ffffff;
+ --swatch-cyan: #0e7d93;
+ --swatch-cyan-onsolid: #ffffff;
+ --swatch-coral: #c4572a;
+ --swatch-coral-onsolid: #ffffff;
+
--color-accent: #d97706;
--color-accent-onsolid: #ffffff;
--color-success: #1f8a70;
@@ -174,6 +193,23 @@
--color-neutral-text: #a9adb2;
--color-neutral-onsolid: #16181a;
+ --swatch-teal: #4ea89a;
+ --swatch-teal-onsolid: #10201d;
+ --swatch-amber: #d8a44c;
+ --swatch-amber-onsolid: #221806;
+ --swatch-steel: #7e93bd;
+ --swatch-steel-onsolid: #141a26;
+ --swatch-rose: #c97b7b;
+ --swatch-rose-onsolid: #210f0f;
+ --swatch-violet: #9c8fd6;
+ --swatch-violet-onsolid: #17131f;
+ --swatch-lime: #a3c66a;
+ --swatch-lime-onsolid: #161f0d;
+ --swatch-cyan: #6db8c9;
+ --swatch-cyan-onsolid: #0d1a1e;
+ --swatch-coral: #d99168;
+ --swatch-coral-onsolid: #241209;
+
--color-accent: #d8a44c;
--color-accent-onsolid: #1b1408;
--color-success: #4ea89a;
diff --git a/src/renderer/src/components/BlockGrid.tsx b/src/renderer/src/components/BlockGrid.tsx
index da76534..36432bb 100644
--- a/src/renderer/src/components/BlockGrid.tsx
+++ b/src/renderer/src/components/BlockGrid.tsx
@@ -1,6 +1,9 @@
-import type { BlockState, BlockStatus } from '@shared/types'
+import type { DownloadUnitState, TorrentPieceStatus } from '@shared/types'
+import { cn } from 'cn'
+import { ArrowDown, ArrowUp } from 'lucide-react'
import { useCallback, useRef, useState } from 'react'
import type { NetworkVisual } from '../theme'
+import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'
import { formatBytes, type NetworkGroup } from '../utils/format'
// The grid is a byte-space map of the file: one square per chunk, running left-to-right,
@@ -23,10 +26,13 @@ const TARGET_CELL_PX = 12
const CELL_GAP_PX = 3
const CELL_HEIGHT_PX = 13
const MIN_COLS = 8
-// Rows visible before the grid starts scrolling.
-const MAX_VISIBLE_ROWS = 6
+// Rows visible before the grid starts scrolling: few enough that the network table below keeps
+// room for its rows at the window's minimum height.
+const MAX_VISIBLE_ROWS = 4
// Room for the hover outline (1.5px, offset 1) so it isn't clipped against the scroll edges.
const GRID_INSET_PX = 3
+// Rows drawn beyond the visible ones on each side, so a scroll doesn't show blank rows first.
+const BUFFER_ROWS = 2
// A cell whose bytes can't be traced to a network must not borrow a network's color: the brand
// amber IS the USB network's color (--color-accent and --color-usb are the same hex), so the old
@@ -42,7 +48,7 @@ interface CellSegment {
}
interface DisplayCell {
- status: BlockStatus
+ status: TorrentPieceStatus
/** The network that delivered the most bytes here — what the cell reads out as, and what
* colors it when its share is drawn as a single block. */
interfaceId?: string
@@ -53,6 +59,7 @@ interface DisplayCell {
fillRatio: number
totalBytes: number
bytesDownloaded: number
+ provisionalBytes: number
/** 1-based chunk number, matching the "Chunk #N" badges in the streams table so a hovered
* square points back at a specific stream's work. */
chunkNumber: number
@@ -65,7 +72,11 @@ interface DisplayCell {
* retry or a pause/resume handed from one network to another would otherwise be repainted in the
* finishing network's color. `orderedInterfaceIds` fixes the order contributors are listed in, so
* a square's readout doesn't reshuffle between progress pushes. */
-function describeBlocks(blocks: BlockState[], orderedInterfaceIds: string[]): DisplayCell[] {
+function describeBlocks(
+ blocks: DownloadUnitState[],
+ orderedInterfaceIds: string[],
+ firstIndex = 0
+): DisplayCell[] {
return blocks.map((block, index) => {
const totalBytes = block.rangeEnd !== null ? block.rangeEnd - block.rangeStart + 1 : 0
@@ -102,10 +113,15 @@ function describeBlocks(blocks: BlockState[], orderedInterfaceIds: string[]): Di
interfaceId:
dominantInterfaceId ?? (block.status === 'downloading' ? block.interfaceId : undefined),
segments,
- fillRatio: totalBytes > 0 ? block.bytesDownloaded / totalBytes : 0,
+ fillRatio:
+ totalBytes > 0
+ ? (block.bytesDownloaded + (block.kind === 'torrent' ? block.provisionalBytes : 0)) /
+ totalBytes
+ : 0,
totalBytes,
bytesDownloaded: block.bytesDownloaded,
- chunkNumber: index + 1
+ provisionalBytes: block.kind === 'torrent' ? block.provisionalBytes : 0,
+ chunkNumber: firstIndex + index + 1
}
})
}
@@ -138,12 +154,14 @@ function describeContributors(
}
interface BlockGridProps {
- blocks?: BlockState[]
+ blocks?: DownloadUnitState[]
groups: NetworkGroup[]
visuals: NetworkVisual[]
knownSize: boolean
remainingBytes: number
isPaused?: boolean
+ /** A torrent's grid: its blocks are the torrent's pieces. */
+ pieces?: boolean
}
export function BlockGrid({
@@ -152,11 +170,21 @@ export function BlockGrid({
visuals,
knownSize,
remainingBytes,
- isPaused = false
+ isPaused = false,
+ pieces = false
}: BlockGridProps): React.JSX.Element {
+ const unit = pieces ? 'Piece' : 'Chunk'
const [gridWidth, setGridWidth] = useState(0)
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)
const observerRef = useRef<ResizeObserver | null>(null)
+ const scrollerRef = useRef<HTMLDivElement | null>(null)
+ // How far the grid is scrolled: which rows are in view, for the way to what's active (below).
+ const [scrollTop, setScrollTop] = useState(0)
+
+ const fittedCols = Math.floor((gridWidth + CELL_GAP_PX) / (TARGET_CELL_PX + CELL_GAP_PX))
+ // 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 ?? 0, Math.max(MIN_COLS, fittedCols))
// A callback ref rather than useEffect: the measured node only exists on the grid branch
// below, so this has to re-observe whenever that node mounts or unmounts.
@@ -178,33 +206,76 @@ export function BlockGrid({
}
})
- const fittedCols = Math.floor((gridWidth + CELL_GAP_PX) / (TARGET_CELL_PX + CELL_GAP_PX))
- // 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.id)
- const cells = gridWidth > 0 ? describeBlocks(blocks, orderedInterfaceIds) : []
const chunkBytes =
blocks[0].rangeEnd !== null ? blocks[0].rangeEnd - blocks[0].rangeStart + 1 : 0
const rows = Math.ceil(blocks.length / cols)
const visibleRows = Math.min(rows, MAX_VISIBLE_ROWS)
+ // Only the rows in view (and a few either side) are drawn: a big torrent has hundreds of
+ // thousands of pieces. Padding above and below stands in for the rest, so the scroll height
+ // is the whole file's.
+ const rowStride = CELL_HEIGHT_PX + CELL_GAP_PX
+ const startRow = Math.max(0, Math.floor(scrollTop / rowStride) - BUFFER_ROWS)
+ const endRow = Math.min(rows, Math.floor(scrollTop / rowStride) + visibleRows + BUFFER_ROWS)
+ const firstIndex = startRow * cols
+ const cells =
+ gridWidth > 0
+ ? describeBlocks(blocks.slice(firstIndex, endRow * cols), orderedInterfaceIds, firstIndex)
+ : []
// Cut the viewport exactly on a row boundary, so a scrollable grid never shows a half-row
// that could be mistaken for a shorter square.
const gridMaxHeight =
visibleRows * CELL_HEIGHT_PX + (visibleRows - 1) * CELL_GAP_PX + GRID_INSET_PX * 2
+ // The grid stays where it's scrolled: following the work moved it from under the reader, and
+ // a torrent's work is all over the file. When none of what's in flight is in view, a pill
+ // points the way to the nearest of it, and goes there.
+ const firstInView = Math.round(scrollTop / rowStride)
+ const lastInView = firstInView + visibleRows - 1
+ const activeRows = blocks.flatMap((block, index) =>
+ block.status === 'downloading' ? [Math.floor(index / cols)] : []
+ )
+ const nearestActive =
+ rows <= MAX_VISIBLE_ROWS || activeRows.some((row) => row >= firstInView && row <= lastInView)
+ ? null
+ : activeRows.reduce<number | null>((nearest, row) => {
+ const distance = (r: number): number =>
+ r < firstInView ? firstInView - r : r - lastInView
+ return nearest === null || distance(row) < distance(nearest) ? row : nearest
+ }, null)
+ const goToActive = (): void => {
+ if (nearestActive === null) return
+ const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ scrollerRef.current?.scrollTo({
+ // A row of what's before it above, for context.
+ top: Math.max(0, nearestActive - 1) * rowStride,
+ behavior: reduce ? 'auto' : 'smooth'
+ })
+ }
+
// Hovering reads out into the legend line rather than a native `title` tooltip: the grid
// re-renders on every progress push, which resets Chromium's tooltip timer so it never
// appears on an active block — and a tooltip advertises nothing to hover in the first place.
- const hoveredCell = hoveredIndex !== null ? cells[hoveredIndex] : undefined
+ const hoveredCell =
+ hoveredIndex !== null && blocks[hoveredIndex]
+ ? describeBlocks([blocks[hoveredIndex]], orderedInterfaceIds, hoveredIndex)[0]
+ : undefined
let readout: string
if (hoveredCell) {
const where =
describeContributors(hoveredCell, visualByInterfaceId) ??
- (hoveredCell.status === 'pending' ? 'queued' : '—')
- readout = `Chunk #${hoveredCell.chunkNumber} · ${formatBytes(hoveredCell.bytesDownloaded)} / ${formatBytes(hoveredCell.totalBytes)} · ${where}`
+ (hoveredCell.status === 'pending'
+ ? 'queued'
+ : hoveredCell.status === 'skipped'
+ ? 'skipped: in no file chosen'
+ : '—')
+ const provisional =
+ hoveredCell.provisionalBytes > 0
+ ? ` · ${formatBytes(hoveredCell.provisionalBytes)} received, awaiting verification`
+ : ''
+ readout = `${unit} #${hoveredCell.chunkNumber} · ${formatBytes(hoveredCell.bytesDownloaded)} verified${provisional} / ${formatBytes(hoveredCell.totalBytes)} · ${where}`
} else {
- readout = `${blocks.length} chunks · ${formatBytes(chunkBytes)} each`
+ readout = `${blocks.length} ${unit.toLowerCase()}s · ${formatBytes(chunkBytes)} each`
}
return (
@@ -232,99 +303,132 @@ export function BlockGrid({
)}
</div>
- <div
- onMouseLeave={() => setHoveredIndex(null)}
- style={{
- maxHeight: gridMaxHeight,
- // gridMaxHeight is measured including the inset padding, so say so rather than
- // leaning on the global reset — a content-box here would cut a half-row.
- boxSizing: 'border-box',
- overflowY: rows > MAX_VISIBLE_ROWS ? 'auto' : 'visible',
- // The scrollbar takes width from the grid, and the ResizeObserver sits on the grid
- // itself rather than this scroller, so the column count already accounts for it.
- padding: GRID_INSET_PX,
- margin: -GRID_INSET_PX
- }}
- >
+ <div className="relative">
+ {nearestActive !== null && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ onClick={goToActive}
+ aria-label={`Show the ${unit.toLowerCase()}s in progress`}
+ className={cn(
+ 'absolute right-4 z-10 flex size-6 cursor-pointer items-center justify-center rounded-full border-[0.5px] border-[var(--border-strong)] bg-card text-[var(--text-secondary)] shadow-[0_2px_8px_rgba(0,0,0,0.18)] hover:text-foreground dark:shadow-[0_2px_8px_rgba(0,0,0,0.55)] focus-visible:outline-2 focus-visible:outline-ring',
+ nearestActive < firstInView ? '-top-1' : '-bottom-1'
+ )}
+ >
+ {nearestActive < firstInView ? (
+ <ArrowUp aria-hidden className="size-3.5" />
+ ) : (
+ <ArrowDown aria-hidden className="size-3.5" />
+ )}
+ </button>
+ }
+ />
+ <TooltipContent>{`Show the ${unit.toLowerCase()}s in progress`}</TooltipContent>
+ </Tooltip>
+ )}
<div
- ref={measureGrid}
+ ref={scrollerRef}
+ onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
+ onMouseLeave={() => setHoveredIndex(null)}
style={{
- display: 'grid',
- gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`,
- gap: CELL_GAP_PX,
- width: '100%',
- minHeight: CELL_HEIGHT_PX
+ maxHeight: gridMaxHeight,
+ // gridMaxHeight is measured including the inset padding, so say so rather than
+ // leaning on the global reset — a content-box here would cut a half-row.
+ boxSizing: 'border-box',
+ overflowY: rows > MAX_VISIBLE_ROWS ? 'auto' : 'visible',
+ // The scrollbar takes width from the grid, and the ResizeObserver sits on the grid
+ // itself rather than this scroller, so the column count already accounts for it.
+ padding: GRID_INSET_PX,
+ margin: -GRID_INSET_PX
}}
>
- {cells.map((cell, index) => {
- const visual = cell.interfaceId
- ? visualByInterfaceId.get(cell.interfaceId)
- : undefined
+ <div
+ ref={measureGrid}
+ style={{
+ display: 'grid',
+ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`,
+ gap: CELL_GAP_PX,
+ width: '100%',
+ minHeight: CELL_HEIGHT_PX,
+ paddingTop: startRow * rowStride,
+ paddingBottom: (rows - endRow) * rowStride
+ }}
+ >
+ {cells.map((cell, slot) => {
+ const index = firstIndex + slot
+ const visual = cell.interfaceId
+ ? visualByInterfaceId.get(cell.interfaceId)
+ : undefined
- // Base track uses theme-aware tokens (not hardcoded white-based rgba) so a
- // mostly-pending bucket stays visible in light theme, not just dark.
- let background = 'var(--track-bg)'
- let border = '0.5px solid var(--border-strong)'
- let boxShadow = 'none'
- let opacity = 1
- const fillColor = visual?.solid || UNATTRIBUTED_SOLID
+ // Base track uses theme-aware tokens (not hardcoded white-based rgba) so a
+ // mostly-pending bucket stays visible in light theme, not just dark.
+ let background = 'var(--track-bg)'
+ let border = '0.5px solid var(--border-strong)'
+ let boxShadow = 'none'
+ let opacity = 1
+ const fillColor = visual?.solid || UNATTRIBUTED_SOLID
- if (cell.status === 'downloading') {
- background = visual?.bg || UNATTRIBUTED_BG
- border = `1px solid ${visual?.solid || UNATTRIBUTED_SOLID}`
- boxShadow = isPaused ? 'none' : `0 0 7px ${visual?.solid || UNATTRIBUTED_SOLID}`
- opacity = isPaused ? 0.6 : 1
- } else if (cell.status === 'completed') {
- border = 'none'
- opacity = 0.92
- }
+ if (cell.status === 'downloading') {
+ background = visual?.bg || UNATTRIBUTED_BG
+ border = `1px solid ${visual?.solid || UNATTRIBUTED_SOLID}`
+ boxShadow = isPaused ? 'none' : `0 0 7px ${visual?.solid || UNATTRIBUTED_SOLID}`
+ opacity = isPaused ? 0.6 : 1
+ } else if (cell.status === 'completed') {
+ border = 'none'
+ opacity = 0.92
+ } else if (cell.status === 'skipped') {
+ // None of the files chosen needs it: there, but not this download's.
+ border = '0.5px dashed var(--border-strong)'
+ opacity = 0.3
+ }
- const rawFillPercent = Math.min(1, Math.max(0, cell.fillRatio)) * 100
- // A square is only ~12px wide, so the first bytes of a chunk round to nothing —
- // floor a started chunk to a visible sliver rather than 0 width.
- const fillPercent = rawFillPercent > 0 ? Math.max(6, Math.round(rawFillPercent)) : 0
+ const rawFillPercent = Math.min(1, Math.max(0, cell.fillRatio)) * 100
+ // A square is only ~12px wide, so the first bytes of a chunk round to nothing —
+ // floor a started chunk to a visible sliver rather than 0 width.
+ const fillPercent = rawFillPercent > 0 ? Math.max(6, Math.round(rawFillPercent)) : 0
- return (
- <div
- key={index}
- onMouseEnter={() => setHoveredIndex(index)}
- style={{
- position: 'relative',
- height: CELL_HEIGHT_PX,
- borderRadius: 2.5,
- background,
- border,
- boxShadow,
- opacity,
- outline: hoveredIndex === index ? '1.5px solid var(--text-secondary)' : 'none',
- outlineOffset: 1,
- overflow: 'hidden',
- transition: 'opacity 0.3s, box-shadow 0.15s',
- // A multi-GB file can mean thousands of cells; skip layout/paint work for the
- // ones scrolled out of view (MAX_VISIBLE_ROWS caps what's visible, not what's
- // rendered) rather than hand-rolling a virtualized list for a fixed-size grid.
- contentVisibility: 'auto',
- containIntrinsicSize: `${TARGET_CELL_PX}px ${CELL_HEIGHT_PX}px`
- }}
- >
- {/* One square, one color: the network that actually delivered most of this
+ return (
+ <div
+ key={index}
+ onMouseEnter={() => setHoveredIndex(index)}
+ style={{
+ position: 'relative',
+ height: CELL_HEIGHT_PX,
+ borderRadius: 2.5,
+ background,
+ border,
+ boxShadow,
+ opacity,
+ outline:
+ hoveredIndex === index ? '1.5px solid var(--text-secondary)' : 'none',
+ outlineOffset: 1,
+ overflow: 'hidden',
+ transition: 'opacity 0.3s, box-shadow 0.15s'
+ }}
+ >
+ {/* One square, one color: the network that actually delivered most of this
square's bytes. The full per-network breakdown is still exact underneath —
hovering reads it out — but the grid itself stays a glanceable map of which
network owns which stretch of the file rather than a stack of gradients. */}
- {fillPercent > 0 && (
- <div
- style={{
- position: 'absolute',
- inset: 0,
- width: `${fillPercent}%`,
- background: fillColor,
- transition: 'width 0.15s, background 0.15s'
- }}
- />
- )}
- </div>
- )
- })}
+ {fillPercent > 0 && (
+ <div
+ style={{
+ position: 'absolute',
+ inset: 0,
+ width: `${fillPercent}%`,
+ background: fillColor,
+ opacity:
+ cell.provisionalBytes > 0 && cell.bytesDownloaded === 0 ? 0.55 : 1,
+ transition: 'width 0.15s, background 0.15s'
+ }}
+ />
+ )}
+ </div>
+ )
+ })}
+ </div>
</div>
</div>
</div>
diff --git a/src/renderer/src/components/DetailHeader.tsx b/src/renderer/src/components/DetailHeader.tsx
new file mode 100644
index 0000000..d720723
--- /dev/null
+++ b/src/renderer/src/components/DetailHeader.tsx
@@ -0,0 +1,143 @@
+import type { DownloadState, FinishedDownload } from '@shared/types'
+import { ChevronLeft } from 'lucide-react'
+import { useState } from 'react'
+import { useAppStore } from '../store/useAppStore'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger
+} from './ui/alert-dialog'
+import { Button, buttonVariants } from './ui/button'
+import { describeError } from '../utils/format'
+import { Checkbox } from './ui/checkbox'
+
+/** The top of a download's own screen, laid out as the list's header is: the way back to the
+ * list on the left; Remove… and what the download can do next (`children`, the main action
+ * last) on the right. */
+export function DetailHeader({
+ download,
+ children
+}: {
+ download: DownloadState | FinishedDownload
+ children?: React.ReactNode
+}): React.JSX.Element {
+ const setView = useAppStore((store) => store.setView)
+
+ return (
+ <div className="flex h-12 shrink-0 items-center gap-2 border-b-[0.5px] border-border px-5">
+ <button
+ type="button"
+ onClick={() => setView({ name: 'list' })}
+ className="-ml-2 flex items-center gap-1 rounded-md px-1.5 py-1 font-sans text-[15px] leading-none font-medium text-[var(--text-secondary)] hover:text-foreground"
+ >
+ <ChevronLeft className="size-4.5" />
+ Downloads
+ </button>
+ <div className="flex-1" />
+ <RemoveButton download={download} />
+ {children}
+ </div>
+ )
+}
+
+/** Remove…, asked first. An unfinished download loses what it has; a finished one leaves the
+ * list, and its file goes to the Trash only if asked — from where it can still be put back. */
+function RemoveButton({
+ download
+}: {
+ download: DownloadState | FinishedDownload
+}): React.JSX.Element {
+ const setView = useAppStore((store) => store.setView)
+ const [trashFile, setTrashFile] = useState(false)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const finished = 'unitsWritten' in download || download.status === 'completed'
+ const missing = 'missing' in download && download.missing === true
+ const trashName = window.plexo.platform === 'win32' ? 'Recycle Bin' : 'Trash'
+
+ return (
+ <AlertDialog
+ onOpenChange={() => {
+ setTrashFile(false)
+ setError(null)
+ }}
+ >
+ <AlertDialogTrigger
+ render={
+ <Button type="button" variant={finished ? 'secondary' : 'destructive'}>
+ {finished ? 'Remove from list…' : 'Cancel download…'}
+ </Button>
+ }
+ />
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {finished ? 'Remove from list' : 'Cancel download'}: {download.fileName}?
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {finished
+ ? 'This removes the download from your list. Its files stay on your computer.'
+ : 'This stops the download and deletes its downloaded data.'}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {finished &&
+ !missing &&
+ (download.kind !== 'torrent' ||
+ !download.folder ||
+ !('unitsWritten' in download) ||
+ !!download.downloadedFiles?.length) && (
+ <label className="flex items-center gap-2.5 text-[13px]">
+ <Checkbox checked={trashFile} onCheckedChange={setTrashFile} />
+ Also move downloaded files to the {trashName}. Unrelated files stay in place.
+ </label>
+ )}
+ <AlertDialogFooter>
+ {error && (
+ <p role="alert" className="text-[13px] text-destructive">
+ {error}
+ </p>
+ )}
+ <AlertDialogCancel disabled={busy}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ className={buttonVariants({
+ variant: finished && !trashFile ? 'default' : 'destructive',
+ size: 'sm'
+ })}
+ disabled={busy}
+ onClick={(event) => {
+ event.preventDefault()
+ setBusy(true)
+ void window.plexo
+ .removeDownload(download.id, { trashFile })
+ .then(() => {
+ useAppStore.setState((store) => {
+ const downloads = { ...store.downloads }
+ delete downloads[download.id]
+ return {
+ downloads,
+ history: store.history.filter((item) => item.id !== download.id)
+ }
+ })
+ setView({ name: 'list' })
+ })
+ .catch((cause) => setError(describeError(cause)))
+ .finally(() => setBusy(false))
+ }}
+ >
+ {trashFile
+ ? `Move files to ${trashName}`
+ : finished
+ ? 'Remove from list'
+ : 'Cancel download'}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
diff --git a/src/renderer/src/components/DownloadFilterMenu.tsx b/src/renderer/src/components/DownloadFilterMenu.tsx
new file mode 100644
index 0000000..888d99a
--- /dev/null
+++ b/src/renderer/src/components/DownloadFilterMenu.tsx
@@ -0,0 +1,64 @@
+import { Menu } from '@base-ui/react/menu'
+import { Check, ChevronDown } from 'lucide-react'
+import type { DownloadFilter } from '../store/useAppStore'
+
+const DOWNLOAD_FILTERS: { value: DownloadFilter; label: string }[] = [
+ { value: 'all', label: 'All downloads' },
+ { value: 'progress', label: 'In progress' },
+ { value: 'finished', label: 'Finished' },
+ { value: 'failed', label: 'Needs attention' }
+]
+
+export function DownloadFilterMenu({
+ value,
+ counts,
+ onChange
+}: {
+ value: DownloadFilter
+ counts: Record<DownloadFilter, number>
+ onChange: (value: DownloadFilter) => void
+}): React.JSX.Element {
+ const label = DOWNLOAD_FILTERS.find((filter) => filter.value === value)!.label
+ return (
+ <Menu.Root>
+ <h1>
+ <Menu.Trigger className="flex h-8 items-center gap-2 rounded-lg px-2.5 font-sans text-[14px] leading-none font-semibold outline-none hover:bg-secondary focus-visible:ring-2 focus-visible:ring-ring">
+ {label}
+ <ChevronDown aria-hidden className="size-3.5 text-muted-foreground" />
+ </Menu.Trigger>
+ </h1>
+ <Menu.Portal>
+ <Menu.Positioner align="start" sideOffset={8} className="isolate z-50">
+ <Menu.Popup className="w-52 rounded-xl border border-border bg-popover p-1.5 text-popover-foreground shadow-lg outline-none">
+ <Menu.RadioGroup
+ value={value}
+ onValueChange={onChange}
+ aria-label="Filter downloads"
+ className="flex flex-col gap-0.5"
+ >
+ {DOWNLOAD_FILTERS.map((filter) => (
+ <Menu.RadioItem
+ key={filter.value}
+ value={filter.value}
+ label={filter.label}
+ closeOnClick
+ className="flex cursor-default items-center gap-2.5 rounded-md px-2 py-1.5 text-[13px] outline-none data-checked:bg-muted data-highlighted:bg-muted"
+ >
+ <span className="size-4 shrink-0">
+ <Menu.RadioItemIndicator>
+ <Check aria-hidden className="size-4 text-primary" />
+ </Menu.RadioItemIndicator>
+ </span>
+ <span className="flex-1">{filter.label}</span>
+ <span className="font-mono text-[11.5px] text-muted-foreground tabular-nums">
+ {counts[filter.value]}
+ </span>
+ </Menu.RadioItem>
+ ))}
+ </Menu.RadioGroup>
+ </Menu.Popup>
+ </Menu.Positioner>
+ </Menu.Portal>
+ </Menu.Root>
+ )
+}
diff --git a/src/renderer/src/components/FixLinkDialog.tsx b/src/renderer/src/components/FixLinkDialog.tsx
new file mode 100644
index 0000000..7f8525a
--- /dev/null
+++ b/src/renderer/src/components/FixLinkDialog.tsx
@@ -0,0 +1,90 @@
+import type { DownloadState } from '@shared/types'
+import { useState } from 'react'
+import { describeError, formatBytes } from '../utils/format'
+import { Button } from './ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from './ui/dialog'
+import { Input } from './ui/input'
+
+/** Asks for a fresh link to a download whose link stopped working; it carries on from where it
+ * stopped (see DownloadManager.relink). Open while `download` is set. */
+export function FixLinkDialog({
+ download,
+ onClose
+}: {
+ download: DownloadState | null
+ onClose: () => void
+}): React.JSX.Element {
+ const [url, setUrl] = useState('')
+ const [error, setError] = useState<string | null>(null)
+ const [fixing, setFixing] = useState(false)
+
+ const close = (): void => {
+ setUrl('')
+ setError(null)
+ onClose()
+ }
+
+ const handleFix = async (): Promise<void> => {
+ if (!download || !url.trim()) return
+ setFixing(true)
+ setError(null)
+ try {
+ await window.plexo.relinkDownload(download.id, url.trim())
+ close()
+ } catch (failure) {
+ setError(describeError(failure))
+ } finally {
+ setFixing(false)
+ }
+ }
+
+ return (
+ <Dialog
+ disablePointerDismissal
+ open={download !== null}
+ onOpenChange={(open) => !open && close()}
+ >
+ <DialogContent showCloseButton={false}>
+ <DialogHeader>
+ <DialogTitle>Paste a new link</DialogTitle>
+ <DialogDescription>
+ {download &&
+ `Paste a new link to the same file: ${download.fileName}${download.totalBytes > 0 ? ` (${formatBytes(download.totalBytes)})` : ''}. Plexo resumes from where the download stopped.`}
+ </DialogDescription>
+ </DialogHeader>
+ <form
+ className="flex flex-col gap-2"
+ onSubmit={(event) => {
+ event.preventDefault()
+ void handleFix()
+ }}
+ >
+ <Input
+ autoFocus
+ aria-label="New link"
+ placeholder="https://…"
+ value={url}
+ onChange={(event) => setUrl(event.target.value)}
+ className="font-mono"
+ />
+ {error && <div className="text-[12px] text-[var(--color-danger)]">{error}</div>}
+ <DialogFooter>
+ <Button type="button" variant="secondary" onClick={close}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={fixing || !url.trim()}>
+ {fixing ? 'Checking…' : 'Continue download'}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/src/renderer/src/components/LimitsDialog.tsx b/src/renderer/src/components/LimitsDialog.tsx
new file mode 100644
index 0000000..6cc5ede
--- /dev/null
+++ b/src/renderer/src/components/LimitsDialog.tsx
@@ -0,0 +1,696 @@
+import { DATA_LIMIT_PERIODS, dataUsageLabel, nextDataReset } from '@shared/dataLimits'
+import {
+ DEFAULT_SLOW_MODE_SPEED,
+ DOWNLOADS_AT_ONCE,
+ type DataLimitPeriod,
+ type NetworkPreference
+} from '@shared/types'
+import { Minus, Plus } from 'lucide-react'
+import { useEffect, useId, useState } from 'react'
+import { useNetworkUsage } from '../hooks/useNetworks'
+import { useNetworkVisuals } from '../hooks/useNetworkVisuals'
+import { useAppStore } from '../store/useAppStore'
+import { describeError, formatBytes, formatSpeed } from '../utils/format'
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogCancel,
+ AlertDialogAction
+} from './ui/alert-dialog'
+import { Button } from './ui/button'
+import { Dialog, DialogContent, DialogTitle } from './ui/dialog'
+import { Input } from './ui/input'
+import { Switch } from './ui/switch'
+import { ToggleGroup, ToggleGroupItem } from './ui/toggle-group'
+
+/** What the dialog edits: a copy taken when it opens, written back only on Save. */
+type Draft = Pick<
+ ReturnType<typeof useAppStore.getState>,
+ 'speedLimit' | 'slowMode' | 'slowModeSpeed' | 'downloadsAtOnce' | 'networkPreferences'
+>
+
+/** All downloads as a fresh install has them. */
+const GENERAL_DEFAULTS = {
+ speedLimit: undefined,
+ slowMode: false,
+ slowModeSpeed: DEFAULT_SLOW_MODE_SPEED,
+ downloadsAtOnce: DOWNLOADS_AT_ONCE.default
+} satisfies Partial<Draft>
+
+const KB = 1024
+const MB = 1024 ** 2
+const GB = 1024 ** 3
+
+const sectionClass = 'flex flex-col gap-2.5 border-t-[0.5px] border-border py-3'
+const headingClass = 'font-sans text-[14px] leading-none font-semibold'
+const hintClass = 'text-[12.5px] leading-snug text-[var(--text-secondary)]'
+const navLabelClass =
+ 'px-2.5 pt-3 pb-1.5 font-mono text-[10px] tracking-[0.18em] text-muted-foreground uppercase'
+
+/** A number of `unit`s typed in, as bytes; anything that isn't a positive number is ignored. */
+function NumberInput({
+ bytes,
+ unit,
+ unitBytes,
+ label,
+ disabled = false,
+ showUnit = true,
+ onChange
+}: {
+ bytes: number
+ unit: string
+ unitBytes: number
+ label: string
+ disabled?: boolean
+ showUnit?: boolean
+ onChange: (bytes: number) => void
+}): React.JSX.Element {
+ // Keep the draft as typed; changing units remounts it using the same byte value.
+ const [text, setText] = useState(() => String(bytes / unitBytes))
+ return (
+ <span className="flex items-center gap-2">
+ <Input
+ aria-label={label}
+ inputMode="decimal"
+ disabled={disabled}
+ value={text}
+ onChange={(event) => {
+ setText(event.target.value)
+ const value = Number(event.target.value)
+ const converted = Math.round(value * unitBytes)
+ if (Number.isSafeInteger(converted) && converted > 0) onChange(converted)
+ }}
+ className="w-20 text-right font-mono tabular-nums"
+ />
+ {showUnit && <span className="font-mono text-[12px] text-muted-foreground">{unit}</span>}
+ </span>
+ )
+}
+
+function SpeedInput({
+ bytes,
+ label,
+ disabled = false,
+ onChange
+}: {
+ bytes: number
+ label: string
+ disabled?: boolean
+ onChange: (bytes: number) => void
+}): React.JSX.Element {
+ const [unit, setUnit] = useState<'KB/s' | 'MB/s'>(() => (bytes < MB ? 'KB/s' : 'MB/s'))
+ return (
+ <div className="flex items-center gap-2">
+ <NumberInput
+ key={unit}
+ bytes={bytes}
+ unit={unit}
+ unitBytes={unit === 'KB/s' ? KB : MB}
+ label={`${label}, in ${unit}`}
+ disabled={disabled}
+ showUnit={false}
+ onChange={onChange}
+ />
+ <ToggleGroup
+ aria-label={`${label} unit`}
+ value={[unit]}
+ disabled={disabled}
+ onValueChange={(values) => {
+ if (values[0] === 'KB/s' || values[0] === 'MB/s') setUnit(values[0])
+ }}
+ size="sm"
+ spacing={0.5}
+ className="bg-secondary p-0.5"
+ >
+ <ToggleGroupItem value="KB/s">KB/s</ToggleGroupItem>
+ <ToggleGroupItem value="MB/s">MB/s</ToggleGroupItem>
+ </ToggleGroup>
+ </div>
+ )
+}
+
+/** No limit, or an editable limit. Turning it off retains the last value while open. */
+function LimitChoice({
+ label,
+ value,
+ fallback,
+ unit,
+ unitBytes,
+ onChange,
+ children
+}: {
+ children?: React.ReactNode
+ label: string
+ value: number | undefined
+ fallback: number
+ unit: string
+ unitBytes: number
+ onChange: (bytes: number | undefined) => void
+}): React.JSX.Element {
+ const name = useId()
+ const [lastValue, setLastValue] = useState(value ?? fallback)
+ const enabled = value !== undefined
+ const changeValue = (bytes: number): void => {
+ setLastValue(bytes)
+ onChange(bytes)
+ }
+ return (
+ <div role="radiogroup" aria-label={label} className="flex flex-col gap-2">
+ <label className="flex w-fit items-center gap-2.5 text-[13px]">
+ <input
+ type="radio"
+ name={name}
+ checked={!enabled}
+ onChange={() => {
+ if (value !== undefined) setLastValue(value)
+ onChange(undefined)
+ }}
+ className="size-4 accent-[var(--color-accent)]"
+ />
+ No limit
+ </label>
+ <div className="flex flex-wrap items-center gap-2.5">
+ <label className="flex items-center gap-2.5 text-[13px]">
+ <input
+ type="radio"
+ name={name}
+ checked={enabled}
+ onChange={() => onChange(lastValue)}
+ className="size-4 accent-[var(--color-accent)]"
+ />
+ Limit to
+ </label>
+ {unit === 'MB/s' ? (
+ <SpeedInput
+ key={enabled ? 'on' : 'off'}
+ bytes={value ?? lastValue}
+ label={label}
+ disabled={!enabled}
+ onChange={changeValue}
+ />
+ ) : (
+ <NumberInput
+ key={enabled ? 'on' : 'off'}
+ bytes={value ?? lastValue}
+ unit={unit}
+ unitBytes={unitBytes}
+ label={`${label}, in ${unit}`}
+ disabled={!enabled}
+ onChange={changeValue}
+ />
+ )}
+ {children}
+ </div>
+ </div>
+ )
+}
+
+function GeneralPage({
+ running,
+ draft,
+ change
+}: {
+ running: number
+ draft: Draft
+ change: (patch: Partial<Draft>) => void
+}): React.JSX.Element {
+ const { speedLimit, slowMode, slowModeSpeed, downloadsAtOnce } = draft
+ const [confirmReset, setConfirmReset] = useState(false)
+ const atDefaults = Object.entries(GENERAL_DEFAULTS).every(
+ ([key, value]) => draft[key as keyof typeof GENERAL_DEFAULTS] === value
+ )
+
+ return (
+ <>
+ <div className="flex flex-col gap-1 pb-3">
+ <h3 className="font-sans text-[18px] leading-none font-semibold">All downloads</h3>
+ <div className="font-mono text-[12px] text-muted-foreground">
+ {running === 0 ? 'No active downloads' : `${running} downloading right now`}
+ </div>
+ </div>
+
+ <section className={sectionClass}>
+ <h4 className={headingClass}>Total speed</h4>
+ <p className={hintClass}>Limits the combined download speed across all networks.</p>
+ <LimitChoice
+ label="Total speed"
+ value={speedLimit}
+ fallback={20 * MB}
+ unit="MB/s"
+ unitBytes={MB}
+ onChange={(speedLimit) => change({ speedLimit })}
+ />
+ </section>
+
+ <section className={sectionClass}>
+ <h4 className={headingClass}>Slow mode</h4>
+ <p className={hintClass}>
+ Replaces the total speed limit while enabled. Useful during calls or streaming.
+ </p>
+ <div className="flex flex-wrap items-center gap-3">
+ <SpeedInput
+ bytes={slowModeSpeed}
+ label="Slow mode speed"
+ onChange={(slowModeSpeed) => change({ slowModeSpeed })}
+ />
+ <label className="ml-auto flex items-center gap-2 text-[13px]">
+ Enabled
+ <Switch checked={slowMode} onCheckedChange={(slowMode) => change({ slowMode })} />
+ </label>
+ </div>
+ </section>
+
+ <section className={sectionClass}>
+ <h4 className={headingClass}>Downloads at once</h4>
+ <p className={hintClass}>Other downloads wait in the queue and start automatically.</p>
+ <div className="flex items-center gap-3 text-[13.5px]">
+ <div className="flex items-center rounded-lg border border-input">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Decrease simultaneous downloads"
+ disabled={downloadsAtOnce <= DOWNLOADS_AT_ONCE.min}
+ onClick={() => change({ downloadsAtOnce: downloadsAtOnce - 1 })}
+ >
+ <Minus />
+ </Button>
+ <output
+ aria-label="Downloads at once"
+ className="w-8 text-center font-mono tabular-nums"
+ >
+ {downloadsAtOnce}
+ </output>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Increase simultaneous downloads"
+ disabled={downloadsAtOnce >= DOWNLOADS_AT_ONCE.max}
+ onClick={() => change({ downloadsAtOnce: downloadsAtOnce + 1 })}
+ >
+ <Plus />
+ </Button>
+ </div>
+ at the same time
+ </div>
+ </section>
+ <div className="flex flex-wrap items-center gap-2 border-t-[0.5px] border-border pt-3">
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={atDefaults}
+ onClick={() => setConfirmReset(true)}
+ >
+ Reset to defaults…
+ </Button>
+ </div>
+ <AlertDialog open={confirmReset} onOpenChange={setConfirmReset}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Reset all downloads to defaults?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This resets total speed, slow mode and downloads at once. Network limits stay
+ unchanged.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction onClick={() => change(GENERAL_DEFAULTS)}>
+ Reset to defaults
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ )
+}
+
+function NetworkPage({
+ id,
+ name,
+ used,
+ onUsageReset,
+ preference,
+ change
+}: {
+ id: string
+ name: string
+ used: number
+ onUsageReset: () => void
+ preference: NetworkPreference | undefined
+ change: (patch: NetworkPreference) => void
+}): React.JSX.Element {
+ const dataLimit = preference?.dataLimit
+ const period = preference?.dataLimitPeriod ?? 'month'
+ const [reset, setReset] = useState<'usage' | 'limits' | null>(null)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const confirmReset = async (): Promise<void> => {
+ setBusy(true)
+ setError(null)
+ try {
+ if (reset === 'usage') {
+ await window.plexo.resetNetworkUsage(id)
+ onUsageReset()
+ } else change({ speedLimit: undefined, dataLimit: undefined })
+ setReset(null)
+ } catch (cause) {
+ setError(describeError(cause))
+ } finally {
+ setBusy(false)
+ }
+ }
+ const [now, setNow] = useState(() => Date.now())
+ useEffect(() => {
+ const timer = setInterval(() => setNow(Date.now()), 60_000)
+ return () => clearInterval(timer)
+ }, [])
+
+ return (
+ <>
+ <div className="flex flex-col gap-1 pb-3">
+ <h3 className="font-sans text-[18px] leading-none font-semibold">{name}</h3>
+ <div className="font-mono text-[12px] text-muted-foreground">
+ {formatBytes(used)} used by Plexo {dataUsageLabel(period)}
+ </div>
+ </div>
+
+ <section className={sectionClass}>
+ <h4 className={headingClass}>Speed</h4>
+ <p className={hintClass}>Limits the combined download speed on {name}.</p>
+ <LimitChoice
+ label={`${name} speed`}
+ value={preference?.speedLimit}
+ fallback={10 * MB}
+ unit="MB/s"
+ unitBytes={MB}
+ onChange={(speedLimit) => change({ speedLimit })}
+ />
+ </section>
+
+ <section className={sectionClass}>
+ <h4 className={headingClass}>Data limit</h4>
+ <p className={hintClass}>
+ Stops downloads on {name} at the limit. Uploads and other apps don’t count.
+ </p>
+ <LimitChoice
+ label={`${name} data limit`}
+ value={dataLimit}
+ fallback={5 * GB}
+ unit="GB"
+ unitBytes={GB}
+ onChange={(limit) => change({ dataLimit: limit })}
+ >
+ <span className="text-[12px] text-muted-foreground">per</span>
+ <ToggleGroup
+ aria-label={`${name} data limit period`}
+ value={[period]}
+ disabled={dataLimit === undefined}
+ onValueChange={(values) => {
+ const next = values[0]
+ if (next === 'day' || next === 'week' || next === 'month') {
+ change({ dataLimitPeriod: next })
+ }
+ }}
+ size="sm"
+ spacing={0.5}
+ className="bg-secondary p-0.5"
+ >
+ {DATA_LIMIT_PERIODS.map((entry) => (
+ <ToggleGroupItem key={entry.value} value={entry.value}>
+ {entry.label}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ </LimitChoice>
+ {dataLimit !== undefined && (
+ <>
+ <UsageBar used={used} limit={dataLimit} period={period} />
+ <p className="text-[11.5px] text-muted-foreground">
+ Resets{' '}
+ {period === 'day'
+ ? 'tomorrow at midnight'
+ : `on ${nextDataReset(period, now).toLocaleDateString(undefined, { day: 'numeric', month: 'long' })}`}
+ . {period === 'week' && 'Weeks start Monday. '}Raise the limit or reset data usage to
+ keep using this network sooner.
+ </p>
+ </>
+ )}
+ </section>
+ <div className="flex flex-wrap items-center gap-2 border-t-[0.5px] border-border pt-3">
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={busy || used === 0}
+ onClick={() => setReset('usage')}
+ >
+ Reset data usage…
+ </Button>
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={busy || (preference?.speedLimit === undefined && dataLimit === undefined)}
+ onClick={() => setReset('limits')}
+ >
+ Remove limits…
+ </Button>
+ </div>
+ <AlertDialog open={reset !== null} onOpenChange={(open) => !open && !busy && setReset(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {reset === 'usage' ? `Reset data usage for ${name}?` : `Remove limits for ${name}?`}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {reset === 'usage'
+ ? `This resets ${name}’s usage ${dataUsageLabel(period)} to zero. Its configured limits and usage for other periods stay unchanged. Downloads can use this network again if its data limit was reached.`
+ : `This removes ${name}’s speed and data limits. Its recorded data usage stays unchanged. The total speed limit and slow mode still apply.`}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {error && (
+ <p role="alert" className="text-[13px] text-destructive">
+ {error}
+ </p>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={busy}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ disabled={busy}
+ onClick={(event) => {
+ event.preventDefault()
+ void confirmReset()
+ }}
+ >
+ {reset === 'usage' ? 'Reset data usage' : 'Remove limits'}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ )
+}
+
+/** "5.00 of 5 GB this month", with a bar that turns red once the limit is reached. */
+export function UsageBar({
+ used,
+ limit,
+ period = 'month'
+}: {
+ used: number
+ limit: number
+ period?: DataLimitPeriod
+}): React.JSX.Element {
+ const reached = used >= limit
+ const color = reached ? 'var(--color-danger)' : 'var(--color-wifi)'
+ return (
+ <div className="flex items-center gap-3">
+ <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted">
+ <div
+ className="h-full rounded-full"
+ style={{ width: `${Math.min(100, (used / limit) * 100)}%`, background: color }}
+ />
+ </div>
+ <div
+ className={`font-mono text-[11.5px] whitespace-nowrap ${reached ? 'text-[var(--color-danger)]' : 'text-muted-foreground'}`}
+ >
+ {formatBytes(used)} of {formatBytes(limit)} {dataUsageLabel(period)}
+ </div>
+ </div>
+ )
+}
+
+/** One line under a network's name: its limits, or that it has reached one. */
+function describeLimits(preference: NetworkPreference | undefined, used: number): string {
+ if (preference?.dataLimit !== undefined && used >= preference.dataLimit) {
+ return 'Data limit reached'
+ }
+ const parts = [
+ preference?.speedLimit !== undefined && formatSpeed(preference.speedLimit),
+ preference?.dataLimit !== undefined &&
+ `${formatBytes(preference.dataLimit)} per ${preference.dataLimitPeriod ?? 'month'}`
+ ].filter(Boolean)
+ return parts.length > 0 ? parts.join(' · ') : 'No limit'
+}
+
+/** Speed & data limits: every download's together, and each network's. Nothing changes until
+ * Save; Cancel (or Escape) leaves everything as it was. Resetting data usage is the exception:
+ * it's an action, not a setting, so it happens once confirmed. */
+export function LimitsDialog({
+ open,
+ onOpenChange,
+ page,
+ onPageChange
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ /** The network shown, by interface id; null for General. */
+ page: string | null
+ onPageChange: (page: string | null) => void
+}): React.JSX.Element {
+ return (
+ <Dialog open={open} disablePointerDismissal onOpenChange={onOpenChange}>
+ <DialogContent
+ showCloseButton={false}
+ className="flex h-[min(520px,calc(100%-2rem))] max-w-[680px] flex-col gap-0 p-0 sm:max-w-[680px]"
+ >
+ {/* Mounted only while open, so each opening starts a fresh draft. */}
+ <LimitsEditor page={page} onPageChange={onPageChange} onClose={() => onOpenChange(false)} />
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function LimitsEditor({
+ page,
+ onPageChange,
+ onClose
+}: {
+ page: string | null
+ onPageChange: (page: string | null) => void
+ onClose: () => void
+}): React.JSX.Element {
+ const interfaces = useAppStore((store) => store.interfaces)
+ const [draft, setDraft] = useState<Draft>(() => {
+ const { speedLimit, slowMode, slowModeSpeed, downloadsAtOnce, networkPreferences } =
+ useAppStore.getState()
+ return { speedLimit, slowMode, slowModeSpeed, downloadsAtOnce, networkPreferences }
+ })
+ const change = (patch: Partial<Draft>): void =>
+ setDraft((previous) => ({ ...previous, ...patch }))
+ const changeNetwork = (id: string, patch: NetworkPreference): void =>
+ setDraft((previous) => ({
+ ...previous,
+ networkPreferences: {
+ ...previous.networkPreferences,
+ [id]: { ...previous.networkPreferences[id], ...patch }
+ }
+ }))
+ // Only what changed is written, so a running download isn't re-limited for nothing.
+ const save = (): void => {
+ const store = useAppStore.getState()
+ if (draft.speedLimit !== store.speedLimit) store.setSpeedLimit(draft.speedLimit)
+ if (draft.slowMode !== store.slowMode) store.setSlowMode(draft.slowMode)
+ if (draft.slowModeSpeed !== store.slowModeSpeed) store.setSlowModeSpeed(draft.slowModeSpeed)
+ if (draft.downloadsAtOnce !== store.downloadsAtOnce) {
+ store.setDownloadsAtOnce(draft.downloadsAtOnce)
+ }
+ for (const [id, preference] of Object.entries(draft.networkPreferences)) {
+ if (preference !== store.networkPreferences[id]) store.setNetworkPreference(id, preference)
+ }
+ onClose()
+ }
+ const { speedLimit, slowMode, networkPreferences: preferences } = draft
+ const running = useAppStore(
+ (store) =>
+ Object.values(store.downloads).filter((download) => download.status === 'downloading').length
+ )
+ const networkVisual = useNetworkVisuals()
+ const [usageRevision, setUsageRevision] = useState(0)
+ const usage = useNetworkUsage(true, usageRevision)
+ const shown = interfaces.find((iface) => iface.id === page)
+
+ const navItem = (
+ key: string | null,
+ dot: string,
+ name: string,
+ detail: string,
+ warn = false
+ ): React.JSX.Element => (
+ <button
+ key={key ?? 'general'}
+ type="button"
+ aria-current={page === key ? 'page' : undefined}
+ onClick={() => onPageChange(key)}
+ className="flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring aria-[current=page]:bg-primary/10"
+ >
+ <span className="mt-1.5 size-2 shrink-0 rounded-full" style={{ background: dot }} />
+ <span className="flex min-w-0 flex-col gap-1">
+ <span className="truncate text-[13.5px] font-medium">{name}</span>
+ <span
+ className={`font-mono text-[11px] ${warn ? 'text-[var(--color-usb)]' : 'text-muted-foreground'}`}
+ >
+ {detail}
+ </span>
+ </span>
+ </button>
+ )
+
+ return (
+ <>
+ <div className="flex items-center border-b-[0.5px] border-border px-4 py-3">
+ <DialogTitle className="text-[16px] font-semibold">Speed &amp; data limits</DialogTitle>
+ </div>
+ <div className="flex min-h-0 flex-1">
+ <nav className="flex w-[190px] shrink-0 flex-col gap-0.5 overflow-y-auto border-r-[0.5px] border-border p-2">
+ <div className={navLabelClass}>General</div>
+ {navItem(
+ null,
+ 'var(--text-secondary)',
+ 'All downloads',
+ slowMode ? 'Slow mode on' : speedLimit ? formatSpeed(speedLimit) : 'No limit'
+ )}
+ <div className={navLabelClass}>Networks</div>
+ {interfaces.map((iface) => {
+ const visual = networkVisual(iface.id, iface.kind, iface.displayName)
+ const detail = describeLimits(preferences[iface.id], usage[iface.id] ?? 0)
+ return navItem(
+ iface.id,
+ visual.solid,
+ visual.name,
+ detail,
+ detail === 'Data limit reached'
+ )
+ })}
+ </nav>
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 py-3">
+ {shown ? (
+ <NetworkPage
+ key={shown.id}
+ id={shown.id}
+ name={networkVisual(shown.id, shown.kind, shown.displayName).name}
+ used={usage[shown.id] ?? 0}
+ onUsageReset={() => setUsageRevision((value) => value + 1)}
+ preference={preferences[shown.id]}
+ change={(patch) => changeNetwork(shown.id, patch)}
+ />
+ ) : (
+ <GeneralPage running={running} draft={draft} change={change} />
+ )}
+ </div>
+ </div>
+ <div className="flex items-center justify-end gap-2 border-t-[0.5px] border-border px-4 py-2">
+ <Button type="button" variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button type="button" onClick={save}>
+ Save
+ </Button>
+ </div>
+ </>
+ )
+}
diff --git a/src/renderer/src/components/NetworkCard.tsx b/src/renderer/src/components/NetworkCard.tsx
deleted file mode 100644
index 8cc8dad..0000000
--- a/src/renderer/src/components/NetworkCard.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-import type { NetworkInterfaceInfo } from '@shared/types'
-import { useNetworkVisuals } from '../hooks/useNetworkVisuals'
-import { ColorBadge } from './ColorBadge'
-import { NetworkEditPopover } from './NetworkEditPopover'
-import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'
-
-interface NetworkCardProps {
- iface: NetworkInterfaceInfo
- selected: boolean
- latencyMs: number | null | undefined
- onToggle: () => void
-}
-
-function Checkbox({
- checked,
- color,
- onColor
-}: {
- checked: boolean
- color: string
- onColor: string
-}): React.JSX.Element {
- if (checked) {
- return (
- <div
- className="flex size-[15px] shrink-0 items-center justify-center rounded-[4px] font-sans text-[9px] leading-none font-bold shadow-[inset_0_0_0_0.5px_var(--checkbox-shadow)]"
- style={{ background: color, color: onColor }}
- >
- ✓
- </div>
- )
- }
- return (
- <div className="size-[15px] shrink-0 rounded-[4px] border-[0.5px] border-[var(--icon-muted-strong)] bg-[var(--input-bg)] shadow-[inset_0_1px_1px_var(--checkbox-inset-shadow)]" />
- )
-}
-
-export function NetworkCard({
- iface,
- selected,
- latencyMs,
- onToggle
-}: NetworkCardProps): React.JSX.Element {
- const visual = useNetworkVisuals()(iface.id, iface.kind, iface.displayName)
- const hasLatency = latencyMs != null
- const latencyText = hasLatency
- ? 'Latency measured'
- : 'Latency unavailable; downloads may still work'
-
- return (
- <div
- className="flex flex-col gap-[11px] rounded-[11px] border-[0.5px] p-[15px]"
- style={{
- background: selected ? visual.bg : 'var(--bg-secondary)',
- borderColor: selected ? visual.border : 'var(--border)'
- }}
- >
- <div className="flex items-center gap-[9px]">
- <div className="flex min-w-0 flex-1 items-center gap-[9px]">
- <button
- type="button"
- role="checkbox"
- aria-checked={selected}
- onClick={onToggle}
- // min-h-6: WCAG 2.5.8's 24px floor — this is the primary "select this network" control
- // and previously sized to its ~15px content (the checkbox glyph + name text).
- className="flex min-h-6 min-w-0 shrink items-center gap-[9px] border-none bg-transparent p-0 text-left [font:inherit] text-inherit"
- >
- <Checkbox checked={selected} color={visual.solid} onColor={visual.onSolid} />
- <div
- className={`min-w-0 truncate font-sans text-[13px] leading-normal font-semibold ${
- selected ? 'text-foreground' : 'text-[var(--text-secondary)]'
- }`}
- >
- {visual.name}
- </div>
- </button>
- <NetworkEditPopover
- interfaceId={iface.id}
- interfaceKind={iface.kind}
- osName={iface.displayName}
- />
- </div>
- <ColorBadge
- bg={selected ? visual.bg : 'transparent'}
- border={selected ? visual.border : 'var(--border)'}
- text={selected ? visual.text : 'var(--text-tertiary)'}
- className="font-mono text-[10px] tracking-[0.1em]"
- >
- {visual.label}
- </ColorBadge>
- </div>
- <div className="truncate font-mono text-[10.5px] leading-normal text-muted-foreground">
- {iface.device} · {iface.addresses[0]?.address}
- </div>
- <div className="flex items-end justify-between">
- <div className="flex flex-col gap-[5px]">
- <div className="font-mono text-[9px] leading-none font-medium tracking-[0.12em] text-muted-foreground">
- PING
- </div>
- <div
- className="font-mono text-[13px] leading-none font-medium"
- style={{ color: hasLatency && selected ? visual.text : 'var(--text-secondary)' }}
- >
- {hasLatency ? `${latencyMs} ms` : '—'}
- </div>
- </div>
- <Tooltip>
- <TooltipTrigger
- render={
- <span
- role="img"
- tabIndex={0}
- aria-label={latencyText}
- className={`size-[7px] shrink-0 rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/50 ${
- hasLatency ? 'bg-[var(--color-success)]' : 'bg-[var(--icon-muted)]'
- }`}
- />
- }
- />
- <TooltipContent>{latencyText}</TooltipContent>
- </Tooltip>
- </div>
- </div>
- )
-}
diff --git a/src/renderer/src/components/NetworkRow.tsx b/src/renderer/src/components/NetworkRow.tsx
index 34fa877..3af4c5a 100644
--- a/src/renderer/src/components/NetworkRow.tsx
+++ b/src/renderer/src/components/NetworkRow.tsx
@@ -1,8 +1,8 @@
-import type { BlockState, ChunkState, NetworkStatus } from '@shared/types'
+import type { HttpBlockState, HttpStreamState, NetworkStatus } from '@shared/types'
import { useState } from 'react'
import { DANGER, type NetworkVisual } from '../theme'
-import type { NetworkGroup } from '../utils/format'
-import { formatBytes, formatSpeed } from '../utils/format'
+import type { HttpNetworkGroup, NetworkGroup, TorrentNetworkGroup } from '../utils/format'
+import { describeError, formatBytes, formatSpeed } from '../utils/format'
import { ColorBadge } from './ColorBadge'
import { NetworkEditPopover } from './NetworkEditPopover'
import { TruncatedText } from './TruncatedText'
@@ -15,23 +15,18 @@ interface NetworkRowProps {
visual: NetworkVisual
sharePercent: number
totalBytes?: number | null
- blocks?: BlockState[]
+ blocks?: HttpBlockState[]
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'
+ failed: 'Failed',
+ limit: 'Data limit reached'
}
-// Every row — this one and each expanded stream row — is a direct col-span-full subgrid child of
-// DownloadingScreen's networks grid, so all rows share one set of column tracks instead of each
-// re-deriving its own and hoping they line up. The grid's side gutters live *inside* its first and
-// last tracks (see NETWORK_ROW_GRID_COLUMNS), which is what lets a row's divider and fill be a
-// plain border/background on the row itself: its box already reaches both window edges.
const rowClass = 'col-span-full grid grid-cols-subgrid items-center gap-3'
function ProgressBar({
@@ -61,28 +56,263 @@ function ProgressBar({
)
}
-/** What an expanded stream row shows: the block that stream is working on right now and how far
- * along it is. A stream holding no block (idle, or finished) has nothing of its own to measure,
- * so it shows only what it has delivered in total. */
-function describeStream(
- chunk: ChunkState,
- blocks: BlockState[] | undefined
+function streamProgress(
+ stream: HttpStreamState,
+ blocks?: HttpBlockState[]
): {
- block: BlockState | undefined
+ block: HttpBlockState | undefined
+ done: boolean
size: number
downloaded: number
percent: number
- done: boolean
} {
- const block = chunk.currentBlockIndex != null ? blocks?.[chunk.currentBlockIndex] : undefined
- const done = chunk.status === 'completed' || block?.status === 'completed'
- if (!block) {
- return { block, size: 0, downloaded: chunk.bytesDownloaded, percent: done ? 100 : 0, done }
+ const block = stream.currentBlockIndex == null ? undefined : blocks?.[stream.currentBlockIndex]
+ const done = stream.status === 'completed' || block?.status === 'completed'
+ const size = block?.rangeEnd == null ? 0 : block.rangeEnd - block.rangeStart + 1
+ const downloaded = block?.bytesDownloaded ?? stream.bytesDownloaded
+ return {
+ block,
+ done,
+ size,
+ downloaded,
+ percent: done ? 100 : size > 0 ? Math.min(100, (downloaded / size) * 100) : 0
}
+}
+
+function HttpStreamRows({
+ group,
+ visual,
+ blocks
+}: {
+ group: HttpNetworkGroup
+ visual: NetworkVisual
+ blocks?: HttpBlockState[]
+}): React.JSX.Element {
+ return (
+ <>
+ {group.streams.map((stream, index) => {
+ const progress = streamProgress(stream, blocks)
+ const active = stream.status === 'downloading'
+ const status = progress.done
+ ? 'Done'
+ : stream.status === 'paused'
+ ? 'Paused'
+ : stream.status === 'retrying'
+ ? 'Retrying…'
+ : 'Idle'
+ return (
+ <div
+ role="row"
+ key={stream.id}
+ className={`${rowClass} border-[var(--border-subtle)] bg-card py-[6px] font-mono text-[11px] leading-[1.2] ${index === 0 ? 'border-t-[0.5px] pt-[9px]' : ''} ${index === group.streams.length - 1 ? 'border-b-[0.5px] pb-[11px]' : ''}`}
+ >
+ <div role="cell" className="flex justify-center pl-5">
+ <div
+ className="size-[5px] rounded-full"
+ style={{
+ background: active || progress.done ? visual.solid : 'var(--icon-muted)',
+ opacity: active || progress.done ? 1 : 0.4
+ }}
+ />
+ </div>
+ <div role="cell" className="flex min-w-0 items-center gap-[6px]">
+ <span className="font-medium whitespace-nowrap text-foreground">
+ Stream #{index + 1}
+ </span>
+ {progress.block && (
+ <span className="rounded-[3px] border-[0.5px] border-border bg-secondary px-[4.5px] py-[1.5px] text-[9px] leading-none whitespace-nowrap text-muted-foreground">
+ Chunk #{progress.block.index + 1}
+ </span>
+ )}
+ {/* A lit dot and a speed say it's fetching; only what isn't the usual gets a word. */}
+ {active && stream.hedge ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <ColorBadge
+ bg={visual.bg}
+ border={visual.border}
+ text={visual.text}
+ tabIndex={0}
+ className="h-[13px] rounded-[3px] px-[5px] py-px text-[9px] font-semibold tracking-[0.04em] outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ BACKUP
+ </ColorBadge>
+ }
+ />
+ <TooltipContent>
+ Racing another stream for this chunk, which was running slowly
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ !active && (
+ <span
+ className={`text-[9.5px] ${stream.status === 'retrying' ? 'text-destructive' : 'text-muted-foreground'}`}
+ >
+ {status}
+ </span>
+ )
+ )}
+ </div>
+ <ProgressBar
+ className="h-[5px]"
+ label={`Stream #${index + 1} progress`}
+ percent={progress.percent}
+ color={visual.solid}
+ />
+ <div
+ role="cell"
+ className="text-right font-mono text-[11px] leading-none font-medium tabular-nums"
+ style={{
+ color: progress.done ? visual.text : active ? 'var(--text)' : 'var(--text-tertiary)'
+ }}
+ >
+ {shareOf(stream.bytesDownloaded, group.bytesDownloaded)}
+ </div>
+ <div
+ role="cell"
+ className="text-right font-mono text-[11px] leading-none font-medium whitespace-nowrap tabular-nums"
+ style={{ color: active ? visual.text : 'var(--text-tertiary)' }}
+ >
+ {active ? formatSpeed(stream.speedBytesPerSec) : '—'}
+ </div>
+ <div
+ role="cell"
+ className="pr-5 text-right font-mono text-[11px] leading-none whitespace-nowrap text-[var(--text-secondary)] tabular-nums"
+ >
+ {formatBytes(stream.bytesDownloaded)}
+ </div>
+ </div>
+ )
+ })}
+ </>
+ )
+}
+
+/** A share as the table shows it: 0% for nothing, <1% for a sliver, never past 100%. */
+function shareOf(part: number, whole: number): string {
+ if (part <= 0 || whole <= 0) return '0%'
+ const percent = Math.min(100, Math.round((part / whole) * 100))
+ return percent === 0 ? '<1%' : `${percent}%`
+}
- const size = block.rangeEnd !== null ? block.rangeEnd - block.rangeStart + 1 : 0
- const percent = done ? 100 : size > 0 ? Math.min(100, (block.bytesDownloaded / size) * 100) : 0
- return { block, size, downloaded: block.bytesDownloaded, percent, done }
+/** Download, and upload once there is any: the arrows only when both are shown. */
+function TwoWay({
+ down,
+ up,
+ showUp,
+ labels
+}: {
+ down: string
+ up: string
+ showUp: boolean
+ labels: [string, string]
+}): React.JSX.Element {
+ return (
+ <>
+ <div>
+ <span className="sr-only">{labels[0]} </span>
+ {showUp && <span aria-hidden>↓ </span>}
+ {down}
+ </div>
+ {showUp && (
+ <div className="text-muted-foreground">
+ <span className="sr-only">{labels[1]} </span>
+ <span aria-hidden>↑ </span>
+ {up}
+ </div>
+ )}
+ </>
+ )
+}
+
+function PeerRows({
+ group,
+ visual
+}: {
+ group: TorrentNetworkGroup
+ visual: NetworkVisual
+}): React.JSX.Element {
+ // What the network's peers have sent between them: each one's share of it.
+ const received = group.peers.reduce((sum, peer) => sum + peer.bytesDownloaded, 0)
+ return (
+ <>
+ {group.peers.map((peer, index) => {
+ const receiving = peer.status === 'receiving' && peer.speedBytesPerSec > 0
+ const sent = peer.bytesUploaded > 0
+ return (
+ <div
+ role="row"
+ key={peer.id}
+ className={`${rowClass} border-[var(--border-subtle)] bg-card py-[6px] font-mono text-[11px] leading-[1.2] ${index === 0 ? 'border-t-[0.5px] pt-[9px]' : ''} ${index === group.peers.length - 1 ? 'border-b-[0.5px] pb-[11px]' : ''}`}
+ >
+ <div role="cell" className="flex justify-center pl-5">
+ {/* Its state, with its speed: no word needed beside it. */}
+ <div
+ role="img"
+ aria-label={receiving ? 'Receiving' : 'Idle'}
+ className="size-[5px] rounded-full"
+ style={{
+ background: receiving ? visual.solid : 'var(--icon-muted)',
+ opacity: receiving ? 1 : 0.4
+ }}
+ />
+ </div>
+ <div role="cell" className="flex min-w-0 items-center gap-[6px]">
+ <span className="font-medium whitespace-nowrap text-foreground">
+ {/* Unique in the download: a number is never another peer's, here or on
+ another network. */}
+ Peer #{peer.id + 1}
+ </span>
+ {/* The client it runs, as a stream shows its chunk. */}
+ {peer.client && (
+ <span className="min-w-0 truncate rounded-[3px] border-[0.5px] border-border bg-secondary px-[4.5px] py-[1.5px] text-[9px] leading-none whitespace-nowrap text-muted-foreground">
+ {peer.client}
+ </span>
+ )}
+ </div>
+ {/* A peer has no progress of its own: a piece counts once verified, and several
+ peers may send parts of one. */}
+ <div role="cell" className="text-muted-foreground">
+ —
+ </div>
+ <div
+ role="cell"
+ className="text-right font-mono text-[11px] leading-none font-medium tabular-nums"
+ style={{ color: receiving ? 'var(--text)' : 'var(--text-tertiary)' }}
+ >
+ {shareOf(peer.bytesDownloaded, received)}
+ </div>
+ <div
+ role="cell"
+ className="text-right font-mono text-[11px] leading-[1.35] font-medium whitespace-nowrap tabular-nums"
+ style={{ color: receiving ? visual.text : 'var(--text-tertiary)' }}
+ >
+ <TwoWay
+ down={receiving ? formatSpeed(peer.speedBytesPerSec) : '—'}
+ up={
+ peer.uploadSpeedBytesPerSec > 0 ? formatSpeed(peer.uploadSpeedBytesPerSec) : '—'
+ }
+ showUp={sent}
+ labels={['Receiving at', 'Sending at']}
+ />
+ </div>
+ <div
+ role="cell"
+ className="pr-5 text-right font-mono text-[11px] leading-[1.35] whitespace-nowrap text-[var(--text-secondary)] tabular-nums"
+ >
+ <TwoWay
+ down={formatBytes(peer.bytesDownloaded)}
+ up={formatBytes(peer.bytesUploaded)}
+ showUp={sent}
+ labels={['Received', 'Sent']}
+ />
+ </div>
+ </div>
+ )
+ })}
+ </>
+ )
}
export function NetworkRow({
@@ -94,12 +324,15 @@ export function NetworkRow({
onSwitch
}: NetworkRowProps): React.JSX.Element {
const [expanded, setExpanded] = useState(false)
+ const connections = group.transfer === 'http' ? group.streams : group.peers
+ const isActive =
+ group.transfer === 'http'
+ ? group.streams.some((stream) => stream.status === 'downloading')
+ : group.peers.some((peer) => peer.status === 'receiving')
const hasError = group.status === 'failed'
- const isActive = group.chunks.some((chunk) => chunk.status === 'downloading')
-
const rounded = Math.round(sharePercent)
const shareLabel = group.bytesDownloaded === 0 ? '0%' : rounded === 0 ? '<1%' : `${rounded}%`
-
+ const noun = group.transfer === 'http' ? 'stream' : 'peer'
return (
<>
<div
@@ -117,7 +350,6 @@ export function NetworkRow({
}}
/>
<div role="cell" className="flex min-w-0 items-center gap-[6px]">
- {/* Switching off the last network in use pauses the download. */}
<Checkbox
checked={group.enabled}
onCheckedChange={(checked) => onSwitch(checked)}
@@ -127,25 +359,24 @@ export function NetworkRow({
/>
<TruncatedText
text={visual.name}
- className={`font-sans text-[12.5px] leading-[1.2] font-semibold ${
- group.enabled ? 'text-foreground' : 'text-[var(--text-secondary)]'
- }`}
+ className={`font-sans text-[12.5px] leading-[1.2] font-semibold ${group.enabled ? 'text-foreground' : 'text-[var(--text-secondary)]'}`}
/>
<NetworkEditPopover
interfaceId={group.id}
interfaceKind={group.kind}
osName={group.label}
/>
- {group.chunks.length > 0 && (
+ {connections.length > 0 && (
<Button
type="button"
variant="outline"
size="xs"
- onClick={() => setExpanded((v) => !v)}
+ onClick={() => setExpanded((value) => !value)}
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'}
+ {connections.length} {noun}
+ {connections.length === 1 ? '' : 's'}{' '}
<span aria-hidden className="text-[7.5px] opacity-75">
{expanded ? '▲' : '▼'}
</span>
@@ -157,15 +388,15 @@ export function NetworkRow({
render={
<span
tabIndex={group.error ? 0 : undefined}
- className={`rounded-sm font-mono text-[10px] whitespace-nowrap outline-none focus-visible:ring-2 focus-visible:ring-ring/50 ${
- hasError ? 'text-destructive' : 'text-muted-foreground'
- }`}
+ className={`rounded-sm font-mono text-[10px] whitespace-nowrap outline-none ${hasError ? 'text-destructive' : 'text-muted-foreground'}`}
>
- {STATUS_TEXT[group.status]}
+ {group.status === 'unreachable' && group.transfer === 'torrent'
+ ? 'Can’t reach peers'
+ : STATUS_TEXT[group.status]}
</span>
}
/>
- <TooltipContent>{group.error}</TooltipContent>
+ <TooltipContent>{group.error && describeError(group.error)}</TooltipContent>
</Tooltip>
)}
</div>
@@ -188,135 +419,40 @@ export function NetworkRow({
</div>
<div
role="cell"
- className="text-right font-mono text-[12.5px] leading-none font-semibold tabular-nums"
+ className="text-right font-mono text-[11px] leading-[1.35] font-semibold whitespace-nowrap tabular-nums"
style={{ color: isActive ? visual.text : 'var(--text-tertiary)' }}
>
- {isActive ? formatSpeed(group.speedBytesPerSec) : '—'}
+ <TwoWay
+ down={isActive ? formatSpeed(group.speedBytesPerSec) : '—'}
+ // Like down: a dash while nothing is going out. Each direction is idle on its own.
+ up={
+ group.transfer === 'torrent' && group.uploadSpeedBytesPerSec > 0
+ ? formatSpeed(group.uploadSpeedBytesPerSec)
+ : '—'
+ }
+ // Always for a torrent, so it's plain each network uploads too.
+ showUp={group.transfer === 'torrent'}
+ labels={['Downloading at', 'Uploading at']}
+ />
</div>
<div
role="cell"
- className="pr-5 text-right font-mono text-[11.5px] leading-none text-[var(--text-secondary)] tabular-nums"
+ className="pr-5 text-right font-mono text-[11.5px] leading-[1.35] text-[var(--text-secondary)] tabular-nums"
>
- {formatBytes(group.bytesDownloaded)}
+ <TwoWay
+ down={formatBytes(group.bytesDownloaded)}
+ up={formatBytes(group.transfer === 'torrent' ? group.bytesUploaded : 0)}
+ showUp={group.transfer === 'torrent'}
+ labels={['Downloaded', 'Uploaded']}
+ />
</div>
</div>
-
{expanded &&
- group.chunks.map((chunk, index) => {
- const isFirst = index === 0
- const isLast = index === group.chunks.length - 1
- const isChunkActive = chunk.status === 'downloading'
- const stream = describeStream(chunk, blocks)
- const statusText = stream.done
- ? 'Done'
- : chunk.status === 'paused'
- ? 'Paused'
- : chunk.status === 'retrying'
- ? 'Retrying…'
- : 'Idle'
-
- return (
- <div
- role="row"
- key={chunk.id}
- className={`${rowClass} border-[var(--border-subtle)] bg-card py-[6px] font-mono text-[11px] leading-[1.2] ${
- isFirst ? 'border-t-[0.5px] pt-[9px]' : ''
- } ${isLast ? 'border-b-[0.5px] pb-[11px]' : ''}`}
- >
- <div role="cell" className="flex justify-center pl-5">
- <div
- className="size-[5px] rounded-full"
- style={{
- background: isChunkActive || stream.done ? visual.solid : 'var(--icon-muted)',
- opacity: isChunkActive || stream.done ? 1 : 0.4
- }}
- />
- </div>
-
- <div role="cell" className="flex min-w-0 items-center gap-[6px]">
- <span className="font-medium whitespace-nowrap text-foreground">
- Stream #{index + 1}
- </span>
- {stream.block && (
- <span className="rounded-[3px] border-[0.5px] border-border bg-secondary px-[4.5px] py-[1.5px] font-mono text-[9px] leading-none whitespace-nowrap text-muted-foreground">
- Chunk #{stream.block.index + 1}
- </span>
- )}
- {isChunkActive ? (
- <Tooltip disabled={!chunk.hedge}>
- <TooltipTrigger
- render={
- <ColorBadge
- bg={visual.bg}
- border={visual.border}
- text={visual.text}
- tabIndex={chunk.hedge ? 0 : undefined}
- // Height is pinned, not `h-auto`: this badge swaps in and out as a
- // stream goes active, and the cell is only as tall as "Stream #N"
- // (13.2px). Left to size itself the badge came out taller than that and
- // grew the row on every swap. 13px keeps it under, whatever line-height
- // it ends up inheriting.
- className="h-[13px] rounded-[3px] px-[5px] py-px text-[9px] font-semibold tracking-[0.04em] outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
- >
- {chunk.hedge ? 'BACKUP' : 'ACTIVE'}
- </ColorBadge>
- }
- />
- <TooltipContent>
- Racing another stream for this chunk, which was running slowly
- </TooltipContent>
- </Tooltip>
- ) : (
- <span
- className={`text-[9.5px] ${
- chunk.status === 'retrying' ? 'text-destructive' : 'text-muted-foreground'
- }`}
- >
- {statusText}
- </span>
- )}
- </div>
-
- <ProgressBar
- className="h-[5px]"
- label={`Stream #${index + 1} progress`}
- percent={stream.percent}
- color={visual.solid}
- />
-
- <div
- role="cell"
- className="text-right font-mono text-[11px] leading-none font-medium tabular-nums"
- style={{
- color: stream.done
- ? visual.text
- : isChunkActive
- ? 'var(--text)'
- : 'var(--text-tertiary)'
- }}
- >
- {stream.block || stream.done ? `${Math.round(stream.percent)}%` : '—'}
- </div>
-
- <div
- role="cell"
- className="text-right font-mono text-[11px] leading-none font-medium tabular-nums"
- style={{ color: isChunkActive ? visual.text : 'var(--text-tertiary)' }}
- >
- {isChunkActive ? formatSpeed(chunk.speedBytesPerSec) : '—'}
- </div>
-
- <div
- role="cell"
- className="pr-5 text-right font-mono text-[11px] leading-none whitespace-nowrap text-[var(--text-secondary)] tabular-nums"
- >
- {stream.size > 0
- ? `${formatBytes(stream.downloaded)} / ${formatBytes(stream.size)}`
- : formatBytes(stream.downloaded)}
- </div>
- </div>
- )
- })}
+ (group.transfer === 'http' ? (
+ <HttpStreamRows group={group} visual={visual} blocks={blocks} />
+ ) : (
+ <PeerRows group={group} visual={visual} />
+ ))}
</>
)
}
diff --git a/src/renderer/src/components/NetworksMenu.tsx b/src/renderer/src/components/NetworksMenu.tsx
new file mode 100644
index 0000000..85cfd56
--- /dev/null
+++ b/src/renderer/src/components/NetworksMenu.tsx
@@ -0,0 +1,169 @@
+import { ChevronDown, ChevronRight } from 'lucide-react'
+import { useState } from 'react'
+import { useLatencyPolling, useNetworkUsage } from '../hooks/useNetworks'
+import { useNetworkVisuals } from '../hooks/useNetworkVisuals'
+import { useAppStore } from '../store/useAppStore'
+import { formatSpeed } from '../utils/format'
+import { UsageBar } from './LimitsDialog'
+import { NetworkEditPopover } from './NetworkEditPopover'
+import { Popover, PopoverContent, PopoverTrigger } from './ui/popover'
+import { Button } from './ui/button'
+import { Switch } from './ui/switch'
+
+/** The networks new downloads combine, switched on or off here; each download can still change
+ * its own. Also how fast each is going right now, and how much of its data limit is left. */
+export function NetworksMenu({
+ onOpenLimits
+}: {
+ /** Opens Speed & data limits on that network's page, or General for null. */
+ onOpenLimits: (page: string | null) => void
+}): React.JSX.Element {
+ const interfaces = useAppStore((store) => store.interfaces)
+ const preferences = useAppStore((store) => store.networkPreferences)
+ const setNetworkPreference = useAppStore((store) => store.setNetworkPreference)
+ const downloads = useAppStore((store) => store.downloads)
+ const networkVisual = useNetworkVisuals()
+ const latencies = useAppStore((store) => store.latencies)
+ const [open, setOpen] = useState(false)
+ const usage = useNetworkUsage(open)
+ useLatencyPolling(open)
+
+ // Every running download's speed over each network, added up.
+ const speeds = new Map<string, number>()
+ for (const download of Object.values(downloads)) {
+ if (download.status !== 'downloading') continue
+ for (const network of download.networks) {
+ speeds.set(network.id, (speeds.get(network.id) ?? 0) + network.speedBytesPerSec)
+ }
+ }
+ const total = [...speeds.values()].reduce((sum, speed) => sum + speed, 0)
+ const on = interfaces.filter((iface) => !preferences[iface.id]?.off)
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ render={<Button type="button" variant="secondary" className="gap-2.5 px-3 text-[13px]" />}
+ >
+ <span className="flex gap-1" aria-hidden>
+ {interfaces.slice(0, 4).map((iface) => (
+ <span
+ key={iface.id}
+ className="size-2 rounded-full"
+ style={{
+ background: networkVisual(iface.id, iface.kind, iface.displayName).solid,
+ opacity: preferences[iface.id]?.off ? 0.3 : 1
+ }}
+ />
+ ))}
+ </span>
+ {interfaces.length === 0 ? (
+ <span className="text-[var(--color-danger)]">No network</span>
+ ) : (
+ <>
+ {on.length} {on.length === 1 ? 'network' : 'networks'}
+ {total > 0 && (
+ <span className="font-mono text-[11.5px] text-muted-foreground">
+ {formatSpeed(total)}
+ </span>
+ )}
+ </>
+ )}
+ <ChevronDown className="size-3.5 text-muted-foreground" />
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-[340px] gap-0 p-0">
+ <div className="flex flex-col gap-1.5 border-b-[0.5px] border-border p-4">
+ <div className="text-[14px] font-semibold">Default networks</div>
+ <div className="text-[12.5px] leading-snug text-[var(--text-secondary)]">
+ New downloads combine the networks turned on here. You can change this for any single
+ download.
+ </div>
+ </div>
+ {interfaces.map((iface) => {
+ const visual = networkVisual(iface.id, iface.kind, iface.displayName)
+ const preference = preferences[iface.id]
+ const used = usage[iface.id] ?? 0
+ const dataLimit = preference?.dataLimit
+ const reached = dataLimit !== undefined && used >= dataLimit
+ const speed = speeds.get(iface.id) ?? 0
+ return (
+ <div
+ key={iface.id}
+ // The whole row opens this network's limits (the chevron's button stretches over it);
+ // the switch and the pencil sit above it and do their own thing.
+ className="group relative flex flex-col gap-2 border-b-[0.5px] border-border px-4 py-3 hover:bg-muted"
+ >
+ <div className="flex items-center gap-3">
+ <span
+ className="size-2 shrink-0 rounded-full"
+ style={{ background: visual.solid }}
+ />
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-1">
+ <span className="truncate text-[13.5px] font-medium">{visual.name}</span>
+ <span className="relative z-10 flex">
+ <NetworkEditPopover
+ interfaceId={iface.id}
+ interfaceKind={iface.kind}
+ osName={iface.displayName}
+ />
+ </span>
+ </div>
+ <div
+ className={`font-mono text-[11px] ${reached ? 'text-[var(--color-danger)]' : 'text-muted-foreground'}`}
+ >
+ {reached
+ ? 'Data limit reached'
+ : [
+ iface.displayName,
+ speed > 0 ? formatSpeed(speed) : 'Idle',
+ typeof latencies[iface.id] === 'number' &&
+ `${Math.round(latencies[iface.id]!)} ms`
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </div>
+ </div>
+ <Switch
+ className="relative z-10"
+ aria-label={`Use ${visual.name} for new downloads`}
+ checked={!preference?.off}
+ onCheckedChange={(checked) =>
+ setNetworkPreference(iface.id, { off: checked ? undefined : true })
+ }
+ />
+ <button
+ type="button"
+ aria-label={`${visual.name} limits`}
+ className="text-muted-foreground outline-none group-hover:text-foreground after:absolute after:inset-0 focus-visible:after:ring-2 focus-visible:after:ring-ring focus-visible:after:ring-inset"
+ onClick={() => {
+ setOpen(false)
+ onOpenLimits(iface.id)
+ }}
+ >
+ <ChevronRight className="size-4" />
+ </button>
+ </div>
+ {dataLimit !== undefined && (
+ <UsageBar
+ used={used}
+ limit={dataLimit}
+ period={preference?.dataLimitPeriod ?? 'month'}
+ />
+ )}
+ </div>
+ )
+ })}
+ <button
+ type="button"
+ className="px-4 py-3 text-[13px] font-medium text-primary hover:underline"
+ onClick={() => {
+ setOpen(false)
+ onOpenLimits(null)
+ }}
+ >
+ Speed &amp; data limits…
+ </button>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/src/renderer/src/components/NewDownloadDialog.tsx b/src/renderer/src/components/NewDownloadDialog.tsx
new file mode 100644
index 0000000..64fad65
--- /dev/null
+++ b/src/renderer/src/components/NewDownloadDialog.tsx
@@ -0,0 +1,472 @@
+import type { ProbeResult } from '@shared/types'
+import { cn } from 'cn'
+import { AlertTriangle, FolderOpen, X } from 'lucide-react'
+import { useEffect, useRef, useState } from 'react'
+import { useNetworkVisuals } from '../hooks/useNetworkVisuals'
+import { useAppStore } from '../store/useAppStore'
+import {
+ acceptedLink,
+ describeError,
+ describeFileCount,
+ fileExtensionBadge,
+ formatBytes,
+ toDisplayPath
+} from '../utils/format'
+import { Button } from './ui/button'
+import { Dialog, DialogContent, DialogTitle } from './ui/dialog'
+import { ToggleGroup, ToggleGroupItem } from './ui/toggle-group'
+import { TorrentFileList } from './TorrentFiles'
+import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'
+
+type ProbeState =
+ | { status: 'idle' }
+ | { status: 'probing' }
+ | { status: 'ready'; result: ProbeResult }
+ | { status: 'error'; message: string }
+
+const PROBE_DEBOUNCE_MS = 600
+
+type StreamsChoice = 'auto' | number
+/** Streams per network the user can pick instead of Auto. */
+const STREAMS_CHOICES: StreamsChoice[] = ['auto', 4, 8, 16, 32]
+
+const labelClass = 'w-16 shrink-0 text-[12.5px] text-[var(--text-secondary)]'
+
+/** New download: a link, then only what differs from one download to the next — its name (or a
+ * torrent's files), where it goes, over which networks, and how many streams each runs. Everything set once for every
+ * download lives in Speed & data limits and the networks menu. */
+export function NewDownloadDialog(): React.JSX.Element {
+ const open = useAppStore((store) => store.newDownloadOpen)
+ const close = useAppStore((store) => store.closeNewDownload)
+
+ return (
+ <Dialog open={open} disablePointerDismissal onOpenChange={(next) => !next && close()}>
+ <DialogContent
+ showCloseButton={false}
+ className="flex max-h-[calc(100%-2rem)] flex-col gap-0 p-0 sm:max-w-[560px]"
+ >
+ {/* Mounted only while open, so each opening starts fresh from the link field. */}
+ {open && <NewDownloadForm onDone={close} />}
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element {
+ const interfaces = useAppStore((store) => store.interfaces)
+ const homeDir = useAppStore((store) => store.homeDir)
+ const url = useAppStore((store) => store.draftUrl)
+ const setUrl = useAppStore((store) => store.setDraftUrl)
+ const destinationDir = useAppStore((store) => store.destinationDir)
+ const setDestinationDir = useAppStore((store) => store.setDestinationDir)
+ const full = useAppStore(
+ (store) =>
+ Object.values(store.downloads).filter((download) => download.status === 'downloading')
+ .length >= store.downloadsAtOnce
+ )
+ const networkVisual = useNetworkVisuals()
+ const linkInput = useRef<HTMLInputElement>(null)
+
+ const [probe, setProbe] = useState<ProbeState>({ status: 'idle' })
+ // Tracks deselections rather than selections, so a newly-detected interface starts selected.
+ // Starts from the default networks: the ones switched off in the networks menu.
+ const [deselectedInterfaceIds, setDeselectedInterfaceIds] = useState<string[]>(() =>
+ Object.entries(useAppStore.getState().networkPreferences)
+ .filter(([, preference]) => preference.off)
+ .map(([id]) => id)
+ )
+ const [starting, setStarting] = useState(false)
+ const [startError, setStartError] = useState<string | null>(null)
+ const [fileNameOverride, setFileNameOverride] = useState<string | null>(null)
+ // A torrent's files left out, by index: every file is downloaded unless unticked.
+ const [skippedFiles, setSkippedFiles] = useState<number[]>([])
+ // For this download only: the next one starts on Auto again.
+ const [streamsChoice, setStreamsChoice] = useState<StreamsChoice>('auto')
+
+ // Opened with nothing in it: a link on the clipboard is most likely what it's for, as download
+ // managers have long assumed. Anything else on the clipboard is left alone.
+ useEffect(() => {
+ if (useAppStore.getState().draftUrl) return
+ void window.plexo
+ .readClipboardText()
+ .then((text) => {
+ const link = acceptedLink(text)
+ const { draftUrl, startedUrl } = useAppStore.getState()
+ if (link && link !== startedUrl && !draftUrl) setUrl(link)
+ })
+ .catch(() => {})
+ }, [setUrl])
+
+ useEffect(() => {
+ const trimmed = url.trim()
+ if (!trimmed) {
+ // Resetting derived probe state when its trigger (the URL) is cleared.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setProbe({ status: 'idle' })
+ setFileNameOverride(null)
+ setSkippedFiles([])
+ return
+ }
+
+ // Set once the link changes, cleared included: a magnet can take a while to answer, and its
+ // answer is no longer wanted then.
+ let stale = false
+ setProbe({ status: 'probing' })
+ setFileNameOverride(null)
+ setSkippedFiles([])
+ const timer = setTimeout(async () => {
+ try {
+ const result = await window.plexo.probeUrl(trimmed)
+ if (stale) return
+ setProbe({ status: 'ready', result })
+ } catch (error) {
+ if (stale) return
+ setProbe({ status: 'error', message: describeError(error) })
+ }
+ }, PROBE_DEBOUNCE_MS)
+
+ return () => {
+ stale = true
+ clearTimeout(timer)
+ }
+ }, [url])
+
+ const ready = probe.status === 'ready' ? probe.result : null
+ const torrent = ready?.kind === 'torrent' ? ready.torrent : null
+ const chosenFiles = torrent
+ ? torrent.files.flatMap((_, index) => (skippedFiles.includes(index) ? [] : [index]))
+ : []
+ // What will be downloaded: a torrent's chosen files, or the whole file.
+ const sizeToFetch = torrent
+ ? chosenFiles.reduce((sum, index) => sum + torrent.files[index].length, 0)
+ : (ready?.totalBytes ?? null)
+ const multiChunkAllowed = ready !== null && ready.supportsRanges && ready.totalBytes !== null
+ const isSingleStreamOnly = ready !== null && !multiChunkAllowed
+
+ const detectedIds = interfaces.map((iface) => iface.id)
+ const enabledIds = detectedIds.filter((id) => !deselectedInterfaceIds.includes(id))
+ const selectedInterfaceIds = isSingleStreamOnly ? enabledIds.slice(0, 1) : enabledIds
+
+ const canStart =
+ probe.status === 'ready' &&
+ (!torrent || chosenFiles.length > 0) &&
+ selectedInterfaceIds.length > 0 &&
+ Boolean(destinationDir) &&
+ !starting
+ const startLabel = starting
+ ? 'Starting…'
+ : probe.status === 'probing'
+ ? 'Checking…'
+ : full
+ ? 'Add to queue'
+ : 'Download'
+
+ // Two networks on one subnet: the OS sends both down one route, so there's nothing to combine.
+ let subnetConflict: { subnet: string; names: string[] } | null = null
+ if (selectedInterfaceIds.length > 1) {
+ const subnets = new Map<string, string[]>()
+ for (const id of selectedInterfaceIds) {
+ const iface = interfaces.find((i) => i.id === id)
+ const subnet = iface?.addresses.find((address) => address.family === 4)?.subnet
+ if (subnet && iface) {
+ const names = subnets.get(subnet) ?? []
+ names.push(networkVisual(iface.id, iface.kind, iface.displayName).name)
+ subnets.set(subnet, names)
+ }
+ }
+ for (const [subnet, names] of subnets.entries()) {
+ if (names.length > 1) {
+ subnetConflict = { subnet, names }
+ break
+ }
+ }
+ }
+
+ const handleToggleInterface = (id: string): void => {
+ if (isSingleStreamOnly) {
+ // Single-stream mode can only download through 1 interface at a time
+ setDeselectedInterfaceIds(detectedIds.filter((otherId) => otherId !== id))
+ return
+ }
+ setDeselectedInterfaceIds((prev) => {
+ if (prev.includes(id)) return prev.filter((entry) => entry !== id)
+ // Keep at least 1 interface selected
+ const remaining = detectedIds.filter((other) => !prev.includes(other) && other !== id)
+ return remaining.length === 0 ? prev : [...prev, id]
+ })
+ }
+
+ const handleBrowse = async (): Promise<void> => {
+ const chosen = await window.plexo.chooseDestinationFolder(destinationDir)
+ if (chosen) setDestinationDir(chosen)
+ }
+
+ // A .torrent file goes in the link field as its path; the probe reads it from there.
+ const handleOpenTorrent = async (): Promise<void> => {
+ const path = await window.plexo.chooseTorrentFile()
+ if (path) setUrl(path)
+ }
+
+ const handleStart = async (): Promise<void> => {
+ if (probe.status !== 'ready' || !canStart) return
+ setStarting(true)
+ setStartError(null)
+ try {
+ const common = {
+ url: probe.result.finalUrl,
+ destinationDir,
+ suggestedFileName: fileNameOverride?.trim() || probe.result.suggestedFileName,
+ totalBytes: probe.result.totalBytes ?? 0,
+ supportsRanges: multiChunkAllowed,
+ interfaceIds: selectedInterfaceIds,
+ etag: probe.result.etag,
+ lastModified: probe.result.lastModified
+ }
+ const id = await window.plexo.startDownload(
+ probe.result.kind === 'torrent'
+ ? {
+ ...common,
+ kind: 'torrent',
+ infoHash: probe.result.torrent.infoHash,
+ selectedFiles: skippedFiles.length > 0 ? chosenFiles : undefined
+ }
+ : {
+ ...common,
+ kind: 'http',
+ streamsPerNetwork: streamsChoice === 'auto' ? undefined : streamsChoice
+ }
+ )
+ // Started: the link is spent, so the next download starts from an empty one. Its own
+ // screen opens, unless it was only added to the queue.
+ useAppStore.setState({
+ startedUrl: url.trim(),
+ draftUrl: '',
+ ...(full ? {} : { view: { name: 'download', id } as const })
+ })
+ onDone()
+ } catch (error) {
+ setStartError(describeError(error))
+ setStarting(false)
+ }
+ }
+
+ const fileName = ready ? (fileNameOverride ?? ready.suggestedFileName) : ''
+
+ return (
+ <form
+ className="flex min-h-0 flex-col"
+ onSubmit={(event) => {
+ event.preventDefault()
+ void handleStart()
+ }}
+ >
+ <div className="border-b-[0.5px] border-border px-5 py-4">
+ <DialogTitle className="text-[16px] font-semibold">New download</DialogTitle>
+ </div>
+
+ <div className="flex min-h-0 flex-col gap-3.5 overflow-y-auto px-5 py-4">
+ <div className="flex items-center gap-2">
+ <div
+ className={cn(
+ 'flex h-9 min-w-0 flex-1 items-center gap-2 rounded-[9px] border bg-[var(--input-bg)] px-3',
+ probe.status === 'error' ? 'border-destructive' : 'border-input'
+ )}
+ >
+ <input
+ ref={linkInput}
+ autoFocus
+ type="text"
+ value={url}
+ onChange={(event) => setUrl(event.target.value)}
+ placeholder="Paste a link: https:// or magnet:"
+ spellCheck={false}
+ aria-label="Link"
+ className="min-w-0 flex-1 border-none bg-transparent font-mono text-[13px] text-foreground outline-none"
+ />
+ {url && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ onClick={() => {
+ setUrl('')
+ linkInput.current?.focus()
+ }}
+ aria-label="Clear link"
+ className="flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground hover:bg-secondary hover:text-foreground"
+ >
+ <X aria-hidden className="size-3.5" />
+ </button>
+ }
+ />
+ <TooltipContent>Clear link</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ <Button type="button" variant="secondary" onClick={handleOpenTorrent} className="h-9">
+ <FolderOpen data-icon="inline-start" />
+ Open .torrent…
+ </Button>
+ </div>
+
+ {probe.status === 'probing' && (
+ <div className="font-mono text-[11.5px] text-muted-foreground">Checking the link…</div>
+ )}
+ {probe.status === 'error' && (
+ <div className="flex items-center gap-2 text-[12.5px] text-[var(--color-danger)]">
+ <AlertTriangle className="size-4 shrink-0" />
+ {probe.message}
+ </div>
+ )}
+
+ {ready && (
+ <div className="flex items-center gap-3">
+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg border-[0.5px] border-border bg-card font-mono text-[10px] font-semibold text-muted-foreground">
+ {torrent && torrent.files.length > 1 ? 'DIR' : fileExtensionBadge(fileName)}
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ {torrent ? (
+ <div className="truncate text-[14px] font-medium">{ready.suggestedFileName}</div>
+ ) : (
+ <input
+ type="text"
+ value={fileName}
+ onChange={(event) => setFileNameOverride(event.target.value)}
+ aria-label="File name"
+ spellCheck={false}
+ className="min-w-0 rounded-md border border-transparent bg-transparent px-1 -ml-1 text-[14px] font-medium outline-none hover:border-input focus:border-input"
+ />
+ )}
+ <div className="font-mono text-[11.5px] text-muted-foreground">
+ {[
+ torrent && describeFileCount(chosenFiles.length, torrent.files.length),
+ sizeToFetch !== null ? formatBytes(sizeToFetch) : 'size unknown',
+ !torrent &&
+ (isSingleStreamOnly
+ ? ready.supportsRanges
+ ? 'Uses one connection. The file size is unknown.'
+ : 'Uses one connection. This server doesn’t support parallel downloads.'
+ : 'resumable')
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {torrent && (
+ <TorrentFileList
+ files={torrent.files}
+ skipped={skippedFiles}
+ onChange={setSkippedFiles}
+ />
+ )}
+
+ <div className="flex items-center gap-3">
+ <div className={labelClass}>Save to</div>
+ <div className="min-w-0 flex-1 truncate font-mono text-[12.5px]">
+ {toDisplayPath(destinationDir, homeDir)}
+ </div>
+ <Button type="button" variant="secondary" size="sm" onClick={handleBrowse}>
+ Change…
+ </Button>
+ </div>
+
+ <div className="flex items-start gap-3">
+ <div className={cn(labelClass, 'pt-1.5')} id="new-download-networks">
+ Networks
+ </div>
+ <div
+ role="group"
+ aria-labelledby="new-download-networks"
+ className="flex min-w-0 flex-1 flex-wrap gap-1.5"
+ >
+ {interfaces.map((iface) => {
+ const visual = networkVisual(iface.id, iface.kind, iface.displayName)
+ const selected = selectedInterfaceIds.includes(iface.id)
+ return (
+ <button
+ key={iface.id}
+ type="button"
+ aria-pressed={selected}
+ onClick={() => handleToggleInterface(iface.id)}
+ className={cn(
+ 'flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-[12.5px] transition-colors',
+ selected
+ ? 'border-transparent'
+ : 'border-border text-[var(--text-secondary)] opacity-70'
+ )}
+ style={
+ selected ? { background: visual.bg, borderColor: visual.border } : undefined
+ }
+ >
+ <span className="size-2 rounded-full" style={{ background: visual.solid }} />
+ {visual.name}
+ </button>
+ )
+ })}
+ </div>
+ </div>
+
+ {/* A torrent's speed comes from its peers, and an unsplittable file has one stream. */}
+ {ready && !torrent && !isSingleStreamOnly && (
+ <div className="flex items-center gap-3">
+ <div className={labelClass} id="new-download-streams">
+ Streams
+ </div>
+ <ToggleGroup
+ value={[String(streamsChoice)]}
+ onValueChange={(values) => {
+ if (values.length === 0) return
+ setStreamsChoice(values[0] === 'auto' ? 'auto' : Number(values[0]))
+ }}
+ aria-labelledby="new-download-streams"
+ variant="pill"
+ size="xs"
+ spacing={1}
+ >
+ {STREAMS_CHOICES.map((choice) => (
+ // h-6/min-w-6: WCAG 2.5.8's 24px floor — the xs toggle size is 20px.
+ <ToggleGroupItem key={choice} value={String(choice)} className="h-6 min-w-6 px-2">
+ {choice === 'auto' ? 'Auto' : choice}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ <div className="font-mono text-[11px] text-muted-foreground">per network</div>
+ </div>
+ )}
+
+ {subnetConflict && (
+ <div className="flex items-start gap-2 text-[12px] leading-snug text-[var(--color-usb-text)]">
+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
+ {subnetConflict.names.join(' and ')} share a subnet ({subnetConflict.subnet}), so the
+ computer sends both down one route and they can’t be combined.
+ </div>
+ )}
+ {isSingleStreamOnly && selectedInterfaceIds.length === 1 && interfaces.length > 1 && (
+ <div className="text-[12px] text-muted-foreground">
+ This download uses one connection on one network.
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2 border-t-[0.5px] border-border px-4 py-2">
+ {startError ? (
+ <div className="min-w-0 flex-1 truncate text-[12.5px] text-[var(--color-danger)]">
+ {startError}
+ </div>
+ ) : (
+ <div className="flex-1" />
+ )}
+ <Button type="button" variant="secondary" onClick={onDone}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={!canStart}>
+ {startLabel}
+ </Button>
+ </div>
+ </form>
+ )
+}
diff --git a/src/renderer/src/components/ScreenFooter.tsx b/src/renderer/src/components/ScreenFooter.tsx
index 50fe1ab..d470e83 100644
--- a/src/renderer/src/components/ScreenFooter.tsx
+++ b/src/renderer/src/components/ScreenFooter.tsx
@@ -12,7 +12,7 @@ export function ScreenFooter({
return (
<div
className={cn(
- 'flex shrink-0 items-center gap-3 border-t-[0.5px] border-t-[var(--footer-border)] bg-secondary px-5 py-[11px]',
+ 'flex shrink-0 items-center gap-3 border-t-[0.5px] border-t-[var(--footer-border)] bg-secondary px-5 py-2',
className
)}
>
diff --git a/src/renderer/src/components/StatusBar.tsx b/src/renderer/src/components/StatusBar.tsx
new file mode 100644
index 0000000..8dad46e
--- /dev/null
+++ b/src/renderer/src/components/StatusBar.tsx
@@ -0,0 +1,70 @@
+import { useEffect, useState } from 'react'
+import { useAppStore } from '../store/useAppStore'
+import { formatBytes, formatSpeed } from '../utils/format'
+import { ScreenFooter } from './ScreenFooter'
+import { ThemeToggle } from './ThemeToggle'
+import { Switch } from './ui/switch'
+import { UpdateIndicator } from './UpdateIndicator'
+
+const FREE_SPACE_POLL_MS = 30_000
+
+/** Along the bottom of every screen: how fast everything is going and under what limit, the
+ * queue, the slow mode switch, and the room left where downloads are saved. */
+export function StatusBar(): React.JSX.Element {
+ const downloads = useAppStore((store) => store.downloads)
+ const speedLimit = useAppStore((store) => store.speedLimit)
+ const slowMode = useAppStore((store) => store.slowMode)
+ const slowModeSpeed = useAppStore((store) => store.slowModeSpeed)
+ const setSlowMode = useAppStore((store) => store.setSlowMode)
+ const destinationDir = useAppStore((store) => store.destinationDir)
+ const [free, setFree] = useState<number | null>(null)
+
+ useEffect(() => {
+ let disposed = false
+ const load = (): void => {
+ void window.plexo
+ .freeSpace(destinationDir)
+ .then((bytes) => !disposed && setFree(bytes))
+ .catch(() => {})
+ }
+ load()
+ const interval = setInterval(load, FREE_SPACE_POLL_MS)
+ return () => {
+ disposed = true
+ clearInterval(interval)
+ }
+ }, [destinationDir])
+
+ let speed = 0
+ let waiting = 0
+ for (const download of Object.values(downloads)) {
+ if (download.status === 'downloading') speed += download.speedBytesPerSec
+ if (download.status === 'queued') waiting++
+ }
+ const limit = slowMode ? slowModeSpeed : speedLimit
+
+ return (
+ <ScreenFooter className="gap-4 font-mono text-[11.5px] text-muted-foreground">
+ {/* At rest it says nothing: a zero speed or an empty queue only reads as broken. */}
+ {(speed > 0 || limit !== undefined) && (
+ <span className="tabular-nums">
+ {speed > 0 && (
+ <>
+ ↓ <span className="text-foreground">{formatSpeed(speed)}</span>
+ </>
+ )}
+ {limit !== undefined && `${speed > 0 ? ' · ' : ''}limit ${formatSpeed(limit)}`}
+ </span>
+ )}
+ {waiting > 0 && <span>{waiting} waiting in the queue</span>}
+ <div className="flex-1" />
+ <label className="flex items-center gap-2">
+ Slow mode
+ <Switch checked={slowMode} onCheckedChange={setSlowMode} />
+ </label>
+ {free !== null && <span>{formatBytes(free)} free</span>}
+ <UpdateIndicator />
+ <ThemeToggle />
+ </ScreenFooter>
+ )
+}
diff --git a/src/renderer/src/components/TitleBar.tsx b/src/renderer/src/components/TitleBar.tsx
index 7d24391..8763ed2 100644
--- a/src/renderer/src/components/TitleBar.tsx
+++ b/src/renderer/src/components/TitleBar.tsx
@@ -1,76 +1,22 @@
-import { ColorBadge } from './ColorBadge'
-import { ThemeToggle } from './ThemeToggle'
-import { UpdateIndicator } from './UpdateIndicator'
-
-export type TitleBarStatus =
- | { kind: 'none' }
- | { kind: 'combined'; networkCount: number }
- | { kind: 'paused'; networkCount: number }
- | { kind: 'offline' }
+import { TITLE_BAR_HEIGHT } from '../theme'
const isMac = window.plexo.platform === 'darwin'
-const pillClass =
- 'h-auto flex items-center gap-[7px] rounded-full px-2.5 py-1 font-mono text-[10px] leading-none font-semibold tracking-[0.08em] uppercase whitespace-nowrap'
-const pillDotClass = 'size-1.5 shrink-0 rounded-full'
-
-export function TitleBar({ status }: { status: TitleBarStatus }): React.JSX.Element {
- const dimmed = status.kind === 'offline'
-
+/** The window's title bar, the same on every OS: its name, centered, on a strip the window is
+ * dragged by. The OS's own controls sit over it (see main/index.ts): macOS's traffic lights at
+ * the left, Windows' and Linux's minimize/maximize/close at the right. */
+export function TitleBar(): React.JSX.Element {
return (
<div
- className={`flex h-11 shrink-0 items-center gap-[13px] border-b-[0.5px] border-border bg-card pr-3.5 [-webkit-app-region:drag] ${
- // Real traffic lights are inset here on macOS (see main/index.ts, trafficLightPosition) —
- // 16px inset + ~52px cluster width + a clear ~26px gap before our own content starts.
- isMac ? 'pl-[94px]' : 'pl-3.5'
+ style={{ height: TITLE_BAR_HEIGHT }}
+ className={`flex shrink-0 items-center justify-center border-b-[0.5px] border-border bg-card [-webkit-app-region:drag] ${
+ // Clear of the controls on either side, so the name stays centered between them.
+ isMac ? 'px-[94px]' : 'px-[140px]'
}`}
>
- <div
- // Matches the "LOCKUP · horizontal" wordmark spec from the final icon design.
- className={`font-sans text-[13px] leading-none font-bold tracking-[-0.02em] ${
- dimmed ? 'text-muted-foreground' : 'text-foreground'
- }`}
- >
+ <div className="truncate font-sans text-[13px] leading-none font-semibold text-[var(--text-secondary)]">
Plexo
</div>
- <div className="flex-1" />
- {status.kind === 'combined' && (
- <ColorBadge
- bg="var(--color-wifi-bg)"
- border="var(--color-wifi-border)"
- text="var(--color-wifi-text)"
- className={pillClass}
- >
- <div
- className={`${pillDotClass} bg-[var(--color-wifi)] animate-[plexo-glow_2s_ease-in-out_infinite]`}
- />
- {status.networkCount} {status.networkCount === 1 ? 'network' : 'networks'} combined
- </ColorBadge>
- )}
- {status.kind === 'paused' && (
- <ColorBadge
- bg="var(--color-usb-bg)"
- border="var(--color-usb-border)"
- text="var(--color-usb-text)"
- className={pillClass}
- >
- <div className={`${pillDotClass} bg-[var(--color-usb)]`} />
- {status.networkCount} {status.networkCount === 1 ? 'network' : 'networks'} · Paused
- </ColorBadge>
- )}
- {status.kind === 'offline' && (
- <ColorBadge
- bg="var(--color-danger-bg)"
- border="var(--color-danger-border)"
- text="var(--color-danger)"
- className={pillClass}
- >
- <div className={`${pillDotClass} bg-[var(--color-danger)]`} />
- Offline
- </ColorBadge>
- )}
- <UpdateIndicator />
- <ThemeToggle />
</div>
)
}
diff --git a/src/renderer/src/components/TorrentBadge.tsx b/src/renderer/src/components/TorrentBadge.tsx
new file mode 100644
index 0000000..21c9422
--- /dev/null
+++ b/src/renderer/src/components/TorrentBadge.tsx
@@ -0,0 +1,14 @@
+import { Badge } from './ui/badge'
+
+/** Next to a torrent's name, wherever it's listed: the name alone doesn't say where it comes from.
+ * Neutral, so it never competes with a status badge. */
+export function TorrentBadge(): React.JSX.Element {
+ return (
+ <Badge
+ variant="outline"
+ className="h-4 rounded-[3.5px] px-[6px] font-mono text-[9.5px] leading-none font-semibold tracking-[0.08em] text-muted-foreground"
+ >
+ TORRENT
+ </Badge>
+ )
+}
diff --git a/src/renderer/src/components/TorrentFiles.tsx b/src/renderer/src/components/TorrentFiles.tsx
new file mode 100644
index 0000000..441b9db
--- /dev/null
+++ b/src/renderer/src/components/TorrentFiles.tsx
@@ -0,0 +1,153 @@
+import type { TorrentFileEntry, TorrentInfo, TorrentPieceState } from '@shared/types'
+import { cn } from 'cn'
+import { Folder } from 'lucide-react'
+import { useEffect, useState } from 'react'
+import { describeError, formatBytes, formatPercent, pathInTorrent } from '../utils/format'
+import { Checkbox } from './ui/checkbox'
+
+/** Bytes of each file that are in verified pieces. Files and pieces both run in byte order, so
+ * one pass over each. */
+function verifiedBytes(files: TorrentFileEntry[], pieces: TorrentPieceState[]): number[] {
+ // Exclusive. A piece's rangeEnd is never null: that's for HTTP downloads of unknown size.
+ const endOf = (piece: TorrentPieceState): number => (piece.rangeEnd ?? piece.rangeStart) + 1
+ let start = 0
+ let first = 0
+ return files.map((file) => {
+ const end = start + file.length
+ while (first < pieces.length && endOf(pieces[first]) <= start) first++
+ let done = 0
+ for (let at = first; at < pieces.length && pieces[at].rangeStart < end; at++) {
+ const piece = pieces[at]
+ if (piece.status === 'completed') {
+ done += Math.min(end, endOf(piece)) - Math.max(start, piece.rangeStart)
+ }
+ }
+ start = end
+ return done
+ })
+}
+
+/** A torrent's files, each ticked to be downloaded. Several come in the torrent's folder, whose
+ * row above them, by its name, ticks all of them. Given `done` (each file's bytes in), each shows
+ * how far it is, and one all in stays ticked: it's downloaded. */
+export function TorrentFileList({
+ files,
+ skipped,
+ onChange,
+ done
+}: {
+ files: TorrentInfo['files']
+ skipped: number[]
+ onChange: (skipped: number[]) => void
+ done?: number[]
+}): React.JSX.Element {
+ // A torrent in a folder (always so with several files) starts every path with it.
+ const parts = files[0]?.path.split(/[\\/]/) ?? []
+ const folder = parts.length > 1 ? parts[0] : null
+ const finished = (index: number): boolean =>
+ done !== undefined && done[index] >= files[index].length
+ return (
+ <div
+ role="group"
+ aria-label="Files"
+ className="max-h-44 overflow-y-auto rounded-[9px] border border-border px-3 py-1.5"
+ >
+ {folder && (
+ <label className="flex items-center gap-2 py-0.5 font-mono text-[11.5px] font-medium">
+ <Checkbox
+ checked={skipped.length === 0}
+ indeterminate={skipped.length > 0 && skipped.length < files.length}
+ onCheckedChange={(checked) =>
+ // Unticking all leaves the downloaded ones: they're in.
+ onChange(checked ? [] : files.flatMap((_, index) => (finished(index) ? [] : [index])))
+ }
+ />
+ <Folder aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate">{folder}</span>
+ </label>
+ )}
+ {files.map((file, index) => (
+ <label
+ key={index}
+ className={cn('flex items-center gap-2 py-0.5 font-mono text-[11.5px]', folder && 'pl-6')}
+ >
+ <Checkbox
+ checked={!skipped.includes(index)}
+ disabled={finished(index)}
+ onCheckedChange={(checked) =>
+ onChange(checked ? skipped.filter((entry) => entry !== index) : [...skipped, index])
+ }
+ />
+ <span className="min-w-0 flex-1 truncate">{pathInTorrent(file.path)}</span>
+ <span className="shrink-0 text-muted-foreground">{formatBytes(file.length)}</span>
+ {done && (
+ <span className="w-14 shrink-0 text-right tabular-nums text-[var(--text-secondary)]">
+ {skipped.includes(index)
+ ? 'Skipped'
+ : finished(index)
+ ? 'Done'
+ : `${formatPercent(done[index], file.length)}%`}
+ </span>
+ )}
+ </label>
+ ))}
+ </div>
+ )
+}
+
+/** A torrent download's files once it has started: how far each is, and which to fetch, changed
+ * as it runs. The choice is main's, `selected` as its state has it (unset: every file): a change
+ * is asked for, and shows once the state it's sent back has it. */
+export function TorrentFiles({
+ downloadId,
+ pieces,
+ selected
+}: {
+ downloadId: string
+ pieces: TorrentPieceState[]
+ selected: number[] | undefined
+}): React.JSX.Element | null {
+ const [files, setFiles] = useState<TorrentFileEntry[] | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ useEffect(() => {
+ let stale = false
+ void window.plexo.torrentFiles(downloadId).then((entries) => {
+ if (!stale) setFiles(entries)
+ })
+ return () => {
+ stale = true
+ }
+ }, [downloadId])
+
+ if (!files) return null
+ const skipped = selected
+ ? files.flatMap((_, index) => (selected.includes(index) ? [] : [index]))
+ : []
+ const choose = (next: number[]): void => {
+ if (next.length === files.length) {
+ setError('Keep at least one file.')
+ return
+ }
+ setError(null)
+ const chosen = files.flatMap((_, index) => (next.includes(index) ? [] : [index]))
+ window.plexo
+ .chooseTorrentFiles(downloadId, chosen)
+ .catch((cause) => setError(describeError(cause)))
+ }
+
+ return (
+ <div className="mt-3 flex flex-col gap-1.5">
+ <TorrentFileList
+ files={files}
+ skipped={skipped}
+ onChange={choose}
+ done={verifiedBytes(files, pieces)}
+ />
+ {error && (
+ <p role="alert" className="text-[12px] text-[var(--color-danger)]">
+ {error}
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/src/renderer/src/components/ui/alert-dialog.tsx b/src/renderer/src/components/ui/alert-dialog.tsx
index 360ed4d..bac7bc5 100644
--- a/src/renderer/src/components/ui/alert-dialog.tsx
+++ b/src/renderer/src/components/ui/alert-dialog.tsx
@@ -19,7 +19,7 @@ function AlertDialogBackdrop({
<AlertDialogPrimitive.Backdrop
data-slot="alert-dialog-backdrop"
className={cn(
- 'fixed inset-0 z-50 bg-black/40 data-[ending-style]:opacity-0 data-[starting-style]:opacity-0 dark:bg-black/60',
+ 'fixed inset-0 isolate z-50 bg-black/10 supports-backdrop-filter:backdrop-blur-xs data-[ending-style]:opacity-0 data-[starting-style]:opacity-0',
className
)}
{...props}
@@ -37,7 +37,7 @@ function AlertDialogContent({
<AlertDialogPrimitive.Popup
data-slot="alert-dialog-content"
className={cn(
- 'fixed top-1/2 left-1/2 z-50 w-full max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-lg bg-popover p-4 text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[ending-style]:scale-95 data-[ending-style]:opacity-0 data-[starting-style]:scale-95 data-[starting-style]:opacity-0',
+ 'fixed top-1/2 left-1/2 z-50 w-full max-w-[calc(100%-2rem)] sm:max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-xl bg-popover p-4 text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[ending-style]:scale-95 data-[ending-style]:opacity-0 data-[starting-style]:scale-95 data-[starting-style]:opacity-0',
className
)}
{...props}
diff --git a/src/renderer/src/components/ui/dialog.tsx b/src/renderer/src/components/ui/dialog.tsx
index 0ae72ff..94c88d4 100644
--- a/src/renderer/src/components/ui/dialog.tsx
+++ b/src/renderer/src/components/ui/dialog.tsx
@@ -48,7 +48,7 @@ function DialogContent({
<DialogPrimitive.Popup
data-slot="dialog-content"
className={cn(
- 'fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
+ 'fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
className
)}
{...props}
@@ -86,7 +86,7 @@ function DialogFooter({
<div
data-slot="dialog-footer"
className={cn(
- '-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end',
+ '-mx-4 -mb-4 mt-2 flex items-center justify-end gap-2 rounded-b-xl border-t-[0.5px] border-border bg-popover px-4 py-2',
className
)}
{...props}
diff --git a/src/renderer/src/components/ui/switch.tsx b/src/renderer/src/components/ui/switch.tsx
new file mode 100644
index 0000000..7e8b7e2
--- /dev/null
+++ b/src/renderer/src/components/ui/switch.tsx
@@ -0,0 +1,22 @@
+import { Switch as SwitchPrimitive } from '@base-ui/react/switch'
+import { cn } from 'cn'
+
+function Switch({ className, ...props }: SwitchPrimitive.Root.Props): React.JSX.Element {
+ return (
+ <SwitchPrimitive.Root
+ data-slot="switch"
+ className={cn(
+ 'peer inline-flex h-[22px] w-[38px] shrink-0 items-center rounded-full border border-transparent bg-input p-0.5 transition-colors outline-none focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-checked:bg-[var(--color-wifi)] dark:bg-input/80',
+ className
+ )}
+ {...props}
+ >
+ <SwitchPrimitive.Thumb
+ data-slot="switch-thumb"
+ className="pointer-events-none block size-4 rounded-full bg-white shadow-sm transition-transform data-checked:translate-x-4"
+ />
+ </SwitchPrimitive.Root>
+ )
+}
+
+export { Switch }
diff --git a/src/renderer/src/components/ui/tooltip.tsx b/src/renderer/src/components/ui/tooltip.tsx
index 34adeab..852fd2e 100644
--- a/src/renderer/src/components/ui/tooltip.tsx
+++ b/src/renderer/src/components/ui/tooltip.tsx
@@ -1,5 +1,6 @@
import { Tooltip as TooltipPrimitive } from '@base-ui/react/tooltip'
import { cn } from 'cn'
+import { TITLE_BAR_HEIGHT } from '../../theme'
function TooltipProvider({
delay = 0,
@@ -36,6 +37,8 @@ function TooltipContent({
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
+ // Flips below rather than open under the title bar and its window controls.
+ collisionPadding={{ top: TITLE_BAR_HEIGHT + 4, right: 5, bottom: 5, left: 5 }}
className="isolate z-50"
>
<TooltipPrimitive.Popup
diff --git a/src/renderer/src/hooks/useDownloadEvents.ts b/src/renderer/src/hooks/useDownloadEvents.ts
index 7a0c904..9763450 100644
--- a/src/renderer/src/hooks/useDownloadEvents.ts
+++ b/src/renderer/src/hooks/useDownloadEvents.ts
@@ -1,26 +1,50 @@
import { useEffect } from 'react'
import { useAppStore } from '../store/useAppStore'
-/** Subscribes once to main-process download progress pushes for the lifetime of the app. */
+/** Subscribes once to main-process download pushes for the lifetime of the app. */
export function useDownloadEvents(): void {
const receiveDownloadUpdate = useAppStore((store) => store.receiveDownloadUpdate)
+ const receiveHistory = useAppStore((store) => store.receiveHistory)
useEffect(() => {
let disposed = false
- // Subscribed before the snapshot is asked for, so nothing sent in between is missed; each
+ const loadHistory = (): void => {
+ void window.plexo
+ .listHistory()
+ .then((history) => {
+ if (!disposed) receiveHistory(history)
+ })
+ .catch(() => {})
+ }
+ // Subscribed before the snapshots are asked for, so nothing sent in between is missed; each
// update carries a count, so whichever arrives late can't undo the other.
const unsubscribe = window.plexo.onDownloadUpdated(receiveDownloadUpdate)
+ // A bulk removal changes history once per download: list it once they've settled, rather
+ // than re-checking every entry's file after each one. The rows already went from the store.
+ let reload: ReturnType<typeof setTimeout> | undefined
+ const unsubscribeHistory = window.plexo.onHistoryChanged(() => {
+ clearTimeout(reload)
+ reload = setTimeout(loadHistory, 150)
+ })
+ // A finished file can only be moved or deleted while Plexo is in the background: listing
+ // again on coming back keeps "moved or deleted" true to the disk, as browsers do when their
+ // downloads list is opened.
+ window.addEventListener('focus', loadHistory)
void window.plexo
- .getCurrentDownload()
- .then((snapshot) => {
- if (!disposed && snapshot) receiveDownloadUpdate(snapshot)
+ .listDownloads()
+ .then((snapshots) => {
+ if (!disposed) for (const snapshot of snapshots) receiveDownloadUpdate(snapshot)
})
.catch(() => {})
+ loadHistory()
return () => {
disposed = true
+ clearTimeout(reload)
+ window.removeEventListener('focus', loadHistory)
unsubscribe()
+ unsubscribeHistory()
}
- }, [receiveDownloadUpdate])
+ }, [receiveDownloadUpdate, receiveHistory])
}
diff --git a/src/renderer/src/hooks/useNetworkVisuals.ts b/src/renderer/src/hooks/useNetworkVisuals.ts
index c84e3f6..0b81a5c 100644
--- a/src/renderer/src/hooks/useNetworkVisuals.ts
+++ b/src/renderer/src/hooks/useNetworkVisuals.ts
@@ -8,17 +8,20 @@ export type ResolveNetworkVisual = (
osName: string
) => NetworkVisual
-/** Colors are assigned across every known network at once (detected interfaces plus any in the
- * current download), so each screen agrees on which network is which color. */
+/** Colors are assigned across every known network at once (detected interfaces plus any a
+ * download, running or finished, used), so each screen agrees on which network is which color. */
export function useNetworkVisuals(): ResolveNetworkVisual {
const interfaces = useAppStore((store) => store.interfaces)
- const downloadNetworks = useAppStore((store) => store.currentDownload?.networks)
+ const downloads = useAppStore((store) => store.downloads)
+ const history = useAppStore((store) => store.history)
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 network of downloadNetworks ?? []) {
- if (!networks.has(network.id)) networks.set(network.id, network.kind)
+ for (const download of [...Object.values(downloads), ...history]) {
+ for (const network of download.networks) {
+ 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.ts
index fc0c63c..37ffc66 100644
--- a/src/renderer/src/hooks/useNetworks.ts
+++ b/src/renderer/src/hooks/useNetworks.ts
@@ -1,4 +1,4 @@
-import { useEffect } from 'react'
+import { useEffect, useState } from 'react'
import { useAppStore } from '../store/useAppStore'
const LATENCY_POLL_MS = 5000
@@ -16,13 +16,42 @@ export function useNetworkEvents(): void {
}, [loadInterfaces, receiveInterfaces])
}
-/** Keeps each network's latency readout fresh while a screen that shows it is mounted. */
-export function useLatencyPolling(): void {
+/** Keeps each network's latency readout fresh while `active` (something showing it is open). */
+export function useLatencyPolling(active: boolean): void {
const refreshLatencies = useAppStore((store) => store.refreshLatencies)
useEffect(() => {
+ if (!active) return
void refreshLatencies()
const interval = setInterval(refreshLatencies, LATENCY_POLL_MS)
return () => clearInterval(interval)
- }, [refreshLatencies])
+ }, [active, refreshLatencies])
+}
+
+const USAGE_POLL_MS = 2000
+
+/** What each network has received in its selected calendar period, by id, kept fresh while `active` (a screen that
+ * shows data limits is open). */
+export function useNetworkUsage(active: boolean, revision = 0): Record<string, number> {
+ const preferences = useAppStore((store) => store.networkPreferences)
+ const [usage, setUsage] = useState<Record<string, number>>({})
+
+ useEffect(() => {
+ if (!active) return
+ let disposed = false
+ const load = (): void => {
+ void window.plexo
+ .networkUsage()
+ .then((next) => !disposed && setUsage(next))
+ .catch(() => {})
+ }
+ load()
+ const interval = setInterval(load, USAGE_POLL_MS)
+ return () => {
+ disposed = true
+ clearInterval(interval)
+ }
+ }, [active, preferences, revision])
+
+ return usage
}
diff --git a/src/renderer/src/hooks/useOpenedLinks.ts b/src/renderer/src/hooks/useOpenedLinks.ts
new file mode 100644
index 0000000..ba42d5f
--- /dev/null
+++ b/src/renderer/src/hooks/useOpenedLinks.ts
@@ -0,0 +1,74 @@
+import { useEffect } from 'react'
+import { useAppStore } from '../store/useAppStore'
+import { acceptedLink } from '../utils/format'
+
+/** Opens New download with a link the OS handed Plexo — a magnet link clicked, a .torrent opened
+ * — for the user to look at and start (see main/openLinks.ts). */
+export function useOpenedLinks(): void {
+ const openNewDownload = useAppStore((store) => store.openNewDownload)
+
+ useEffect(() => {
+ const take = (): void => {
+ void window.plexo
+ .takePendingLink()
+ .then((link) => {
+ if (link) openNewDownload(link)
+ })
+ .catch(() => {})
+ }
+ const unsubscribe = window.plexo.onLinkReceived(take)
+ // One handed over before the window was ready to hear of it.
+ take()
+ return unsubscribe
+ }, [openNewDownload])
+}
+
+const isMac = window.plexo.platform === 'darwin'
+
+/** The ways into New download from anywhere in the window, as download managers have them:
+ * pasting a link (outside a text field), ⌘N / Ctrl+N, and dropping a link or a .torrent. */
+export function useNewDownloadShortcuts(): void {
+ const openNewDownload = useAppStore((store) => store.openNewDownload)
+
+ useEffect(() => {
+ const busy = (target: EventTarget | null): boolean =>
+ useAppStore.getState().newDownloadOpen ||
+ (target instanceof HTMLElement &&
+ (target.isContentEditable || ['INPUT', 'TEXTAREA'].includes(target.tagName)))
+
+ const onPaste = (event: ClipboardEvent): void => {
+ if (busy(event.target)) return
+ const link = acceptedLink(event.clipboardData?.getData('text') ?? '')
+ if (link) openNewDownload(link)
+ }
+ const onKeyDown = (event: KeyboardEvent): void => {
+ if (event.key.toLowerCase() !== 'n' || !(isMac ? event.metaKey : event.ctrlKey)) return
+ if (useAppStore.getState().newDownloadOpen) return
+ event.preventDefault()
+ openNewDownload()
+ }
+ // Never let a drop navigate the window to what was dropped.
+ const onDragOver = (event: DragEvent): void => event.preventDefault()
+ const onDrop = (event: DragEvent): void => {
+ event.preventDefault()
+ const file = event.dataTransfer?.files[0]
+ const link = file
+ ? /\.torrent$/i.test(file.name)
+ ? window.plexo.pathForFile(file)
+ : null
+ : acceptedLink(event.dataTransfer?.getData('text') ?? '')
+ if (link) openNewDownload(link)
+ }
+
+ window.addEventListener('paste', onPaste)
+ window.addEventListener('keydown', onKeyDown)
+ window.addEventListener('dragover', onDragOver)
+ window.addEventListener('drop', onDrop)
+ return () => {
+ window.removeEventListener('paste', onPaste)
+ window.removeEventListener('keydown', onKeyDown)
+ window.removeEventListener('dragover', onDragOver)
+ window.removeEventListener('drop', onDrop)
+ }
+ }, [openNewDownload])
+}
diff --git a/src/renderer/src/screens/CompleteScreen.tsx b/src/renderer/src/screens/CompleteScreen.tsx
index cfe0f43..ae89d43 100644
--- a/src/renderer/src/screens/CompleteScreen.tsx
+++ b/src/renderer/src/screens/CompleteScreen.tsx
@@ -1,28 +1,34 @@
-import type { DownloadState } from '@shared/types'
+import type { DownloadState, FinishedDownload } from '@shared/types'
import { HeroBand } from '../components/HeroBand'
-import { ScreenFooter } from '../components/ScreenFooter'
+import { DetailHeader } from '../components/DetailHeader'
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, toDisplayPath } from '../utils/format'
+import {
+ describeFileCount,
+ dirnameOf,
+ formatBytes,
+ formatDuration,
+ formatSpeed,
+ toDisplayPath,
+ wantedBytes
+} from '../utils/format'
const sectionHeaderClass =
'font-mono text-[10px] leading-none tracking-[0.16em] text-muted-foreground uppercase'
export function CompleteScreen({
- download,
- onNewDownload
+ download
}: {
- download: DownloadState
- onNewDownload: () => void
+ /** Just finished, or as history keeps it. */
+ download: DownloadState | FinishedDownload
}): React.JSX.Element {
const homeDir = useAppStore((store) => store.homeDir)
- const peakSpeedBytesPerSec = useAppStore((store) => store.peakSpeedBytesPerSec)
- const speedHistoryByInterface = useAppStore((store) => store.speedHistoryByInterface)
const networkVisual = useNetworkVisuals()
+ const missing = 'missing' in download && download.missing === true
- const finalSize = download.totalBytes || download.bytesDownloaded
+ const finalSize = wantedBytes(download) || download.bytesDownloaded
const totalPausedMs = download.totalPausedMs ?? 0
// completedAt is always set by the time a download reaches 'completed' — the
// fallback here is just to keep this pure (no Date.now() during render).
@@ -38,13 +44,27 @@ export function CompleteScreen({
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.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
+ const isTorrent = download.kind === 'torrent'
+ // "Chunks" in the block grid means byte ranges, not parallel connections. A torrent's are its
+ // pieces, those its chosen files needed.
+ const totalChunkCount =
+ 'unitsWritten' in download
+ ? download.unitsWritten
+ : download.kind === 'torrent'
+ ? download.pieces.filter((piece) => piece.status !== 'skipped').length
+ : download.totalBlocks
+ const files = isTorrent && download.files.total > 1 ? download.files : null
- const handleReveal = (): void => void window.plexo.revealInFolder(download.destinationPath)
+ // Gone since the list was read: main sends history again, marking it missing here.
+ const handleReveal = (): void => void window.plexo.revealDownload(download.id)
return (
<div className="flex h-full flex-col bg-background">
+ <DetailHeader download={download}>
+ <Button type="button" onClick={handleReveal} disabled={missing}>
+ {window.plexo.platform === 'darwin' ? 'Show in Finder' : 'Show in folder'}
+ </Button>
+ </DetailHeader>
<div role="status" className="sr-only">
Download complete: {download.fileName}
</div>
@@ -67,8 +87,11 @@ export function CompleteScreen({
{download.fileName}
</div>
<div className="mt-[5px] truncate font-mono text-[11.5px] leading-[1.3] text-muted-foreground">
+ {files && `${describeFileCount(files.chosen, files.total)} · `}
{formatBytes(finalSize)} ·{' '}
- {toDisplayPath(dirnameOf(download.destinationPath), homeDir)}
+ {missing
+ ? 'moved or deleted since'
+ : toDisplayPath(dirnameOf(download.destinationPath), homeDir)}
</div>
</div>
<div className="flex flex-col items-end gap-[5px]">
@@ -91,10 +114,19 @@ export function CompleteScreen({
{[
{ label: 'Size', value: formatBytes(finalSize) },
{ label: 'Time', value: formatDuration(elapsedSeconds) },
- { label: 'Peak', value: formatSpeed(peakSpeedBytesPerSec) },
+ {
+ label: 'Peak',
+ value:
+ download.peakSpeedBytesPerSec === undefined
+ ? '—'
+ : formatSpeed(download.peakSpeedBytesPerSec)
+ },
{ label: 'Networks', value: String(groups.length) },
// The most it ran at once: streams that didn't make it faster were closed along the way.
- { label: 'Streams', value: String(download.peakStreams ?? download.chunks.length) }
+ {
+ label: isTorrent ? 'Peers' : 'Streams',
+ value: String(isTorrent ? download.peakPeers : download.peakStreams)
+ }
].map((stat, index) => (
<div
key={stat.label}
@@ -116,7 +148,7 @@ export function CompleteScreen({
<h2 className={sectionHeaderClass}>Speed over the download</h2>
<ThroughputChart
order={groups.map((g, i) => ({ interfaceId: g.id, solid: visuals[i].solid }))}
- historyByInterface={speedHistoryByInterface}
+ historyByInterface={download.speedHistory ?? {}}
/>
</div>
@@ -148,22 +180,17 @@ export function CompleteScreen({
</div>
))}
</div>
- </div>
-
- <ScreenFooter>
- <div className="shrink-0 font-mono text-[11px] leading-[1.4] whitespace-nowrap text-muted-foreground">
- {`written in ${totalChunkCount} chunks · ${totalRetries} ${
- totalRetries === 1 ? 'retry' : 'retries'
- }`}
+ <div className="mt-auto pt-3 font-mono text-[11px] leading-[1.4] text-muted-foreground">
+ {[
+ `written in ${totalChunkCount} ${isTorrent ? 'pieces' : 'chunks'}`,
+ // What its peers got from it while it downloaded.
+ isTorrent && `uploaded ${formatBytes(download.bytesUploaded ?? 0)}`,
+ `${totalRetries} ${totalRetries === 1 ? 'retry' : 'retries'}`
+ ]
+ .filter(Boolean)
+ .join(' · ')}
</div>
- <div className="flex-1" />
- <Button type="button" variant="secondary" onClick={onNewDownload}>
- New Download
- </Button>
- <Button type="button" onClick={handleReveal}>
- {window.plexo.platform === 'darwin' ? 'Reveal in Finder' : 'Show in folder'}
- </Button>
- </ScreenFooter>
+ </div>
</div>
)
}
diff --git a/src/renderer/src/screens/DownloadingScreen.tsx b/src/renderer/src/screens/DownloadingScreen.tsx
index b2d1f02..b5b434b 100644
--- a/src/renderer/src/screens/DownloadingScreen.tsx
+++ b/src/renderer/src/screens/DownloadingScreen.tsx
@@ -1,31 +1,25 @@
import type { DownloadState } from '@shared/types'
-import { useEffect, useState } from 'react'
+import { Folder } from 'lucide-react'
+import { memo, useEffect, useState } from 'react'
import { BlockGrid } from '../components/BlockGrid'
import { ColorBadge } from '../components/ColorBadge'
import { CombineDiagram } from '../components/CombineDiagram'
import { CyclableChip } from '../components/CyclableChip'
import { HeroBand } from '../components/HeroBand'
import { NetworkRow } from '../components/NetworkRow'
-import { ScreenFooter } from '../components/ScreenFooter'
+import { DetailHeader } from '../components/DetailHeader'
import { ThroughputChart } from '../components/ThroughputChart'
+import { TorrentFiles } from '../components/TorrentFiles'
+import { TorrentBadge } from '../components/TorrentBadge'
import { TruncatedText } from '../components/TruncatedText'
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger
-} from '../components/ui/alert-dialog'
-import { Button, buttonVariants } from '../components/ui/button'
+import { Button } from '../components/ui/button'
import { Tooltip, TooltipContent, TooltipTrigger } from '../components/ui/tooltip'
import { useNetworkVisuals } from '../hooks/useNetworkVisuals'
import { useAppStore } from '../store/useAppStore'
import { KIND_PALETTE, NETWORK_ROW_GRID_COLUMNS } from '../theme'
import {
+ describeError,
+ describeFileCount,
dirnameOf,
fileExtensionBadge,
formatBytes,
@@ -33,15 +27,17 @@ import {
formatPercent,
formatSpeed,
groupByNetwork,
+ isFolder,
networksInPlay,
splitFormattedBytes,
- toDisplayPath
+ toDisplayPath,
+ wantedBytes
} from '../utils/format'
/** Inline "·" separator between adjacent stats. `shrink` pins it at its natural width inside a
* flex row that might otherwise squeeze it (footer rows), matching each call site's prior style. */
-function Dot({ shrink }: { shrink?: boolean }): React.JSX.Element {
- return <span className={`opacity-35 ${shrink ? 'shrink-0' : ''}`}>·</span>
+function Dot(): React.JSX.Element {
+ return <span className="opacity-35">·</span>
}
function InlineStat({ label, value }: { label: string; value: string }): React.JSX.Element {
@@ -90,19 +86,32 @@ 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…'
+ if (enabled.some((network) => network.status === 'unreachable')) {
+ return download.kind === 'torrent'
+ ? 'Can’t reach peers. Retrying…'
+ : 'Can’t reach the server. Retrying…'
+ }
+ return enabled.length > 0 && enabled.every((network) => network.status === 'limit')
+ ? 'Every network in use has reached its data limit. Raise one in Speed & data limits.'
: 'Waiting for a network. Reconnect one or switch one on.'
}
-export function DownloadingScreen({ download }: { download: DownloadState }): React.JSX.Element {
+// Memoized: App re-renders on every download's progress, and this one's grid and tables are
+// the heaviest thing on screen. Its download keeps its object until its own update arrives.
+export const DownloadingScreen = memo(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)
- const peakSpeedBytesPerSec = useAppStore((store) => store.peakSpeedBytesPerSec)
+ const speedHistory = download.speedHistory ?? {}
+ const peakSpeedBytesPerSec = download.peakSpeedBytesPerSec
const networkVisual = useNetworkVisuals()
- const isPaused = download.status === 'paused'
- const percent = formatPercent(download.bytesDownloaded, download.totalBytes)
+ const isQueued = download.status === 'queued'
+ // Waiting in the queue looks like a pause: nothing moves.
+ const isPaused = download.status === 'paused' || isQueued
+ const isTorrent = download.kind === 'torrent'
+ const percent = formatPercent(download.bytesDownloaded, wantedBytes(download))
const knownSize = download.totalBytes > 0
const [now, setNow] = useState(() => Date.now())
@@ -116,6 +125,7 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
// status away from 'paused' (an ETag re-check over the network for a real download) — with no
// feedback in between, a slow check reads as the button not having registered the click.
const [resuming, setResuming] = useState(false)
+ const [filesOpen, setFilesOpen] = useState(false)
useEffect(() => {
if (!isPaused || download.error) {
// eslint-disable-next-line react-hooks/set-state-in-effect
@@ -125,14 +135,15 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
useEffect(() => {
if (isPaused) {
- document.title = knownSize ? `Plexo — Paused (${percent}%)` : 'Plexo — Paused'
+ const label = isQueued ? 'Queued' : 'Paused'
+ document.title = knownSize ? `Plexo — ${label} (${percent}%)` : `Plexo — ${label}`
} else {
document.title = knownSize ? `Plexo — ${percent}%` : 'Plexo — downloading'
}
return () => {
document.title = 'Plexo'
}
- }, [percent, knownSize, isPaused])
+ }, [percent, knownSize, isPaused, isQueued])
const totalPausedMs =
(download.totalPausedMs || 0) +
@@ -140,16 +151,14 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
const elapsedSeconds = Math.max(0, (now - download.startedAt - totalPausedMs) / 1000)
const handlePauseResume = (): void => {
- if (isPaused) {
+ // A queued one is paused out of the queue, as a running one is.
+ if (isPaused && !isQueued) {
setResuming(true)
void window.plexo.resumeDownload(download.id)
} else {
void window.plexo.pauseDownload(download.id)
}
}
- const handleConfirmCancel = (): void => {
- void window.plexo.cancelDownload(download.id)
- }
const effectiveSpeed = isPaused ? 0 : download.speedBytesPerSec
const speed = splitFormattedBytes(effectiveSpeed)
@@ -163,7 +172,9 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
const waiting = waitingFor(download)
const totalRetries = rows.reduce((sum, row) => sum + row.retries, 0)
- const remainingBytes = knownSize ? Math.max(0, download.totalBytes - download.bytesDownloaded) : 0
+ const remainingBytes = knownSize
+ ? Math.max(0, wantedBytes(download) - download.bytesDownloaded)
+ : 0
const avgSpeedBytesPerSec = elapsedSeconds > 0 ? download.bytesDownloaded / elapsedSeconds : 0
@@ -194,14 +205,28 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
const activeChipOption =
chipOptions.length > 0 ? chipOptions[chipModeIndex % chipOptions.length] : null
- const statusBadge = isPaused ? { label: 'PAUSED', palette: KIND_PALETTE.usb } : null
+ const statusBadge = isPaused
+ ? { label: isQueued ? 'QUEUED' : 'PAUSED', palette: KIND_PALETTE.usb }
+ : null
- const throughputStatusLabel = isPaused ? null : `LAST ${speedHistory.length}S`
- const pauseResumeLabel = resuming ? 'Resuming…' : isPaused ? 'Resume' : 'Pause'
+ const throughputStatusLabel = isPaused
+ ? null
+ : `LAST ${Object.values(speedHistory)[0]?.length ?? 0}S`
+ const pauseResumeLabel = resuming ? 'Resuming…' : isPaused && !isQueued ? 'Resume' : 'Pause'
return (
<div className="flex h-full flex-col bg-background">
- {/* Hero band — always visible at top */}
+ <DetailHeader download={download}>
+ <Button
+ type="button"
+ variant={isPaused && !isQueued ? 'default' : 'secondary'}
+ onClick={handlePauseResume}
+ disabled={resuming}
+ >
+ {pauseResumeLabel}
+ </Button>
+ </DetailHeader>
+ {/* Hero band — always visible under the header */}
<HeroBand>
<div className="flex items-center gap-[14px]">
<CombineDiagram
@@ -224,7 +249,13 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
<div className="flex items-center gap-2 font-mono text-[10px] leading-none font-medium tabular-nums text-muted-foreground">
<InlineStat label="AVG" value={formatSpeed(avgSpeedBytesPerSec)} />
<Dot />
- <InlineStat label="PEAK" value={formatSpeed(peakSpeedBytesPerSec)} />
+ {/* A dash until a speed has been held long enough to call it the peak. */}
+ <InlineStat
+ label="PEAK"
+ value={
+ peakSpeedBytesPerSec === undefined ? '—' : formatSpeed(peakSpeedBytesPerSec)
+ }
+ />
</div>
{isPaused || waiting
? (download.error || waiting) && (
@@ -232,7 +263,7 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
role="alert"
className="mt-0.5 font-sans text-[11px] leading-[1.2] font-medium text-destructive"
>
- {download.error ?? waiting}
+ {download.error ? describeError(download.error) : waiting}
</div>
)
: activeChipOption && (
@@ -262,7 +293,7 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
interfaceId: g.id,
solid: visuals[i].solid
}))}
- historyByInterface={speedHistoryByInterface}
+ historyByInterface={speedHistory}
/>
</div>
</div>
@@ -272,17 +303,24 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
<div className="shrink-0 p-[16px_20px_0px]">
<div className="flex items-center gap-[14px]">
<div className="flex size-11 shrink-0 items-center justify-center rounded-[10px] border-[0.5px] border-[var(--border-strong)] bg-card font-mono text-[10.5px] leading-none font-bold tracking-[0.04em] text-[var(--text-secondary)]">
- {fileExtensionBadge(download.fileName)}
+ {isFolder(download) ? (
+ <Folder aria-label="Folder" className="size-[18px]" />
+ ) : (
+ fileExtensionBadge(download.fileName)
+ )}
</div>
- <div className="min-w-0 flex-1">
- <TruncatedText
- text={download.fileName}
- className="font-sans text-[15px] leading-[1.3] font-semibold tracking-[-0.01em] text-foreground"
- />
- <div className="mt-1 flex items-center gap-[7px] font-mono text-[12.5px] leading-[1.2] tabular-nums text-[var(--text-secondary)]">
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ <div className="flex min-w-0 items-center gap-2">
+ <TruncatedText
+ text={download.fileName}
+ className="font-sans text-[15px] leading-[1.3] font-semibold tracking-[-0.01em] text-foreground"
+ />
+ {isTorrent && <TorrentBadge />}
+ </div>
+ <div className="flex min-w-0 items-center gap-[7px] font-mono text-[12.5px] leading-[1.2] tabular-nums text-[var(--text-secondary)]">
<span>
{formatBytes(download.bytesDownloaded)}
- {knownSize ? ` of ${formatBytes(download.totalBytes)}` : ''}
+ {knownSize ? ` of ${formatBytes(wantedBytes(download))}` : ''}
</span>
{knownSize && (
<>
@@ -290,11 +328,38 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
<span className="font-semibold text-foreground">{percent}%</span>
</>
)}
- {!isPaused && knownSize && effectiveSpeed > 0 && (
+ {isTorrent && (
+ <>
+ <Dot />
+ <span>
+ {download.peers.length} {download.peers.length === 1 ? 'peer' : 'peers'}
+ </span>
+ </>
+ )}
+ {/* Several files: they open below. One is the name above. */}
+ {download.kind === 'torrent' && download.files.total > 1 && (
+ <>
+ <Dot />
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ onClick={() => setFilesOpen((open) => !open)}
+ aria-expanded={filesOpen}
+ 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"
+ >
+ {describeFileCount(download.files.chosen, download.files.total)}{' '}
+ <span aria-hidden className="text-[7.5px] opacity-75">
+ {filesOpen ? '▲' : '▼'}
+ </span>
+ </Button>
+ </>
+ )}
+ {!isPaused && download.timeLeftSeconds !== undefined && (
<>
<Dot />
<span className="text-[var(--text-secondary)]">
- {formatEta(remainingBytes, effectiveSpeed)} left
+ {formatEta(download.timeLeftSeconds)} left
</span>
</>
)}
@@ -312,22 +377,57 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
{statusBadge.label}
</ColorBadge>
)}
+ {totalRetries > 0 && (
+ <>
+ <Dot />
+ <span className="text-[var(--color-usb)]">
+ {totalRetries} {totalRetries === 1 ? 'retry' : 'retries'}
+ </span>
+ </>
+ )}
+ {/* Last and to the right: the one part that gives way when the line runs short. */}
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="ml-auto flex min-w-0 items-center gap-1.5 pl-3 text-[11px] text-muted-foreground">
+ <Folder aria-hidden className="size-3 shrink-0" />
+ <span className="sr-only">Saving to</span>
+ <span className="truncate">
+ {toDisplayPath(dirnameOf(download.destinationPath), homeDir)}
+ </span>
+ </span>
+ }
+ />
+ <TooltipContent>Saving to: {download.destinationPath}</TooltipContent>
+ </Tooltip>
</div>
</div>
</div>
+ {download.kind === 'torrent' && filesOpen && (
+ <TorrentFiles
+ downloadId={download.id}
+ pieces={download.pieces}
+ selected={download.files.selected}
+ />
+ )}
</div>
- {/* Block grid + network table — share remaining flexible space, scroll internally */}
- <div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-5 pt-3 pb-2">
+ {/* Block grid: pinned with the file info. It's capped in height and scrolls itself. */}
+ <div className="shrink-0 px-5 pt-3">
<BlockGrid
- blocks={download.blocks}
+ blocks={download.kind === 'http' ? download.blocks : download.pieces}
groups={groups}
visuals={visuals}
knownSize={knownSize}
remainingBytes={remainingBytes}
isPaused={isPaused}
+ pieces={isTorrent}
/>
+ </div>
+ {/* Network table: only its rows scroll, under their column headers. Edge to edge: its rows
+ pad themselves. */}
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto pb-2">
<div className="mt-3">
<div
role="table"
@@ -337,11 +437,31 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
>
<div
role="row"
- className="col-span-full grid grid-cols-subgrid gap-x-3 border-b border-border pt-2.5 pb-[7px] font-mono text-[9.5px] leading-none tracking-[0.12em] text-muted-foreground uppercase"
+ className="sticky top-0 z-10 col-span-full grid grid-cols-subgrid gap-x-3 border-b border-border bg-background pt-2.5 pb-[7px] font-mono text-[9.5px] leading-none tracking-[0.12em] text-muted-foreground uppercase"
>
<div role="columnheader" aria-label="Status" />
<div role="columnheader">Network</div>
- <div role="columnheader">Progress</div>
+ <div role="columnheader">
+ {isTorrent ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ className="rounded-sm text-inherit uppercase focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
+ >
+ Progress
+ </button>
+ }
+ />
+ <TooltipContent>
+ Percentage of the download completed with verified data from this network.
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ 'Progress'
+ )}
+ </div>
<div role="columnheader" className="text-right">
Share
</div>
@@ -349,7 +469,7 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
Speed
</div>
<div role="columnheader" className="pr-5 text-right">
- Downloaded
+ {isTorrent ? 'Transferred' : 'Downloaded'}
</div>
</div>
{rows.map((row, index) => (
@@ -362,8 +482,8 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
? (row.bytesDownloaded / totalDownloadedByNetworks) * 100
: 0
}
- totalBytes={download.totalBytes}
- blocks={download.blocks}
+ totalBytes={wantedBytes(download)}
+ blocks={download.kind === 'http' ? download.blocks : undefined}
onSwitch={(enabled) =>
void window.plexo.setDownloadNetwork(download.id, row.id, enabled)
}
@@ -372,64 +492,6 @@ export function DownloadingScreen({ download }: { download: DownloadState }): Re
</div>
</div>
</div>
-
- {/* Footer is always pinned at the bottom, never scrolled off-screen */}
- <ScreenFooter>
- <div className="flex min-w-0 flex-1 items-center gap-[7px] overflow-hidden font-mono text-[11px] leading-[1.4] text-muted-foreground">
- <Tooltip>
- <TooltipTrigger
- render={
- <span className="shrink-0 whitespace-nowrap">
- Saving to {toDisplayPath(dirnameOf(download.destinationPath), homeDir)}
- </span>
- }
- />
- <TooltipContent>Saving to: {download.destinationPath}</TooltipContent>
- </Tooltip>
- <Dot shrink />
- <span className="shrink-0">Resumable</span>
- {totalRetries > 0 && (
- <>
- <Dot shrink />
- <span className="shrink-0 text-[var(--color-usb)]">
- {totalRetries} {totalRetries === 1 ? 'retry' : 'retries'}
- </span>
- </>
- )}
- </div>
- <Button
- type="button"
- variant={isPaused ? 'default' : 'secondary'}
- onClick={handlePauseResume}
- disabled={resuming}
- >
- {pauseResumeLabel}
- </Button>
- <AlertDialog>
- <AlertDialogTrigger
- render={
- <Button type="button" variant="destructive">
- Cancel
- </Button>
- }
- />
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Cancel this download?</AlertDialogTitle>
- <AlertDialogDescription>Progress will be lost.</AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Keep downloading</AlertDialogCancel>
- <AlertDialogAction
- className={buttonVariants({ variant: 'destructive', size: 'sm' })}
- onClick={handleConfirmCancel}
- >
- Cancel download
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </ScreenFooter>
</div>
)
-}
+})
diff --git a/src/renderer/src/screens/DownloadsScreen.tsx b/src/renderer/src/screens/DownloadsScreen.tsx
new file mode 100644
index 0000000..88b31f2
--- /dev/null
+++ b/src/renderer/src/screens/DownloadsScreen.tsx
@@ -0,0 +1,767 @@
+import type { DownloadState, FinishedDownload } from '@shared/types'
+import { ChevronRight, Pause, Play, Plus, RotateCw, X, type LucideIcon } from 'lucide-react'
+import { cn } from 'cn'
+import { memo, useCallback, useEffect, useState } from 'react'
+import { DownloadFilterMenu } from '../components/DownloadFilterMenu'
+import { CombineDiagram } from '../components/CombineDiagram'
+import { FixLinkDialog } from '../components/FixLinkDialog'
+import { LimitsDialog } from '../components/LimitsDialog'
+import { NetworksMenu } from '../components/NetworksMenu'
+import { TorrentBadge } from '../components/TorrentBadge'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle
+} from '../components/ui/alert-dialog'
+import { Button, buttonVariants } from '../components/ui/button'
+import { Checkbox } from '../components/ui/checkbox'
+import { Tooltip, TooltipContent, TooltipTrigger } from '../components/ui/tooltip'
+import { useNetworkVisuals, type ResolveNetworkVisual } from '../hooks/useNetworkVisuals'
+import { useAppStore, type DownloadFilter } from '../store/useAppStore'
+import {
+ describeError,
+ fileExtensionBadge,
+ formatBytes,
+ formatEta,
+ formatPercent,
+ formatSpeed,
+ formatWhen,
+ isFolder,
+ linkExpired,
+ sourceOf,
+ wantedBytes
+} from '../utils/format'
+
+type Item = DownloadState | FinishedDownload
+
+interface Group {
+ label: string
+ items: Item[]
+}
+
+function filterOf(item: Item): Exclude<DownloadFilter, 'all'> {
+ if ('unitsWritten' in item || item.status === 'completed') return 'finished'
+ return item.status === 'error' ? 'failed' : 'progress'
+}
+
+const isFinished = (item: Item): item is FinishedDownload => 'unitsWritten' in item
+
+function groupsOf(downloads: DownloadState[], history: FinishedDownload[]): Group[] {
+ const byStatus = (status: DownloadState['status']): DownloadState[] =>
+ downloads.filter((download) => download.status === status)
+ return [
+ { label: 'Downloading', items: byStatus('downloading') },
+ {
+ label: 'Queued',
+ items: byStatus('queued').sort((a, b) => (a.queuedAt ?? 0) - (b.queuedAt ?? 0))
+ },
+ { label: 'Paused', items: byStatus('paused') },
+ { label: 'Needs attention', items: byStatus('error') },
+ // Completed but not in history yet: on its way there, so listed with it.
+ { label: 'Finished', items: [...byStatus('completed'), ...history] }
+ ].filter((group) => group.items.length > 0)
+}
+
+/** "2 downloading · 1 queued", or "all done". */
+function summaryOf(downloads: DownloadState[]): string {
+ const count = (status: DownloadState['status']): number =>
+ downloads.filter((download) => download.status === status).length
+ const parts = [
+ [count('downloading'), 'downloading'],
+ [count('queued'), 'queued'],
+ [count('paused'), 'paused'],
+ [count('error'), 'need attention']
+ ]
+ .filter(([n]) => (n as number) > 0)
+ .map(([n, label]) => `${n} ${label}`)
+ return parts.length > 0 ? parts.join(' · ') : 'all done'
+}
+
+const groupLabelClass =
+ 'font-mono text-[10.5px] leading-none font-medium tracking-[0.18em] text-muted-foreground uppercase'
+
+export function DownloadsScreen(): React.JSX.Element {
+ const downloadsById = useAppStore((store) => store.downloads)
+ const history = useAppStore((store) => store.history)
+ const setView = useAppStore((store) => store.setView)
+ const openNewDownload = useAppStore((store) => store.openNewDownload)
+ const removeDownload = useAppStore((store) => store.removeDownload)
+ const filter = useAppStore((store) => store.downloadFilter)
+ const setFilter = useAppStore((store) => store.setDownloadFilter)
+ const [selected, setSelected] = useState<Set<string>>(new Set())
+ const [fixing, setFixing] = useState<DownloadState | null>(null)
+ const [confirmation, setConfirmation] = useState<{
+ kind: 'cancel' | 'trash'
+ ids: string[]
+ } | null>(null)
+ const [busy, setBusy] = useState(false)
+ const [actionError, setActionError] = useState<string | null>(null)
+ const [limitsOpen, setLimitsOpen] = useState(false)
+ const [limitsPage, setLimitsPage] = useState<string | null>(null)
+ const [now, setNow] = useState(() => Date.now())
+
+ useEffect(() => {
+ const interval = setInterval(() => setNow(Date.now()), 30_000)
+ return () => clearInterval(interval)
+ }, [])
+
+ const downloads = Object.values(downloadsById)
+ .filter((download) => download.status !== 'cancelled')
+ .sort((a, b) => a.startedAt - b.startedAt)
+ const allGroups = groupsOf(downloads, history)
+ const allItems = allGroups.flatMap((group) => group.items)
+ const counts: Record<DownloadFilter, number> = {
+ all: allItems.length,
+ progress: 0,
+ finished: 0,
+ failed: 0
+ }
+ for (const item of allItems) counts[filterOf(item)]++
+ const groups = allGroups.filter(
+ (group) => filter === 'all' || filterOf(group.items[0]) === filter
+ )
+ const items = groups.flatMap((group) => group.items)
+ // Only what's still listed counts: one that finished or went is no longer selected.
+ const chosen = items.filter((item) => selected.has(item.id))
+
+ const toggle = useCallback(
+ (ids: string[], on: boolean): void =>
+ setSelected((previous) => {
+ const next = new Set(previous)
+ for (const id of ids) {
+ if (on) next.add(id)
+ else next.delete(id)
+ }
+ return next
+ }),
+ []
+ )
+ // Stable, with the colors resolved once here, so a finished row skips every progress push.
+ const networkVisual = useNetworkVisuals()
+ const selectRow = useCallback((id: string, on: boolean) => toggle([id], on), [toggle])
+ const openRow = useCallback((id: string) => setView({ name: 'download', id }), [setView])
+ const fixRow = useCallback((item: Item) => {
+ if (!isFinished(item)) setFixing(item)
+ }, [])
+ const againRow = useCallback(
+ (item: Item) => {
+ removeDownload(item.id)
+ openNewDownload(item.url)
+ },
+ [removeDownload, openNewDownload]
+ )
+
+ const pausable = chosen.filter(
+ (item): item is DownloadState =>
+ !isFinished(item) && (item.status === 'downloading' || item.status === 'queued')
+ )
+ const resumable = chosen.filter(
+ (item): item is DownloadState => !isFinished(item) && item.status === 'paused'
+ )
+ const retryable = chosen.filter(
+ (item): item is DownloadState =>
+ !isFinished(item) && item.status === 'error' && item.resumable !== false && !linkExpired(item)
+ )
+ const unfinished = chosen.filter((item) => !isFinished(item) && item.status !== 'completed')
+ const finished = chosen.filter((item) => isFinished(item) || item.status === 'completed')
+ const trashable = finished.filter(
+ (item) =>
+ !(isFinished(item) && item.missing) &&
+ (item.kind !== 'torrent' ||
+ !item.folder ||
+ !isFinished(item) ||
+ !!item.downloadedFiles?.length)
+ )
+ const confirmationItems = confirmation
+ ? chosen.filter(
+ (item) =>
+ confirmation.ids.includes(item.id) &&
+ (confirmation.kind === 'cancel' ? unfinished.includes(item) : trashable.includes(item))
+ )
+ : []
+
+ const runAction = async (
+ targets: Item[],
+ action: 'pause' | 'resume' | 'remove' | 'trash'
+ ): Promise<void> => {
+ if (busy) return
+ setBusy(true)
+ setActionError(null)
+ try {
+ for (const item of targets) {
+ if (action === 'pause') await window.plexo.pauseDownload(item.id)
+ else if (action === 'resume') await window.plexo.resumeDownload(item.id)
+ else {
+ await window.plexo.removeDownload(item.id, { trashFile: action === 'trash' })
+ useAppStore.setState((store) => {
+ const { [item.id]: removed, ...downloads } = store.downloads
+ void removed
+ return { downloads, history: store.history.filter((entry) => entry.id !== item.id) }
+ })
+ setSelected((previous) => {
+ const next = new Set(previous)
+ next.delete(item.id)
+ return next
+ })
+ }
+ }
+ } catch (error) {
+ setActionError(describeError(error))
+ } finally {
+ setBusy(false)
+ setConfirmation(null)
+ }
+ }
+
+ return (
+ <div className="flex h-full flex-col bg-background">
+ {chosen.length === 0 ? (
+ <div className="flex h-12 shrink-0 items-center gap-3 border-b-[0.5px] border-border px-5">
+ <DownloadFilterMenu
+ value={filter}
+ counts={counts}
+ onChange={(next) => {
+ setFilter(next)
+ setSelected(new Set())
+ }}
+ />
+ {/* One group already says it in its header. */}
+ {allGroups.length > 1 && (
+ <div className="font-mono text-[11.5px] leading-none text-muted-foreground">
+ {summaryOf(downloads)}
+ </div>
+ )}
+ <div className="flex-1" />
+ <NetworksMenu
+ onOpenLimits={(page) => {
+ setLimitsPage(page)
+ setLimitsOpen(true)
+ }}
+ />
+ <Button type="button" onClick={() => openNewDownload()}>
+ <Plus data-icon="inline-start" />
+ New download
+ </Button>
+ </div>
+ ) : (
+ <div
+ role="toolbar"
+ aria-label="Selected downloads"
+ aria-busy={busy}
+ className="flex h-12 shrink-0 items-center gap-3 border-b-[0.5px] border-border px-5"
+ >
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ aria-label="Deselect all"
+ disabled={busy}
+ onClick={() => setSelected(new Set())}
+ >
+ <X />
+ </Button>
+ }
+ />
+ <TooltipContent>Deselect all</TooltipContent>
+ </Tooltip>
+ <span className="shrink-0 whitespace-nowrap text-[13px] font-semibold">
+ {chosen.length} selected
+ </span>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ disabled={busy || chosen.length === items.length}
+ onClick={() => setSelected(new Set(items.map((item) => item.id)))}
+ >
+ Select all
+ </Button>
+ <div className="flex-1" />
+ <div className="flex min-w-0 items-center gap-2 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+ {pausable.length > 0 && (
+ <Button
+ type="button"
+ size="sm"
+ variant="secondary"
+ disabled={busy}
+ onClick={() => void runAction(pausable, 'pause')}
+ >
+ Pause ({pausable.length})
+ </Button>
+ )}
+ {resumable.length > 0 && (
+ <Button
+ type="button"
+ size="sm"
+ variant="secondary"
+ disabled={busy}
+ onClick={() => void runAction(resumable, 'resume')}
+ >
+ Resume ({resumable.length})
+ </Button>
+ )}
+ {retryable.length > 0 && (
+ <Button
+ type="button"
+ size="sm"
+ variant="secondary"
+ disabled={busy}
+ onClick={() => void runAction(retryable, 'resume')}
+ >
+ Retry ({retryable.length})
+ </Button>
+ )}
+ {finished.length > 0 && (
+ <Button
+ type="button"
+ size="sm"
+ variant="secondary"
+ disabled={busy}
+ onClick={() => void runAction(finished, 'remove')}
+ >
+ Remove from list ({finished.length})
+ </Button>
+ )}
+ {unfinished.length > 0 && (
+ <Button
+ type="button"
+ size="sm"
+ variant="destructive"
+ disabled={busy}
+ onClick={() =>
+ setConfirmation({ kind: 'cancel', ids: unfinished.map((item) => item.id) })
+ }
+ >
+ Cancel downloads… ({unfinished.length})
+ </Button>
+ )}
+ {trashable.length > 0 && (
+ <Button
+ type="button"
+ size="sm"
+ variant="destructive"
+ disabled={busy}
+ onClick={() =>
+ setConfirmation({ kind: 'trash', ids: trashable.map((item) => item.id) })
+ }
+ >
+ Move files to {window.plexo.platform === 'win32' ? 'Recycle Bin' : 'Trash'}… (
+ {trashable.length})
+ </Button>
+ )}
+ </div>
+ </div>
+ )}
+ {actionError && (
+ <div role="alert" className="border-b border-border px-5 py-2 text-[12px] text-destructive">
+ {actionError}
+ </div>
+ )}
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-5 pb-5">
+ {groups.length === 0 &&
+ (filter === 'all' ? (
+ <EmptyState />
+ ) : (
+ <div role="status" className="flex flex-col items-center gap-2 px-5 py-16 text-center">
+ <p className="text-[16px] font-semibold">
+ {filter === 'progress'
+ ? 'No downloads in progress'
+ : filter === 'finished'
+ ? 'No finished downloads'
+ : 'No downloads need attention'}
+ </p>
+ <Button type="button" variant="secondary" onClick={() => setFilter('all')}>
+ Show all downloads
+ </Button>
+ </div>
+ ))}
+ {groups.map((group) => {
+ const ids = group.items.map((item) => item.id)
+ const all = ids.every((id) => selected.has(id))
+ const some = !all && ids.some((id) => selected.has(id))
+ return (
+ <section key={group.label} aria-label={group.label}>
+ <div className="group/group-header flex items-center gap-3 border-b-[0.5px] border-border pt-5 pb-3">
+ <Checkbox
+ className={cn(
+ chosen.length === 0 &&
+ 'opacity-0 group-focus-within/group-header:opacity-100 group-hover/group-header:opacity-100'
+ )}
+ aria-label={
+ group.label === 'Needs attention'
+ ? 'Select all downloads needing attention'
+ : `Select all ${group.label.toLowerCase()} downloads`
+ }
+ checked={all}
+ indeterminate={some}
+ onCheckedChange={(on) => toggle(ids, on)}
+ />
+ <h2 className={groupLabelClass}>
+ {group.label}
+ <span className="ml-2.5 tracking-normal">{group.items.length}</span>
+ </h2>
+ <div className="flex-1" />
+ {group.label === 'Finished' && history.length > 0 && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ className="text-[12.5px] text-[var(--text-secondary)] hover:text-foreground"
+ onClick={() => void window.plexo.clearHistory()}
+ >
+ Clear finished list
+ </button>
+ }
+ />
+ <TooltipContent>Downloaded files stay on your computer</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ {group.items.map((item) => (
+ <DownloadRow
+ key={item.id}
+ item={item}
+ now={now}
+ selected={selected.has(item.id)}
+ selecting={chosen.length > 0}
+ networkVisual={
+ isFinished(item) || item.status === 'completed' ? undefined : networkVisual
+ }
+ onSelect={selectRow}
+ onOpen={openRow}
+ onFix={fixRow}
+ onAgain={againRow}
+ />
+ ))}
+ </section>
+ )
+ })}
+ </div>
+
+ <FixLinkDialog download={fixing} onClose={() => setFixing(null)} />
+ <LimitsDialog
+ open={limitsOpen}
+ onOpenChange={setLimitsOpen}
+ page={limitsPage}
+ onPageChange={setLimitsPage}
+ />
+
+ <AlertDialog
+ open={confirmation !== null}
+ onOpenChange={(open) => !open && setConfirmation(null)}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {confirmation?.kind === 'cancel'
+ ? 'Cancel'
+ : `Move files to ${window.plexo.platform === 'win32' ? 'Recycle Bin' : 'Trash'} for`}{' '}
+ {confirmationItems.length} {confirmationItems.length === 1 ? 'download' : 'downloads'}
+ ?
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {confirmation?.kind === 'cancel'
+ ? 'This stops the selected unfinished downloads and deletes their downloaded data. Finished downloads stay unchanged.'
+ : `This moves the selected finished downloads’ files to the ${window.plexo.platform === 'win32' ? 'Recycle Bin' : 'Trash'} and removes them from the list. Unrelated files stay in place.`}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ disabled={busy || confirmationItems.length === 0}
+ className={buttonVariants({ variant: 'destructive', size: 'sm' })}
+ onClick={() =>
+ void runAction(
+ confirmationItems,
+ confirmation?.kind === 'cancel' ? 'remove' : 'trash'
+ )
+ }
+ >
+ {confirmation?.kind === 'cancel'
+ ? 'Cancel downloads'
+ : `Move files to ${window.plexo.platform === 'win32' ? 'Recycle Bin' : 'Trash'}`}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ )
+}
+
+// Colors are irrelevant here — the diagram is rendered `muted`, which overrides them all to
+// var(--icon-muted) — these are just three placeholder rows to draw the illustration with.
+const PLACEHOLDER_NETWORKS = [
+ { solid: 'var(--icon-muted)', label: 'Wi-Fi' },
+ { solid: 'var(--icon-muted)', label: 'USB' },
+ { solid: 'var(--icon-muted)', label: 'Ethernet' }
+]
+const PASTE_SHORTCUT = window.plexo.platform === 'darwin' ? '⌘V' : 'Ctrl+V'
+const NEW_SHORTCUT = window.plexo.platform === 'darwin' ? '⌘N' : 'Ctrl+N'
+
+/** Nothing listed yet: how to start one — or, with no network connected, how to get one. */
+function EmptyState(): React.JSX.Element {
+ const noNetworks = useAppStore(
+ (store) => store.interfacesStatus === 'ready' && store.interfaces.length === 0
+ )
+ const loadInterfaces = useAppStore((store) => store.loadInterfaces)
+ const openNewDownload = useAppStore((store) => store.openNewDownload)
+
+ return (
+ <div className="flex flex-col items-center gap-4 px-5 pt-16 pb-10 text-center">
+ <CombineDiagram networks={PLACEHOLDER_NETWORKS} muted />
+ {noNetworks ? (
+ <>
+ <div className="font-sans text-[16px] leading-[1.2] font-bold">No networks connected</div>
+ <div className="max-w-[380px] text-[12.5px] leading-[1.6] text-[var(--text-secondary)]">
+ Plexo needs at least one active network. Join a Wi-Fi network, plug in Ethernet, or
+ connect your phone using USB tethering.
+ </div>
+ <div className="mt-1 flex gap-2">
+ <Button type="button" variant="secondary" onClick={() => loadInterfaces()}>
+ Scan again
+ </Button>
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => window.plexo.openNetworkSettings()}
+ >
+ Network settings…
+ </Button>
+ </div>
+ </>
+ ) : (
+ <>
+ <div className="font-sans text-[16px] leading-[1.2] font-bold">No downloads yet</div>
+ <div className="max-w-[380px] text-[12.5px] leading-[1.6] text-[var(--text-secondary)]">
+ Paste a link ({PASTE_SHORTCUT}) or drop a .torrent anywhere in this window.
+ </div>
+ <Button type="button" className="mt-1" onClick={() => openNewDownload()}>
+ <Plus data-icon="inline-start" />
+ New download
+ <span className="ml-1 font-mono text-[11px] opacity-70">{NEW_SHORTCUT}</span>
+ </Button>
+ </>
+ )}
+ </div>
+ )
+}
+
+const DownloadRow = memo(function DownloadRow({
+ item,
+ now,
+ selected,
+ selecting,
+ networkVisual,
+ onSelect,
+ onOpen,
+ onFix,
+ onAgain
+}: {
+ item: Item
+ now: number
+ selected: boolean
+ /** Something is selected: every checkbox shows, not just the hovered row's. */
+ selecting: boolean
+ /** Colors its progress bar; a finished row has none. */
+ networkVisual?: ResolveNetworkVisual
+ onSelect: (id: string, on: boolean) => void
+ onOpen: (id: string) => void
+ onFix: (item: Item) => void
+ onAgain: (item: Item) => void
+}): React.JSX.Element {
+ const finished = isFinished(item) || item.status === 'completed'
+ const badge = isFolder(item) ? 'DIR' : fileExtensionBadge(item.fileName)
+ const wanted = wantedBytes(item)
+ const percent = formatPercent(item.bytesDownloaded, wanted)
+
+ let detail: string
+ let tone = 'text-muted-foreground'
+ let action: { label: string; run: () => void; icon?: LucideIcon } | null = null
+ if (isFinished(item) || item.status === 'completed') {
+ detail = [
+ formatBytes(wanted || item.bytesDownloaded),
+ // A torrent's badge already says where it came from.
+ item.kind === 'http' && sourceOf(item.url),
+ isFinished(item) && item.missing
+ ? 'moved or deleted'
+ : formatWhen(item.completedAt ?? now, now)
+ ]
+ .filter(Boolean)
+ .join(' · ')
+ } else {
+ const download = item
+ const sizes =
+ wanted > 0
+ ? `${formatBytes(download.bytesDownloaded)} of ${formatBytes(wanted)}`
+ : formatBytes(download.bytesDownloaded)
+ switch (download.status) {
+ case 'downloading':
+ detail = [
+ wanted > 0 && `${percent}%`,
+ sizes,
+ formatSpeed(download.speedBytesPerSec),
+ download.timeLeftSeconds !== undefined && formatEta(download.timeLeftSeconds)
+ ]
+ .filter(Boolean)
+ .join(' · ')
+ action = {
+ label: 'Pause',
+ icon: Pause,
+ run: () => void window.plexo.pauseDownload(download.id)
+ }
+ break
+ case 'queued':
+ detail = `Waiting for a turn · ${sizes}`
+ action = {
+ label: 'Pause',
+ icon: Pause,
+ run: () => void window.plexo.pauseDownload(download.id)
+ }
+ break
+ case 'paused':
+ detail = wanted > 0 ? `Paused at ${percent}% · ${sizes}` : `Paused · ${sizes}`
+ action = {
+ label: 'Resume',
+ icon: Play,
+ run: () => void window.plexo.resumeDownload(download.id)
+ }
+ break
+ default:
+ detail = describeError(download.error ?? 'Something went wrong')
+ tone = 'text-[var(--color-danger)]'
+ if (linkExpired(download)) action = { label: 'Fix link', run: () => onFix(item) }
+ else if (download.resumable !== false) {
+ action = {
+ label: 'Retry',
+ icon: RotateCw,
+ run: () => void window.plexo.resumeDownload(download.id)
+ }
+ } else action = { label: 'Download again', run: () => onAgain(item) }
+ }
+ }
+
+ // The bar shows each network's share of the file in its color; a failed one shows in red.
+ const segments =
+ finished || isFinished(item) || !networkVisual
+ ? []
+ : item.status === 'error'
+ ? [
+ {
+ id: 'error',
+ share: item.bytesDownloaded / (wanted || 1),
+ color: 'var(--color-danger)'
+ }
+ ]
+ : item.networks
+ .filter((network) => network.bytesDownloaded > 0)
+ .map((network) => ({
+ id: network.id,
+ share: network.bytesDownloaded / (wanted || 1),
+ color: networkVisual(network.id, network.kind, network.label).solid
+ }))
+
+ return (
+ <div
+ data-selected={selected || undefined}
+ className={cn(
+ 'group/download-row my-0.5 -mx-2 flex items-center gap-3 rounded-lg px-2 py-3 transition-colors',
+ selected
+ ? 'bg-primary/10 hover:bg-primary/15 focus-within:bg-primary/15'
+ : 'hover:bg-secondary focus-within:bg-secondary'
+ )}
+ >
+ <Checkbox
+ className={cn(
+ !selecting &&
+ !selected &&
+ 'opacity-0 group-focus-within/download-row:opacity-100 group-hover/download-row:opacity-100'
+ )}
+ aria-label={`Select ${item.fileName}`}
+ checked={selected}
+ onCheckedChange={(on) => onSelect(item.id, on)}
+ />
+ <button
+ type="button"
+ onClick={() => onOpen(item.id)}
+ className="flex min-w-0 flex-1 items-center gap-3 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg border-[0.5px] border-border bg-card font-mono text-[10px] font-semibold text-muted-foreground">
+ {badge}
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="truncate font-sans text-[14px] leading-tight font-medium">
+ {item.fileName}
+ </span>
+ {item.kind === 'torrent' && <TorrentBadge />}
+ </div>
+ {segments.length > 0 && (
+ <div
+ className={cn(
+ 'flex h-1 overflow-hidden rounded-full bg-muted',
+ // Not moving: the colors stay, faded, so it doesn't read as running.
+ !isFinished(item) &&
+ (item.status === 'paused' || item.status === 'queued') &&
+ 'opacity-40'
+ )}
+ >
+ {segments.map((segment) => (
+ <div
+ key={segment.id}
+ style={{
+ width: `${Math.min(100, segment.share * 100)}%`,
+ background: segment.color
+ }}
+ />
+ ))}
+ </div>
+ )}
+ <div className={`truncate font-mono text-[11.5px] leading-tight ${tone}`}>{detail}</div>
+ </div>
+ </button>
+ {action?.icon ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ aria-label={`${action.label} ${item.fileName}`}
+ onClick={action.run}
+ className="text-muted-foreground group-hover/download-row:text-foreground"
+ >
+ <action.icon />
+ </Button>
+ }
+ />
+ <TooltipContent>{action.label}</TooltipContent>
+ </Tooltip>
+ ) : (
+ action && (
+ <Button type="button" size="sm" variant="secondary" onClick={action.run}>
+ {action.label}
+ </Button>
+ )
+ )}
+ <button
+ type="button"
+ aria-label={`Open ${item.fileName}`}
+ onClick={() => onOpen(item.id)}
+ className="rounded-md p-1 text-muted-foreground transition-colors group-hover/download-row:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
+ >
+ <ChevronRight className="size-4" />
+ </button>
+ </div>
+ )
+})
diff --git a/src/renderer/src/screens/ErrorScreen.tsx b/src/renderer/src/screens/ErrorScreen.tsx
index 7cbe85d..663535c 100644
--- a/src/renderer/src/screens/ErrorScreen.tsx
+++ b/src/renderer/src/screens/ErrorScreen.tsx
@@ -1,34 +1,48 @@
import type { DownloadState } from '@shared/types'
+import { Folder } from 'lucide-react'
import { useState } from 'react'
-import { ScreenFooter } from '../components/ScreenFooter'
+import { FixLinkDialog } from '../components/FixLinkDialog'
+import { DetailHeader } from '../components/DetailHeader'
import { TruncatedText } from '../components/TruncatedText'
import { Button } from '../components/ui/button'
-import { describeError, fileExtensionBadge, formatBytes } from '../utils/format'
+import {
+ describeError,
+ fileExtensionBadge,
+ formatBytes,
+ isFolder,
+ linkExpired,
+ wantedBytes
+} from '../utils/format'
+import { useAppStore } from '../store/useAppStore'
-export function ErrorScreen({
- download,
- onNewDownload,
- onDownloadAgain
-}: {
- download: DownloadState
- onNewDownload: () => void
- onDownloadAgain: () => void
-}): React.JSX.Element {
+export function ErrorScreen({ download }: { download: DownloadState }): React.JSX.Element {
+ const removeDownload = useAppStore((store) => store.removeDownload)
+ const openNewDownload = useAppStore((store) => store.openNewDownload)
+ const setView = useAppStore((store) => store.setView)
+ // Nothing of it can be kept: it goes, and its link waits in New download to start over.
+ const handleDownloadAgain = (): void => {
+ removeDownload(download.id)
+ setView({ name: 'list' })
+ openNewDownload(download.url)
+ }
const [copied, setCopied] = useState(false)
const [resuming, setResuming] = useState(false)
+ const [fixing, setFixing] = useState(false)
+ // Its link stopped working: a fresh one carries on from here, rather than Resume asking again.
+ const expired = linkExpired(download)
const cancelled = download.status === 'cancelled'
// What it downloaded is still there to pick up from.
const resumable = !cancelled && download.resumable !== false && download.bytesDownloaded > 0
const knownSize = download.totalBytes > 0
const percent = knownSize
- ? Math.min(100, Math.round((download.bytesDownloaded / download.totalBytes) * 100))
+ ? Math.min(100, Math.round((download.bytesDownloaded / wantedBytes(download)) * 100))
: 0
- const heading = cancelled ? 'Download Cancelled' : 'Download Failed'
+ const heading = cancelled ? 'Download cancelled' : 'Download failed'
const description = cancelled
? 'The download was stopped before finishing.'
: download.error
? describeError(download.error)
- : 'An error occurred during transfer.'
+ : 'The download stopped unexpectedly. Try again.'
const handleCopyUrl = async (): Promise<void> => {
try {
@@ -42,8 +56,30 @@ export function ErrorScreen({
return (
<div className="flex h-full flex-col bg-background">
+ <DetailHeader download={download}>
+ {expired ? (
+ <Button type="button" onClick={() => setFixing(true)}>
+ Fix link
+ </Button>
+ ) : resumable ? (
+ <Button
+ type="button"
+ disabled={resuming}
+ onClick={() => {
+ setResuming(true)
+ void window.plexo.resumeDownload(download.id).finally(() => setResuming(false))
+ }}
+ >
+ {resuming ? 'Retrying…' : 'Retry'}
+ </Button>
+ ) : (
+ <Button type="button" onClick={handleDownloadAgain}>
+ Download again
+ </Button>
+ )}
+ </DetailHeader>
<div className="flex flex-1 flex-col items-center justify-center px-5 py-6">
- <div className="flex w-full max-w-[440px] flex-col items-center gap-[18px] rounded-[14px] border-[0.5px] border-[var(--border-strong)] bg-card p-[28px_24px] text-center shadow-[0_16px_40px_rgba(0,0,0,0.45),0_2px_8px_rgba(0,0,0,0.2)]">
+ <div className="flex w-full max-w-[440px] flex-col items-center gap-[18px] rounded-xl border-[0.5px] border-border bg-card p-6 text-center">
{/* Status Icon */}
<div
className={`flex size-12 shrink-0 items-center justify-center rounded-full border ${
@@ -109,7 +145,11 @@ export function ErrorScreen({
{/* File capsule */}
<div className="flex w-full items-center gap-[11px] rounded-[9px] border-[0.5px] border-border bg-background p-[10px_12px] text-left">
<div className="flex size-[34px] shrink-0 items-center justify-center rounded-[7px] border-[0.5px] border-[var(--border-strong)] bg-card font-mono text-[8.5px] leading-none font-semibold text-[var(--text-secondary)]">
- {fileExtensionBadge(download.fileName)}
+ {isFolder(download) ? (
+ <Folder aria-label="Folder" className="size-[15px]" />
+ ) : (
+ fileExtensionBadge(download.fileName)
+ )}
</div>
<div className="min-w-0 flex-1">
<TruncatedText
@@ -121,59 +161,34 @@ export function ErrorScreen({
<>
{formatBytes(download.bytesDownloaded)}
{knownSize
- ? ` of ${formatBytes(download.totalBytes)} (${percent}%)`
- : ' transferred'}
+ ? ` of ${formatBytes(wantedBytes(download))} (${percent}%)`
+ : ' downloaded'}
</>
) : (
- 'No data transferred'
+ 'No data downloaded'
)}
</div>
</div>
</div>
- {/* Action Buttons in Center */}
- <div className="mt-1 flex w-full justify-center gap-2.5">
- {resumable && (
- <Button
- type="button"
- disabled={resuming}
- onClick={() => {
- setResuming(true)
- void window.plexo.resumeDownload(download.id).finally(() => setResuming(false))
- }}
- >
- {resuming ? 'Resuming…' : 'Resume'}
- </Button>
- )}
- <Button
+ <div className="flex w-full min-w-0 items-center gap-2 border-t-[0.5px] border-border pt-3">
+ <div className="min-w-0 flex-1 text-left font-mono text-[11px] leading-none text-muted-foreground">
+ <TruncatedText text={download.url} />
+ </div>
+ <button
type="button"
- variant={resumable ? 'secondary' : 'default'}
- onClick={onDownloadAgain}
+ onClick={handleCopyUrl}
+ className={`min-h-6 shrink-0 border-none bg-transparent px-1 py-0.5 font-mono text-[11px] leading-none ${
+ copied ? 'text-[var(--color-success)]' : 'text-primary'
+ }`}
>
- Download Again
- </Button>
- <Button type="button" variant="secondary" onClick={onNewDownload}>
- New Download
- </Button>
+ {copied ? 'Copied' : 'Copy link'}
+ </button>
</div>
</div>
</div>
- {/* Footer with properly constrained, non-overflowing URL */}
- <ScreenFooter className="min-w-0">
- <div className="min-w-0 flex-1 font-mono text-[11px] leading-none text-muted-foreground">
- <TruncatedText text={download.url} />
- </div>
- <button
- type="button"
- onClick={handleCopyUrl}
- className={`min-h-6 shrink-0 border-none bg-transparent px-1 py-0.5 font-mono text-[11px] leading-none ${
- copied ? 'text-[var(--color-success)]' : 'text-primary'
- }`}
- >
- {copied ? 'Copied' : 'Copy URL'}
- </button>
- </ScreenFooter>
+ <FixLinkDialog download={fixing ? download : null} onClose={() => setFixing(false)} />
</div>
)
}
diff --git a/src/renderer/src/screens/IdleScreen.tsx b/src/renderer/src/screens/IdleScreen.tsx
deleted file mode 100644
index ea66fb8..0000000
--- a/src/renderer/src/screens/IdleScreen.tsx
+++ /dev/null
@@ -1,389 +0,0 @@
-import type { ProbeResult } from '@shared/types'
-import { cn } from 'cn'
-import { AlertTriangle, ClipboardPaste, Info } from 'lucide-react'
-import { useEffect, useRef, useState } from 'react'
-import { NetworkCard } from '../components/NetworkCard'
-import { ScreenFooter } from '../components/ScreenFooter'
-import { Alert, AlertDescription, AlertTitle } from '../components/ui/alert'
-import { Button } from '../components/ui/button'
-import { ToggleGroup, ToggleGroupItem } from '../components/ui/toggle-group'
-import { useLatencyPolling } from '../hooks/useNetworks'
-import { useAppStore } from '../store/useAppStore'
-import { describeError, formatBytes, toDisplayPath } from '../utils/format'
-
-type StreamsChoice = 'auto' | number
-/** Streams per network the user can pick instead of Auto. */
-const STREAMS_CHOICES: StreamsChoice[] = ['auto', 4, 8, 16, 32]
-
-type ProbeState =
- | { status: 'idle' }
- | { status: 'probing' }
- | { status: 'ready'; result: ProbeResult }
- | { status: 'error'; message: string }
-
-const PROBE_DEBOUNCE_MS = 600
-const PASTE_SHORTCUT = window.plexo.platform === 'darwin' ? '⌘V' : 'Ctrl+V'
-
-const fieldLabelClass = 'shrink-0 font-mono text-[10px] tracking-[0.14em] text-muted-foreground'
-
-function ErrorAlert({ message }: { message: string }): React.JSX.Element {
- return (
- <Alert variant="destructive" className="py-1.5">
- <AlertTriangle />
- <AlertDescription>{message}</AlertDescription>
- </Alert>
- )
-}
-
-function WarningAlert({ title, message }: { title?: string; message: string }): React.JSX.Element {
- return (
- <Alert className="border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300 py-2">
- <AlertTriangle className="text-amber-600 dark:text-amber-400" />
- {title && <AlertTitle className="text-xs font-semibold">{title}</AlertTitle>}
- <AlertDescription className="text-xs text-amber-800 dark:text-amber-200/90 leading-relaxed">
- {message}
- </AlertDescription>
- </Alert>
- )
-}
-
-function InfoAlert({ title, message }: { title?: string; message: string }): React.JSX.Element {
- return (
- <Alert className="border-blue-500/40 bg-blue-500/10 text-blue-700 dark:text-blue-300 py-2">
- <Info className="text-blue-600 dark:text-blue-400" />
- {title && <AlertTitle className="text-xs font-semibold">{title}</AlertTitle>}
- <AlertDescription className="text-xs text-blue-800 dark:text-blue-200/90 leading-relaxed">
- {message}
- </AlertDescription>
- </Alert>
- )
-}
-
-export function IdleScreen(): React.JSX.Element {
- useLatencyPolling()
-
- const interfaces = useAppStore((store) => store.interfaces)
- const homeDir = useAppStore((store) => store.homeDir)
- const latencies = useAppStore((store) => store.latencies)
- const url = useAppStore((store) => store.draftUrl)
- const setUrl = useAppStore((store) => store.setDraftUrl)
- const destinationDir = useAppStore((store) => store.destinationDir)
- const setDestinationDir = useAppStore((store) => store.setDestinationDir)
-
- const [probe, setProbe] = useState<ProbeState>({ status: 'idle' })
- // Tracks deselections rather than selections, so a newly-detected interface starts selected.
- const [deselectedInterfaceIds, setDeselectedInterfaceIds] = useState<string[]>([])
- const [starting, setStarting] = useState(false)
- const [startError, setStartError] = useState<string | null>(null)
- const [fileNameOverride, setFileNameOverride] = useState<string | null>(null)
- // Auto unless the user picks a count for this download; not remembered for the next one.
- const [streamsChoice, setStreamsChoice] = useState<StreamsChoice>('auto')
-
- const probeRequestId = useRef(0)
-
- useEffect(() => {
- const trimmed = url.trim()
- if (!trimmed) {
- // Resetting derived probe state when its trigger (the URL) is cleared.
- // eslint-disable-next-line react-hooks/set-state-in-effect
- setProbe({ status: 'idle' })
- setFileNameOverride(null)
- return
- }
-
- const requestId = ++probeRequestId.current
- setProbe({ status: 'probing' })
- setFileNameOverride(null)
- const timer = setTimeout(async () => {
- try {
- const result = await window.plexo.probeUrl(trimmed)
- if (probeRequestId.current !== requestId) return
- setProbe({ status: 'ready', result })
- } catch (error) {
- if (probeRequestId.current !== requestId) return
- setProbe({ status: 'error', message: describeError(error) })
- }
- }, PROBE_DEBOUNCE_MS)
-
- return () => clearTimeout(timer)
- }, [url])
-
- const ready = probe.status === 'ready' ? probe.result : null
- const multiChunkAllowed = ready !== null && ready.supportsRanges && ready.totalBytes !== null
- const isSingleStreamOnly = ready !== null && !multiChunkAllowed
- // One request has to carry the whole file: either the server can't serve parts of it, or it
- // didn't say how big it is, so there's no telling where the parts would be.
- const sizeUnknown = isSingleStreamOnly && ready.supportsRanges
-
- const detectedIds = interfaces.map((iface) => iface.id)
- const enabledIds = detectedIds.filter((id) => !deselectedInterfaceIds.includes(id))
- const selectedInterfaceIds = isSingleStreamOnly ? enabledIds.slice(0, 1) : enabledIds
-
- const startLabel = starting ? 'Starting…' : probe.status === 'probing' ? 'Checking…' : 'Start'
- const canStart =
- probe.status === 'ready' &&
- selectedInterfaceIds.length > 0 &&
- Boolean(destinationDir) &&
- !starting
- const footerParts = [
- `${selectedInterfaceIds.length} ${selectedInterfaceIds.length === 1 ? 'network' : 'networks'} selected`
- ]
- // How many streams each network gets is worked out during the download; the one case worth
- // saying up front is a server that can't split the file at all.
- if (isSingleStreamOnly) {
- footerParts.push(
- sizeUnknown
- ? '1 stream: the file’s size isn’t known'
- : '1 stream: the server can’t split this file'
- )
- }
- if (ready && ready.totalBytes !== null) footerParts.push(formatBytes(ready.totalBytes))
-
- let subnetConflict: { subnet: string; names: string[] } | null = null
- if (selectedInterfaceIds.length > 1) {
- const subnets = new Map<string, string[]>()
- for (const id of selectedInterfaceIds) {
- const iface = interfaces.find((i) => i.id === id)
- const subnet = iface?.addresses.find((address) => address.family === 4)?.subnet
- if (subnet) {
- const names = subnets.get(subnet) ?? []
- names.push(iface.displayName)
- subnets.set(subnet, names)
- }
- }
- for (const [subnet, names] of subnets.entries()) {
- if (names.length > 1) {
- subnetConflict = { subnet, names }
- break
- }
- }
- }
-
- const handleToggleInterface = (id: string): void => {
- if (isSingleStreamOnly) {
- // Single-stream mode can only download through 1 interface at a time
- setDeselectedInterfaceIds(detectedIds.filter((otherId) => otherId !== id))
- return
- }
-
- setDeselectedInterfaceIds((prev) => {
- const isCurrentlySelected = !prev.includes(id)
- if (isCurrentlySelected) {
- // Deselecting: keep at least 1 interface selected
- const remainingCount = detectedIds.filter(
- (otherId) => !prev.includes(otherId) && otherId !== id
- ).length
- if (remainingCount === 0) return prev
- return [...prev, id]
- } else {
- return prev.filter((entry) => entry !== id)
- }
- })
- }
-
- const handleBrowse = async (): Promise<void> => {
- const chosen = await window.plexo.chooseDestinationFolder(destinationDir)
- if (chosen) setDestinationDir(chosen)
- }
-
- const handlePaste = async (): Promise<void> => {
- const text = await window.plexo.readClipboardText()
- if (text.trim()) setUrl(text.trim())
- }
-
- const handleStart = async (): Promise<void> => {
- if (probe.status !== 'ready' || !canStart) return
- setStarting(true)
- setStartError(null)
- try {
- await window.plexo.startDownload({
- url: probe.result.finalUrl,
- destinationDir,
- suggestedFileName: fileNameOverride?.trim() || probe.result.suggestedFileName,
- totalBytes: probe.result.totalBytes ?? 0,
- supportsRanges: multiChunkAllowed,
- interfaceIds: selectedInterfaceIds,
- etag: probe.result.etag,
- lastModified: probe.result.lastModified,
- streamsPerNetwork: streamsChoice === 'auto' ? undefined : streamsChoice
- })
- } catch (error) {
- setStartError(describeError(error))
- } finally {
- setStarting(false)
- }
- }
-
- return (
- <div className="flex h-full flex-col bg-background">
- <div className="flex flex-col gap-[9px] px-5 pt-4 pb-3.5">
- <div className="flex items-center gap-[9px]">
- <div
- className={cn(
- 'flex h-9 min-w-0 flex-1 items-center gap-[9px] rounded-[9px] border bg-[var(--input-bg)] px-3',
- probe.status === 'error' ? 'border-destructive' : 'border-input'
- )}
- >
- <div id="idle-link-label" className={fieldLabelClass}>
- LINK
- </div>
- <input
- type="url"
- value={url}
- onChange={(event) => setUrl(event.target.value)}
- placeholder="https://"
- spellCheck={false}
- aria-labelledby="idle-link-label"
- className="min-w-0 flex-1 rounded-[3px] border-none bg-transparent font-mono text-[13px] text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
- />
- <Button
- type="button"
- variant="secondary"
- size="xs"
- onClick={handlePaste}
- className="shrink-0 font-mono text-[9.5px] uppercase tracking-wide"
- >
- <ClipboardPaste data-icon="inline-start" />
- Paste {PASTE_SHORTCUT}
- </Button>
- </div>
- <Button
- type="button"
- onClick={handleStart}
- disabled={!canStart}
- className="h-9 w-28 shrink-0"
- >
- {startLabel}
- </Button>
- </div>
-
- {probe.status === 'error' && <ErrorAlert message={probe.message} />}
-
- {isSingleStreamOnly && (
- <InfoAlert
- title="Single-connection mode"
- message={
- sizeUnknown
- ? 'The server didn’t say how big this file is, so it can’t be split into parts. The download will run as a single stream through whichever network you choose below.'
- : 'This server does not support parallel range requests (206 Partial Content). The download will run as a single stream through whichever network you choose below.'
- }
- />
- )}
-
- {subnetConflict && (
- <WarningAlert
- title="Same local network detected"
- message={`${subnetConflict.names.join(' and ')} are connected to the same subnet (${subnetConflict.subnet}). The operating system routes all traffic through one connection on the same subnet, so speeds cannot be combined. Connect to distinct networks (e.g. Wi-Fi + phone USB tethering) to combine bandwidth.`}
- />
- )}
-
- <div
- className={cn(
- 'flex h-9 items-center gap-[9px] rounded-[9px] border px-3',
- ready ? 'border-border opacity-100' : 'border-dashed border-border opacity-50'
- )}
- >
- <div id="idle-saveas-label" className={fieldLabelClass}>
- SAVE AS
- </div>
- <input
- type="text"
- value={ready ? (fileNameOverride ?? ready.suggestedFileName) : ''}
- onChange={(event) => setFileNameOverride(event.target.value)}
- disabled={!ready}
- placeholder="—"
- aria-labelledby="idle-saveas-label"
- className="min-w-0 flex-1 rounded-[3px] border-none bg-transparent font-mono text-[12.5px] text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
- />
- {ready && ready.totalBytes !== null && (
- <div className="shrink-0 whitespace-nowrap font-mono text-[11px] font-medium text-muted-foreground">
- {formatBytes(ready.totalBytes)} (est.)
- </div>
- )}
- </div>
-
- <div className="flex h-9 items-center gap-[9px] rounded-[9px] border border-border px-3">
- <div className={fieldLabelClass}>TO</div>
- <div className="min-w-0 flex-1 truncate font-mono text-[12.5px] leading-normal text-[var(--text-secondary)]">
- {toDisplayPath(destinationDir, homeDir)}
- </div>
- <Button
- type="button"
- variant="link"
- size="xs"
- onClick={handleBrowse}
- className="h-auto shrink-0 px-0 font-mono text-[11px]"
- >
- Browse…
- </Button>
- </div>
-
- <div
- className={cn(
- 'flex min-h-9 flex-wrap items-center gap-x-3 gap-y-1 rounded-[9px] border border-border px-3 py-1.5',
- isSingleStreamOnly && 'opacity-60'
- )}
- >
- <div id="idle-streams-label" className={fieldLabelClass}>
- STREAMS
- </div>
- <ToggleGroup
- value={[String(streamsChoice)]}
- onValueChange={(values) => {
- if (values.length === 0) return
- setStreamsChoice(values[0] === 'auto' ? 'auto' : Number(values[0]))
- }}
- disabled={isSingleStreamOnly}
- aria-labelledby="idle-streams-label"
- variant="pill"
- size="xs"
- spacing={1}
- >
- {STREAMS_CHOICES.map((choice) => (
- // h-6/min-w-6: WCAG 2.5.8's 24px floor — the xs toggle size is 20px.
- <ToggleGroupItem key={choice} value={String(choice)} className="h-6 min-w-6 px-2">
- {choice === 'auto' ? 'Auto' : choice}
- </ToggleGroupItem>
- ))}
- </ToggleGroup>
- <div className="ml-auto font-mono text-[11px] whitespace-nowrap text-muted-foreground">
- {isSingleStreamOnly
- ? '1 stream'
- : streamsChoice === 'auto'
- ? 'per network, 8 up to 32'
- : 'per network'}
- </div>
- </div>
-
- {startError && <ErrorAlert message={startError} />}
- </div>
-
- <div className="flex-1 overflow-y-auto px-5 pb-3.5">
- <div className="flex items-baseline justify-between border-b border-border pb-2">
- <h2 className="font-mono text-[10px] tracking-[0.16em] text-muted-foreground uppercase">
- Connected Networks
- </h2>
- <div className="shrink-0 font-mono text-[10.5px] text-muted-foreground">
- {interfaces.length} detected · {selectedInterfaceIds.length} selected
- </div>
- </div>
-
- <div className="grid grid-cols-[repeat(auto-fit,minmax(190px,1fr))] gap-2.5 pt-3">
- {interfaces.map((iface) => (
- <NetworkCard
- key={iface.id}
- iface={iface}
- selected={selectedInterfaceIds.includes(iface.id)}
- latencyMs={latencies[iface.id]}
- onToggle={() => handleToggleInterface(iface.id)}
- />
- ))}
- </div>
- </div>
-
- <ScreenFooter className="gap-2.5">
- <div className="font-mono text-[11px] text-muted-foreground">{footerParts.join(' · ')}</div>
- </ScreenFooter>
- </div>
- )
-}
diff --git a/src/renderer/src/screens/NoConnectionsScreen.tsx b/src/renderer/src/screens/NoConnectionsScreen.tsx
deleted file mode 100644
index 7dfff2c..0000000
--- a/src/renderer/src/screens/NoConnectionsScreen.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { CombineDiagram } from '../components/CombineDiagram'
-import { ScreenFooter } from '../components/ScreenFooter'
-import { Button } from '../components/ui/button'
-import { useAppStore } from '../store/useAppStore'
-
-// Colors are irrelevant here — the diagram is rendered `muted`, which overrides them all to
-// var(--icon-muted) — these are just three placeholder rows to draw the illustration with.
-const PLACEHOLDER_NETWORKS = [
- { solid: 'var(--icon-muted)', label: 'Wi-Fi' },
- { solid: 'var(--icon-muted)', label: 'USB' },
- { solid: 'var(--icon-muted)', label: 'Ethernet' }
-]
-
-export function NoConnectionsScreen(): React.JSX.Element {
- const loadInterfaces = useAppStore((store) => store.loadInterfaces)
-
- return (
- <div className="flex h-full flex-col bg-background">
- <div className="flex flex-1 flex-col items-center justify-center gap-4 px-5 pt-10 pb-11">
- <CombineDiagram networks={PLACEHOLDER_NETWORKS} muted />
- <div className="font-sans text-[16px] leading-[1.2] font-bold text-foreground">
- No networks to combine
- </div>
- <div className="max-w-[380px] text-center font-sans text-[12.5px] leading-[1.6] text-[var(--text-secondary)]">
- Plexo needs at least one active network. Join a Wi-Fi network, plug in Ethernet, or
- connect an iPhone over USB with Personal Hotspot enabled.
- </div>
- <div className="mt-1 flex gap-2">
- <Button type="button" variant="secondary" onClick={() => loadInterfaces()}>
- Scan Again
- </Button>
- <Button
- type="button"
- variant="secondary"
- onClick={() => window.plexo.openNetworkSettings()}
- >
- Network Settings…
- </Button>
- </div>
- </div>
-
- <ScreenFooter className="gap-2.5">
- <div className="font-mono text-[11px] leading-[1.4] text-muted-foreground">
- 0 networks · watching for changes
- </div>
- <div className="flex-1" />
- <Button type="button" disabled>
- Start
- </Button>
- </ScreenFooter>
- </div>
- )
-}
diff --git a/src/renderer/src/store/useAppStore.ts b/src/renderer/src/store/useAppStore.ts
index 25026ff..e036d49 100644
--- a/src/renderer/src/store/useAppStore.ts
+++ b/src/renderer/src/store/useAppStore.ts
@@ -3,6 +3,7 @@ import type {
AppSettings,
DownloadState,
DownloadUpdate,
+ FinishedDownload,
NetworkInterfaceInfo,
NetworkPreference,
NetworkPreferences,
@@ -11,14 +12,12 @@ import type {
} from '@shared/types'
import { create } from 'zustand'
-type LoadStatus = 'idle' | 'loading' | 'ready' | 'error'
+export type DownloadFilter = 'all' | 'progress' | 'finished' | 'failed'
-const SPEED_HISTORY_LENGTH = 60
-const SPEED_SAMPLE_INTERVAL_MS = 1000
+type LoadStatus = 'idle' | 'loading' | 'ready' | 'error'
-// Throttling cadence lives outside the store's own state — it's bookkeeping for how often to
-// sample, not something a component should ever read or re-render on.
-let lastSpeedSampleAt = 0
+/** What the window shows: the list of downloads, or one download. */
+export type View = { name: 'list' } | { name: 'download'; id: string }
interface AppStore {
interfaces: NetworkInterfaceInfo[]
@@ -38,18 +37,26 @@ interface AppStore {
homeDir: string
downloadsDir: string
- /** Plexo focuses on one download at a time — this is it. */
- currentDownload: DownloadState | null
- speedHistory: number[]
- /** Same rolling window as speedHistory, split by physical network — for the stacked
- * per-network throughput chart, keyed by interface id. */
- speedHistoryByInterface: Record<string, number[]>
- /** Highest combined speed seen so far this download — a rolling history window would lose it
- * once it ages out, so this is tracked as a running max instead. */
- peakSpeedBytesPerSec: number
+ /** Every download that isn't finished, by id — running, queued, paused or failed. */
+ downloads: Record<string, DownloadState>
+ /** Finished downloads, newest first (see main/download/history.ts). */
+ history: FinishedDownload[]
+ view: View
+ downloadFilter: DownloadFilter
+ setDownloadFilter: (filter: DownloadFilter) => void
+ /** The New download dialog, over whatever the window shows. */
+ newDownloadOpen: boolean
+ /** Persisted — how many downloads run at once; the rest wait in the queue. */
+ downloadsAtOnce: number
+ /** Persisted — the speed limits (see AppSettings). */
+ speedLimit: number | undefined
+ slowMode: boolean
+ slowModeSpeed: number
/** Lifted out of the Idle screen so it survives a swap to/from the No-connections screen. */
draftUrl: string
+ /** The link last started: still on the clipboard afterwards, so not offered again. */
+ startedUrl: string
/** Persisted — the last folder picked, falling back to downloadsDir. */
destinationDir: string
@@ -61,9 +68,21 @@ interface AppStore {
setThemeSource: (source: ThemeSource) => void
checkForUpdate: () => Promise<void>
dismissUpdate: () => void
- /** A snapshot or an update of the current download, from the main process. */
+ /** A snapshot or an update of a download, from the main process. */
receiveDownloadUpdate: (update: DownloadUpdate) => void
- clearCurrentDownload: () => void
+ /** Finished downloads as main lists them; any that finished leave `downloads`. */
+ receiveHistory: (history: FinishedDownload[]) => void
+ /** Removes a download (cancelling one under way), or forgets a finished one. */
+ removeDownload: (id: string, options?: { trashFile?: boolean }) => void
+ setView: (view: View) => void
+ /** Opens New download, with `link` in its link field when one is given. */
+ openNewDownload: (link?: string) => void
+ closeNewDownload: () => void
+ setDownloadsAtOnce: (count: number) => void
+ /** Each one applies at once, to every download (see main/network/limits.ts). */
+ setSpeedLimit: (bytesPerSec: number | undefined) => void
+ setSlowMode: (on: boolean) => void
+ setSlowModeSpeed: (bytesPerSec: number) => void
setDraftUrl: (url: string) => void
setDestinationDir: (dir: string) => void
}
@@ -90,12 +109,19 @@ export const useAppStore = create<AppStore>((set, get) => ({
homeDir: initial.homeDir,
downloadsDir: initial.downloadsDir,
- currentDownload: null,
- speedHistory: [],
- speedHistoryByInterface: {},
- peakSpeedBytesPerSec: 0,
+ downloads: {},
+ history: [],
+ view: { name: 'list' },
+ downloadFilter: 'all',
+ setDownloadFilter: (downloadFilter) => set({ downloadFilter }),
+ newDownloadOpen: false,
+ downloadsAtOnce: initial.downloadsAtOnce,
+ speedLimit: initial.speedLimit,
+ slowMode: initial.slowMode,
+ slowModeSpeed: initial.slowModeSpeed,
draftUrl: '',
+ startedUrl: '',
destinationDir: initial.destinationDir ?? initial.downloadsDir,
loadInterfaces: async () => {
@@ -157,45 +183,54 @@ export const useAppStore = create<AppStore>((set, get) => ({
},
receiveDownloadUpdate: (update) => {
- const previous = get().currentDownload
+ const { downloads, history } = get()
+ // Finished already: an update that arrives late mustn't bring it back.
+ if (history.some((entry) => entry.id === update.state.id)) return
+ const previous = downloads[update.state.id] ?? null
const download = applyDownloadUpdate(previous, update)
if (!download || download === previous) return
- const isNewDownload = !previous || previous.id !== download.id
-
- let speedHistory = isNewDownload ? [] : get().speedHistory
- let speedHistoryByInterface = isNewDownload ? {} : get().speedHistoryByInterface
- let peakSpeedBytesPerSec = isNewDownload ? 0 : get().peakSpeedBytesPerSec
- if (isNewDownload) lastSpeedSampleAt = 0
-
- if (download.status === 'downloading') {
- peakSpeedBytesPerSec = Math.max(peakSpeedBytesPerSec, download.speedBytesPerSec)
-
- const now = Date.now()
- if (now - lastSpeedSampleAt >= SPEED_SAMPLE_INTERVAL_MS) {
- lastSpeedSampleAt = now
- speedHistory = [...speedHistory, download.speedBytesPerSec].slice(-SPEED_HISTORY_LENGTH)
-
- const nextByInterface: Record<string, number[]> = {}
- for (const network of download.networks) {
- const previousSeries = speedHistoryByInterface[network.id] ?? []
- nextByInterface[network.id] = [...previousSeries, network.speedBytesPerSec].slice(
- -SPEED_HISTORY_LENGTH
- )
- }
- speedHistoryByInterface = nextByInterface
- }
- }
+ set({ downloads: { ...downloads, [download.id]: download } })
+ },
+
+ receiveHistory: (history) => {
+ const downloads = { ...get().downloads }
+ for (const entry of history) delete downloads[entry.id]
+ set({ history, downloads })
+ },
+
+ removeDownload: (id, options) => {
+ const { [id]: removed, ...downloads } = get().downloads
+ void removed
+ set({ downloads, history: get().history.filter((entry) => entry.id !== id) })
+ void window.plexo.removeDownload(id, options).catch(() => {})
+ },
- set({ currentDownload: download, speedHistory, speedHistoryByInterface, peakSpeedBytesPerSec })
+ setView: (view) => set({ view }),
+
+ openNewDownload: (link) =>
+ set(link === undefined ? { newDownloadOpen: true } : { newDownloadOpen: true, draftUrl: link }),
+
+ closeNewDownload: () => set({ newDownloadOpen: false }),
+
+ setDownloadsAtOnce: (downloadsAtOnce) => {
+ set({ downloadsAtOnce })
+ persist({ downloadsAtOnce })
+ },
+
+ setSpeedLimit: (speedLimit) => {
+ set({ speedLimit })
+ persist({ speedLimit })
+ },
+
+ setSlowMode: (slowMode) => {
+ set({ slowMode })
+ persist({ slowMode })
},
- clearCurrentDownload: () =>
- set({
- currentDownload: null,
- speedHistory: [],
- speedHistoryByInterface: {},
- peakSpeedBytesPerSec: 0
- }),
+ setSlowModeSpeed: (slowModeSpeed) => {
+ set({ slowModeSpeed })
+ persist({ slowModeSpeed })
+ },
setDraftUrl: (draftUrl) => set({ draftUrl }),
setDestinationDir: (destinationDir) => {
diff --git a/src/renderer/src/theme.ts b/src/renderer/src/theme.ts
index a02bc27..2dc9e6c 100644
--- a/src/renderer/src/theme.ts
+++ b/src/renderer/src/theme.ts
@@ -54,20 +54,31 @@ export const DANGER = 'var(--color-danger)'
// the same column, which is routinely wider than the collapsed row's "<name> · N streams" — so
// the track (and everything right of it) would jump wider the instant you expand. 190px already
// covers that expanded content, so expanding never grows the track further.
-export const NETWORK_ROW_GRID_COLUMNS = '30px minmax(190px, max-content) 1fr 48px 78px 160px'
+// Keep a speed value and its unit together, including torrent direction arrows. Let unusually
+// long values grow the track rather than wrap or overflow into the adjacent byte totals.
+export const NETWORK_ROW_GRID_COLUMNS =
+ '30px minmax(190px, max-content) 1fr 48px minmax(104px, max-content) 160px'
+
+/** A swatch's colors, as CSS custom properties (main.css): a light and a dark value each. */
+function swatch<Id extends string>(
+ id: Id,
+ label: string
+): { id: Id; label: string; solid: string; onSolid: string } {
+ return { id, label, solid: `var(--swatch-${id})`, onSolid: `var(--swatch-${id}-onsolid)` }
+}
// A curated set of user-selectable network colors, distinct from (and in addition to) the
// kind defaults above — each ships its own on-solid text color so it's legible without having
-// to compute contrast for an arbitrary user-picked hue at runtime.
+// to compute contrast for an arbitrary user-picked hue at runtime, in light mode and dark.
export const NETWORK_COLOR_SWATCHES = [
- { id: 'teal', label: 'Teal', solid: '#4ea89a', onSolid: '#10201d' },
- { id: 'amber', label: 'Amber', solid: '#d8a44c', onSolid: '#221806' },
- { id: 'steel', label: 'Steel', solid: '#7e93bd', onSolid: '#141a26' },
- { id: 'rose', label: 'Rose', solid: '#c97b7b', onSolid: '#210f0f' },
- { id: 'violet', label: 'Violet', solid: '#9c8fd6', onSolid: '#17131f' },
- { id: 'lime', label: 'Lime', solid: '#a3c66a', onSolid: '#161f0d' },
- { id: 'cyan', label: 'Cyan', solid: '#6db8c9', onSolid: '#0d1a1e' },
- { id: 'coral', label: 'Coral', solid: '#d99168', onSolid: '#241209' }
+ swatch('teal', 'Teal'),
+ swatch('amber', 'Amber'),
+ swatch('steel', 'Steel'),
+ swatch('rose', 'Rose'),
+ swatch('violet', 'Violet'),
+ swatch('lime', 'Lime'),
+ swatch('cyan', 'Cyan'),
+ swatch('coral', 'Coral')
] as const
export type NetworkColorId = (typeof NETWORK_COLOR_SWATCHES)[number]['id']
@@ -162,3 +173,6 @@ export function resolveNetworkVisual(
name
}
}
+
+/** In px. Drawn inside the window, so popups have to keep clear of it themselves. */
+export const TITLE_BAR_HEIGHT = window.plexo.platform === 'darwin' ? 32 : 44
diff --git a/src/renderer/src/utils/format.ts b/src/renderer/src/utils/format.ts
index 7bc8d1d..fb9634b 100644
--- a/src/renderer/src/utils/format.ts
+++ b/src/renderer/src/utils/format.ts
@@ -1,4 +1,12 @@
-import type { ChunkState, DownloadNetwork, DownloadState } from '@shared/types'
+import type {
+ DownloadNetwork,
+ DownloadState,
+ FinishedDownload,
+ HttpDownloadNetwork,
+ HttpDownloadState,
+ TorrentDownloadNetwork,
+ TorrentDownloadState
+} from '@shared/types'
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB']
@@ -17,10 +25,8 @@ export function formatSpeed(bytesPerSec: number): string {
return `${formatBytes(bytesPerSec)}/s`
}
-export function formatEta(remainingBytes: number, bytesPerSec: number): string {
- if (bytesPerSec <= 0 || remainingBytes <= 0) return '—'
- const seconds = remainingBytes / bytesPerSec
- if (!Number.isFinite(seconds)) return '—'
+export function formatEta(seconds: number): string {
+ if (!Number.isFinite(seconds) || seconds <= 0) return '—'
if (seconds < 60) return `${Math.max(1, Math.ceil(seconds))}s`
const totalSec = Math.round(seconds)
const mins = Math.floor(totalSec / 60)
@@ -31,6 +37,22 @@ export function formatEta(remainingBytes: number, bytesPerSec: number): string {
return `${hrs}h ${remMins}m`
}
+/** "3 files", or "2 of 4 files" when only some were chosen. */
+export function describeFileCount(chosen: number, total: number): string {
+ const files = `${total} ${total === 1 ? 'file' : 'files'}`
+ return chosen === total ? files : `${chosen} of ${files}`
+}
+
+/** A torrent file's path within the torrent's own folder, which every path starts with. */
+export function pathInTorrent(path: string): string {
+ return path.split(/[\\/]/).slice(1).join('/') || path
+}
+
+/** What a download fetches: all of it, bar a torrent's pieces no chosen file needs. */
+export function wantedBytes(download: DownloadState | FinishedDownload): number {
+ return download.totalBytes - (download.kind === 'torrent' ? download.skippedBytes : 0)
+}
+
export function formatPercent(bytesDownloaded: number, totalBytes: number): number {
if (totalBytes <= 0) return 0
return Math.min(100, Math.round((bytesDownloaded / totalBytes) * 100))
@@ -41,12 +63,50 @@ export function fileNameFromPath(path: string): string {
}
/** Short uppercase file-type badge from a name's extension, e.g. "Xcode_16.2.xip" -> "XIP", "photo.jpeg" -> "JPEG". */
+/** A download that is a folder: a torrent's, of its files. */
+export function isFolder(download: DownloadState | FinishedDownload): boolean {
+ return download.kind === 'torrent' && download.folder
+}
+
export function fileExtensionBadge(fileName: string): string {
const dotIndex = fileName.lastIndexOf('.')
if (dotIndex <= 0 || dotIndex === fileName.length - 1) return 'FILE'
return fileName.slice(dotIndex + 1, dotIndex + 5).toUpperCase()
}
+/** When something happened, as a list shows it: "Just now", "12 min ago", "Today 08:55",
+ * "Yesterday 21:10", or the date. */
+export function formatWhen(time: number, now: number): string {
+ const minutes = Math.floor((now - time) / 60_000)
+ if (minutes < 1) return 'Just now'
+ if (minutes < 60) return `${minutes} min ago`
+ const date = new Date(time)
+ const clock = date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
+ const days = Math.round(
+ (new Date(now).setHours(0, 0, 0, 0) - new Date(time).setHours(0, 0, 0, 0)) / 86_400_000
+ )
+ if (days === 0) return `Today ${clock}`
+ if (days === 1) return `Yesterday ${clock}`
+ return date.toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' })
+}
+
+/** What Plexo can download: a web link, a magnet link, or a .torrent file on this computer. */
+export function acceptedLink(text: string): string | null {
+ const link = text.trim()
+ if (/^(https?:\/\/|magnet:\?)/i.test(link)) return link
+ if (/^(\/|[a-z]:\\).*\.torrent$/i.test(link)) return link
+ return null
+}
+
+/** Where a link's download comes from, in a word: its host. */
+export function sourceOf(url: string): string {
+ try {
+ return new URL(url).host
+ } catch {
+ return url
+ }
+}
+
/** m:ss, or h:mm:ss past an hour. */
export function formatDuration(seconds: number): string {
if (!Number.isFinite(seconds) || seconds <= 0) return '0:00'
@@ -71,17 +131,26 @@ export function dirnameOf(path: string): string {
return path.slice(0, index)
}
-/** A download's network with the streams it runs: what one row on screen shows. */
-export interface NetworkGroup extends DownloadNetwork {
- chunks: ChunkState[]
+export interface HttpNetworkGroup extends HttpDownloadNetwork {
+ streams: HttpDownloadState['streams']
+}
+
+export interface TorrentNetworkGroup extends TorrentDownloadNetwork {
+ peers: TorrentDownloadState['peers']
}
-export function groupByNetwork(
- download: Pick<DownloadState, 'networks' | 'chunks'>
-): NetworkGroup[] {
+export type NetworkGroup = HttpNetworkGroup | TorrentNetworkGroup
+
+export function groupByNetwork(download: DownloadState): NetworkGroup[] {
+ if (download.kind === 'http') {
+ return download.networks.map((network) => ({
+ ...network,
+ streams: download.streams.filter((stream) => stream.interfaceId === network.id)
+ }))
+ }
return download.networks.map((network) => ({
...network,
- chunks: download.chunks.filter((chunk) => chunk.interfaceId === network.id)
+ peers: download.peers.filter((peer) => peer.interfaceId === network.id)
}))
}
@@ -107,76 +176,15 @@ export function toDisplayPath(path: string, homeDir: string): string {
return path
}
-const IPC_INVOKE_PREFIX = /^Error invoking remote method '[^']*':\s*/
-const NESTED_ERROR_PREFIX = /^Error:\s*/
-
-const ERROR_HINTS: Array<{ pattern: RegExp; message: string }> = [
- {
- pattern: /Download is incomplete/,
- message: 'The download did not finish every range. Try downloading again.'
- },
- {
- pattern: /Download file size does not match/,
- message: 'The downloaded file did not match its expected size, so Plexo did not publish it.'
- },
- {
- pattern: /ENOTFOUND|EAI_AGAIN/,
- message: 'Could not resolve that host — check the URL and your connection.'
- },
- {
- pattern: /ECONNREFUSED/,
- message: 'The server refused the connection — it may be down or blocking requests.'
- },
- {
- pattern: /ECONNRESET|socket hang up/,
- message: 'The connection was reset by the server — try again in a moment.'
- },
- {
- pattern: /ETIMEDOUT|ESOCKETTIMEDOUT/,
- message: 'The connection timed out — check your network and try again.'
- },
- {
- pattern: /CERT|SSL|TLS/i,
- message: "The server's security certificate could not be verified."
- },
- {
- pattern: /Invalid URL|ERR_INVALID_URL/,
- message: 'That doesn’t look like a valid URL.'
- },
- {
- pattern: /Server responded with status 401/,
- message: 'This link requires you to sign in — Plexo can’t download it.'
- },
- {
- pattern: /Server responded with status 403/,
- message: 'Access to this file was denied by the server.'
- },
- {
- pattern: /Server responded with status 404/,
- message: 'That file could not be found — check the link and try again.'
- },
- {
- pattern: /Server responded with status 4\d\d/,
- message: 'The server rejected this request — check the link and try again.'
- },
- {
- pattern: /Server responded with status 5\d\d/,
- message: 'The server is having trouble right now — try again later.'
- }
-]
-
-/** Electron wraps a rejected IPC call as "Error invoking remote method 'x': Error: <message>" —
- * strip that framework noise and translate common network errors and internal consistency-check
- * failures into plain English. Used for both the pre-download probe and a download's own
- * `error` field, so a failure partway through a transfer reads exactly as friendly as one caught
- * before it started. */
-export function describeError(error: unknown): string {
- const raw = error instanceof Error ? error.message : String(error)
- const stripped = raw.replace(IPC_INVOKE_PREFIX, '').replace(NESTED_ERROR_PREFIX, '')
-
- for (const { pattern, message } of ERROR_HINTS) {
- if (pattern.test(stripped)) return message
- }
+export { describeError } from '@shared/errors'
+
+const LINK_REFUSED = /status (401|403|404|410) for range request/
- return stripped
+/** A download whose link the server now refuses: a fresh link to the same file picks it up. */
+export function linkExpired(download: DownloadState): boolean {
+ return (
+ download.kind === 'http' &&
+ download.status === 'error' &&
+ LINK_REFUSED.test(download.error ?? '')
+ )
}
diff --git a/src/shared/dataLimits.ts b/src/shared/dataLimits.ts
new file mode 100644
index 0000000..eaf985d
--- /dev/null
+++ b/src/shared/dataLimits.ts
@@ -0,0 +1,27 @@
+import type { DataLimitPeriod } from './types'
+
+export const DATA_LIMIT_PERIODS: { value: DataLimitPeriod; label: string; usage: string }[] = [
+ { value: 'day', label: 'Day', usage: 'today' },
+ { value: 'week', label: 'Week', usage: 'this week' },
+ { value: 'month', label: 'Month', usage: 'this month' }
+]
+
+/** Calendar boundaries in the same local time zone used by the usage counter. Weeks start Monday. */
+export function dataPeriodKey(period: DataLimitPeriod, time: number): string {
+ const date = new Date(time)
+ if (period === 'week') date.setDate(date.getDate() - ((date.getDay() + 6) % 7))
+ const month = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
+ return period === 'month' ? month : `${month}-${String(date.getDate()).padStart(2, '0')}`
+}
+
+export function nextDataReset(period: DataLimitPeriod, time: number): Date {
+ const date = new Date(time)
+ date.setHours(0, 0, 0, 0)
+ if (period === 'month') date.setMonth(date.getMonth() + 1, 1)
+ else date.setDate(date.getDate() + (period === 'day' ? 1 : 7 - ((date.getDay() + 6) % 7)))
+ return date
+}
+
+export function dataUsageLabel(period: DataLimitPeriod): string {
+ return DATA_LIMIT_PERIODS.find((entry) => entry.value === period)!.usage
+}
diff --git a/src/shared/downloadUpdate.ts b/src/shared/downloadUpdate.ts
index 049f7b1..8e40de7 100644
--- a/src/shared/downloadUpdate.ts
+++ b/src/shared/downloadUpdate.ts
@@ -5,20 +5,31 @@ export function applyDownloadUpdate(
current: DownloadState | null,
update: DownloadUpdate
): DownloadState | null {
- const { state, blocks: changed, seq } = update
- if (current?.id === state.id) {
- // A snapshot taken after this was sent already has it.
+ if ('blocks' in update) {
+ const { state, blocks: changed, seq } = update
+ if (current?.id === state.id && current.kind === 'http') {
+ if ((current.seq ?? 0) >= seq) return current
+ let blocks = current.blocks
+ if (changed.length > 0) {
+ blocks = [...blocks]
+ for (const block of changed) blocks[block.index] = block
+ }
+ return { ...state, blocks, seq }
+ }
+ if (changed.length < state.totalBlocks) return current
+ return { ...state, blocks: changed, seq }
+ }
+
+ const { state, pieces: changed, seq } = update
+ if (current?.id === state.id && current.kind === 'torrent') {
if ((current.seq ?? 0) >= seq) return current
- // A new array only when a block changed, so what shows the blocks can tell when they did.
- let blocks = current.blocks
+ let pieces = current.pieces
if (changed.length > 0) {
- blocks = [...(blocks ?? [])]
- for (const block of changed) blocks[block.index] = block
+ pieces = [...pieces]
+ for (const piece of changed) pieces[piece.index] = piece
}
- return { ...state, blocks, seq }
+ return { ...state, pieces, seq }
}
- // Another download: only an update with every block in it stands on its own — the first one
- // sent for a download, or a snapshot. Until one comes there is nothing whole to show.
- if (changed.length < (state.totalBlocks ?? 0)) return current
- return { ...state, blocks: changed, seq }
+ if (changed.length < state.totalPieces) return current
+ return { ...state, pieces: changed, seq }
}
diff --git a/src/shared/errors.ts b/src/shared/errors.ts
new file mode 100644
index 0000000..e1a525e
--- /dev/null
+++ b/src/shared/errors.ts
@@ -0,0 +1,106 @@
+const IPC_INVOKE_PREFIX = /^Error invoking remote method '[^']*':\s*/
+const NESTED_ERROR_PREFIX = /^Error:\s*/
+
+/** A link that worked and then stopped: signed links run out, and a server turns them away. */
+const LINK_REFUSED = /status (401|403|404|410) for range request/
+
+const ERROR_HINTS: Array<{ pattern: RegExp; message: string }> = [
+ {
+ pattern: /ENOSPC|EDQUOT/,
+ message:
+ 'There isn’t enough space to save this download. Free up space or choose another folder.'
+ },
+ {
+ pattern: /EACCES|EPERM/,
+ message:
+ 'Plexo doesn’t have permission to access this file or folder. Check its permissions or choose another folder.'
+ },
+ {
+ pattern: /ENOENT/,
+ message: 'The file or folder is missing. Check the download location and try again.'
+ },
+ { pattern: /EROFS/, message: 'This drive is read-only. Choose another download folder.' },
+ {
+ pattern: /EIO/,
+ message: 'Plexo couldn’t read or write the download. Check the drive and try again.'
+ },
+ {
+ pattern:
+ /Invalid torrent metadata|Invalid torrent|Invalid info hash|Invalid infoHash|Invalid magnet/i,
+ message: 'Plexo couldn’t read this torrent. Try another magnet link or .torrent file.'
+ },
+ {
+ pattern: LINK_REFUSED,
+ message: 'This link no longer works. Paste a new link to continue.'
+ },
+ {
+ pattern: /Download is incomplete/,
+ message: 'Plexo couldn’t download every part of the file. Try downloading again.'
+ },
+ {
+ pattern: /Download file size does not match/,
+ message:
+ 'The downloaded file has an unexpected size. Plexo couldn’t save the completed file. Try downloading again.'
+ },
+ {
+ pattern: /ENOTFOUND|EAI_AGAIN/,
+ message: 'Plexo couldn’t find the server. Check the link and your connection.'
+ },
+ {
+ pattern: /ECONNREFUSED/,
+ message: 'The server refused the connection. Try again later.'
+ },
+ {
+ pattern: /ECONNRESET|socket hang up/,
+ message: 'The connection was interrupted. Try again in a moment.'
+ },
+ {
+ pattern: /ETIMEDOUT|ESOCKETTIMEDOUT/,
+ message: 'The connection timed out. Check your network and try again.'
+ },
+ {
+ pattern: /CERT|SSL|TLS/i,
+ message:
+ 'The server’s security certificate couldn’t be verified. Check the link or try again later.'
+ },
+ {
+ pattern: /Invalid URL|ERR_INVALID_URL/,
+ message: 'That doesn’t look like a valid link.'
+ },
+ {
+ pattern: /Server responded with status 401/,
+ message: 'This link requires authentication. Try a direct download link.'
+ },
+ {
+ pattern: /Server responded with status 403/,
+ message: 'The server denied access to this file. Check the link or try a new one.'
+ },
+ {
+ pattern: /Server responded with status 404/,
+ message: 'The file couldn’t be found. Check the link and try again.'
+ },
+ {
+ pattern: /Server responded with status 4\d\d/,
+ message: 'The server rejected the download. Check the link and try again.'
+ },
+ {
+ pattern: /Server responded with status 5\d\d/,
+ message: 'The server is having trouble. Try again later.'
+ }
+]
+
+/** Electron wraps a rejected IPC call as "Error invoking remote method 'x': Error: <message>" —
+ * strip that framework noise and translate common network errors and internal consistency-check
+ * failures into plain English. Used for both the pre-download probe and a download's own
+ * `error` field, so a failure partway through a transfer reads exactly as friendly as one caught
+ * before it started. */
+export function describeError(error: unknown): string {
+ const raw = error instanceof Error ? error.message : String(error)
+ const stripped = raw.replace(IPC_INVOKE_PREFIX, '').replace(NESTED_ERROR_PREFIX, '')
+
+ for (const { pattern, message } of ERROR_HINTS) {
+ if (pattern.test(stripped)) return message
+ }
+
+ return stripped
+}
diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.ts
index e0ba3df..83ac514 100644
--- a/src/shared/ipc-channels.ts
+++ b/src/shared/ipc-channels.ts
@@ -7,16 +7,28 @@ export const IpcChannels = {
getInitialState: 'app:get-initial-state',
updateSettings: 'app:update-settings',
chooseDestinationFolder: 'dialog:choose-destination-folder',
+ chooseTorrentFile: 'dialog:choose-torrent-file',
readClipboardText: 'clipboard:read-text',
- revealInFolder: 'shell:reveal-in-folder',
+ revealDownload: 'shell:reveal-download',
startDownload: 'download:start',
- getCurrentDownload: 'download:get-current',
+ listDownloads: 'download:list',
+ listHistory: 'history:list',
+ clearHistory: 'history:clear',
+ networkUsage: 'network:usage',
+ resetNetworkUsage: 'network:reset-usage',
+ freeSpace: 'disk:free-space',
+ historyChanged: 'history:changed',
+ torrentFiles: 'download:torrent-files',
+ chooseTorrentFiles: 'download:choose-torrent-files',
pauseDownload: 'download:pause',
resumeDownload: 'download:resume',
+ relinkDownload: 'download:relink',
setDownloadNetwork: 'download:set-network',
cancelDownload: 'download:cancel',
removeDownload: 'download:remove',
downloadUpdated: 'download:updated',
networksChanged: 'network:changed',
+ linkReceived: 'app:link-received',
+ takePendingLink: 'app:take-pending-link',
checkForUpdate: 'update:check'
} as const
diff --git a/src/shared/ipc-contract.ts b/src/shared/ipc-contract.ts
index c24a0f9..c988727 100644
--- a/src/shared/ipc-contract.ts
+++ b/src/shared/ipc-contract.ts
@@ -1,14 +1,16 @@
import type {
AppSettings,
DownloadUpdate,
+ FinishedDownload,
NetworkInterfaceInfo,
ProbeResult,
StartDownloadRequest,
+ TorrentFileEntry,
UpdateInfo
} from './types'
/** The request/response half of the IPC surface (every IpcChannels entry except the
- * main->renderer push events, downloadUpdated and networksChanged) — one source of truth for
+ * main->renderer push events, downloadUpdated, networksChanged, historyChanged and linkReceived) — 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 {
@@ -19,14 +21,38 @@ export interface IpcContract {
updateSettings: { args: [patch: AppSettings]; result: void }
probeUrl: { args: [url: string]; result: ProbeResult }
chooseDestinationFolder: { args: [defaultPath: string]; result: string | null }
+ chooseTorrentFile: { args: []; result: string | null }
readClipboardText: { args: []; result: string }
- revealInFolder: { args: [filePath: string]; result: void }
+ /** Shows a download's file in its folder, by the download's own path. False when nothing is
+ * there any more: history is re-sent, with it marked missing. */
+ revealDownload: { args: [id: string]; result: boolean }
startDownload: { args: [request: StartDownloadRequest]; result: string }
- getCurrentDownload: { args: []; result: DownloadUpdate | null }
+ /** Every download, oldest first, each as a snapshot. */
+ listDownloads: { args: []; result: DownloadUpdate[] }
+ /** Finished downloads, newest first. One is forgotten with removeDownload. */
+ listHistory: { args: []; result: FinishedDownload[] }
+ /** Forgets every finished download; their files stay. */
+ clearHistory: { args: []; result: void }
+ /** Bytes each network has received in its selected calendar period, by id (see NetworkPreference.dataLimit). */
+ networkUsage: { args: []; result: Record<string, number> }
+ resetNetworkUsage: { args: [id: string]; result: void }
+ /** Bytes free on the drive holding `dir`; null when it can't be told. */
+ freeSpace: { args: [dir: string]; result: number | null }
+ /** A torrent download's files, in the torrent's order; empty for any other download. */
+ torrentFiles: { args: [id: string]; result: TorrentFileEntry[] }
+ /** Which of a torrent download's files to fetch, by index, as it runs or not. Refused for one
+ * already downloaded, or with no room on disk for what's added. */
+ chooseTorrentFiles: { args: [id: string, selected: number[]]; result: void }
pauseDownload: { args: [id: string]; result: void }
resumeDownload: { args: [id: string]; result: void }
+ /** A fresh link to the same file, for a download whose link stopped working; it resumes. */
+ relinkDownload: { args: [id: string, url: 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 }
+ /** Removes a download, cancelling one under way. A finished one's file stays, unless
+ * `trashFile`: then it goes to the Trash. */
+ removeDownload: { args: [id: string, options?: { trashFile?: boolean }]; result: void }
checkForUpdate: { args: []; result: UpdateInfo | null }
+ /** A link the OS handed over (main/openLinks.ts), once; null when there's none. */
+ takePendingLink: { args: []; result: string | null }
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 86c6a36..eaec0b4 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -21,7 +21,7 @@ export interface NetworkInterfaceInfo {
mac?: string
}
-export interface ProbeResult {
+interface ProbeResultBase {
requestedUrl: string
/** URL after following redirects — this is what the download should actually fetch. */
finalUrl: string
@@ -35,18 +35,49 @@ export interface ProbeResult {
lastModified: string | null
}
-export type DownloadStatus = 'downloading' | 'paused' | 'completed' | 'error' | 'cancelled'
+export interface HttpProbeResult extends ProbeResultBase {
+ kind: 'http'
+}
+
+export interface TorrentProbeResult extends ProbeResultBase {
+ kind: 'torrent'
+ torrent: TorrentInfo
+}
+
+export type ProbeResult = HttpProbeResult | TorrentProbeResult
+
+export interface TorrentInfo {
+ infoHash: string
+ pieceLength: number
+ /** Where each file will be written, relative to the destination folder, already checked to be
+ * safe (see main/download/torrent/paths.ts). */
+ files: { path: string; length: number }[]
+}
-/** A stream's state. `pending` means it is waiting for work: it holds no block, either because
+/** One of a torrent download's files, for listing them while it runs. */
+export interface TorrentFileEntry {
+ /** As TorrentInfo's: relative to the destination folder, the torrent's own folder first. */
+ path: string
+ length: number
+ /** Chosen to be downloaded. */
+ chosen: boolean
+}
+
+/** `queued`: waiting for one of the downloads running at once to end (see
+ * AppSettings.downloadsAtOnce). */
+export type DownloadStatus =
+ 'queued' | 'downloading' | 'paused' | 'completed' | 'error' | 'cancelled'
+
+/** An HTTP 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). A stream that fails for good leaves the list;
* what went wrong is its network's to report (see DownloadNetwork). */
-export type ChunkStatus =
+export type HttpStreamStatus =
'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 {
+export interface HttpStreamState {
id: number
/** The network it runs on: a DownloadNetwork's id. */
interfaceId: string
@@ -56,7 +87,7 @@ export interface ChunkState {
/** New bytes it has delivered. */
bytesDownloaded: number
speedBytesPerSec: number
- status: ChunkStatus
+ status: HttpStreamStatus
/** 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
@@ -64,13 +95,29 @@ export interface ChunkState {
hedge?: boolean
}
-export type BlockStatus = 'pending' | 'downloading' | 'completed'
+/** A live BitTorrent peer connection. A peer does not own a piece: it may contribute blocks to
+ * several pieces, and several peers may contribute to one piece. */
+export interface TorrentPeerState {
+ /** Unique in the download, in the order its peers connected: "Peer #(id + 1)". */
+ id: number
+ interfaceId: string
+ status: 'connected' | 'receiving'
+ /** The client it runs, as its peer id names it ("qBittorrent 4.6.2"); null when unknown. */
+ client: string | null
+ bytesDownloaded: number
+ speedBytesPerSec: number
+ bytesUploaded: number
+ uploadSpeedBytesPerSec: number
+}
+
+export type HttpBlockStatus = 'pending' | 'downloading' | 'completed'
+/** `skipped`: a piece that none of the files chosen for this torrent needs. */
+export type TorrentPieceStatus = HttpBlockStatus | 'skipped'
-export interface BlockState {
+interface WorkUnitState {
index: number
rangeStart: number
rangeEnd: number | null
- status: BlockStatus
/** The network currently leasing this block (or the last one to touch it). Only meaningful
* as "who is working on it now" — for who actually *delivered* the bytes, read
* `bytesByInterface`, since a block can be started on one network and finished on another
@@ -83,6 +130,21 @@ export interface BlockState {
bytesByInterface: Record<string, number>
}
+export interface HttpBlockState extends WorkUnitState {
+ kind: 'http'
+ status: HttpBlockStatus
+}
+
+export interface TorrentPieceState extends WorkUnitState {
+ kind: 'torrent'
+ status: TorrentPieceStatus
+ /** Bytes received in this run but not yet hash-verified. This is live activity, not durable
+ * progress, and may fall back to zero after a failed verification. */
+ provisionalBytes: number
+}
+
+export type DownloadUnitState = HttpBlockState | TorrentPieceState
+
/**
* - on: in use.
* - off: the user switched it off. A network that turns up mid-download starts off.
@@ -91,11 +153,13 @@ export interface BlockState {
* 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.
+ * - limit: it has used up its data for the chosen period (NetworkPreference.dataLimit). It's used again
+ * once the period ends or the limit is raised.
*/
-export type NetworkStatus = 'on' | 'off' | 'offline' | 'unreachable' | 'failed'
+export type NetworkStatus = 'on' | 'off' | 'offline' | 'unreachable' | 'failed' | 'limit'
/** A network as one download sees it: whether the user has it on, and how it is doing. */
-export interface DownloadNetwork {
+interface DownloadNetworkBase {
/** A NetworkInterfaceInfo id. */
id: string
/** Its name and kind as the OS last reported them. */
@@ -112,7 +176,19 @@ export interface DownloadNetwork {
retries: number
}
-export interface DownloadState {
+export interface HttpDownloadNetwork extends DownloadNetworkBase {
+ transfer: 'http'
+}
+
+export interface TorrentDownloadNetwork extends DownloadNetworkBase {
+ transfer: 'torrent'
+ bytesUploaded: number
+ uploadSpeedBytesPerSec: number
+}
+
+export type DownloadNetwork = HttpDownloadNetwork | TorrentDownloadNetwork
+
+interface DownloadStateBase {
id: string
url: string
fileName: string
@@ -121,48 +197,110 @@ export interface DownloadState {
totalBytes: number
bytesDownloaded: number
speedBytesPerSec: number
+ /** Seconds left at this speed, smoothed (see updateTimeLeft); unset when there's no telling:
+ * the size unknown, or nothing moving. */
+ timeLeftSeconds?: number
status: 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
- blocks?: BlockState[]
- totalBlocks?: number
- blockSizeBytes?: number
error?: 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?: boolean
startedAt: number
+ /** While queued: its place in the queue, lowest first. */
+ queuedAt?: number
pausedAt?: number
totalPausedMs?: number
completedAt?: number
+ /** Each network's speed, by network id, sampled once a second over the last minute it ran.
+ * Every series is as long as the others, so they line up in time. */
+ speedHistory?: Record<string, number[]>
+ /** The best combined speed held for a few seconds, so it only ever rises; unset until it has
+ * run that long. A download done sooner gets the best speed it showed. */
+ peakSpeedBytesPerSec?: number
/** The update this state is as of (see DownloadUpdate). */
seq?: number
}
+export interface HttpDownloadState extends DownloadStateBase {
+ kind: 'http'
+ networks: HttpDownloadNetwork[]
+ streams: HttpStreamState[]
+ peakStreams: number
+ blocks: HttpBlockState[]
+ totalBlocks: number
+ blockSizeBytes: number
+}
+
+export interface TorrentDownloadState extends DownloadStateBase {
+ kind: 'torrent'
+ networks: TorrentDownloadNetwork[]
+ peers: TorrentPeerState[]
+ peakPeers: number
+ pieces: TorrentPieceState[]
+ totalPieces: number
+ pieceLength: number
+ /** How many files it has, how many are chosen, and which (by index; unset: every one). */
+ files: { chosen: number; total: number; selected?: number[] }
+ /** Its files come in the torrent's folder (`fileName`), rather than as one file. */
+ folder: boolean
+ /** Of `totalBytes`, the bytes of pieces that no chosen file needs. */
+ skippedBytes: number
+ bytesUploaded: number
+ uploadSpeedBytesPerSec: number
+}
+
+export type DownloadState = HttpDownloadState | TorrentDownloadState
+
+/** A finished download as history keeps it: its state without the work units and connections,
+ * which only a running download needs. */
+export type FinishedDownload = (
+ Omit<HttpDownloadState, 'blocks' | 'streams'> | Omit<TorrentDownloadState, 'pieces' | 'peers'>
+) & {
+ /** The blocks or pieces it was written in (a torrent's: those its chosen files needed). */
+ unitsWritten: number
+ /** Set when listed: its file or folder is no longer where it was saved. */
+ missing?: boolean
+ /** Chosen torrent files relative to its destination folder, retained for safe file removal. */
+ downloadedFiles?: string[]
+}
+
/** What the main process sends as a download changes: everything but its blocks, and only the
* blocks that changed since it last sent. A download can have tens of thousands of blocks, and
* copying every one several times a second would cost the process that carries every byte. A
* snapshot is the same with every block in it. */
-export interface DownloadUpdate {
- /** Counts what the main process has sent for the download. A snapshot has the count it was
- * taken at. */
+export interface HttpDownloadUpdate {
seq: number
- state: Omit<DownloadState, 'blocks'>
- blocks: BlockState[]
+ state: Omit<HttpDownloadState, 'blocks'>
+ blocks: HttpBlockState[]
}
+export interface TorrentDownloadUpdate {
+ seq: number
+ state: Omit<TorrentDownloadState, 'pieces'>
+ pieces: TorrentPieceState[]
+}
+
+export type DownloadUpdate = HttpDownloadUpdate | TorrentDownloadUpdate
+
/** User customization for one physical network, keyed by NetworkInterfaceInfo.id — lets a
* cryptic OS device name (e.g. "feth0") get a real label, and a color distinct from its
* kind's default. Persisted in the main process, independent of any single download. */
+export type DataLimitPeriod = 'day' | 'week' | 'month'
+
export interface NetworkPreference {
customName?: string
/** One of the app's curated swatch ids (see NETWORK_COLOR_SWATCHES) — not a raw hex, so every
* swatch is guaranteed to have a legible on-solid text color already picked out for it. */
colorId?: string
+ /** Left out of new downloads by default (see the title bar's networks). A download can still
+ * be started on it. */
+ off?: boolean
+ /** Bytes a second all downloads together may take over it. */
+ speedLimit?: number
+ /** Bytes Plexo may receive in the chosen calendar period. */
+ dataLimit?: number
+ /** Defaults to month for existing settings. Weeks start Monday in local time. */
+ dataLimitPeriod?: DataLimitPeriod
}
export type NetworkPreferences = Record<string, NetworkPreference>
@@ -185,8 +323,18 @@ export interface AppSettings {
destinationDir?: string
/** User customizations (name/color) per network interface id. */
networkPreferences?: NetworkPreferences
+ /** How many downloads run at once; the rest wait in the queue. */
+ downloadsAtOnce?: number
+ /** Bytes a second every download together may take, over every network; unset: no limit. */
+ speedLimit?: number
+ /** While on, slowModeSpeed stands in for speedLimit: a one-click lower limit for calls. */
+ slowMode?: boolean
+ slowModeSpeed?: number
}
+export const DOWNLOADS_AT_ONCE = { default: 2, min: 1, max: 8 }
+export const DEFAULT_SLOW_MODE_SPEED = 2 * 1024 ** 2
+
/** Everything the renderer needs for its first paint, read synchronously by the preload so no
* saved value flashes in over a default a moment after launch. */
export interface InitialState {
@@ -194,11 +342,15 @@ export interface InitialState {
downloadsDir: string
themeSource: ThemeSource
networkPreferences: NetworkPreferences
+ downloadsAtOnce: number
+ speedLimit?: number
+ slowMode: boolean
+ slowModeSpeed: number
/** The last folder picked, if it still exists — otherwise the renderer uses downloadsDir. */
destinationDir?: string
}
-export interface StartDownloadRequest {
+interface StartDownloadRequestBase {
url: string
destinationDir: string
suggestedFileName: string
@@ -209,6 +361,20 @@ export interface StartDownloadRequest {
interfaceIds: string[]
etag: string | null
lastModified: string | null
+}
+
+export interface StartHttpDownloadRequest extends StartDownloadRequestBase {
+ kind: 'http'
/** Streams per network the user picked; left out, the count is decided automatically. */
streamsPerNetwork?: number
}
+
+export interface StartTorrentDownloadRequest extends StartDownloadRequestBase {
+ kind: 'torrent'
+ /** The download starts from the .torrent retained when this info hash was probed. */
+ infoHash: string
+ /** For a torrent: the files to download, as indexes into its probe's `files`. Left out: all. */
+ selectedFiles?: number[]
+}
+
+export type StartDownloadRequest = StartHttpDownloadRequest | StartTorrentDownloadRequest
diff --git a/tsconfig.e2e.json b/tsconfig.e2e.json
index e7fe5ed..f2289b0 100644
--- a/tsconfig.e2e.json
+++ b/tsconfig.e2e.json
@@ -1,6 +1,11 @@
{
"extends": "@electron-toolkit/tsconfig/tsconfig.node.json",
- "include": ["e2e/**/*", "playwright.config.ts", "src/preload/globals.d.ts"],
+ "include": [
+ "e2e/**/*",
+ "playwright.config.ts",
+ "src/preload/globals.d.ts",
+ "src/main/download/torrent/modules.d.ts"
+ ],
"compilerOptions": {
"noEmit": true,
"lib": ["ESNext", "DOM"]