Speed up downloads by combining multiple network connections in parallel
TypeScript bandwidth-aggregationcross-platformdesktop-appdownloaderdownloadmanagerlinuxmacosmulticonnectionparallel-downloadswindows
Type the IPC contract between preload and main, drop the raw ipcRenderer bridge
Anmol Kapil715e257f2c48
diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.tsindex 44f3256..35c3dcd 100644--- a/src/main/ipc/handlers.ts+++ b/src/main/ipc/handlers.ts@@ -1,13 +1,16 @@import { is } from '@electron-toolkit/utils'-import { clipboard, dialog, ipcMain, nativeTheme, shell, type BrowserWindow } from 'electron'+import {+ clipboard,+ dialog,+ ipcMain,+ nativeTheme,+ shell,+ type BrowserWindow,+ type IpcMainInvokeEvent+} from 'electron'import { IpcChannels } from '../../shared/ipc-channels'-import type {- NetworkInterfaceInfo,- NetworkPreference,- StartDownloadRequest,- StartSimulatedDownloadRequest,- ThemeSource-} from '../../shared/types'+import type { IpcContract } from '../../shared/ipc-contract'+import type { NetworkInterfaceInfo, ThemeSource } from '../../shared/types'import { DownloadManager } from '../download/downloadManager'import { getDefaultDownloadsDir, getHomeDir } from '../download/paths'import { probeUrl } from '../download/probe'@@ -21,6 +24,22 @@ const NETWORK_SETTINGS_URL =? 'ms-settings:network-status': 'x-apple.systempreferences:com.apple.preference.network'+/** Typed wrapper around ipcMain.handle — the channel name picks its args/result shape out of+ * IpcContract, so a handler here that doesn't match what plexoApi (preload) actually calls is a+ * compile error instead of a silent runtime mismatch. */+function handle<K extends keyof IpcContract>(+ channel: K,+ listener: (+ event: IpcMainInvokeEvent,+ ...args: IpcContract[K]['args']+ ) => IpcContract[K]['result'] | Promise<IpcContract[K]['result']>+): void {+ ipcMain.handle(+ IpcChannels[channel],+ listener as (event: IpcMainInvokeEvent, ...args: unknown[]) => unknown+ )+}+export function registerIpcHandlers(getWindow: () => BrowserWindow | null): DownloadManager {let cachedInterfaces: NetworkInterfaceInfo[] = []@@ -35,38 +54,41 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): DownrefreshInterfaces)- ipcMain.handle(IpcChannels.listInterfaces, refreshInterfaces)+ handle('listInterfaces', refreshInterfaces)- ipcMain.handle(IpcChannels.pingInterfaces, async () => measureLatencies(cachedInterfaces))+ handle('pingInterfaces', async () => measureLatencies(cachedInterfaces))- ipcMain.handle(IpcChannels.getNetworkPreferences, async () => loadNetworkPreferences())+ handle('getNetworkPreferences', async () => loadNetworkPreferences())- ipcMain.handle(- IpcChannels.setNetworkPreference,- async (_event, id: string, patch: NetworkPreference) => saveNetworkPreference(id, patch)- )+ handle('setNetworkPreference', async (_event, id, patch) => saveNetworkPreference(id, patch))++ // The app only ever assigns 'light'/'dark' to nativeTheme.themeSource (main/index.ts's startup+ // call to loadThemeSource() never resolves to 'system') — narrow Electron's wider type here+ // rather than widening our own ThemeSource just to match it.+ const currentThemeSource = (): ThemeSource =>+ nativeTheme.themeSource === 'dark' ? 'dark' : 'light'- ipcMain.handle(IpcChannels.getThemeSource, async () => nativeTheme.themeSource)+ handle('getThemeSource', async () => currentThemeSource())- ipcMain.handle(IpcChannels.setThemeSource, async (_event, source: ThemeSource) => {+ handle('setThemeSource', async (_event, source) => {nativeTheme.themeSource = sourceawait saveThemeSource(source)- return nativeTheme.themeSource+ return currentThemeSource()})- ipcMain.handle(IpcChannels.openNetworkSettings, async () => {+ handle('openNetworkSettings', async () => {await shell.openExternal(NETWORK_SETTINGS_URL)})- ipcMain.handle(IpcChannels.probeUrl, async (_event, url: string) => probeUrl(url))+ handle('probeUrl', async (_event, url) => probeUrl(url))- ipcMain.handle(IpcChannels.getInitialPaths, async () => ({+ handle('getInitialPaths', async () => ({homeDir: getHomeDir(),downloadsDir: getDefaultDownloadsDir(),isDev: is.dev}))- ipcMain.handle(IpcChannels.chooseDestinationFolder, async (_event, defaultPath: string) => {+ handle('chooseDestinationFolder', async (_event, defaultPath) => {const window = getWindow()if (!window) return nullconst result = await dialog.showOpenDialog(window, {@@ -77,7 +99,7 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Downreturn result.filePaths[0]})- ipcMain.handle(IpcChannels.chooseSourceFile, async () => {+ handle('chooseSourceFile', async () => {const window = getWindow()if (!window) return nullconst result = await dialog.showOpenDialog(window, { properties: ['openFile'] })@@ -85,36 +107,31 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Downreturn result.filePaths[0]})- ipcMain.handle(IpcChannels.readClipboardText, async () => clipboard.readText())+ handle('readClipboardText', async () => clipboard.readText())- ipcMain.handle(IpcChannels.revealInFolder, async (_event, filePath: string) => {+ handle('revealInFolder', async (_event, filePath) => {shell.showItemInFolder(filePath)})- ipcMain.handle(IpcChannels.startDownload, async (_event, request: StartDownloadRequest) =>- manager.start(request)- )+ handle('startDownload', async (_event, request) => manager.start(request))- ipcMain.handle(- IpcChannels.startSimulatedDownload,- async (_event, request: StartSimulatedDownloadRequest) => manager.startSimulated(request)- )+ handle('startSimulatedDownload', async (_event, request) => manager.startSimulated(request))- ipcMain.handle(IpcChannels.getCurrentDownload, async () => manager.getCurrentDownload())+ handle('getCurrentDownload', async () => manager.getCurrentDownload())- ipcMain.handle(IpcChannels.pauseDownload, async (_event, id: string) => {+ handle('pauseDownload', async (_event, id) => {await manager.pause(id)})- ipcMain.handle(IpcChannels.resumeDownload, async (_event, id: string) => {+ handle('resumeDownload', async (_event, id) => {manager.resume(id)})- ipcMain.handle(IpcChannels.cancelDownload, async (_event, id: string) => {+ handle('cancelDownload', async (_event, id) => {manager.cancel(id)})- ipcMain.handle(IpcChannels.removeDownload, async (_event, id: string) => {+ handle('removeDownload', async (_event, id) => {manager.remove(id)})diff --git a/src/preload/index.d.ts b/src/preload/index.d.tsindex d31ba58..f6e4230 100644--- a/src/preload/index.d.ts+++ b/src/preload/index.d.ts@@ -1,9 +1,7 @@-import { ElectronAPI } from '@electron-toolkit/preload'import type { PlexoApi } from './index'declare global {interface Window {- electron: ElectronAPIplexo: PlexoApi}}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 4bda27f..b0da9ef 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -1,80 +1,44 @@-import { electronAPI } from '@electron-toolkit/preload'import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'import { IpcChannels } from '../shared/ipc-channels'-import type {- DownloadState,- NetworkInterfaceInfo,- NetworkPreference,- NetworkPreferences,- ProbeResult,- StartDownloadRequest,- StartSimulatedDownloadRequest,- ThemeSource-} from '../shared/types'--export interface InitialPaths {- homeDir: string- downloadsDir: string- /** True in electron-vite's dev server, false in a packaged build — gates the dev tools panel. */- isDev: boolean+import type { IpcContract } from '../shared/ipc-contract'+import type { DownloadState, NetworkPreference, ThemeSource } from '../shared/types'++/** Typed wrapper around ipcRenderer.invoke — the channel name picks its args/result shape out of+ * IpcContract, so a call here that doesn't match what registerIpcHandlers (main) actually handles+ * is a compile error instead of a silent runtime mismatch. */+function invoke<K extends keyof IpcContract>(+ channel: K,+ ...args: IpcContract[K]['args']+): Promise<IpcContract[K]['result']> {+ return ipcRenderer.invoke(IpcChannels[channel], ...args)}const plexoApi = {platform: process.platform,- listInterfaces: (): Promise<NetworkInterfaceInfo[]> =>- ipcRenderer.invoke(IpcChannels.listInterfaces),-- pingInterfaces: (): Promise<Record<string, number | null>> =>- ipcRenderer.invoke(IpcChannels.pingInterfaces),-- openNetworkSettings: (): Promise<void> => ipcRenderer.invoke(IpcChannels.openNetworkSettings),-- getNetworkPreferences: (): Promise<NetworkPreferences> =>- ipcRenderer.invoke(IpcChannels.getNetworkPreferences),-- setNetworkPreference: (id: string, patch: NetworkPreference): Promise<NetworkPreferences> =>- ipcRenderer.invoke(IpcChannels.setNetworkPreference, id, patch),-- getThemeSource: (): Promise<ThemeSource> => ipcRenderer.invoke(IpcChannels.getThemeSource),-- setThemeSource: (source: ThemeSource): Promise<ThemeSource> =>- ipcRenderer.invoke(IpcChannels.setThemeSource, source),-- 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),-- chooseSourceFile: (): Promise<string | null> => ipcRenderer.invoke(IpcChannels.chooseSourceFile),-- 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),-- startSimulatedDownload: (request: StartSimulatedDownloadRequest): Promise<string> =>- ipcRenderer.invoke(IpcChannels.startSimulatedDownload, request),-- getCurrentDownload: (): Promise<DownloadState | null> =>- ipcRenderer.invoke(IpcChannels.getCurrentDownload),-- 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),+ listInterfaces: () => invoke('listInterfaces'),+ pingInterfaces: () => invoke('pingInterfaces'),+ openNetworkSettings: () => invoke('openNetworkSettings'),+ getNetworkPreferences: () => invoke('getNetworkPreferences'),+ setNetworkPreference: (id: string, patch: NetworkPreference) =>+ invoke('setNetworkPreference', id, patch),+ getThemeSource: () => invoke('getThemeSource'),+ setThemeSource: (source: ThemeSource) => invoke('setThemeSource', source),+ probeUrl: (url: string) => invoke('probeUrl', url),+ getInitialPaths: () => invoke('getInitialPaths'),+ chooseDestinationFolder: (defaultPath: string) => invoke('chooseDestinationFolder', defaultPath),+ chooseSourceFile: () => invoke('chooseSourceFile'),+ readClipboardText: () => invoke('readClipboardText'),+ revealInFolder: (filePath: string) => invoke('revealInFolder', filePath),+ startDownload: (request: IpcContract['startDownload']['args'][0]) =>+ invoke('startDownload', request),+ startSimulatedDownload: (request: IpcContract['startSimulatedDownload']['args'][0]) =>+ invoke('startSimulatedDownload', request),+ getCurrentDownload: () => invoke('getCurrentDownload'),+ pauseDownload: (downloadId: string) => invoke('pauseDownload', downloadId),+ resumeDownload: (downloadId: string) => invoke('resumeDownload', downloadId),+ cancelDownload: (downloadId: string) => invoke('cancelDownload', downloadId),+ removeDownload: (downloadId: string) => invoke('removeDownload', downloadId),onDownloadUpdated: (callback: (state: DownloadState) => void): (() => void) => {const listener = (_event: IpcRendererEvent, state: DownloadState): void => callback(state)@@ -91,16 +55,16 @@ const plexoApi = {export type PlexoApi = typeof plexoApi+// Nothing in the renderer needs raw Electron/Node access — only the typed plexoApi above is+// exposed. The @electron-toolkit/preload electronAPI (which hands the renderer an unrestricted+// ipcRenderer.invoke/send/on on any channel) is deliberately not bridged.if (process.contextIsolated) {try {- contextBridge.exposeInMainWorld('electron', electronAPI)contextBridge.exposeInMainWorld('plexo', plexoApi)} catch (error) {console.error(error)}} else {- // @ts-ignore (define in dts)- window.electron = electronAPI// @ts-ignore (define in dts)window.plexo = plexoApi}diff --git a/src/shared/ipc-contract.ts b/src/shared/ipc-contract.tsnew file mode 100644index 0000000..21135c8--- /dev/null+++ b/src/shared/ipc-contract.ts@@ -0,0 +1,41 @@+import type {+ DownloadState,+ InitialPaths,+ NetworkInterfaceInfo,+ NetworkPreference,+ NetworkPreferences,+ ProbeResult,+ StartDownloadRequest,+ StartSimulatedDownloadRequest,+ ThemeSource+} from './types'++/** The request/response half of the IPC surface (every IpcChannels entry except the two+ * main->renderer push events, downloadUpdated and toggleDevToolsPanel) — one source of truth for+ * both plexoApi (preload) and registerIpcHandlers (main), so a signature drift between the two+ * is a compile error instead of a runtime one. */+export interface IpcContract {+ listInterfaces: { args: []; result: NetworkInterfaceInfo[] }+ pingInterfaces: { args: []; result: Record<string, number | null> }+ openNetworkSettings: { args: []; result: void }+ getNetworkPreferences: { args: []; result: NetworkPreferences }+ setNetworkPreference: {+ args: [id: string, patch: NetworkPreference]+ result: NetworkPreferences+ }+ getThemeSource: { args: []; result: ThemeSource }+ setThemeSource: { args: [source: ThemeSource]; result: ThemeSource }+ probeUrl: { args: [url: string]; result: ProbeResult }+ getInitialPaths: { args: []; result: InitialPaths }+ chooseDestinationFolder: { args: [defaultPath: string]; result: string | null }+ chooseSourceFile: { args: []; result: string | null }+ readClipboardText: { args: []; result: string }+ revealInFolder: { args: [filePath: string]; result: void }+ startDownload: { args: [request: StartDownloadRequest]; result: string }+ startSimulatedDownload: { args: [request: StartSimulatedDownloadRequest]; result: string }+ getCurrentDownload: { args: []; result: DownloadState | null }+ pauseDownload: { args: [id: string]; result: void }+ resumeDownload: { args: [id: string]; result: void }+ cancelDownload: { args: [id: string]; result: void }+ removeDownload: { args: [id: string]; result: void }+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 037252d..03fabc6 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -134,6 +134,13 @@ export interface StartSimulatedDownloadRequest {assembleSpeedBytesPerSec?: number}+export interface InitialPaths {+ homeDir: string+ downloadsDir: string+ /** True in electron-vite's dev server, false in a packaged build — gates the dev tools panel. */+ isDev: boolean+}+export interface StartDownloadRequest {url: stringdestinationDir: string