Speed up downloads by combining multiple network connections in parallel
TypeScript bandwidth-aggregationcross-platformdesktop-appdownloaderdownloadmanagerlinuxmacosmulticonnectionparallel-downloadswindows
Implement Plexo: multi-connection macOS download manager
Anmol Kapil64231da7a6cc
diff --git a/electron-builder.yml b/electron-builder.ymlindex 925a5ad..39ddc96 100644--- a/electron-builder.yml+++ b/electron-builder.yml@@ -1,5 +1,5 @@-appId: com.electron.app-productName: plexo+appId: com.plexo.app+productName: Plexodirectories:buildResources: buildfiles:@@ -21,10 +21,7 @@ nsis:mac:entitlementsInherit: build/entitlements.mac.plistextendInfo:- - NSCameraUsageDescription: Application requests access to the device's camera.- - NSMicrophoneUsageDescription: Application requests access to the device's microphone.- - NSDocumentsFolderUsageDescription: Application requests access to the user's Documents folder.- - NSDownloadsFolderUsageDescription: Application requests access to the user's Downloads folder.+ - NSDownloadsFolderUsageDescription: Plexo saves downloaded files to your Downloads folder.notarize: falsedmg:artifactName: ${name}-${version}.${ext}diff --git a/electron.vite.config.ts b/electron.vite.config.tsindex cbe0735..b607844 100644--- a/electron.vite.config.ts+++ b/electron.vite.config.ts@@ -3,12 +3,25 @@ import { defineConfig } from 'electron-vite'import react from '@vitejs/plugin-react'export default defineConfig({- main: {},- preload: {},+ main: {+ resolve: {+ alias: {+ '@shared': resolve('src/shared')+ }+ }+ },+ preload: {+ resolve: {+ alias: {+ '@shared': resolve('src/shared')+ }+ }+ },renderer: {resolve: {alias: {- '@renderer': resolve('src/renderer/src')+ '@renderer': resolve('src/renderer/src'),+ '@shared': resolve('src/shared')}},plugins: [react()]diff --git a/package-lock.json b/package-lock.jsonindex 2f6bb6f..601a6bd 100644--- a/package-lock.json+++ b/package-lock.json@@ -10,7 +10,8 @@"hasInstallScript": true,"dependencies": {"@electron-toolkit/preload": "^3.0.2",- "@electron-toolkit/utils": "^4.0.0"+ "@electron-toolkit/utils": "^4.0.0",+ "zustand": "^5.0.15"},"devDependencies": {"@electron-toolkit/eslint-config-prettier": "^3.0.0",@@ -2363,7 +2364,7 @@"version": "19.3.0","resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz","integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",- "dev": true,+ "devOptional": true,"license": "MIT","dependencies": {"csstype": "^3.2.2"@@ -3699,7 +3700,7 @@"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz","integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",- "dev": true,+ "devOptional": true,"license": "MIT"},"node_modules/data-view-buffer": {@@ -7357,7 +7358,7 @@"version": "19.3.0","resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz","integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==",- "dev": true,+ "devOptional": true,"license": "MIT","engines": {"node": ">=0.10.0"@@ -9504,6 +9505,35 @@"peerDependencies": {"zod": "^3.25.0 || ^4.0.0"}+ },+ "node_modules/zustand": {+ "version": "5.0.15",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.15.tgz",+ "integrity": "sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A==",+ "license": "MIT",+ "engines": {+ "node": ">=12.20.0"+ },+ "peerDependencies": {+ "@types/react": ">=18.0.0",+ "immer": ">=9.0.6",+ "react": ">=18.0.0",+ "use-sync-external-store": ">=1.2.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "use-sync-external-store": {+ "optional": true+ }+ }}}}diff --git a/package.json b/package.jsonindex 8c8195d..c831e36 100644--- a/package.json+++ b/package.json@@ -1,10 +1,9 @@{"name": "plexo","version": "1.0.0",- "description": "An Electron application with React and TypeScript",+ "description": "Speed up downloads by combining multiple network connections in parallel","main": "./out/main/index.js","author": "example.com",- "homepage": "https://electron-vite.org","scripts": {"format": "prettier --write .","lint": "eslint --cache .",@@ -22,7 +21,8 @@},"dependencies": {"@electron-toolkit/preload": "^3.0.2",- "@electron-toolkit/utils": "^4.0.0"+ "@electron-toolkit/utils": "^4.0.0",+ "zustand": "^5.0.15"},"devDependencies": {"@electron-toolkit/eslint-config-prettier": "^3.0.0",diff --git a/src/main/download/chunkDownloader.ts b/src/main/download/chunkDownloader.tsnew file mode 100644index 0000000..e66b9be--- /dev/null+++ b/src/main/download/chunkDownloader.ts@@ -0,0 +1,97 @@+import { createWriteStream } from 'node:fs'+import { request as httpRequest, type ClientRequest, type IncomingMessage } from 'node:http'+import { request as httpsRequest } from 'node:https'+import { URL } from 'node:url'++export interface ChunkDownloadOptions {+ url: string+ rangeStart: number+ /** null = open-ended range, download to end of file. */+ rangeEnd: number | null+ /** Local IP of the network interface this chunk's connection binds to. */+ localAddress: string+ destinationPath: string+ /** true when resuming a paused chunk — appends to the existing part file instead of overwriting it. */+ append: boolean+ onProgress: (bytesDownloadedThisRun: number) => void+ signal: AbortSignal+}++/** Downloads a single byte range of a URL, bound to one network interface, into a part file. */+export function downloadChunk(options: ChunkDownloadOptions): Promise<void> {+ const { url, rangeStart, rangeEnd, localAddress, destinationPath, append, onProgress, signal } =+ options++ return new Promise((resolve, reject) => {+ if (signal.aborted) {+ reject(new DOMException('Aborted', 'AbortError'))+ return+ }++ const parsed = new URL(url)+ const requester = parsed.protocol === 'https:' ? httpsRequest : httpRequest+ let bytesDownloaded = 0+ let settled = false++ const finish = (fn: () => void): void => {+ if (settled) return+ settled = true+ signal.removeEventListener('abort', onAbort)+ fn()+ }++ const fail = (error: Error): void =>+ finish(() => {+ req.destroy()+ reject(error)+ })++ const onAbort = (): void => fail(new DOMException('Aborted', 'AbortError'))+ signal.addEventListener('abort', onAbort)++ const rangeHeader =+ rangeEnd === null ? `bytes=${rangeStart}-` : `bytes=${rangeStart}-${rangeEnd}`++ const req: ClientRequest = requester(+ {+ method: 'GET',+ hostname: parsed.hostname,+ port: parsed.port || undefined,+ path: `${parsed.pathname}${parsed.search}`,+ localAddress,+ // localAddress is always an IPv4 interface address — force the remote+ // host to resolve to IPv4 too, or binding fails with EINVAL when DNS+ // hands back an IPv6 address for it instead.+ family: 4,+ headers: { 'User-Agent': 'Plexo/1.0', Range: rangeHeader }+ },+ (res: IncomingMessage) => {+ // A 200 is only correct here if we asked for the whole file from byte+ // 0 — otherwise the server ignored our Range and we'd silently write+ // the wrong bytes into this chunk's slot.+ const isValidFullBody = res.statusCode === 200 && rangeStart === 0+ if (res.statusCode !== 206 && !isValidFullBody) {+ fail(new Error(`Unexpected status ${res.statusCode} for range request`))+ res.resume()+ return+ }++ const fileStream = createWriteStream(destinationPath, { flags: append ? 'a' : 'w' })++ res.on('data', (chunk: Buffer) => {+ bytesDownloaded += chunk.length+ onProgress(bytesDownloaded)+ })++ res.on('error', fail)+ fileStream.on('error', fail)+ fileStream.on('finish', () => finish(resolve))++ res.pipe(fileStream)+ }+ )++ req.on('error', fail)+ req.end()+ })+}diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.tsnew file mode 100644index 0000000..017dd06--- /dev/null+++ b/src/main/download/downloadManager.ts@@ -0,0 +1,343 @@+import { randomUUID } from 'node:crypto'+import { createReadStream, createWriteStream } from 'node:fs'+import { mkdir, rm } from 'node:fs/promises'+import { basename, join } from 'node:path'+import type { BrowserWindow } from 'electron'+import { app } from 'electron'+import { IpcChannels } from '../../shared/ipc-channels'+import type {+ ChunkState,+ DownloadState,+ NetworkInterfaceInfo,+ StartDownloadRequest+} from '../../shared/types'+import { downloadChunk } from './chunkDownloader'+import { getAvailableDestinationPath } from './paths'++interface ChunkRuntime {+ controller: AbortController+ partPath: string+}++interface DownloadRuntime {+ state: DownloadState+ requestPayload: StartDownloadRequest+ activeInterfaces: NetworkInterfaceInfo[]+ chunkRuntimes: Map<number, ChunkRuntime>+ tempDir: string+ lastProgressByChunk: Map<number, { bytes: number; time: number }>+ pushScheduled: boolean+}++const PROGRESS_THROTTLE_MS = 200++function splitIntoRanges(+ totalBytes: number,+ count: number+): Array<{ start: number; end: number | null }> {+ const ranges: Array<{ start: number; end: number | null }> = []+ const baseSize = Math.floor(totalBytes / count)+ let start = 0+ for (let index = 0; index < count; index += 1) {+ const isLast = index === count - 1+ const end = isLast ? totalBytes - 1 : start + baseSize - 1+ ranges.push({ start, end })+ start = end + 1+ }+ return ranges+}++/** Appends one file's bytes onto an already-open writable, without ending it. */+function appendFileToStream(sourcePath: string, output: NodeJS.WritableStream): Promise<void> {+ return new Promise((resolve, reject) => {+ const input = createReadStream(sourcePath)+ input.on('error', reject)+ input.on('data', (chunk) => {+ const canContinue = output.write(chunk)+ if (!canContinue) {+ input.pause()+ output.once('drain', () => input.resume())+ }+ })+ input.on('end', resolve)+ })+}++export class DownloadManager {+ private runtimes = new Map<string, DownloadRuntime>()++ constructor(+ private getWindow: () => BrowserWindow | null,+ private getInterfaceById: (id: string) => NetworkInterfaceInfo | undefined+ ) {}++ async start(requestPayload: StartDownloadRequest): Promise<string> {+ const interfaces = requestPayload.interfaceIds+ .map((interfaceId) => this.getInterfaceById(interfaceId))+ .filter((iface): iface is NetworkInterfaceInfo => Boolean(iface))++ if (interfaces.length === 0) {+ throw new Error('Select at least one network interface')+ }++ const id = randomUUID()+ const tempDir = join(app.getPath('temp'), 'plexo', id)+ await mkdir(tempDir, { recursive: true })++ const destinationPath = getAvailableDestinationPath(+ requestPayload.destinationDir,+ requestPayload.suggestedFileName+ )++ const canSplit =+ requestPayload.supportsRanges && requestPayload.totalBytes > 0 && interfaces.length > 1+ const ranges = canSplit+ ? splitIntoRanges(requestPayload.totalBytes, interfaces.length)+ : [{ start: 0, end: requestPayload.totalBytes > 0 ? requestPayload.totalBytes - 1 : null }]+ const activeInterfaces = canSplit ? interfaces : [interfaces[0]]++ const chunks: ChunkState[] = ranges.map((range, index) => ({+ id: index,+ interfaceId: activeInterfaces[index].id,+ interfaceLabel: activeInterfaces[index].displayName,+ interfaceKind: activeInterfaces[index].kind,+ rangeStart: range.start,+ rangeEnd: range.end,+ bytesDownloaded: 0,+ speedBytesPerSec: 0,+ status: 'pending'+ }))++ const state: DownloadState = {+ id,+ url: requestPayload.url,+ fileName: basename(destinationPath),+ destinationPath,+ totalBytes: requestPayload.totalBytes,+ bytesDownloaded: 0,+ speedBytesPerSec: 0,+ status: 'downloading',+ chunks,+ startedAt: Date.now()+ }++ const runtime: DownloadRuntime = {+ state,+ requestPayload,+ activeInterfaces,+ chunkRuntimes: new Map(),+ tempDir,+ lastProgressByChunk: new Map(),+ pushScheduled: false+ }+ this.runtimes.set(id, runtime)+ this.pushUpdate(runtime)++ void this.runChunksToCompletion(runtime, runtime.state.chunks)++ return id+ }++ pause(id: string): void {+ const runtime = this.runtimes.get(id)+ if (!runtime || runtime.state.status !== 'downloading') return++ runtime.state.status = 'paused'+ for (const chunkRuntime of runtime.chunkRuntimes.values()) {+ chunkRuntime.controller.abort()+ }+ this.pushUpdate(runtime)+ }++ resume(id: string): void {+ const runtime = this.runtimes.get(id)+ if (!runtime || runtime.state.status !== 'paused') return++ runtime.state.status = 'downloading'+ const pending = runtime.state.chunks.filter((chunk) => chunk.status !== 'completed')+ for (const chunk of pending) {+ runtime.lastProgressByChunk.delete(chunk.id)+ chunk.speedBytesPerSec = 0+ }+ this.pushUpdate(runtime)++ void this.runChunksToCompletion(runtime, pending)+ }++ cancel(id: string): void {+ const runtime = this.runtimes.get(id)+ if (!runtime || (runtime.state.status !== 'downloading' && runtime.state.status !== 'paused'))+ return++ runtime.state.status = 'cancelled'+ for (const chunkRuntime of runtime.chunkRuntimes.values()) {+ chunkRuntime.controller.abort()+ }+ this.pushUpdate(runtime)+ void this.cleanupTempDir(runtime)+ }++ remove(id: string): void {+ const runtime = this.runtimes.get(id)+ if (runtime && (runtime.state.status === 'downloading' || runtime.state.status === 'paused')) {+ this.cancel(id)+ }+ this.runtimes.delete(id)+ }++ cancelAll(): void {+ for (const id of this.runtimes.keys()) {+ this.cancel(id)+ }+ }++ /** Runs (or resumes) a set of chunks in parallel, then reassembles once they're all done. */+ private async runChunksToCompletion(+ runtime: DownloadRuntime,+ chunks: ChunkState[]+ ): Promise<void> {+ const tasks = chunks.map((chunk) => this.runChunk(runtime, chunk))+ // Each task catches its own errors below, so this never rejects.+ await Promise.all(tasks)++ if (runtime.state.status !== 'downloading') {+ // Paused, errored, or cancelled — nothing left to do right now.+ if (runtime.state.status === 'error' || runtime.state.status === 'cancelled') {+ this.pushUpdate(runtime)+ await this.cleanupTempDir(runtime)+ }+ return+ }++ try {+ await this.reassemble(runtime)+ runtime.state.status = 'completed'+ runtime.state.completedAt = Date.now()+ runtime.state.bytesDownloaded = runtime.state.totalBytes || runtime.state.bytesDownloaded+ } catch (error) {+ runtime.state.status = 'error'+ runtime.state.error = error instanceof Error ? error.message : String(error)+ }++ this.pushUpdate(runtime)+ await this.cleanupTempDir(runtime)+ }++ private async runChunk(runtime: DownloadRuntime, chunk: ChunkState): Promise<void> {+ const iface = runtime.activeInterfaces[chunk.id]+ const resumeOffset = chunk.bytesDownloaded+ const controller = new AbortController()+ const existing = runtime.chunkRuntimes.get(chunk.id)+ const partPath = existing?.partPath ?? join(runtime.tempDir, `part-${chunk.id}`)+ runtime.chunkRuntimes.set(chunk.id, { controller, partPath })+ chunk.status = 'downloading'+ this.scheduleUpdate(runtime)++ try {+ await downloadChunk({+ url: runtime.requestPayload.url,+ rangeStart: chunk.rangeStart + resumeOffset,+ rangeEnd: chunk.rangeEnd,+ localAddress: iface.address,+ destinationPath: partPath,+ append: resumeOffset > 0,+ signal: controller.signal,+ onProgress: (bytesThisRun) =>+ this.onChunkProgress(runtime, chunk.id, resumeOffset + bytesThisRun)+ })+ chunk.status = 'completed'+ } catch (error) {+ if (controller.signal.aborted) {+ chunk.status = runtime.state.status === 'paused' ? 'paused' : 'cancelled'+ } else {+ const message = error instanceof Error ? error.message : String(error)+ chunk.status = 'error'+ chunk.error = message+ // Fail fast: one broken connection shouldn't leave the others+ // downloading a file we're about to discard anyway.+ if (runtime.state.status === 'downloading') {+ runtime.state.status = 'error'+ runtime.state.error = message+ for (const chunkRuntime of runtime.chunkRuntimes.values()) {+ chunkRuntime.controller.abort()+ }+ }+ }+ } finally {+ this.scheduleUpdate(runtime)+ }+ }++ private onChunkProgress(+ runtime: DownloadRuntime,+ chunkId: number,+ bytesDownloaded: number+ ): void {+ const chunk = runtime.state.chunks.find((entry) => entry.id === chunkId)+ if (!chunk) return++ const now = Date.now()+ const previous = runtime.lastProgressByChunk.get(chunkId)+ if (previous && now > previous.time) {+ const deltaBytes = bytesDownloaded - previous.bytes+ const deltaSeconds = (now - previous.time) / 1000+ chunk.speedBytesPerSec = deltaSeconds > 0 ? deltaBytes / deltaSeconds : chunk.speedBytesPerSec+ }+ runtime.lastProgressByChunk.set(chunkId, { bytes: bytesDownloaded, time: now })+ chunk.bytesDownloaded = bytesDownloaded++ runtime.state.bytesDownloaded = runtime.state.chunks.reduce(+ (sum, entry) => sum + entry.bytesDownloaded,+ 0+ )+ runtime.state.speedBytesPerSec = runtime.state.chunks.reduce(+ (sum, entry) => sum + entry.speedBytesPerSec,+ 0+ )++ this.scheduleUpdate(runtime)+ }++ private scheduleUpdate(runtime: DownloadRuntime): void {+ if (runtime.pushScheduled) return+ runtime.pushScheduled = true+ setTimeout(() => {+ runtime.pushScheduled = false+ this.pushUpdate(runtime)+ }, PROGRESS_THROTTLE_MS)+ }++ private pushUpdate(runtime: DownloadRuntime): void {+ const window = this.getWindow()+ if (!window || window.isDestroyed()) return+ window.webContents.send(IpcChannels.downloadUpdated, structuredClone(runtime.state))+ }++ private async reassemble(runtime: DownloadRuntime): Promise<void> {+ const output = createWriteStream(runtime.state.destinationPath)++ try {+ for (const chunk of runtime.state.chunks) {+ const chunkRuntime = runtime.chunkRuntimes.get(chunk.id)+ if (!chunkRuntime) throw new Error(`Missing part file for chunk ${chunk.id}`)+ await appendFileToStream(chunkRuntime.partPath, output)+ }+ } catch (error) {+ output.destroy()+ throw error+ }++ await new Promise<void>((resolve, reject) => {+ output.on('error', reject)+ output.end(resolve)+ })+ }++ private async cleanupTempDir(runtime: DownloadRuntime): Promise<void> {+ try {+ await rm(runtime.tempDir, { recursive: true, force: true })+ } catch {+ // Best-effort cleanup — a leftover temp dir isn't worth surfacing an error for.+ }+ }+}diff --git a/src/main/download/paths.ts b/src/main/download/paths.tsnew file mode 100644index 0000000..dd60e4f--- /dev/null+++ b/src/main/download/paths.ts@@ -0,0 +1,25 @@+import { app } from 'electron'+import { existsSync } from 'node:fs'+import { basename, extname, join } from 'node:path'++export function getDefaultDownloadsDir(): string {+ return app.getPath('downloads')+}++export function getHomeDir(): string {+ return app.getPath('home')+}++/** <directory>/<fileName>, or <directory>/<fileName> (1), (2), ... if it already exists. */+export function getAvailableDestinationPath(directory: string, fileName: string): string {+ const ext = extname(fileName)+ const base = basename(fileName, ext)++ let candidate = join(directory, fileName)+ let counter = 1+ while (existsSync(candidate)) {+ candidate = join(directory, `${base} (${counter})${ext}`)+ counter += 1+ }+ return candidate+}diff --git a/src/main/download/probe.ts b/src/main/download/probe.tsnew file mode 100644index 0000000..a6217ad--- /dev/null+++ b/src/main/download/probe.ts@@ -0,0 +1,105 @@+import { request as httpRequest } from 'node:http'+import { request as httpsRequest } from 'node:https'+import { URL } from 'node:url'+import type { ProbeResult } from '../../shared/types'++const MAX_REDIRECTS = 5+const USER_AGENT = 'Plexo/1.0'++type Headers = Record<string, string | string[] | undefined>++function headerValue(headers: Headers, name: string): string | undefined {+ const value = headers[name]+ return Array.isArray(value) ? value[0] : value+}++interface ProbeResponse {+ statusCode: number+ headers: Headers+}++/** GET with a 1-byte range: cheaper than fetching the body, and unlike HEAD it+ * also tells us (via the 206 status) whether range requests actually work. */+function requestOneByte(url: URL): Promise<ProbeResponse> {+ return new Promise((resolve, reject) => {+ const requester = url.protocol === 'https:' ? httpsRequest : httpRequest+ const req = requester(+ {+ method: 'GET',+ hostname: url.hostname,+ port: url.port || undefined,+ path: `${url.pathname}${url.search}`,+ headers: { 'User-Agent': USER_AGENT, Range: 'bytes=0-0' }+ },+ (res) => {+ res.destroy()+ resolve({ statusCode: res.statusCode ?? 0, headers: res.headers as Headers })+ }+ )+ req.on('error', reject)+ req.end()+ })+}++function fileNameFromHeaders(headers: Headers, url: URL): string {+ const disposition = headerValue(headers, 'content-disposition')+ if (disposition) {+ const match = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(disposition)+ if (match?.[1]) {+ try {+ return decodeURIComponent(match[1])+ } catch {+ return match[1]+ }+ }+ }+ const pathname = decodeURIComponent(url.pathname)+ const base = pathname.split('/').filter(Boolean).pop()+ return base && base.length > 0 ? base : 'download'+}++export async function probeUrl(rawUrl: string): Promise<ProbeResult> {+ let current = new URL(rawUrl)+ let response: ProbeResponse | null = null++ for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) {+ response = await requestOneByte(current)+ if (response.statusCode >= 300 && response.statusCode < 400) {+ const location = headerValue(response.headers, 'location')+ if (!location) break+ current = new URL(location, current)+ continue+ }+ break+ }++ if (!response || response.statusCode === 0 || response.statusCode >= 400) {+ throw new Error(`Server responded with status ${response?.statusCode || 'unknown'}`)+ }++ const contentRange = headerValue(response.headers, 'content-range')+ const acceptRanges = headerValue(response.headers, 'accept-ranges')+ const supportsRanges =+ response.statusCode === 206 || (acceptRanges != null && acceptRanges !== 'none')++ let totalBytes: number | null = null+ if (contentRange) {+ const match = /\/(\d+)$/.exec(contentRange)+ if (match) totalBytes = Number(match[1])+ }+ if (totalBytes === null && response.statusCode === 200) {+ // Only trust Content-Length on a full (200) response — on a 206 it+ // describes the single byte we asked for, not the whole file.+ const contentLength = headerValue(response.headers, 'content-length')+ if (contentLength) totalBytes = Number(contentLength)+ }++ return {+ requestedUrl: rawUrl,+ finalUrl: current.toString(),+ supportsRanges,+ totalBytes,+ suggestedFileName: fileNameFromHeaders(response.headers, current),+ contentType: headerValue(response.headers, 'content-type') ?? null+ }+}diff --git a/src/main/index.ts b/src/main/index.tsindex 06e06b4..8330c24 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,15 +1,22 @@-import { app, shell, BrowserWindow, ipcMain } from 'electron'+import { electronApp, is, optimizer } from '@electron-toolkit/utils'+import { app, BrowserWindow, shell } from 'electron'import { join } from 'path'-import { electronApp, optimizer, is } from '@electron-toolkit/utils'import icon from '../../resources/icon.png?asset'+import { registerIpcHandlers } from './ipc/handlers'+import type { DownloadManager } from './download/downloadManager'++let mainWindow: BrowserWindow | null = null+let downloadManager: DownloadManager | null = nullfunction createWindow(): void {- // Create the browser window.- const mainWindow = new BrowserWindow({- width: 900,- height: 670,+ mainWindow = new BrowserWindow({+ width: 760,+ height: 560,+ minWidth: 620,+ minHeight: 420,show: false,autoHideMenuBar: true,+ title: 'Plexo',...(process.platform === 'linux' ? { icon } : {}),webPreferences: {preload: join(__dirname, '../preload/index.js'),@@ -18,7 +25,11 @@ function createWindow(): void {})mainWindow.on('ready-to-show', () => {- mainWindow.show()+ mainWindow?.show()+ })++ mainWindow.on('closed', () => {+ mainWindow = null})mainWindow.webContents.setWindowOpenHandler((details) => {@@ -26,8 +37,6 @@ function createWindow(): void {return { action: 'deny' }})- // HMR for renderer base on electron-vite cli.- // Load the remote URL for development or the local html file for production.if (is.dev && process.env['ELECTRON_RENDERER_URL']) {mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])} else {@@ -35,40 +44,28 @@ function createWindow(): void {}}-// This method will be called when Electron has finished-// initialization and is ready to create browser windows.-// Some APIs can only be used after this event occurs.app.whenReady().then(() => {- // Set app user model id for windows- electronApp.setAppUserModelId('com.electron')+ electronApp.setAppUserModelId('com.plexo.app')- // Default open or close DevTools by F12 in development- // and ignore CommandOrControl + R in production.- // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utilsapp.on('browser-window-created', (_, window) => {optimizer.watchWindowShortcuts(window)})- // IPC test- ipcMain.on('ping', () => console.log('pong'))+ downloadManager = registerIpcHandlers(() => mainWindow)createWindow()app.on('activate', function () {- // On macOS it's common to re-create a window in the app when the- // dock icon is clicked and there are no other windows open.if (BrowserWindow.getAllWindows().length === 0) createWindow()})})-// Quit when all windows are closed, except on macOS. There, it's common-// for applications and their menu bar to stay active until the user quits-// explicitly with Cmd + Q.+app.on('before-quit', () => {+ downloadManager?.cancelAll()+})+app.on('window-all-closed', () => {if (process.platform !== 'darwin') {app.quit()}})--// In this file you can include the rest of your app's specific main process-// code. You can also put them in separate files and require them here.diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.tsnew file mode 100644index 0000000..de80445--- /dev/null+++ b/src/main/ipc/handlers.ts@@ -0,0 +1,75 @@+import { clipboard, dialog, ipcMain, shell, type BrowserWindow } from 'electron'+import { IpcChannels } from '../../shared/ipc-channels'+import type { NetworkInterfaceInfo, StartDownloadRequest } from '../../shared/types'+import { DownloadManager } from '../download/downloadManager'+import { getDefaultDownloadsDir, getHomeDir } from '../download/paths'+import { probeUrl } from '../download/probe'+import { measureLatencies } from '../network/latency'+import { listActiveInterfaces } from '../network/interfaces'++const NETWORK_SETTINGS_URL = 'x-apple.systempreferences:com.apple.preference.network'++export function registerIpcHandlers(getWindow: () => BrowserWindow | null): DownloadManager {+ let cachedInterfaces: NetworkInterfaceInfo[] = []++ const manager = new DownloadManager(getWindow, (id) =>+ cachedInterfaces.find((iface) => iface.id === id)+ )++ ipcMain.handle(IpcChannels.listInterfaces, async () => {+ cachedInterfaces = await listActiveInterfaces()+ return cachedInterfaces+ })++ ipcMain.handle(IpcChannels.pingInterfaces, async () => measureLatencies(cachedInterfaces))++ ipcMain.handle(IpcChannels.openNetworkSettings, async () => {+ await shell.openExternal(NETWORK_SETTINGS_URL)+ })++ ipcMain.handle(IpcChannels.probeUrl, async (_event, url: string) => probeUrl(url))++ ipcMain.handle(IpcChannels.getInitialPaths, async () => ({+ homeDir: getHomeDir(),+ downloadsDir: getDefaultDownloadsDir()+ }))++ ipcMain.handle(IpcChannels.chooseDestinationFolder, async (_event, defaultPath: string) => {+ const window = getWindow()+ if (!window) return null+ const result = await dialog.showOpenDialog(window, {+ defaultPath,+ properties: ['openDirectory', 'createDirectory']+ })+ if (result.canceled || result.filePaths.length === 0) return null+ return result.filePaths[0]+ })++ ipcMain.handle(IpcChannels.readClipboardText, async () => clipboard.readText())++ ipcMain.handle(IpcChannels.revealInFolder, async (_event, filePath: string) => {+ shell.showItemInFolder(filePath)+ })++ ipcMain.handle(IpcChannels.startDownload, async (_event, request: StartDownloadRequest) =>+ manager.start(request)+ )++ ipcMain.handle(IpcChannels.pauseDownload, async (_event, id: string) => {+ manager.pause(id)+ })++ ipcMain.handle(IpcChannels.resumeDownload, async (_event, id: string) => {+ manager.resume(id)+ })++ ipcMain.handle(IpcChannels.cancelDownload, async (_event, id: string) => {+ manager.cancel(id)+ })++ ipcMain.handle(IpcChannels.removeDownload, async (_event, id: string) => {+ manager.remove(id)+ })++ return manager+}diff --git a/src/main/network/interfaces.ts b/src/main/network/interfaces.tsnew file mode 100644index 0000000..830583a--- /dev/null+++ b/src/main/network/interfaces.ts@@ -0,0 +1,68 @@+import { execFile } from 'node:child_process'+import { networkInterfaces } from 'node:os'+import { promisify } from 'node:util'+import type { NetworkInterfaceInfo, NetworkInterfaceKind } from '../../shared/types'++const execFileAsync = promisify(execFile)++/**+ * macOS device names (en0, en1, ...) don't say what they are. `networksetup`+ * knows the human-readable "Hardware Port" for each device (Wi-Fi, iPhone USB,+ * Thunderbolt Bridge, ...), which is what lets us label a USB-tethered phone+ * as such instead of just "en6".+ */+async function getHardwarePortNames(): Promise<Map<string, string>> {+ const deviceToName = new Map<string, string>()+ try {+ const { stdout } = await execFileAsync('networksetup', ['-listallhardwareports'])+ const blocks = stdout.split(/\n\s*\n/)+ for (const block of blocks) {+ const portMatch = /Hardware Port:\s*(.+)/.exec(block)+ const deviceMatch = /Device:\s*(.+)/.exec(block)+ if (portMatch && deviceMatch) {+ deviceToName.set(deviceMatch[1].trim(), portMatch[1].trim())+ }+ }+ } catch {+ // networksetup missing or failed — callers fall back to raw device names.+ }+ return deviceToName+}++function classifyInterface(hardwarePortName: string): NetworkInterfaceKind {+ const name = hardwarePortName.toLowerCase()+ if (name.includes('wi-fi') || name.includes('airport')) return 'wifi'+ if (name.includes('iphone') || name.includes('ipad') || name.includes('usb')) return 'usb'+ if (name.includes('bridge')) return 'bridge'+ if (name.includes('ethernet') || name.includes('lan')) return 'ethernet'+ return 'other'+}++/**+ * Active, externally-routable IPv4 interfaces on this Mac. Each one has its+ * own local IP, which is what lets us bind a download's outgoing connection+ * to a specific interface (see chunkDownloader's `localAddress` option).+ */+export async function listActiveInterfaces(): Promise<NetworkInterfaceInfo[]> {+ const hardwarePorts = await getHardwarePortNames()+ const all = networkInterfaces()+ const result: NetworkInterfaceInfo[] = []++ for (const [device, addresses] of Object.entries(all)) {+ if (!addresses) continue+ const ipv4 = addresses.find((addr) => addr.family === 'IPv4' && !addr.internal)+ if (!ipv4) continue++ const hardwareName = hardwarePorts.get(device)+ result.push({+ id: device,+ device,+ displayName: hardwareName ?? device,+ address: ipv4.address,+ kind: classifyInterface(hardwareName ?? ''),+ mac: ipv4.mac && ipv4.mac !== '00:00:00:00:00:00' ? ipv4.mac : undefined+ })+ }++ return result+}diff --git a/src/main/network/latency.ts b/src/main/network/latency.tsnew file mode 100644index 0000000..570b11f--- /dev/null+++ b/src/main/network/latency.ts@@ -0,0 +1,37 @@+import { connect } from 'node:net'+import type { NetworkInterfaceInfo } from '../../shared/types'++const PROBE_HOST = '1.1.1.1'+const PROBE_PORT = 443+const TIMEOUT_MS = 2000++/** Rough per-interface latency: time to open a TCP connection to a reliable+ * host, sourced from that interface's local address. null means unreachable. */+function measureLatency(localAddress: string): Promise<number | null> {+ return new Promise((resolve) => {+ const start = Date.now()+ const socket = connect({ host: PROBE_HOST, port: PROBE_PORT, localAddress, family: 4 })+ let settled = false++ const finish = (result: number | null): void => {+ if (settled) return+ settled = true+ socket.destroy()+ resolve(result)+ }++ socket.setTimeout(TIMEOUT_MS)+ socket.once('connect', () => finish(Date.now() - start))+ socket.once('timeout', () => finish(null))+ socket.once('error', () => finish(null))+ })+}++export async function measureLatencies(+ interfaces: NetworkInterfaceInfo[]+): Promise<Record<string, number | null>> {+ const entries = await Promise.all(+ interfaces.map(async (iface) => [iface.id, await measureLatency(iface.address)] as const)+ )+ return Object.fromEntries(entries)+}diff --git a/src/preload/index.d.ts b/src/preload/index.d.tsindex a153669..d31ba58 100644--- a/src/preload/index.d.ts+++ b/src/preload/index.d.ts@@ -1,8 +1,9 @@import { ElectronAPI } from '@electron-toolkit/preload'+import type { PlexoApi } from './index'declare global {interface Window {electron: ElectronAPI- api: unknown+ plexo: PlexoApi}}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 2d18524..b1dc8ba 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -1,16 +1,67 @@-import { contextBridge } from 'electron'import { electronAPI } from '@electron-toolkit/preload'+import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'+import { IpcChannels } from '../shared/ipc-channels'+import type {+ DownloadState,+ NetworkInterfaceInfo,+ ProbeResult,+ StartDownloadRequest+} from '../shared/types'-// Custom APIs for renderer-const api = {}+export interface InitialPaths {+ homeDir: string+ downloadsDir: string+}++const plexoApi = {+ listInterfaces: (): Promise<NetworkInterfaceInfo[]> =>+ ipcRenderer.invoke(IpcChannels.listInterfaces),++ pingInterfaces: (): Promise<Record<string, number | null>> =>+ ipcRenderer.invoke(IpcChannels.pingInterfaces),++ openNetworkSettings: (): Promise<void> => ipcRenderer.invoke(IpcChannels.openNetworkSettings),++ probeUrl: (url: string): Promise<ProbeResult> => ipcRenderer.invoke(IpcChannels.probeUrl, url),++ getInitialPaths: (): Promise<InitialPaths> => ipcRenderer.invoke(IpcChannels.getInitialPaths),++ chooseDestinationFolder: (defaultPath: string): Promise<string | null> =>+ ipcRenderer.invoke(IpcChannels.chooseDestinationFolder, defaultPath),++ readClipboardText: (): Promise<string> => ipcRenderer.invoke(IpcChannels.readClipboardText),++ revealInFolder: (filePath: string): Promise<void> =>+ ipcRenderer.invoke(IpcChannels.revealInFolder, filePath),++ startDownload: (request: StartDownloadRequest): Promise<string> =>+ ipcRenderer.invoke(IpcChannels.startDownload, request),++ pauseDownload: (downloadId: string): Promise<void> =>+ ipcRenderer.invoke(IpcChannels.pauseDownload, downloadId),++ resumeDownload: (downloadId: string): Promise<void> =>+ ipcRenderer.invoke(IpcChannels.resumeDownload, downloadId),++ cancelDownload: (downloadId: string): Promise<void> =>+ ipcRenderer.invoke(IpcChannels.cancelDownload, downloadId),++ removeDownload: (downloadId: string): Promise<void> =>+ ipcRenderer.invoke(IpcChannels.removeDownload, downloadId),++ onDownloadUpdated: (callback: (state: DownloadState) => void): (() => void) => {+ const listener = (_event: IpcRendererEvent, state: DownloadState): void => callback(state)+ ipcRenderer.on(IpcChannels.downloadUpdated, listener)+ return () => ipcRenderer.removeListener(IpcChannels.downloadUpdated, listener)+ }+}++export type PlexoApi = typeof plexoApi-// Use `contextBridge` APIs to expose Electron APIs to-// renderer only if context isolation is enabled, otherwise-// just add to the DOM global.if (process.contextIsolated) {try {contextBridge.exposeInMainWorld('electron', electronAPI)- contextBridge.exposeInMainWorld('api', api)+ contextBridge.exposeInMainWorld('plexo', plexoApi)} catch (error) {console.error(error)}@@ -18,5 +69,5 @@ if (process.contextIsolated) {// @ts-ignore (define in dts)window.electron = electronAPI// @ts-ignore (define in dts)- window.api = api+ window.plexo = plexoApi}diff --git a/src/renderer/index.html b/src/renderer/index.htmlindex e198e05..35ec383 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -2,7 +2,7 @@<html><head><meta charset="UTF-8" />- <title>Electron</title>+ <title>Plexo</title><!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --><metahttp-equiv="Content-Security-Policy"diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex 73de51c..1bd4459 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -1,35 +1,39 @@-import Versions from './components/Versions'-import electronLogo from './assets/electron.svg'+import { useDownloadEvents } from './hooks/useDownloadEvents'+import { CompleteScreen } from './screens/CompleteScreen'+import { DownloadingScreen } from './screens/DownloadingScreen'+import { ErrorScreen } from './screens/ErrorScreen'+import { IdleScreen } from './screens/IdleScreen'+import { NoConnectionsScreen } from './screens/NoConnectionsScreen'+import { useAppStore } from './store/useAppStore'function App(): React.JSX.Element {- const ipcHandle = (): void => window.electron.ipcRenderer.send('ping')+ useDownloadEvents()- return (- <>- <img alt="logo" className="logo" src={electronLogo} />- <div className="creator">Powered by electron-vite</div>- <div className="text">- Build an Electron app with <span className="react">React</span>- and <span className="ts">TypeScript</span>- </div>- <p className="tip">- Please try pressing <code>F12</code> to open the devTool- </p>- <div className="actions">- <div className="action">- <a href="https://electron-vite.org/" target="_blank" rel="noreferrer">- Documentation- </a>- </div>- <div className="action">- <a target="_blank" rel="noreferrer" onClick={ipcHandle}>- Send IPC- </a>- </div>- </div>- <Versions></Versions>- </>- )+ 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 handleNewDownload = (): void => {+ if (currentDownload) void window.plexo.removeDownload(currentDownload.id)+ clearCurrentDownload()+ }++ if (currentDownload) {+ if (currentDownload.status === 'downloading' || currentDownload.status === 'paused') {+ return <DownloadingScreen download={currentDownload} />+ }+ if (currentDownload.status === 'completed') {+ return <CompleteScreen download={currentDownload} onNewDownload={handleNewDownload} />+ }+ return <ErrorScreen download={currentDownload} onNewDownload={handleNewDownload} />+ }++ if (interfacesStatus === 'ready' && interfaces.length === 0) {+ return <NoConnectionsScreen />+ }++ return <IdleScreen />}export default Appdiff --git a/src/renderer/src/assets/base.css b/src/renderer/src/assets/base.cssdeleted file mode 100644index 5ed6406..0000000--- a/src/renderer/src/assets/base.css+++ /dev/null@@ -1,67 +0,0 @@-:root {- --ev-c-white: #ffffff;- --ev-c-white-soft: #f8f8f8;- --ev-c-white-mute: #f2f2f2;-- --ev-c-black: #1b1b1f;- --ev-c-black-soft: #222222;- --ev-c-black-mute: #282828;-- --ev-c-gray-1: #515c67;- --ev-c-gray-2: #414853;- --ev-c-gray-3: #32363f;-- --ev-c-text-1: rgba(255, 255, 245, 0.86);- --ev-c-text-2: rgba(235, 235, 245, 0.6);- --ev-c-text-3: rgba(235, 235, 245, 0.38);-- --ev-button-alt-border: transparent;- --ev-button-alt-text: var(--ev-c-text-1);- --ev-button-alt-bg: var(--ev-c-gray-3);- --ev-button-alt-hover-border: transparent;- --ev-button-alt-hover-text: var(--ev-c-text-1);- --ev-button-alt-hover-bg: var(--ev-c-gray-2);-}--:root {- --color-background: var(--ev-c-black);- --color-background-soft: var(--ev-c-black-soft);- --color-background-mute: var(--ev-c-black-mute);-- --color-text: var(--ev-c-text-1);-}--*,-*::before,-*::after {- box-sizing: border-box;- margin: 0;- font-weight: normal;-}--ul {- list-style: none;-}--body {- min-height: 100vh;- color: var(--color-text);- background: var(--color-background);- line-height: 1.6;- font-family:- Inter,- -apple-system,- BlinkMacSystemFont,- 'Segoe UI',- Roboto,- Oxygen,- Ubuntu,- Cantarell,- 'Fira Sans',- 'Droid Sans',- 'Helvetica Neue',- sans-serif;- text-rendering: optimizeLegibility;- -webkit-font-smoothing: antialiased;- -moz-osx-font-smoothing: grayscale;-}diff --git a/src/renderer/src/assets/electron.svg b/src/renderer/src/assets/electron.svgdeleted file mode 100644index 45ef09c..0000000--- a/src/renderer/src/assets/electron.svg+++ /dev/null@@ -1,10 +0,0 @@-<svg viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">- <circle cx="64" cy="64" r="64" fill="#2F3242"/>- <ellipse cx="63.9835" cy="23.2036" rx="4.48794" ry="4.495" stroke="#A2ECFB" stroke-width="3.6" stroke-linecap="round"/>- <path d="M51.3954 39.5028C52.3733 39.6812 53.3108 39.033 53.4892 38.055C53.6676 37.0771 53.0194 36.1396 52.0414 35.9612L51.3954 39.5028ZM28.6153 43.5751L30.1748 44.4741L30.1748 44.4741L28.6153 43.5751ZM28.9393 60.9358C29.4332 61.7985 30.5329 62.0976 31.3957 61.6037C32.2585 61.1098 32.5575 60.0101 32.0636 59.1473L28.9393 60.9358ZM37.6935 66.7457C37.025 66.01 35.8866 65.9554 35.1508 66.6239C34.415 67.2924 34.3605 68.4308 35.029 69.1666L37.6935 66.7457ZM53.7489 81.7014L52.8478 83.2597L53.7489 81.7014ZM96.9206 89.515C97.7416 88.9544 97.9526 87.8344 97.3919 87.0135C96.8313 86.1925 95.7113 85.9815 94.8904 86.5422L96.9206 89.515ZM52.0414 35.9612C46.4712 34.9451 41.2848 34.8966 36.9738 35.9376C32.6548 36.9806 29.0841 39.1576 27.0559 42.6762L30.1748 44.4741C31.5693 42.0549 34.1448 40.3243 37.8188 39.4371C41.5009 38.5479 46.1547 38.5468 51.3954 39.5028L52.0414 35.9612ZM27.0559 42.6762C24.043 47.9029 25.2781 54.5399 28.9393 60.9358L32.0636 59.1473C28.6579 53.1977 28.1088 48.0581 30.1748 44.4741L27.0559 42.6762ZM35.029 69.1666C39.6385 74.24 45.7158 79.1355 52.8478 83.2597L54.6499 80.1432C47.8081 76.1868 42.0298 71.5185 37.6935 66.7457L35.029 69.1666ZM52.8478 83.2597C61.344 88.1726 70.0465 91.2445 77.7351 92.3608C85.359 93.4677 92.2744 92.6881 96.9206 89.515L94.8904 86.5422C91.3255 88.9767 85.4902 89.849 78.2524 88.7982C71.0793 87.7567 62.809 84.8612 54.6499 80.1432L52.8478 83.2597ZM105.359 84.9077C105.359 81.4337 102.546 78.6127 99.071 78.6127V82.2127C100.553 82.2127 101.759 83.4166 101.759 84.9077H105.359ZM99.071 78.6127C95.5956 78.6127 92.7831 81.4337 92.7831 84.9077H96.3831C96.3831 83.4166 97.5892 82.2127 99.071 82.2127V78.6127ZM92.7831 84.9077C92.7831 88.3817 95.5956 91.2027 99.071 91.2027V87.6027C97.5892 87.6027 96.3831 86.3988 96.3831 84.9077H92.7831ZM99.071 91.2027C102.546 91.2027 105.359 88.3817 105.359 84.9077H101.759C101.759 86.3988 100.553 87.6027 99.071 87.6027V91.2027Z" fill="#A2ECFB"/>- <path d="M91.4873 65.382C90.8456 66.1412 90.9409 67.2769 91.7002 67.9186C92.4594 68.5603 93.5951 68.465 94.2368 67.7058L91.4873 65.382ZM99.3169 43.6354L97.7574 44.5344L99.3169 43.6354ZM84.507 35.2412C83.513 35.2282 82.6967 36.0236 82.6838 37.0176C82.6708 38.0116 83.4661 38.8279 84.4602 38.8409L84.507 35.2412ZM74.9407 39.8801C75.9127 39.6716 76.5315 38.7145 76.323 37.7425C76.1144 36.7706 75.1573 36.1517 74.1854 36.3603L74.9407 39.8801ZM53.7836 46.3728L54.6847 47.931L53.7836 46.3728ZM25.5491 80.9047C25.6932 81.8883 26.6074 82.5688 27.5911 82.4247C28.5747 82.2806 29.2552 81.3664 29.1111 80.3828L25.5491 80.9047ZM94.2368 67.7058C97.8838 63.3907 100.505 58.927 101.752 54.678C103.001 50.4213 102.9 46.2472 100.876 42.7365L97.7574 44.5344C99.1494 46.9491 99.3603 50.0419 98.2974 53.6644C97.2323 57.2945 94.9184 61.3223 91.4873 65.382L94.2368 67.7058ZM100.876 42.7365C97.9119 37.5938 91.7082 35.335 84.507 35.2412L84.4602 38.8409C91.1328 38.9278 95.7262 41.0106 97.7574 44.5344L100.876 42.7365ZM74.1854 36.3603C67.4362 37.8086 60.0878 40.648 52.8826 44.8146L54.6847 47.931C61.5972 43.9338 68.5948 41.2419 74.9407 39.8801L74.1854 36.3603ZM52.8826 44.8146C44.1366 49.872 36.9669 56.0954 32.1491 62.3927C27.3774 68.63 24.7148 75.2115 25.5491 80.9047L29.1111 80.3828C28.4839 76.1026 30.4747 70.5062 35.0084 64.5802C39.496 58.7143 46.2839 52.7889 54.6847 47.931L52.8826 44.8146Z" fill="#A2ECFB"/>- <path d="M49.0825 87.2295C48.7478 86.2934 47.7176 85.8059 46.7816 86.1406C45.8455 86.4753 45.358 87.5055 45.6927 88.4416L49.0825 87.2295ZM78.5635 96.4256C79.075 95.5732 78.7988 94.4675 77.9464 93.9559C77.0941 93.4443 75.9884 93.7205 75.4768 94.5729L78.5635 96.4256ZM79.5703 85.1795C79.2738 86.1284 79.8027 87.1379 80.7516 87.4344C81.7004 87.7308 82.71 87.2019 83.0064 86.2531L79.5703 85.1795ZM84.3832 64.0673H82.5832H84.3832ZM69.156 22.5301C68.2477 22.1261 67.1838 22.535 66.7799 23.4433C66.3759 24.3517 66.7848 25.4155 67.6931 25.8194L69.156 22.5301ZM45.6927 88.4416C47.5994 93.7741 50.1496 98.2905 53.2032 101.505C56.2623 104.724 59.9279 106.731 63.9835 106.731V103.131C61.1984 103.131 58.4165 101.765 55.8131 99.0249C53.2042 96.279 50.8768 92.2477 49.0825 87.2295L45.6927 88.4416ZM63.9835 106.731C69.8694 106.731 74.8921 102.542 78.5635 96.4256L75.4768 94.5729C72.0781 100.235 68.0122 103.131 63.9835 103.131V106.731ZM83.0064 86.2531C85.0269 79.7864 86.1832 72.1831 86.1832 64.0673H82.5832C82.5832 71.8536 81.4723 79.0919 79.5703 85.1795L83.0064 86.2531ZM86.1832 64.0673C86.1832 54.1144 84.4439 44.922 81.4961 37.6502C78.5748 30.4436 74.3436 24.8371 69.156 22.5301L67.6931 25.8194C71.6364 27.5731 75.3846 32.1564 78.1598 39.0026C80.9086 45.7836 82.5832 54.507 82.5832 64.0673H86.1832Z" fill="#A2ECFB"/>- <path fill-rule="evenodd" clip-rule="evenodd" d="M103.559 84.9077C103.559 82.4252 101.55 80.4127 99.071 80.4127C96.5924 80.4127 94.5831 82.4252 94.5831 84.9077C94.5831 87.3902 96.5924 89.4027 99.071 89.4027C101.55 89.4027 103.559 87.3902 103.559 84.9077V84.9077Z" stroke="#A2ECFB" stroke-width="3.6" stroke-linecap="round"/>- <path fill-rule="evenodd" clip-rule="evenodd" d="M28.8143 89.4027C31.2929 89.4027 33.3023 87.3902 33.3023 84.9077C33.3023 82.4252 31.2929 80.4127 28.8143 80.4127C26.3357 80.4127 24.3264 82.4252 24.3264 84.9077C24.3264 87.3902 26.3357 89.4027 28.8143 89.4027V89.4027V89.4027Z" stroke="#A2ECFB" stroke-width="3.6" stroke-linecap="round"/>- <path fill-rule="evenodd" clip-rule="evenodd" d="M64.8501 68.0857C62.6341 68.5652 60.451 67.1547 59.9713 64.9353C59.4934 62.7159 60.9007 60.5293 63.1167 60.0489C65.3326 59.5693 67.5157 60.9798 67.9954 63.1992C68.4742 65.4186 67.066 67.6052 64.8501 68.0857Z" fill="#A2ECFB"/>-</svg>diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.cssindex 0179fc4..827514c 100644--- a/src/renderer/src/assets/main.css+++ b/src/renderer/src/assets/main.css@@ -1,171 +1,44 @@-@import './base.css';--body {- display: flex;- align-items: center;- justify-content: center;- overflow: hidden;- background-image: url('./wavy-lines.svg');- background-size: cover;- user-select: none;+:root {+ color-scheme: light;}-code {- font-weight: 600;- padding: 3px 5px;- border-radius: 2px;- background-color: var(--color-background-mute);- font-family:- ui-monospace,- SFMono-Regular,- SF Mono,- Menlo,- Consolas,- Liberation Mono,- monospace;- font-size: 85%;+* {+ box-sizing: border-box;}+html,+body,#root {- display: flex;- align-items: center;- justify-content: center;- flex-direction: column;- margin-bottom: 80px;-}--.logo {- margin-bottom: 20px;- -webkit-user-drag: none;- height: 128px;- width: 128px;- will-change: filter;- transition: filter 300ms;-}--.logo:hover {- filter: drop-shadow(0 0 1.2em #6988e6aa);-}--.creator {- font-size: 14px;- line-height: 16px;- color: var(--ev-c-text-2);- font-weight: 600;- margin-bottom: 10px;-}--.text {- font-size: 28px;- color: var(--ev-c-text-1);- font-weight: 700;- line-height: 32px;- text-align: center;- margin: 0 10px;- padding: 16px 0;-}--.tip {- font-size: 16px;- line-height: 24px;- color: var(--ev-c-text-2);- font-weight: 600;+ height: 100%;+ margin: 0;}-.react {- background: -webkit-linear-gradient(315deg, #087ea4 55%, #7c93ee);- background-clip: text;- -webkit-background-clip: text;- -webkit-text-fill-color: transparent;- font-weight: 700;-}--.ts {- background: -webkit-linear-gradient(315deg, #3178c6 45%, #f0dc4e);- background-clip: text;- -webkit-background-clip: text;- -webkit-text-fill-color: transparent;- font-weight: 700;-}--.actions {- display: flex;- padding-top: 32px;- margin: -6px;- flex-wrap: wrap;- justify-content: flex-start;-}--.action {- flex-shrink: 0;- padding: 6px;-}--.action a {- cursor: pointer;- text-decoration: none;- display: inline-block;- border: 1px solid transparent;- text-align: center;- font-weight: 600;- white-space: nowrap;- border-radius: 20px;- padding: 0 20px;- line-height: 38px;- font-size: 14px;- border-color: var(--ev-button-alt-border);- color: var(--ev-button-alt-text);- background-color: var(--ev-button-alt-bg);-}--.action a:hover {- border-color: var(--ev-button-alt-hover-border);- color: var(--ev-button-alt-hover-text);- background-color: var(--ev-button-alt-hover-bg);+body {+ overflow: hidden;+ font-family: -apple-system, 'SF Pro Text', 'Helvetica Neue', Helvetica, sans-serif;+ -webkit-font-smoothing: antialiased;+ color: #1d1d1f;+ user-select: none;}-.versions {- position: absolute;- bottom: 30px;- margin: 0 auto;- padding: 15px 0;- font-family: 'Menlo', 'Lucida Console', monospace;- display: inline-flex;- overflow: hidden;- align-items: center;- border-radius: 22px;- background-color: #202127;- backdrop-filter: blur(24px);+input,+[contenteditable] {+ user-select: text;}-.versions li {- display: block;- float: left;- border-right: 1px solid var(--ev-c-gray-1);- padding: 0 20px;- font-size: 14px;- line-height: 14px;- opacity: 0.8;- &:last-child {- border: none;- }+button {+ font: inherit;}-@media (max-width: 720px) {- .text {- font-size: 20px;- }+::-webkit-scrollbar {+ width: 10px;}-@media (max-width: 620px) {- .versions {- display: none;- }+::-webkit-scrollbar-track {+ background: transparent;}-@media (max-width: 350px) {- .tip,- .actions {- display: none;- }+::-webkit-scrollbar-thumb {+ background-color: #d0d0d2;+ border-radius: 9999px;}diff --git a/src/renderer/src/assets/wavy-lines.svg b/src/renderer/src/assets/wavy-lines.svgdeleted file mode 100644index d08c611..0000000--- a/src/renderer/src/assets/wavy-lines.svg+++ /dev/null@@ -1,25 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1422 800" opacity="0.3">- <defs>- <linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="oooscillate-grad">- <stop stop-color="hsl(206, 75%, 49%)" stop-opacity="1" offset="0%"></stop>- <stop stop-color="hsl(331, 90%, 56%)" stop-opacity="1" offset="100%"></stop>- </linearGradient>- </defs>- <g stroke-width="1" stroke="url(#oooscillate-grad)" fill="none" stroke-linecap="round">- <path d="M 0 448 Q 355.5 -100 711 400 Q 1066.5 900 1422 448" opacity="0.05"></path>- <path d="M 0 420 Q 355.5 -100 711 400 Q 1066.5 900 1422 420" opacity="0.11"></path>- <path d="M 0 392 Q 355.5 -100 711 400 Q 1066.5 900 1422 392" opacity="0.18"></path>- <path d="M 0 364 Q 355.5 -100 711 400 Q 1066.5 900 1422 364" opacity="0.24"></path>- <path d="M 0 336 Q 355.5 -100 711 400 Q 1066.5 900 1422 336" opacity="0.30"></path>- <path d="M 0 308 Q 355.5 -100 711 400 Q 1066.5 900 1422 308" opacity="0.37"></path>- <path d="M 0 280 Q 355.5 -100 711 400 Q 1066.5 900 1422 280" opacity="0.43"></path>- <path d="M 0 252 Q 355.5 -100 711 400 Q 1066.5 900 1422 252" opacity="0.49"></path>- <path d="M 0 224 Q 355.5 -100 711 400 Q 1066.5 900 1422 224" opacity="0.56"></path>- <path d="M 0 196 Q 355.5 -100 711 400 Q 1066.5 900 1422 196" opacity="0.62"></path>- <path d="M 0 168 Q 355.5 -100 711 400 Q 1066.5 900 1422 168" opacity="0.68"></path>- <path d="M 0 140 Q 355.5 -100 711 400 Q 1066.5 900 1422 140" opacity="0.75"></path>- <path d="M 0 112 Q 355.5 -100 711 400 Q 1066.5 900 1422 112" opacity="0.81"></path>- <path d="M 0 84 Q 355.5 -100 711 400 Q 1066.5 900 1422 84" opacity="0.87"></path>- <path d="M 0 56 Q 355.5 -100 711 400 Q 1066.5 900 1422 56" opacity="0.94"></path>- </g>-</svg>diff --git a/src/renderer/src/components/ConnectionRow.tsx b/src/renderer/src/components/ConnectionRow.tsxnew file mode 100644index 0000000..bfee701--- /dev/null+++ b/src/renderer/src/components/ConnectionRow.tsx@@ -0,0 +1,106 @@+import type { NetworkInterfaceInfo } from '@shared/types'+import { FONT_MONO, FONT_UI, SUCCESS } from '../theme'+import { KindBadge } from './KindBadge'++interface ConnectionRowProps {+ iface: NetworkInterfaceInfo+ selected: boolean+ latencyMs: number | null | undefined+ onToggle: () => void+}++function Checkbox({ checked }: { checked: boolean }): React.JSX.Element {+ if (checked) {+ return (+ <div+ style={{+ width: 14,+ height: 14,+ borderRadius: 4,+ background: 'oklch(0.58 0.19 255)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: '#fff',+ font: `700 9px/1 ${FONT_UI}`,+ boxShadow: 'inset 0 0 0 0.5px rgba(0,0,0,0.15)',+ flexShrink: 0+ }}+ >+ ✓+ </div>+ )+ }+ return (+ <div+ style={{+ width: 14,+ height: 14,+ borderRadius: 4,+ background: '#fff',+ border: '0.5px solid #b0b0b2',+ boxShadow: 'inset 0 1px 1px rgba(0,0,0,0.04)',+ flexShrink: 0+ }}+ />+ )+}++export function ConnectionRow({+ iface,+ selected,+ latencyMs,+ onToggle+}: ConnectionRowProps): React.JSX.Element {+ const online = latencyMs != null++ return (+ <button+ type="button"+ onClick={onToggle}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: 10,+ padding: '9px 20px',+ borderWidth: '0.5px 0 0 0',+ borderStyle: 'solid',+ borderColor: '#ececee',+ background: 'transparent',+ width: '100%',+ textAlign: 'left',+ cursor: 'pointer',+ font: 'inherit'+ }}+ >+ <Checkbox checked={selected} />+ <KindBadge kind={iface.kind} />+ <div style={{ font: `13px/1 ${FONT_UI}`, color: '#1d1d1f' }}>{iface.displayName}</div>+ <div style={{ font: `11.5px/1 ${FONT_MONO}`, color: '#8a8a8e' }}>{iface.device}</div>+ <div style={{ flex: 1 }} />+ <div style={{ font: `11.5px/1 ${FONT_MONO}`, color: '#6e6e73' }}>{iface.address}</div>+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: 6,+ width: 96,+ justifyContent: 'flex-end'+ }}+ >+ <div+ style={{+ width: 7,+ height: 7,+ borderRadius: '50%',+ background: online ? SUCCESS : '#c2c2c6',+ flexShrink: 0+ }}+ />+ <div style={{ font: `11.5px/1 ${FONT_MONO}`, color: '#6e6e73' }}>+ {online ? `${latencyMs} ms` : '—'}+ </div>+ </div>+ </button>+ )+}diff --git a/src/renderer/src/components/FieldsSection.tsx b/src/renderer/src/components/FieldsSection.tsxnew file mode 100644index 0000000..f87920e--- /dev/null+++ b/src/renderer/src/components/FieldsSection.tsx@@ -0,0 +1,72 @@+import { FONT_MONO, FONT_UI, secondaryButtonStyle } from '../theme'++const labelStyle: React.CSSProperties = {+ width: 60,+ textAlign: 'right',+ font: `13px/1 ${FONT_UI}`,+ color: '#3c3c3e',+ flexShrink: 0+}++const fieldBoxStyle: React.CSSProperties = {+ flex: 1,+ minWidth: 0,+ border: '0.5px solid #b9b9bb',+ borderRadius: 6,+ background: '#fff',+ boxShadow: 'inset 0 1px 1px rgba(0,0,0,0.05)',+ padding: '6px 9px',+ font: `13px/1.3 ${FONT_MONO}`,+ color: '#1d1d1f',+ whiteSpace: 'nowrap',+ overflow: 'hidden',+ textOverflow: 'ellipsis'+}++interface FieldsSectionProps {+ url: string+ onUrlChange: (url: string) => void+ displayDestinationDir: string+ onBrowse: () => void+ disabled?: boolean+}++export function FieldsSection({+ url,+ onUrlChange,+ displayDestinationDir,+ onBrowse,+ disabled = false+}: FieldsSectionProps): React.JSX.Element {+ return (+ <div+ style={{+ padding: '18px 20px 16px',+ display: 'flex',+ flexDirection: 'column',+ gap: 10,+ opacity: disabled ? 0.5 : 1,+ pointerEvents: disabled ? 'none' : 'auto'+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>+ <div style={labelStyle}>URL</div>+ <input+ type="text"+ value={url}+ onChange={(event) => onUrlChange(event.target.value)}+ placeholder="https://"+ disabled={disabled}+ style={{ ...fieldBoxStyle, border: '0.5px solid #b9b9bb', outline: 'none' }}+ />+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>+ <div style={labelStyle}>Save to</div>+ <div style={fieldBoxStyle}>{displayDestinationDir}</div>+ <button type="button" onClick={onBrowse} disabled={disabled} style={secondaryButtonStyle}>+ Browse…+ </button>+ </div>+ </div>+ )+}diff --git a/src/renderer/src/components/KindBadge.tsx b/src/renderer/src/components/KindBadge.tsxnew file mode 100644index 0000000..50d85df--- /dev/null+++ b/src/renderer/src/components/KindBadge.tsx@@ -0,0 +1,23 @@+import type { NetworkInterfaceKind } from '@shared/types'+import { FONT_MONO, KIND_PALETTE } from '../theme'++export function KindBadge({ kind }: { kind: NetworkInterfaceKind }): React.JSX.Element {+ const palette = KIND_PALETTE[kind]+ return (+ <div+ style={{+ width: 38,+ textAlign: 'center',+ borderRadius: 4,+ background: palette.bg,+ color: palette.text,+ font: `600 9.5px/1 ${FONT_MONO}`,+ letterSpacing: '0.04em',+ padding: '4px 0',+ flexShrink: 0+ }}+ >+ {palette.label}+ </div>+ )+}diff --git a/src/renderer/src/components/StreamRow.tsx b/src/renderer/src/components/StreamRow.tsxnew file mode 100644index 0000000..eb7f09e--- /dev/null+++ b/src/renderer/src/components/StreamRow.tsx@@ -0,0 +1,89 @@+import type { ChunkState } from '@shared/types'+import { DANGER, FONT_MONO, FONT_UI, KIND_PALETTE } from '../theme'+import { formatBytes, formatSpeed } from '../utils/format'+import { KindBadge } from './KindBadge'++export function StreamRow({+ chunk,+ totalBytes+}: {+ chunk: ChunkState+ totalBytes: number+}): React.JSX.Element {+ const chunkSize =+ chunk.rangeEnd !== null ? chunk.rangeEnd - chunk.rangeStart + 1 : totalBytes - chunk.rangeStart+ const percent =+ chunkSize > 0 ? Math.min(100, Math.round((chunk.bytesDownloaded / chunkSize) * 100)) : 0+ const barColor = chunk.status === 'error' ? DANGER : KIND_PALETTE[chunk.interfaceKind].solid++ return (+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ padding: '10px 20px',+ borderTop: '0.5px solid #ececee'+ }}+ >+ <KindBadge kind={chunk.interfaceKind} />+ <div+ style={{+ width: 150,+ font: `13px/1 ${FONT_UI}`,+ whiteSpace: 'nowrap',+ overflow: 'hidden',+ textOverflow: 'ellipsis'+ }}+ >+ {chunk.interfaceLabel}+ </div>+ <div+ style={{+ flex: 1,+ minWidth: 0,+ height: 5,+ borderRadius: 3,+ background: '#e4e4e6',+ overflow: 'hidden'+ }}+ >+ <div+ style={{ width: `${percent}%`, height: '100%', borderRadius: 3, background: barColor }}+ />+ </div>+ <div+ style={{+ width: 38,+ textAlign: 'right',+ font: `11.5px/1 ${FONT_MONO}`,+ fontVariantNumeric: 'tabular-nums'+ }}+ >+ {percent}%+ </div>+ <div+ style={{+ width: 92,+ textAlign: 'right',+ font: `11.5px/1 ${FONT_MONO}`,+ color: '#1d1d1f',+ fontVariantNumeric: 'tabular-nums'+ }}+ >+ {chunk.status === 'downloading' ? formatSpeed(chunk.speedBytesPerSec) : '—'}+ </div>+ <div+ style={{+ width: 74,+ textAlign: 'right',+ font: `11.5px/1 ${FONT_MONO}`,+ color: '#8a8a8e',+ fontVariantNumeric: 'tabular-nums'+ }}+ >+ {formatBytes(chunk.bytesDownloaded)}+ </div>+ </div>+ )+}diff --git a/src/renderer/src/components/Versions.tsx b/src/renderer/src/components/Versions.tsxdeleted file mode 100644index 37a9ff0..0000000--- a/src/renderer/src/components/Versions.tsx+++ /dev/null@@ -1,15 +0,0 @@-import { useState } from 'react'--function Versions(): React.JSX.Element {- const [versions] = useState(window.electron.process.versions)-- return (- <ul className="versions">- <li className="electron-version">Electron v{versions.electron}</li>- <li className="chrome-version">Chromium v{versions.chrome}</li>- <li className="node-version">Node v{versions.node}</li>- </ul>- )-}--export default Versionsdiff --git a/src/renderer/src/hooks/useDownloadEvents.ts b/src/renderer/src/hooks/useDownloadEvents.tsnew file mode 100644index 0000000..1f5ebe4--- /dev/null+++ b/src/renderer/src/hooks/useDownloadEvents.ts@@ -0,0 +1,11 @@+import { useEffect } from 'react'+import { useAppStore } from '../store/useAppStore'++/** Subscribes once to main-process download progress pushes for the lifetime of the app. */+export function useDownloadEvents(): void {+ const setCurrentDownload = useAppStore((store) => store.setCurrentDownload)++ useEffect(() => {+ return window.plexo.onDownloadUpdated(setCurrentDownload)+ }, [setCurrentDownload])+}diff --git a/src/renderer/src/hooks/useNetworkPolling.ts b/src/renderer/src/hooks/useNetworkPolling.tsnew file mode 100644index 0000000..40597a7--- /dev/null+++ b/src/renderer/src/hooks/useNetworkPolling.ts@@ -0,0 +1,27 @@+import { useEffect } from 'react'+import { useAppStore } from '../store/useAppStore'++const POLL_INTERVAL_MS = 5000++/** Keeps the interface list and their latency readouts fresh while a screen that shows them is mounted —+ * e.g. so plugging in a phone over USB, or losing Wi-Fi, is reflected without the user restarting Plexo. */+export function useNetworkPolling(enabled: boolean): void {+ const loadInterfaces = useAppStore((store) => store.loadInterfaces)+ const refreshLatencies = useAppStore((store) => store.refreshLatencies)++ useEffect(() => {+ if (!enabled) return++ let cancelled = false+ const tick = async (): Promise<void> => {+ await loadInterfaces()+ if (!cancelled) await refreshLatencies()+ }+ void tick()+ const interval = setInterval(tick, POLL_INTERVAL_MS)+ return () => {+ cancelled = true+ clearInterval(interval)+ }+ }, [enabled, loadInterfaces, refreshLatencies])+}diff --git a/src/renderer/src/screens/CompleteScreen.tsx b/src/renderer/src/screens/CompleteScreen.tsxnew file mode 100644index 0000000..33ee490--- /dev/null+++ b/src/renderer/src/screens/CompleteScreen.tsx@@ -0,0 +1,180 @@+import type { DownloadState } from '@shared/types'+import { useAppStore } from '../store/useAppStore'+import {+ FONT_MONO,+ FONT_UI,+ KIND_PALETTE,+ SUCCESS,+ footerStyle,+ footerTextStyle,+ primaryButtonStyle,+ secondaryButtonStyle,+ sectionHeaderLabelStyle+} from '../theme'+import { dirnameOf, formatBytes, formatDuration, formatSpeed, toDisplayPath } from '../utils/format'++const statLabelStyle: React.CSSProperties = {+ font: `600 9.5px/1 ${FONT_UI}`,+ letterSpacing: '0.08em',+ textTransform: 'uppercase',+ color: '#8a8a8e'+}++const statValueStyle: React.CSSProperties = {+ font: `15px/1 ${FONT_MONO}`,+ fontVariantNumeric: 'tabular-nums'+}++export function CompleteScreen({+ download,+ onNewDownload+}: {+ download: DownloadState+ onNewDownload: () => void+}): React.JSX.Element {+ const homeDir = useAppStore((store) => store.homeDir)++ const finalSize = download.totalBytes || download.bytesDownloaded+ // 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).+ const elapsedSeconds = ((download.completedAt ?? download.startedAt) - download.startedAt) / 1000+ const avgSpeed = elapsedSeconds > 0 ? finalSize / elapsedSeconds : 0++ const totalWeight = download.chunks.reduce((sum, chunk) => sum + chunk.bytesDownloaded, 0) || 1++ const handleReveal = (): void => void window.plexo.revealInFolder(download.destinationPath)++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#fff' }}>+ <div style={{ padding: '22px 20px 18px', display: 'flex', alignItems: 'center', gap: 14 }}>+ <div+ style={{+ width: 30,+ height: 30,+ borderRadius: '50%',+ background: SUCCESS,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: '#fff',+ font: `700 15px/1 ${FONT_UI}`,+ flexShrink: 0+ }}+ >+ ✓+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0 }}>+ <div style={{ font: `600 15px/1.2 ${FONT_UI}` }}>Download complete</div>+ <div+ style={{+ font: `12px/1.3 ${FONT_MONO}`,+ color: '#6e6e73',+ whiteSpace: 'nowrap',+ overflow: 'hidden',+ textOverflow: 'ellipsis'+ }}+ >+ {download.fileName} — {toDisplayPath(dirnameOf(download.destinationPath), homeDir)}+ </div>+ </div>+ </div>++ <div+ style={{+ margin: '0 20px 18px',+ display: 'grid',+ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',+ border: '0.5px solid #e0e0e2',+ borderRadius: 8,+ overflow: 'hidden',+ background: '#fafafa'+ }}+ >+ {[+ { label: 'Size', value: formatBytes(finalSize) },+ { label: 'Time', value: formatDuration(elapsedSeconds) },+ { label: 'Avg speed', value: formatSpeed(avgSpeed) },+ { label: 'Streams', value: String(download.chunks.length) }+ ].map((stat, index) => (+ <div+ key={stat.label}+ style={{+ padding: '11px 14px',+ display: 'flex',+ flexDirection: 'column',+ gap: 5,+ borderLeft: index > 0 ? '0.5px solid #e0e0e2' : undefined+ }}+ >+ <div style={statLabelStyle}>{stat.label}</div>+ <div style={statValueStyle}>{stat.value}</div>+ </div>+ ))}+ </div>++ <div+ style={{ margin: '0 20px 20px', display: 'flex', flexDirection: 'column', gap: 9, flex: 1 }}+ >+ <div style={sectionHeaderLabelStyle}>Contribution</div>+ <div+ style={{+ display: 'flex',+ height: 8,+ borderRadius: 4,+ overflow: 'hidden',+ background: '#e4e4e6'+ }}+ >+ {download.chunks.map((chunk) => (+ <div+ key={chunk.id}+ style={{+ flex: chunk.bytesDownloaded,+ background: KIND_PALETTE[chunk.interfaceKind].solid+ }}+ />+ ))}+ </div>+ <div+ style={{+ display: 'flex',+ gap: 18,+ font: `11px/1 ${FONT_MONO}`,+ color: '#6e6e73',+ flexWrap: 'wrap'+ }}+ >+ {download.chunks.map((chunk) => (+ <div key={chunk.id} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>+ <div+ style={{+ width: 6,+ height: 6,+ borderRadius: '50%',+ background: KIND_PALETTE[chunk.interfaceKind].solid+ }}+ />+ {KIND_PALETTE[chunk.interfaceKind].label} {formatBytes(chunk.bytesDownloaded)} ·{' '}+ {Math.round((chunk.bytesDownloaded / totalWeight) * 100)}%+ </div>+ ))}+ </div>+ </div>++ <div style={footerStyle}>+ <div style={footerTextStyle}>Reassembled from {download.chunks.length} chunks</div>+ <div style={{ flex: 1 }} />+ <button type="button" onClick={onNewDownload} style={secondaryButtonStyle}>+ New Download+ </button>+ <button+ type="button"+ onClick={handleReveal}+ style={{ ...primaryButtonStyle, padding: '6px 16px' }}+ >+ Reveal in Finder+ </button>+ </div>+ </div>+ )+}diff --git a/src/renderer/src/screens/DownloadingScreen.tsx b/src/renderer/src/screens/DownloadingScreen.tsxnew file mode 100644index 0000000..64bc900--- /dev/null+++ b/src/renderer/src/screens/DownloadingScreen.tsx@@ -0,0 +1,239 @@+import type { DownloadState } from '@shared/types'+import { useEffect, useState } from 'react'+import { StreamRow } from '../components/StreamRow'+import { useAppStore } from '../store/useAppStore'+import {+ FONT_MONO,+ FONT_UI,+ KIND_PALETTE,+ PROGRESS_GRADIENT,+ footerStyle,+ footerTextStyle,+ secondaryButtonStyle,+ sectionHeaderLabelStyle,+ sectionHeaderMetaStyle+} from '../theme'+import {+ dirnameOf,+ formatBytes,+ formatDuration,+ formatEta,+ formatPercent,+ splitFormattedBytes,+ toDisplayPath+} from '../utils/format'++export function DownloadingScreen({ download }: { download: DownloadState }): React.JSX.Element {+ const homeDir = useAppStore((store) => store.homeDir)+ const speedHistory = useAppStore((store) => store.speedHistory)+ const [now, setNow] = useState(() => Date.now())++ useEffect(() => {+ const interval = setInterval(() => setNow(Date.now()), 1000)+ return () => clearInterval(interval)+ }, [])++ const percent = formatPercent(download.bytesDownloaded, download.totalBytes)+ const knownSize = download.totalBytes > 0+ const isPaused = download.status === 'paused'++ useEffect(() => {+ document.title = knownSize ? `Plexo — ${percent}%` : 'Plexo — downloading'+ return () => {+ document.title = 'Plexo'+ }+ }, [percent, knownSize])++ const elapsedSeconds = (now - download.startedAt) / 1000+ const activeCount = download.chunks.filter((chunk) => chunk.status === 'downloading').length++ const handlePauseResume = (): void => {+ if (isPaused) void window.plexo.resumeDownload(download.id)+ else void window.plexo.pauseDownload(download.id)+ }+ const handleCancel = (): void => void window.plexo.cancelDownload(download.id)++ const speed = splitFormattedBytes(download.speedBytesPerSec)+ const totalSpeed = download.chunks.reduce((sum, chunk) => sum + chunk.speedBytesPerSec, 0)+ const weights = download.chunks.map((chunk) =>+ totalSpeed > 0 ? chunk.speedBytesPerSec : chunk.bytesDownloaded+ )+ const totalWeight = weights.reduce((sum, weight) => sum + weight, 0) || 1+ const maxSpeedSample = Math.max(1, ...speedHistory)++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#fff' }}>+ <div+ style={{+ padding: '18px 20px 16px',+ background: 'linear-gradient(180deg, #13161c, #0d0f14)',+ color: '#fff'+ }}+ >+ <div style={{ display: 'flex', alignItems: 'flex-end', gap: 24 }}>+ <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>+ <div+ style={{+ font: `600 10px/1 ${FONT_UI}`,+ letterSpacing: '0.1em',+ textTransform: 'uppercase',+ color: 'rgba(255,255,255,0.55)'+ }}+ >+ Combined throughput+ </div>+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 7 }}>+ <div+ style={{+ font: `500 38px/1 ${FONT_MONO}`,+ letterSpacing: '-0.02em',+ fontVariantNumeric: 'tabular-nums'+ }}+ >+ {speed.value}+ </div>+ <div style={{ font: `13px/1 ${FONT_MONO}`, color: 'rgba(255,255,255,0.6)' }}>+ {speed.unit}/s+ </div>+ </div>+ </div>++ <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>+ <div+ style={{+ display: 'flex',+ height: 10,+ borderRadius: 5,+ overflow: 'hidden',+ background: 'rgba(255,255,255,0.1)'+ }}+ >+ {download.chunks.map((chunk, index) => (+ <div+ key={chunk.id}+ style={{+ flex: weights[index],+ background: KIND_PALETTE[chunk.interfaceKind].solid+ }}+ />+ ))}+ </div>+ <div+ style={{+ display: 'flex',+ gap: 16,+ font: `10.5px/1 ${FONT_MONO}`,+ color: 'rgba(255,255,255,0.65)',+ flexWrap: 'wrap'+ }}+ >+ {download.chunks.map((chunk, index) => (+ <div key={chunk.id} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>+ <div+ style={{+ width: 6,+ height: 6,+ borderRadius: '50%',+ background: KIND_PALETTE[chunk.interfaceKind].solid+ }}+ />+ {KIND_PALETTE[chunk.interfaceKind].label}{' '}+ {Math.round((weights[index] / totalWeight) * 100)}%+ </div>+ ))}+ </div>+ </div>++ <div style={{ display: 'flex', alignItems: 'flex-end', gap: 2, height: 44 }}>+ {speedHistory.map((value, index) => (+ <div+ key={index}+ style={{+ width: 3,+ borderRadius: 1.5,+ background: 'rgba(255,255,255,0.34)',+ height: `${Math.max(4, (value / maxSpeedSample) * 44)}px`+ }}+ />+ ))}+ </div>+ </div>+ </div>++ <div style={{ padding: '14px 20px 12px', display: 'flex', flexDirection: 'column', gap: 9 }}>+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>+ <div style={{ font: `500 13px/1 ${FONT_UI}` }}>{download.fileName}</div>+ <div style={{ flex: 1 }} />+ <div+ style={{+ font: `11.5px/1 ${FONT_MONO}`,+ color: '#6e6e73',+ fontVariantNumeric: 'tabular-nums'+ }}+ >+ {formatBytes(download.bytesDownloaded)}+ {knownSize ? ` of ${formatBytes(download.totalBytes)} · ${percent}%` : ''}+ {!isPaused && knownSize+ ? ` · ${formatEta(download.totalBytes - download.bytesDownloaded, download.speedBytesPerSec)} left`+ : ''}+ {isPaused ? ' · paused' : ''}+ </div>+ </div>+ <div style={{ height: 6, borderRadius: 3, background: '#e4e4e6', overflow: 'hidden' }}>+ <div+ style={{+ width: knownSize ? `${percent}%` : '100%',+ height: '100%',+ borderRadius: 3,+ background: PROGRESS_GRADIENT+ }}+ />+ </div>+ </div>++ <div+ style={{+ borderTop: '0.5px solid #e0e0e2',+ background: '#fafafa',+ flex: 1,+ overflowY: 'auto'+ }}+ >+ <div+ style={{+ display: 'flex',+ alignItems: 'baseline',+ justifyContent: 'space-between',+ padding: '11px 20px 7px'+ }}+ >+ <div style={sectionHeaderLabelStyle}>Streams</div>+ <div style={sectionHeaderMetaStyle}>+ {download.chunks.length} chunks · {activeCount} active+ </div>+ </div>+ {download.chunks.map((chunk) => (+ <StreamRow key={chunk.id} chunk={chunk} totalBytes={download.totalBytes} />+ ))}+ </div>++ <div style={footerStyle}>+ <div style={footerTextStyle}>+ elapsed {formatDuration(elapsedSeconds)} ·{' '}+ {toDisplayPath(dirnameOf(download.destinationPath), homeDir)}+ </div>+ <div style={{ flex: 1 }} />+ <button type="button" onClick={handlePauseResume} style={secondaryButtonStyle}>+ {isPaused ? 'Resume' : 'Pause'}+ </button>+ <button+ type="button"+ onClick={handleCancel}+ style={{ ...secondaryButtonStyle, padding: '6px 18px' }}+ >+ Cancel+ </button>+ </div>+ </div>+ )+}diff --git a/src/renderer/src/screens/ErrorScreen.tsx b/src/renderer/src/screens/ErrorScreen.tsxnew file mode 100644index 0000000..a3d0804--- /dev/null+++ b/src/renderer/src/screens/ErrorScreen.tsx@@ -0,0 +1,73 @@+import type { DownloadState } from '@shared/types'+import {+ DANGER,+ FONT_MONO,+ FONT_UI,+ footerStyle,+ footerTextStyle,+ primaryButtonStyle+} from '../theme'++export function ErrorScreen({+ download,+ onNewDownload+}: {+ download: DownloadState+ onNewDownload: () => void+}): React.JSX.Element {+ const cancelled = download.status === 'cancelled'++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#fff' }}>+ <div+ style={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ gap: 12,+ padding: 24+ }}+ >+ <div+ style={{+ width: 30,+ height: 30,+ borderRadius: '50%',+ background: cancelled ? '#c2c2c6' : DANGER,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: '#fff',+ font: `700 15px/1 ${FONT_UI}`+ }}+ >+ {cancelled ? '–' : '!'}+ </div>+ <div style={{ font: `600 15px/1.2 ${FONT_UI}` }}>+ {cancelled ? 'Download cancelled' : 'Download failed'}+ </div>+ <div+ style={{+ maxWidth: 420,+ textAlign: 'center',+ font: `12px/1.5 ${FONT_MONO}`,+ color: '#6e6e73'+ }}+ >+ {download.fileName}+ {download.error ? ` — ${download.error}` : ''}+ </div>+ </div>++ <div style={footerStyle}>+ <div style={footerTextStyle}>{download.url}</div>+ <div style={{ flex: 1 }} />+ <button type="button" onClick={onNewDownload} style={primaryButtonStyle}>+ New Download+ </button>+ </div>+ </div>+ )+}diff --git a/src/renderer/src/screens/IdleScreen.tsx b/src/renderer/src/screens/IdleScreen.tsxnew file mode 100644index 0000000..1db97e1--- /dev/null+++ b/src/renderer/src/screens/IdleScreen.tsx@@ -0,0 +1,229 @@+import type { ProbeResult } from '@shared/types'+import { useEffect, useRef, useState } from 'react'+import { ConnectionRow } from '../components/ConnectionRow'+import { FieldsSection } from '../components/FieldsSection'+import { useNetworkPolling } from '../hooks/useNetworkPolling'+import { useAppStore } from '../store/useAppStore'+import {+ disabledPrimaryButtonStyle,+ footerStyle,+ footerTextStyle,+ primaryButtonStyle,+ secondaryButtonStyle,+ sectionHeaderLabelStyle,+ sectionHeaderMetaStyle+} from '../theme'+import { formatBytes, toDisplayPath } from '../utils/format'++type ProbeState =+ | { status: 'idle' }+ | { status: 'probing' }+ | { status: 'ready'; result: ProbeResult; multiConnectionAllowed: boolean }+ | { status: 'error'; message: string }++const PROBE_DEBOUNCE_MS = 600++export function IdleScreen(): React.JSX.Element {+ useNetworkPolling(true)++ const interfaces = useAppStore((store) => store.interfaces)+ const homeDir = useAppStore((store) => store.homeDir)+ const downloadsDir = useAppStore((store) => store.downloadsDir)+ const latencies = useAppStore((store) => store.latencies)+ const loadInitialPaths = useAppStore((store) => store.loadInitialPaths)+ const url = useAppStore((store) => store.draftUrl)+ const setUrl = useAppStore((store) => store.setDraftUrl)+ const destinationDir = useAppStore((store) => store.draftDestinationDir)+ const setDestinationDir = useAppStore((store) => store.setDraftDestinationDir)++ const [probe, setProbe] = useState<ProbeState>({ status: 'idle' })+ const [selectedInterfaceIds, setSelectedInterfaceIds] = useState<string[]>([])+ const [starting, setStarting] = useState(false)+ const [startError, setStartError] = useState<string | null>(null)++ const probeRequestId = useRef(0)++ useEffect(() => {+ loadInitialPaths()+ }, [loadInitialPaths])++ useEffect(() => {+ if (!destinationDir && downloadsDir) setDestinationDir(downloadsDir)+ }, [destinationDir, downloadsDir, setDestinationDir])++ 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' })+ return+ }++ const requestId = ++probeRequestId.current+ setProbe({ status: 'probing' })+ const timer = setTimeout(async () => {+ try {+ const result = await window.plexo.probeUrl(trimmed)+ if (probeRequestId.current !== requestId) return+ const multiConnectionAllowed = result.supportsRanges && result.totalBytes !== null+ setProbe({ status: 'ready', result, multiConnectionAllowed })+ setSelectedInterfaceIds(+ (multiConnectionAllowed ? interfaces : interfaces.slice(0, 1)).map((iface) => iface.id)+ )+ } catch (error) {+ if (probeRequestId.current !== requestId) return+ setProbe({+ status: 'error',+ message: error instanceof Error ? error.message : String(error)+ })+ }+ }, PROBE_DEBOUNCE_MS)++ return () => clearTimeout(timer)+ // interfaces is intentionally omitted: we only want this to re-run when the URL changes,+ // using whatever interface list is current at the moment the probe resolves.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [url])++ const handleToggleInterface = (id: string): void => {+ const multiConnectionAllowed = probe.status === 'ready' && probe.multiConnectionAllowed+ setSelectedInterfaceIds((prev) => {+ if (!multiConnectionAllowed) return [id]+ return prev.includes(id) ? prev.filter((entry) => entry !== id) : [...prev, id]+ })+ }++ const handleBrowse = async (): Promise<void> => {+ const chosen = await window.plexo.chooseDestinationFolder(destinationDir || downloadsDir)+ 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' || selectedInterfaceIds.length === 0 || !destinationDir) return+ setStarting(true)+ setStartError(null)+ try {+ await window.plexo.startDownload({+ url: probe.result.finalUrl,+ destinationDir,+ suggestedFileName: probe.result.suggestedFileName,+ totalBytes: probe.result.totalBytes ?? 0,+ supportsRanges: probe.multiConnectionAllowed,+ interfaceIds: selectedInterfaceIds+ })+ } catch (error) {+ setStartError(error instanceof Error ? error.message : String(error))+ } finally {+ setStarting(false)+ }+ }++ const canStart =+ probe.status === 'ready' &&+ selectedInterfaceIds.length > 0 &&+ Boolean(destinationDir) &&+ !starting++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#fff' }}>+ <FieldsSection+ url={url}+ onUrlChange={setUrl}+ displayDestinationDir={toDisplayPath(destinationDir || downloadsDir, homeDir)}+ onBrowse={handleBrowse}+ />++ {probe.status === 'error' && (+ <div+ style={{+ margin: '0 20px 10px',+ font: '12px/1.4 -apple-system, sans-serif',+ color: 'oklch(0.55 0.2 25)'+ }}+ >+ {probe.message}+ </div>+ )}++ <div+ style={{+ borderTop: '0.5px solid #e0e0e2',+ background: '#fafafa',+ flex: 1,+ overflowY: 'auto'+ }}+ >+ <div+ style={{+ display: 'flex',+ alignItems: 'baseline',+ justifyContent: 'space-between',+ padding: '12px 20px 8px'+ }}+ >+ <div style={sectionHeaderLabelStyle}>Connections</div>+ <div style={sectionHeaderMetaStyle}>{interfaces.length} detected</div>+ </div>++ <div style={{ display: 'flex', flexDirection: 'column' }}>+ {interfaces.map((iface) => (+ <ConnectionRow+ key={iface.id}+ iface={iface}+ selected={selectedInterfaceIds.includes(iface.id)}+ latencyMs={latencies[iface.id]}+ onToggle={() => handleToggleInterface(iface.id)}+ />+ ))}+ </div>++ {probe.status === 'ready' && !probe.multiConnectionAllowed && (+ <div+ style={{+ margin: '0 20px 10px',+ font: '11.5px/1.4 -apple-system, sans-serif',+ color: '#8a8a8e'+ }}+ >+ This server doesn't support multi-connection downloads for this file — pick a+ single connection.+ </div>+ )}+ </div>++ <div style={footerStyle}>+ <div style={footerTextStyle}>+ {selectedInterfaceIds.length} selected+ {probe.status === 'ready' && probe.result.totalBytes !== null+ ? ` · ${formatBytes(probe.result.totalBytes)}`+ : ''}+ </div>+ {startError && (+ <div+ style={{ font: '11.5px/1.4 -apple-system, sans-serif', color: 'oklch(0.55 0.2 25)' }}+ >+ {startError}+ </div>+ )}+ <div style={{ flex: 1 }} />+ <button type="button" onClick={handlePaste} style={secondaryButtonStyle}>+ Paste from Clipboard+ </button>+ <button+ type="button"+ onClick={handleStart}+ disabled={!canStart}+ style={canStart ? primaryButtonStyle : disabledPrimaryButtonStyle}+ >+ Start+ </button>+ </div>+ </div>+ )+}diff --git a/src/renderer/src/screens/NoConnectionsScreen.tsx b/src/renderer/src/screens/NoConnectionsScreen.tsxnew file mode 100644index 0000000..9c608ac--- /dev/null+++ b/src/renderer/src/screens/NoConnectionsScreen.tsx@@ -0,0 +1,109 @@+import { FieldsSection } from '../components/FieldsSection'+import { useNetworkPolling } from '../hooks/useNetworkPolling'+import { useAppStore } from '../store/useAppStore'+import {+ disabledPrimaryButtonStyle,+ footerStyle,+ footerTextStyle,+ secondaryButtonStyle+} from '../theme'+import { toDisplayPath } from '../utils/format'++export function NoConnectionsScreen(): React.JSX.Element {+ useNetworkPolling(true)++ const url = useAppStore((store) => store.draftUrl)+ const setUrl = useAppStore((store) => store.setDraftUrl)+ const destinationDir = useAppStore((store) => store.draftDestinationDir)+ const homeDir = useAppStore((store) => store.homeDir)+ const downloadsDir = useAppStore((store) => store.downloadsDir)+ const loadInterfaces = useAppStore((store) => store.loadInterfaces)++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#fff' }}>+ <FieldsSection+ url={url}+ onUrlChange={setUrl}+ displayDestinationDir={toDisplayPath(destinationDir || downloadsDir, homeDir)}+ onBrowse={() => {}}+ disabled+ />++ <div+ style={{+ borderTop: '0.5px solid #e0e0e2',+ background: '#fafafa',+ flex: 1,+ padding: '40px 20px 44px',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: 12+ }}+ >+ <div+ style={{+ width: 40,+ height: 40,+ borderRadius: '50%',+ border: '1.5px dashed #c2c2c6',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center'+ }}+ >+ <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#c2c2c6' }} />+ </div>+ <div style={{ font: '600 14px/1.2 -apple-system, sans-serif', color: '#3c3c3e' }}>+ No active network interfaces+ </div>+ <div+ style={{+ maxWidth: 400,+ textAlign: 'center',+ font: '12.5px/1.5 -apple-system, sans-serif',+ color: '#6e6e73'+ }}+ >+ Plexo needs at least one connection. Join a Wi-Fi network, plug in Ethernet, or connect an+ iPhone over USB with Personal Hotspot enabled.+ </div>+ <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>+ <button+ type="button"+ onClick={() => loadInterfaces()}+ style={{+ ...secondaryButtonStyle,+ padding: '5px 13px',+ font: '12.5px/1.3 -apple-system, sans-serif'+ }}+ >+ Check Again+ </button>+ <button+ type="button"+ onClick={() => window.plexo.openNetworkSettings()}+ style={{+ ...secondaryButtonStyle,+ padding: '5px 13px',+ font: '12.5px/1.3 -apple-system, sans-serif'+ }}+ >+ Network Settings…+ </button>+ </div>+ </div>++ <div style={footerStyle}>+ <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>+ <div style={{ width: 7, height: 7, borderRadius: '50%', background: '#c2c2c6' }} />+ <div style={{ ...footerTextStyle, color: '#8a8a8e' }}>0 interfaces · monitoring</div>+ </div>+ <div style={{ flex: 1 }} />+ <button type="button" disabled style={disabledPrimaryButtonStyle}>+ Start+ </button>+ </div>+ </div>+ )+}diff --git a/src/renderer/src/store/useAppStore.ts b/src/renderer/src/store/useAppStore.tsnew file mode 100644index 0000000..89a5620--- /dev/null+++ b/src/renderer/src/store/useAppStore.ts@@ -0,0 +1,103 @@+import type { DownloadState, NetworkInterfaceInfo } from '@shared/types'+import { create } from 'zustand'++type LoadStatus = 'idle' | 'loading' | 'ready' | 'error'++const SPEED_HISTORY_LENGTH = 24++interface AppStore {+ interfaces: NetworkInterfaceInfo[]+ interfacesStatus: LoadStatus+ interfacesError: string | null+ latencies: Record<string, number | null>++ homeDir: string+ downloadsDir: string+ pathsStatus: LoadStatus++ /** Plexo focuses on one download at a time — this is it. */+ currentDownload: DownloadState | null+ speedHistory: number[]++ /** Lifted out of the Idle screen so it survives a swap to/from the No-connections screen. */+ draftUrl: string+ draftDestinationDir: string++ loadInterfaces: () => Promise<void>+ refreshLatencies: () => Promise<void>+ loadInitialPaths: () => Promise<void>+ setCurrentDownload: (state: DownloadState) => void+ clearCurrentDownload: () => void+ setDraftUrl: (url: string) => void+ setDraftDestinationDir: (dir: string) => void+}++export const useAppStore = create<AppStore>((set, get) => ({+ interfaces: [],+ interfacesStatus: 'idle',+ interfacesError: null,+ latencies: {},++ homeDir: '',+ downloadsDir: '',+ pathsStatus: 'idle',++ currentDownload: null,+ speedHistory: [],++ draftUrl: '',+ draftDestinationDir: '',++ loadInterfaces: async () => {+ set({ interfacesStatus: 'loading', interfacesError: null })+ try {+ const interfaces = await window.plexo.listInterfaces()+ set({ interfaces, interfacesStatus: 'ready' })+ } catch (error) {+ set({+ interfacesStatus: 'error',+ interfacesError: error instanceof Error ? error.message : String(error)+ })+ }+ },++ refreshLatencies: async () => {+ try {+ const latencies = await window.plexo.pingInterfaces()+ set({ latencies })+ } catch {+ // Latency is a nice-to-have readout — a failed probe just leaves stale values.+ }+ },++ loadInitialPaths: async () => {+ set({ pathsStatus: 'loading' })+ try {+ const { homeDir, downloadsDir } = await window.plexo.getInitialPaths()+ set({ homeDir, downloadsDir, pathsStatus: 'ready' })+ } catch {+ set({ pathsStatus: 'error' })+ }+ },++ setCurrentDownload: (download) => {+ const previous = get().currentDownload+ const isNewDownload = !previous || previous.id !== download.id+ set({+ currentDownload: download,+ speedHistory:+ download.status === 'downloading'+ ? [...(isNewDownload ? [] : get().speedHistory), download.speedBytesPerSec].slice(+ -SPEED_HISTORY_LENGTH+ )+ : isNewDownload+ ? []+ : get().speedHistory+ })+ },++ clearCurrentDownload: () => set({ currentDownload: null, speedHistory: [] }),++ setDraftUrl: (draftUrl) => set({ draftUrl }),+ setDraftDestinationDir: (draftDestinationDir) => set({ draftDestinationDir })+}))diff --git a/src/renderer/src/theme.ts b/src/renderer/src/theme.tsnew file mode 100644index 0000000..a513e97--- /dev/null+++ b/src/renderer/src/theme.ts@@ -0,0 +1,117 @@+import type { NetworkInterfaceKind } from '@shared/types'++export const FONT_UI = `-apple-system, "SF Pro Text", "Helvetica Neue", Helvetica, sans-serif`+export const FONT_MONO = `"SF Mono", ui-monospace, Menlo, monospace`++interface KindPalette {+ solid: string+ bg: string+ text: string+ label: string+}++export const KIND_PALETTE: Record<NetworkInterfaceKind, KindPalette> = {+ wifi: {+ solid: 'oklch(0.6 0.16 250)',+ bg: 'oklch(0.6 0.16 250 / 0.13)',+ text: 'oklch(0.46 0.14 250)',+ label: 'WIFI'+ },+ usb: {+ solid: 'oklch(0.65 0.14 195)',+ bg: 'oklch(0.65 0.14 195 / 0.15)',+ text: 'oklch(0.44 0.11 195)',+ label: 'USB'+ },+ ethernet: {+ solid: 'oklch(0.58 0.17 300)',+ bg: 'oklch(0.58 0.17 300 / 0.13)',+ text: 'oklch(0.44 0.14 300)',+ label: 'ETH'+ },+ bridge: {+ solid: 'oklch(0.55 0.02 260)',+ bg: 'oklch(0.55 0.02 260 / 0.13)',+ text: 'oklch(0.4 0.02 260)',+ label: 'NET'+ },+ other: {+ solid: 'oklch(0.55 0.02 260)',+ bg: 'oklch(0.55 0.02 260 / 0.13)',+ text: 'oklch(0.4 0.02 260)',+ label: 'NET'+ }+}++export const ACCENT_GRADIENT = 'linear-gradient(oklch(0.62 0.19 255), oklch(0.56 0.19 255))'+export const PROGRESS_GRADIENT = 'linear-gradient(90deg, oklch(0.6 0.16 250), oklch(0.62 0.17 290))'+export const SUCCESS = 'oklch(0.62 0.15 150)'+export const DANGER = 'oklch(0.55 0.2 25)'++export const secondaryButtonStyle: React.CSSProperties = {+ border: '0.5px solid #b9b9bb',+ borderRadius: 6,+ background: 'linear-gradient(#fefefe, #f3f3f3)',+ whiteSpace: 'nowrap',+ flexShrink: 0,+ boxShadow: '0 1px 1px rgba(0,0,0,0.05)',+ padding: '6px 14px',+ font: `13px/1.3 ${FONT_UI}`,+ color: '#1d1d1f',+ cursor: 'pointer'+}++export const primaryButtonStyle: React.CSSProperties = {+ border: 'none',+ borderRadius: 6,+ background: ACCENT_GRADIENT,+ boxShadow: '0 1px 2px rgba(0,0,0,0.18), inset 0 0.5px 0 rgba(255,255,255,0.3)',+ whiteSpace: 'nowrap',+ flexShrink: 0,+ padding: '6px 20px',+ font: `500 13px/1.3 ${FONT_UI}`,+ color: '#fff',+ cursor: 'pointer'+}++export const disabledPrimaryButtonStyle: React.CSSProperties = {+ border: '0.5px solid #d2d2d4',+ borderRadius: 6,+ whiteSpace: 'nowrap',+ flexShrink: 0,+ background: '#f4f4f5',+ padding: '6px 20px',+ font: `500 13px/1.3 ${FONT_UI}`,+ color: '#a8a8ac',+ cursor: 'not-allowed'+}++export const footerStyle: React.CSSProperties = {+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ padding: '12px 20px',+ borderTop: '0.5px solid #d8d8da',+ background: '#f0f0f0'+}++export const footerTextStyle: React.CSSProperties = {+ whiteSpace: 'nowrap',+ flexShrink: 0,+ font: `11.5px/1.4 ${FONT_MONO}`,+ color: '#6e6e73'+}++export const sectionHeaderLabelStyle: React.CSSProperties = {+ font: `600 11px/1 ${FONT_UI}`,+ letterSpacing: '0.06em',+ textTransform: 'uppercase',+ color: '#8a8a8e'+}++export const sectionHeaderMetaStyle: React.CSSProperties = {+ whiteSpace: 'nowrap',+ flexShrink: 0,+ font: `11px/1 ${FONT_MONO}`,+ color: '#8a8a8e'+}diff --git a/src/renderer/src/utils/format.ts b/src/renderer/src/utils/format.tsnew file mode 100644index 0000000..c8791e6--- /dev/null+++ b/src/renderer/src/utils/format.ts@@ -0,0 +1,61 @@+const UNITS = ['B', 'KB', 'MB', 'GB', 'TB']++export function formatBytes(bytes: number): string {+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'+ const exponent = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), UNITS.length - 1)+ const value = bytes / 1024 ** exponent+ return `${value.toFixed(exponent === 0 ? 0 : 1)} ${UNITS[exponent]}`+}++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 '—'+ if (seconds < 60) return `${Math.ceil(seconds)}s`+ const minutes = Math.floor(seconds / 60)+ if (minutes < 60) return `${minutes}m ${Math.round(seconds % 60)}s`+ const hours = Math.floor(minutes / 60)+ return `${hours}h ${minutes % 60}m`+}++export function formatPercent(bytesDownloaded: number, totalBytes: number): number {+ if (totalBytes <= 0) return 0+ return Math.min(100, Math.round((bytesDownloaded / totalBytes) * 100))+}++export function fileNameFromPath(path: string): string {+ return path.split('/').pop() ?? path+}++/** m:ss, or h:mm:ss past an hour. */+export function formatDuration(seconds: number): string {+ const total = Math.max(0, Math.round(seconds))+ const hrs = Math.floor(total / 3600)+ const mins = Math.floor((total % 3600) / 60)+ const secs = total % 60+ if (hrs > 0) return `${hrs}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`+ return `${mins}:${String(secs).padStart(2, '0')}`+}++/** "12.3 MB" -> { value: "12.3", unit: "MB" } — for readouts that size the number and unit separately. */+export function splitFormattedBytes(bytes: number): { value: string; unit: string } {+ const [value, unit] = formatBytes(bytes).split(' ')+ return { value, unit }+}++export function dirnameOf(path: string): string {+ const index = path.lastIndexOf('/')+ return index <= 0 ? '/' : path.slice(0, index)+}++/** Shortens an absolute path under the user's home directory to a "~/..." form for display. */+export function toDisplayPath(path: string, homeDir: string): string {+ if (homeDir && (path === homeDir || path.startsWith(`${homeDir}/`))) {+ return `~${path.slice(homeDir.length)}`+ }+ return path+}diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.tsnew file mode 100644index 0000000..9c9d91b--- /dev/null+++ b/src/shared/ipc-channels.ts@@ -0,0 +1,16 @@+export const IpcChannels = {+ listInterfaces: 'network:list-interfaces',+ pingInterfaces: 'network:ping-interfaces',+ openNetworkSettings: 'network:open-settings',+ probeUrl: 'download:probe',+ getInitialPaths: 'paths:get-initial',+ chooseDestinationFolder: 'dialog:choose-destination-folder',+ readClipboardText: 'clipboard:read-text',+ revealInFolder: 'shell:reveal-in-folder',+ startDownload: 'download:start',+ pauseDownload: 'download:pause',+ resumeDownload: 'download:resume',+ cancelDownload: 'download:cancel',+ removeDownload: 'download:remove',+ downloadUpdated: 'download:updated'+} as constdiff --git a/src/shared/types.ts b/src/shared/types.tsnew file mode 100644index 0000000..1a976e0--- /dev/null+++ b/src/shared/types.ts@@ -0,0 +1,66 @@+export type NetworkInterfaceKind = 'wifi' | 'usb' | 'ethernet' | 'bridge' | 'other'++export interface NetworkInterfaceInfo {+ /** Stable identifier for this interface (currently the OS device name, e.g. "en0"). */+ id: string+ device: string+ displayName: string+ address: string+ kind: NetworkInterfaceKind+ mac?: string+}++export interface ProbeResult {+ requestedUrl: string+ /** URL after following redirects — this is what the download should actually fetch. */+ finalUrl: string+ supportsRanges: boolean+ /** null when the server did not report a size. */+ totalBytes: number | null+ suggestedFileName: string+ contentType: string | null+}++export type DownloadStatus = 'downloading' | 'paused' | 'completed' | 'error' | 'cancelled'++export type ChunkStatus = 'pending' | 'downloading' | 'paused' | 'completed' | 'error' | 'cancelled'++export interface ChunkState {+ id: number+ interfaceId: string+ interfaceLabel: string+ interfaceKind: NetworkInterfaceKind+ rangeStart: number+ /** null means an open-ended range (download to end of file). */+ rangeEnd: number | null+ bytesDownloaded: number+ speedBytesPerSec: number+ status: ChunkStatus+ error?: string+}++export interface DownloadState {+ id: string+ url: string+ fileName: string+ destinationPath: string+ /** 0 means the size could not be determined ahead of time. */+ totalBytes: number+ bytesDownloaded: number+ speedBytesPerSec: number+ status: DownloadStatus+ chunks: ChunkState[]+ error?: string+ startedAt: number+ completedAt?: number+}++export interface StartDownloadRequest {+ url: string+ destinationDir: string+ suggestedFileName: string+ /** 0 means unknown. */+ totalBytes: number+ supportsRanges: boolean+ interfaceIds: string[]+}diff --git a/tsconfig.node.json b/tsconfig.node.jsonindex db23a68..7cfb5f0 100644--- a/tsconfig.node.json+++ b/tsconfig.node.json@@ -1,8 +1,12 @@{"extends": "@electron-toolkit/tsconfig/tsconfig.node.json",- "include": ["electron.vite.config.*", "src/main/**/*", "src/preload/**/*"],+ "include": ["electron.vite.config.*", "src/main/**/*", "src/preload/**/*", "src/shared/**/*"],"compilerOptions": {"composite": true,- "types": ["electron-vite/node"]+ "types": ["electron-vite/node"],+ "baseUrl": ".",+ "paths": {+ "@shared/*": ["src/shared/*"]+ }}}diff --git a/tsconfig.web.json b/tsconfig.web.jsonindex 9c16b66..0c7ebed 100644--- a/tsconfig.web.json+++ b/tsconfig.web.json@@ -4,7 +4,8 @@"src/renderer/src/env.d.ts","src/renderer/src/**/*","src/renderer/src/**/*.tsx",- "src/preload/*.d.ts"+ "src/preload/*.d.ts",+ "src/shared/**/*"],"compilerOptions": {"composite": true,@@ -13,6 +14,9 @@"paths": {"@renderer/*": ["src/renderer/src/*"+ ],+ "@shared/*": [+ "src/shared/*"]}}