Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

feat: remember parallel streams and destination folder across launches

Anmol Kapil71843976492e
diff --git a/e2e/ui.spec.ts b/e2e/ui.spec.ts
index 08a5a55..1be103a 100644
--- a/e2e/ui.spec.ts
+++ b/e2e/ui.spec.ts
@@ -125,6 +125,20 @@ test.describe('UI journeys @smoke', () => {
await expect(plexo.page.getByText('Office fibre')).toBeVisible()
})
+ test('streams and destination folder survive a restart', async ({ plexo, dirs }) => {
+ await stubNativeUi(plexo, dirs.dest)
+ await plexo.page.getByRole('button', { name: 'Browse…' }).click()
+ await plexo.page.getByRole('button', { name: '4×' }).click()
+ await expect(plexo.page.getByText(dirs.dest)).toBeVisible()
+
+ await plexo.relaunch()
+ await expect(plexo.page.getByRole('button', { name: '4×' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ )
+ await expect(plexo.page.getByText(dirs.dest)).toBeVisible()
+ })
+
test('a corrupt network-preferences.json does not break the network list', async ({
plexo,
dirs
diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.ts
index f2f6861..83e52d0 100644
--- a/src/main/ipc/handlers.ts
+++ b/src/main/ipc/handlers.ts
@@ -1,3 +1,4 @@
+import { stat } from 'node:fs/promises'
import { is } from '@electron-toolkit/utils'
import {
app,
@@ -11,7 +12,7 @@ import {
} from 'electron'
import { IpcChannels } from '../../shared/ipc-channels'
import type { IpcContract } from '../../shared/ipc-contract'
-import type { NetworkInterfaceInfo, ThemeSource } from '../../shared/types'
+import type { InitialState, NetworkInterfaceInfo, ThemeSource } from '../../shared/types'
import { DownloadManager } from '../download/downloadManager'
import { getDefaultDownloadsDir, getHomeDir } from '../download/paths'
import { probeUrl } from '../download/probe'
@@ -19,11 +20,7 @@ import { deviceBindingSupported } from '../network/deviceBinding'
import { measureLatencies } from '../network/latency'
import { listActiveInterfaces } from '../network/interfaces'
import { loadNetworkPreferences, saveNetworkPreference } from '../network/preferences'
-import {
- loadDismissedUpdateVersion,
- saveDismissedUpdateVersion,
- saveThemeSource
-} from '../settings'
+import { loadSettings, saveSettings } from '../settings'
import { testKnobs } from '../testKnobs'
import { checkForUpdate, UPDATE_PAGE_URL } from '../updateCheck'
@@ -80,8 +77,6 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
const bindingSupport = deviceBindingSupported()
handle('deviceBindingSupported', async () => bindingSupport)
- handle('getNetworkPreferences', async () => loadNetworkPreferences())
-
handle('setNetworkPreference', async (_event, id, patch) => saveNetworkPreference(id, patch))
// The app only ever assigns 'light'/'dark' to nativeTheme.themeSource (main/index.ts's startup
@@ -94,22 +89,65 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
handle('setThemeSource', async (_event, source) => {
nativeTheme.themeSource = source
- await saveThemeSource(source)
+ await saveSettings({ themeSource: source })
return currentThemeSource()
})
+ // Answered via sendSync from the preload, which blocks the page until returnValue is set — so a
+ // throw here must still reply (with no saved values) rather than leave the window never showing.
+ ipcMain.on(IpcChannels.getInitialState, async (event) => {
+ const paths = (): Pick<InitialState, 'homeDir' | 'downloadsDir' | 'isDev'> => ({
+ homeDir: getHomeDir(),
+ downloadsDir: getDefaultDownloadsDir(),
+ isDev: is.dev
+ })
+ try {
+ const [settings, networkPreferences] = await Promise.all([
+ loadSettings(),
+ loadNetworkPreferences()
+ ])
+ const { destinationDir } = settings
+ const destinationExists =
+ typeof destinationDir === 'string' &&
+ (await stat(destinationDir).then(
+ (stats) => stats.isDirectory(),
+ () => false
+ ))
+ event.returnValue = {
+ ...paths(),
+ themeSource: currentThemeSource(),
+ networkPreferences,
+ streamsPerNetwork: settings.streamsPerNetwork,
+ destinationDir: destinationExists ? destinationDir : undefined
+ } satisfies InitialState
+ } catch (error) {
+ console.error('[plexo] failed to read initial state', error)
+ let fallbackPaths: ReturnType<typeof paths>
+ try {
+ fallbackPaths = paths()
+ } catch {
+ fallbackPaths = { homeDir: '', downloadsDir: '', isDev: is.dev }
+ }
+ event.returnValue = {
+ ...fallbackPaths,
+ themeSource: currentThemeSource(),
+ networkPreferences: {}
+ } satisfies InitialState
+ }
+ })
+
+ handle('setStreamsPerNetwork', async (_event, streamsPerNetwork) =>
+ saveSettings({ streamsPerNetwork })
+ )
+
+ handle('setDestinationDir', async (_event, destinationDir) => saveSettings({ destinationDir }))
+
handle('openNetworkSettings', async () => {
await openNetworkSettings()
})
handle('probeUrl', async (_event, url) => probeUrl(url))
- handle('getInitialPaths', async () => ({
- homeDir: getHomeDir(),
- downloadsDir: getDefaultDownloadsDir(),
- isDev: is.dev
- }))
-
handle('chooseDestinationFolder', async (_event, defaultPath) => {
const window = getWindow()
if (!window) return null
@@ -164,14 +202,14 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
? { version: testKnobs.forceUpdateVersion, url: UPDATE_PAGE_URL }
: await checkForUpdate(app.getVersion())
if (!info) return null
- const dismissedVersion = await loadDismissedUpdateVersion()
+ const { dismissedUpdateVersion: dismissedVersion } = await loadSettings()
return { ...info, dismissed: info.version === dismissedVersion }
})()
handle('checkForUpdate', async () => updateCheckPromise)
handle('dismissUpdate', async (_event, version) => {
- await saveDismissedUpdateVersion(version)
+ await saveSettings({ dismissedUpdateVersion: version })
})
return manager
diff --git a/src/main/jsonFile.ts b/src/main/jsonFile.ts
new file mode 100644
index 0000000..adf5c26
--- /dev/null
+++ b/src/main/jsonFile.ts
@@ -0,0 +1,29 @@
+import { readFile, rename, writeFile } from 'node:fs/promises'
+
+/** Parsed contents, or undefined when the file is missing (first run) or unreadable/corrupt. */
+export async function readJson(path: string): Promise<unknown> {
+ try {
+ return JSON.parse(await readFile(path, 'utf-8'))
+ } catch {
+ return undefined
+ }
+}
+
+const writeChains = new Map<string, Promise<unknown>>()
+
+/** Read-modify-write, queued per file so two quick saves can't drop each other's change, and
+ * written via a temp file + rename so a crash mid-write can't leave a half-written file (which
+ * would read back as corrupt and wipe every saved value). */
+export function updateJson<T>(path: string, update: (current: unknown) => T): Promise<T> {
+ const next = (writeChains.get(path) ?? Promise.resolve())
+ .catch(() => {})
+ .then(async () => {
+ const value = update(await readJson(path))
+ const temporaryPath = `${path}.tmp`
+ await writeFile(temporaryPath, JSON.stringify(value, null, 2), 'utf-8')
+ await rename(temporaryPath, path)
+ return value
+ })
+ writeChains.set(path, next)
+ return next
+}
diff --git a/src/main/network/preferences.ts b/src/main/network/preferences.ts
index 4bcaed0..59eab67 100644
--- a/src/main/network/preferences.ts
+++ b/src/main/network/preferences.ts
@@ -1,7 +1,7 @@
-import { readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { app } from 'electron'
import type { NetworkPreference, NetworkPreferences } from '../../shared/types'
+import { readJson, updateJson } from '../jsonFile'
function preferencesPath(): string {
return join(app.getPath('userData'), 'network-preferences.json')
@@ -27,32 +27,26 @@ function sanitizeNetworkPreferences(parsed: unknown): NetworkPreferences {
}
export async function loadNetworkPreferences(): Promise<NetworkPreferences> {
- try {
- const raw = await readFile(preferencesPath(), 'utf-8')
- return sanitizeNetworkPreferences(JSON.parse(raw))
- } catch {
- // No file yet (first run) or it's unreadable/corrupt — either way, no saved prefs.
- return {}
- }
+ return sanitizeNetworkPreferences(await readJson(preferencesPath()))
}
/** Merges `patch` into the stored preference for `id` — an explicit `undefined` field in
* `patch` clears that field, a field simply left out of `patch` is left untouched. An id left
* with no fields set is dropped entirely, so resetting a network removes it from the file. */
-export async function saveNetworkPreference(
+export function saveNetworkPreference(
id: string,
patch: NetworkPreference
): Promise<NetworkPreferences> {
- const current = await loadNetworkPreferences()
- const merged: NetworkPreference = { ...current[id], ...patch }
- const next: NetworkPreferences = { ...current }
-
- if (merged.customName || merged.colorId) {
- next[id] = merged
- } else {
- delete next[id]
- }
+ return updateJson(preferencesPath(), (parsed) => {
+ const current = sanitizeNetworkPreferences(parsed)
+ const merged: NetworkPreference = { ...current[id], ...patch }
+ const next: NetworkPreferences = { ...current }
- await writeFile(preferencesPath(), JSON.stringify(next, null, 2), 'utf-8')
- return next
+ if (merged.customName || merged.colorId) {
+ next[id] = merged
+ } else {
+ delete next[id]
+ }
+ return next
+ })
}
diff --git a/src/main/settings.ts b/src/main/settings.ts
index 53ad4c5..114e7ec 100644
--- a/src/main/settings.ts
+++ b/src/main/settings.ts
@@ -1,7 +1,7 @@
-import { readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { app, nativeTheme } from 'electron'
import type { ThemeSource } from '../shared/types'
+import { readJson, updateJson } from './jsonFile'
function settingsPath(): string {
return join(app.getPath('userData'), 'app-settings.json')
@@ -10,16 +10,20 @@ function settingsPath(): string {
interface AppSettings {
themeSource?: ThemeSource
dismissedUpdateVersion?: string
+ streamsPerNetwork?: number
+ destinationDir?: string
}
-async function loadSettings(): Promise<AppSettings> {
- try {
- const raw = await readFile(settingsPath(), 'utf-8')
- return JSON.parse(raw) as AppSettings
- } catch {
- // No file yet (first run) or it's unreadable/corrupt — either way, no saved settings.
- return {}
- }
+function asSettings(parsed: unknown): AppSettings {
+ return typeof parsed === 'object' && parsed !== null ? (parsed as AppSettings) : {}
+}
+
+export async function loadSettings(): Promise<AppSettings> {
+ return asSettings(await readJson(settingsPath()))
+}
+
+export async function saveSettings(patch: AppSettings): Promise<void> {
+ await updateJson(settingsPath(), (current) => ({ ...asSettings(current), ...patch }))
}
export async function loadThemeSource(): Promise<ThemeSource> {
@@ -31,22 +35,3 @@ export async function loadThemeSource(): Promise<ThemeSource> {
// whatever the OS appearance is right now rather than defaulting to a fixed theme.
return nativeTheme.shouldUseDarkColors ? 'dark' : 'light'
}
-
-export async function saveThemeSource(themeSource: ThemeSource): Promise<void> {
- const settings = await loadSettings()
- await writeFile(settingsPath(), JSON.stringify({ ...settings, themeSource }, null, 2), 'utf-8')
-}
-
-export async function loadDismissedUpdateVersion(): Promise<string | undefined> {
- const settings = await loadSettings()
- return settings.dismissedUpdateVersion
-}
-
-export async function saveDismissedUpdateVersion(version: string): Promise<void> {
- const settings = await loadSettings()
- await writeFile(
- settingsPath(),
- JSON.stringify({ ...settings, dismissedUpdateVersion: version }, null, 2),
- 'utf-8'
- )
-}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 55fa46c..2d65dbb 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -1,7 +1,7 @@
import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'
import { IpcChannels } from '../shared/ipc-channels'
import type { IpcContract } from '../shared/ipc-contract'
-import type { DownloadState, NetworkPreference, ThemeSource } from '../shared/types'
+import type { DownloadState, InitialState, 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
@@ -15,18 +15,21 @@ function invoke<K extends keyof IpcContract>(
const plexoApi = {
platform: process.platform,
+ // Sync on purpose — see InitialState. One small read, once, before the renderer's first paint.
+ initialState: ipcRenderer.sendSync(IpcChannels.getInitialState) as InitialState,
listInterfaces: () => invoke('listInterfaces'),
pingInterfaces: () => invoke('pingInterfaces'),
deviceBindingSupported: () => invoke('deviceBindingSupported'),
openNetworkSettings: () => invoke('openNetworkSettings'),
- getNetworkPreferences: () => invoke('getNetworkPreferences'),
setNetworkPreference: (id: string, patch: NetworkPreference) =>
invoke('setNetworkPreference', id, patch),
getThemeSource: () => invoke('getThemeSource'),
setThemeSource: (source: ThemeSource) => invoke('setThemeSource', source),
+ setStreamsPerNetwork: (streamsPerNetwork: number) =>
+ invoke('setStreamsPerNetwork', streamsPerNetwork),
probeUrl: (url: string) => invoke('probeUrl', url),
- getInitialPaths: () => invoke('getInitialPaths'),
+ setDestinationDir: (dir: string) => invoke('setDestinationDir', dir),
chooseDestinationFolder: (defaultPath: string) => invoke('chooseDestinationFolder', defaultPath),
chooseSourceFile: () => invoke('chooseSourceFile'),
readClipboardText: () => invoke('readClipboardText'),
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index 4823d0b..e528ad6 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -75,17 +75,11 @@ function App(): React.JSX.Element {
const interfacesStatus = useAppStore((store) => store.interfacesStatus)
const currentDownload = useAppStore((store) => store.currentDownload)
const clearCurrentDownload = useAppStore((store) => store.clearCurrentDownload)
- const loadNetworkPreferences = useAppStore((store) => store.loadNetworkPreferences)
- const loadThemeSource = useAppStore((store) => store.loadThemeSource)
- const loadInitialPaths = useAppStore((store) => store.loadInitialPaths)
const checkForUpdate = useAppStore((store) => store.checkForUpdate)
useEffect(() => {
- loadNetworkPreferences()
- loadThemeSource()
- loadInitialPaths()
checkForUpdate()
- }, [loadNetworkPreferences, loadThemeSource, loadInitialPaths, checkForUpdate])
+ }, [checkForUpdate])
const handleNewDownload = (): void => {
if (currentDownload) void window.plexo.removeDownload(currentDownload.id)
diff --git a/src/renderer/src/screens/IdleScreen.tsx b/src/renderer/src/screens/IdleScreen.tsx
index 4835443..2170b81 100644
--- a/src/renderer/src/screens/IdleScreen.tsx
+++ b/src/renderer/src/screens/IdleScreen.tsx
@@ -1,4 +1,4 @@
-import { planDownload } from '@shared/plan'
+import { PRESET_STREAMS, planDownload } from '@shared/plan'
import type { ProbeResult } from '@shared/types'
import { cn } from 'cn'
import { AlertTriangle, ClipboardPaste } from 'lucide-react'
@@ -19,7 +19,6 @@ type ProbeState =
| { status: 'error'; message: string }
const PROBE_DEBOUNCE_MS = 600
-const PRESET_STREAMS = [1, 2, 4, 8] as const
const PASTE_SHORTCUT = window.plexo.platform === 'darwin' ? '⌘V' : 'Ctrl+V'
const fieldLabelClass = 'shrink-0 font-mono text-[10px] tracking-[0.14em] text-muted-foreground'
@@ -42,23 +41,20 @@ export function IdleScreen(): React.JSX.Element {
const latencies = useAppStore((store) => store.latencies)
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 destinationDir = useAppStore((store) => store.destinationDir)
+ const setDestinationDir = useAppStore((store) => store.setDestinationDir)
+ const chunksPerNetwork = useAppStore((store) => store.streamsPerNetwork)
+ const setChunksPerNetwork = useAppStore((store) => store.setStreamsPerNetwork)
const [probe, setProbe] = useState<ProbeState>({ status: 'idle' })
// Tracks deselections rather than selections, so a newly-detected interface starts selected.
const [deselectedInterfaceIds, setDeselectedInterfaceIds] = useState<string[]>([])
- const [chunksPerNetwork, setChunksPerNetwork] = useState(2)
const [starting, setStarting] = useState(false)
const [startError, setStartError] = useState<string | null>(null)
const [fileNameOverride, setFileNameOverride] = useState<string | null>(null)
const probeRequestId = useRef(0)
- useEffect(() => {
- if (!destinationDir && downloadsDir) setDestinationDir(downloadsDir)
- }, [destinationDir, downloadsDir, setDestinationDir])
-
useEffect(() => {
const trimmed = url.trim()
if (!trimmed) {
@@ -277,7 +273,7 @@ export function IdleScreen(): React.JSX.Element {
value={[String(chunksPerNetwork)]}
onValueChange={(values) => {
if (values.length === 0) return
- setChunksPerNetwork(Number(values[0]))
+ void setChunksPerNetwork(Number(values[0]))
}}
disabled={isSingleStreamOnly}
aria-labelledby="idle-streams-label"
diff --git a/src/renderer/src/store/useAppStore.ts b/src/renderer/src/store/useAppStore.ts
index 119094c..321ab1f 100644
--- a/src/renderer/src/store/useAppStore.ts
+++ b/src/renderer/src/store/useAppStore.ts
@@ -6,6 +6,7 @@ import type {
ThemeSource,
UpdateInfo
} from '@shared/types'
+import { PRESET_STREAMS } from '@shared/plan'
import { create } from 'zustand'
import { groupChunksByInterface } from '../utils/format'
@@ -28,6 +29,7 @@ interface AppStore {
/** Persisted in the main process alongside nativeTheme.themeSource. */
themeSource: ThemeSource
+ streamsPerNetwork: number
/** Null until the one-time startup check resolves, or if it found nothing worth showing
* (already up to date, already dismissed, or the check failed). */
@@ -35,7 +37,6 @@ interface AppStore {
homeDir: string
downloadsDir: string
- pathsStatus: LoadStatus
/** True in electron-vite's dev server, false in a packaged build — gates the dev tools panel. */
isDev: boolean
@@ -51,36 +52,41 @@ interface AppStore {
/** Lifted out of the Idle screen so it survives a swap to/from the No-connections screen. */
draftUrl: string
- draftDestinationDir: string
+ /** Persisted — the last folder picked, falling back to downloadsDir. */
+ destinationDir: string
loadInterfaces: () => Promise<void>
refreshLatencies: () => Promise<void>
- loadInitialPaths: () => Promise<void>
- loadNetworkPreferences: () => Promise<void>
setNetworkPreference: (id: string, patch: NetworkPreference) => Promise<void>
- loadThemeSource: () => Promise<void>
setThemeSource: (source: ThemeSource) => Promise<void>
+ setStreamsPerNetwork: (streamsPerNetwork: number) => Promise<void>
checkForUpdate: () => Promise<void>
dismissUpdate: () => void
setCurrentDownload: (state: DownloadState) => void
clearCurrentDownload: () => void
setDraftUrl: (url: string) => void
- setDraftDestinationDir: (dir: string) => void
+ setDestinationDir: (dir: string) => void
}
+// Settings saved by the main process, read once before the first paint (see InitialState).
+const initial = window.plexo.initialState
+const savedStreamsPerNetwork = (PRESET_STREAMS as readonly number[]).find(
+ (preset) => preset === initial.streamsPerNetwork
+)
+
export const useAppStore = create<AppStore>((set, get) => ({
interfaces: [],
interfacesStatus: 'idle',
interfacesError: null,
latencies: {},
- networkPreferences: {},
- themeSource: 'light',
+ networkPreferences: initial.networkPreferences,
+ themeSource: initial.themeSource,
+ streamsPerNetwork: savedStreamsPerNetwork ?? 2,
availableUpdate: null,
- homeDir: '',
- downloadsDir: '',
- pathsStatus: 'idle',
- isDev: false,
+ homeDir: initial.homeDir,
+ downloadsDir: initial.downloadsDir,
+ isDev: initial.isDev,
currentDownload: null,
speedHistory: [],
@@ -88,7 +94,7 @@ export const useAppStore = create<AppStore>((set, get) => ({
peakSpeedBytesPerSec: 0,
draftUrl: '',
- draftDestinationDir: '',
+ destinationDir: initial.destinationDir ?? initial.downloadsDir,
loadInterfaces: async () => {
// A re-scan keeps showing the last result. Dropping back to 'loading' would swap App off the
@@ -116,25 +122,6 @@ export const useAppStore = create<AppStore>((set, get) => ({
}
},
- loadInitialPaths: async () => {
- set({ pathsStatus: 'loading' })
- try {
- const { homeDir, downloadsDir, isDev } = await window.plexo.getInitialPaths()
- set({ homeDir, downloadsDir, isDev, pathsStatus: 'ready' })
- } catch {
- set({ pathsStatus: 'error' })
- }
- },
-
- loadNetworkPreferences: async () => {
- try {
- const networkPreferences = await window.plexo.getNetworkPreferences()
- set({ networkPreferences })
- } catch {
- // Best-effort — a failed read just leaves networks under their OS names/default colors.
- }
- },
-
setNetworkPreference: async (id, patch) => {
// Optimistic update so the rename/recolor feels instant — the IPC round trip resolves
// (or, on failure, quietly leaves the optimistic value as the source of truth for now).
@@ -152,20 +139,20 @@ export const useAppStore = create<AppStore>((set, get) => ({
}
},
- loadThemeSource: async () => {
+ setThemeSource: async (themeSource) => {
+ // Optimistic update, same as setNetworkPreference — the toggle should feel instant.
+ set({ themeSource })
try {
- const themeSource = await window.plexo.getThemeSource()
- set({ themeSource })
+ await window.plexo.setThemeSource(themeSource)
} catch {
- // Best-effort — a failed read just leaves the toggle showing the 'light' default.
+ // Leave the optimistic value in place — not persisted to disk, but still usable this session.
}
},
- setThemeSource: async (themeSource) => {
- // Optimistic update, same as setNetworkPreference — the toggle should feel instant.
- set({ themeSource })
+ setStreamsPerNetwork: async (streamsPerNetwork) => {
+ set({ streamsPerNetwork })
try {
- await window.plexo.setThemeSource(themeSource)
+ await window.plexo.setStreamsPerNetwork(streamsPerNetwork)
} catch {
// Leave the optimistic value in place — not persisted to disk, but still usable this session.
}
@@ -228,5 +215,9 @@ export const useAppStore = create<AppStore>((set, get) => ({
}),
setDraftUrl: (draftUrl) => set({ draftUrl }),
- setDraftDestinationDir: (draftDestinationDir) => set({ draftDestinationDir })
+ setDestinationDir: (destinationDir) => {
+ set({ destinationDir })
+ // Best-effort — a failed save just means the pick isn't remembered next launch.
+ window.plexo.setDestinationDir(destinationDir).catch(() => {})
+ }
}))
diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.ts
index 2ffe7b9..1cc8fe0 100644
--- a/src/shared/ipc-channels.ts
+++ b/src/shared/ipc-channels.ts
@@ -3,12 +3,13 @@ export const IpcChannels = {
pingInterfaces: 'network:ping-interfaces',
deviceBindingSupported: 'network:device-binding-supported',
openNetworkSettings: 'network:open-settings',
- getNetworkPreferences: 'network:get-preferences',
setNetworkPreference: 'network:set-preference',
getThemeSource: 'theme:get-source',
setThemeSource: 'theme:set-source',
+ setStreamsPerNetwork: 'streams:set-per-network',
probeUrl: 'download:probe',
- getInitialPaths: 'paths:get-initial',
+ getInitialState: 'app:get-initial-state',
+ setDestinationDir: 'destination:set-dir',
chooseDestinationFolder: 'dialog:choose-destination-folder',
chooseSourceFile: 'dialog:choose-source-file',
readClipboardText: 'clipboard:read-text',
diff --git a/src/shared/ipc-contract.ts b/src/shared/ipc-contract.ts
index ed80283..bae3bf3 100644
--- a/src/shared/ipc-contract.ts
+++ b/src/shared/ipc-contract.ts
@@ -1,6 +1,5 @@
import type {
DownloadState,
- InitialPaths,
NetworkInterfaceInfo,
NetworkPreference,
NetworkPreferences,
@@ -20,15 +19,15 @@ export interface IpcContract {
pingInterfaces: { args: []; result: Record<string, number | null> }
deviceBindingSupported: { args: []; result: boolean }
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 }
+ setStreamsPerNetwork: { args: [streamsPerNetwork: number]; result: void }
probeUrl: { args: [url: string]; result: ProbeResult }
- getInitialPaths: { args: []; result: InitialPaths }
+ setDestinationDir: { args: [dir: string]; result: void }
chooseDestinationFolder: { args: [defaultPath: string]; result: string | null }
chooseSourceFile: { args: []; result: string | null }
readClipboardText: { args: []; result: string }
diff --git a/src/shared/plan.ts b/src/shared/plan.ts
index 230c305..f6e1c8d 100644
--- a/src/shared/plan.ts
+++ b/src/shared/plan.ts
@@ -17,6 +17,8 @@ export const MAX_BLOCKS = 4096
export const MAX_STREAMS_PER_NETWORK = 8
export const MAX_STREAMS = 32
+/** The per-network stream counts offered in the UI. */
+export const PRESET_STREAMS = [1, 2, 4, 8] as const
/** Blocks planned per stream, at least. Streams pull blocks as they free up, so a fast network
* takes more of them — but only if there are more blocks than streams to begin with. With one
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 198f45c..7e07625 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -156,6 +156,16 @@ export interface InitialPaths {
isDev: boolean
}
+/** Everything the renderer needs for its first paint, read synchronously by the preload so no
+ * saved value flashes in over a default a moment after launch. */
+export interface InitialState extends InitialPaths {
+ themeSource: ThemeSource
+ networkPreferences: NetworkPreferences
+ streamsPerNetwork?: number
+ /** The last folder picked, if it still exists — otherwise the renderer uses downloadsDir. */
+ destinationDir?: string
+}
+
export interface StartDownloadRequest {
url: string
destinationDir: string