Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

refactor: one settings file, one save channel, validated in one place

Anmol Kapil615150ed9137
diff --git a/e2e/ui.spec.ts b/e2e/ui.spec.ts
index 1be103a..63bf4c2 100644
--- a/e2e/ui.spec.ts
+++ b/e2e/ui.spec.ts
@@ -1,4 +1,4 @@
-import { writeFile } from 'node:fs/promises'
+import { access, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { BLOCK, expect, interfacesEnv, NETWORKS, test } from './fixtures'
@@ -106,12 +106,13 @@ test.describe('UI journeys @smoke', () => {
})
test('theme choice survives a restart', async ({ plexo }) => {
- const before = await plexo.api.getThemeSource()
- const next = before === 'light' ? 'dark' : 'light'
+ const themeSource = (): Promise<string> =>
+ plexo.evaluateMain(({ nativeTheme }) => nativeTheme.themeSource, undefined)
+ const next = (await themeSource()) === 'light' ? 'dark' : 'light'
await plexo.page.getByRole('button', { name: `Switch to ${next} theme` }).click()
- await expect.poll(() => plexo.api.getThemeSource()).toBe(next)
+ await expect.poll(themeSource).toBe(next)
await plexo.relaunch()
- expect(await plexo.api.getThemeSource()).toBe(next)
+ expect(await themeSource()).toBe(next)
})
test('renaming a network survives a restart', async ({ plexo }) => {
@@ -139,14 +140,24 @@ test.describe('UI journeys @smoke', () => {
await expect(plexo.page.getByText(dirs.dest)).toBeVisible()
})
- test('a corrupt network-preferences.json does not break the network list', async ({
+ test('a corrupt app-settings.json does not break the app', async ({ plexo, dirs }) => {
+ await plexo.quit()
+ await writeFile(join(dirs.userData, 'app-settings.json'), '{"networkPreferences": {"a": [')
+ await plexo.launch()
+ await expect(plexo.page.getByRole('button', { name: 'Edit network' }).first()).toBeVisible()
+ })
+
+ test('names from the old network-preferences.json are moved into app-settings.json', async ({
plexo,
dirs
}) => {
await plexo.quit()
- await writeFile(join(dirs.userData, 'network-preferences.json'), '{"a": 42, "b": [')
+ const [id] = Object.keys(NETWORKS)
+ const legacyPath = join(dirs.userData, 'network-preferences.json')
+ await writeFile(legacyPath, JSON.stringify({ [id]: { customName: 'Office fibre' } }))
await plexo.launch()
- await expect(plexo.page.getByRole('button', { name: 'Edit network' }).first()).toBeVisible()
+ await expect(plexo.page.getByText('Office fibre')).toBeVisible()
+ await expect(access(legacyPath)).rejects.toThrow()
})
})
diff --git a/src/main/index.ts b/src/main/index.ts
index 8cfb172..20bb718 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -3,7 +3,7 @@ import { app, BrowserWindow, Menu, nativeTheme, shell } from 'electron'
import { join } from 'path'
import icon from '../../resources/icon-dark.png?asset'
import { registerIpcHandlers } from './ipc/handlers'
-import { loadThemeSource } from './settings'
+import { loadThemeSource, migrateLegacyNetworkPreferences } from './settings'
import { testKnobs } from './testKnobs'
import { IpcChannels } from '../shared/ipc-channels'
import type { DownloadManager } from './download/downloadManager'
@@ -97,6 +97,7 @@ app.whenReady().then(async () => {
// Applied before the window is created so the initial background/icon already match —
// the saved preference otherwise only takes effect on the next 'updated' event.
+ await migrateLegacyNetworkPreferences()
nativeTheme.themeSource = await loadThemeSource()
app.on('browser-window-created', (_, window) => {
diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.ts
index 54ddbe2..515e970 100644
--- a/src/main/ipc/handlers.ts
+++ b/src/main/ipc/handlers.ts
@@ -19,7 +19,6 @@ import { probeUrl } from '../download/probe'
import { deviceBindingSupported } from '../network/deviceBinding'
import { measureLatencies } from '../network/latency'
import { listActiveInterfaces } from '../network/interfaces'
-import { loadNetworkPreferences, saveNetworkPreference } from '../network/preferences'
import { loadSettings, saveSettings } from '../settings'
import { testKnobs } from '../testKnobs'
import { checkForUpdate, UPDATE_PAGE_URL } from '../updateCheck'
@@ -79,20 +78,18 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
const bindingSupport = deviceBindingSupported()
handle('deviceBindingSupported', async () => bindingSupport)
- 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'
- handle('getThemeSource', async () => currentThemeSource())
-
- handle('setThemeSource', async (_event, source) => {
- nativeTheme.themeSource = source
- await saveSettings({ themeSource: source })
- return currentThemeSource()
+ handle('updateSettings', async (_event, patch) => {
+ const saved = await saveSettings(patch)
+ // The one setting main also applies — sanitized first, so only 'light'/'dark' reach it.
+ if (patch?.themeSource !== undefined && saved.themeSource) {
+ nativeTheme.themeSource = saved.themeSource
+ }
})
// Answered via sendSync from the preload, which blocks the page until returnValue is set — so a
@@ -104,15 +101,12 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
isDev: is.dev
})
try {
- const [settings, networkPreferences] = await Promise.all([
- loadSettings(),
- loadNetworkPreferences()
- ])
+ const settings = await loadSettings()
const { destinationDir } = settings
// Capped: a folder on a dropped network share can take many seconds to answer, and launch
// waits on this reply — past the cap it's treated as gone and Downloads is used instead.
const destinationExists =
- typeof destinationDir === 'string' &&
+ destinationDir !== undefined &&
(await Promise.race([
stat(destinationDir).then(
(stats) => stats.isDirectory(),
@@ -123,7 +117,7 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
event.returnValue = {
...paths(),
themeSource: currentThemeSource(),
- networkPreferences,
+ networkPreferences: settings.networkPreferences ?? {},
streamsPerNetwork: settings.streamsPerNetwork,
destinationDir: destinationExists ? destinationDir : undefined
} satisfies InitialState
@@ -143,12 +137,6 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
}
})
- handle('setStreamsPerNetwork', async (_event, streamsPerNetwork) =>
- saveSettings({ streamsPerNetwork })
- )
-
- handle('setDestinationDir', async (_event, destinationDir) => saveSettings({ destinationDir }))
-
handle('openNetworkSettings', async () => {
await openNetworkSettings()
})
@@ -215,9 +203,5 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down
handle('checkForUpdate', async () => updateCheckPromise)
- handle('dismissUpdate', async (_event, version) => {
- await saveSettings({ dismissedUpdateVersion: version })
- })
-
return manager
}
diff --git a/src/main/network/preferences.ts b/src/main/network/preferences.ts
deleted file mode 100644
index 59eab67..0000000
--- a/src/main/network/preferences.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-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')
-}
-
-/** Trusts nothing past "this is valid JSON" — a hand-edited or partially-migrated file could have
- * any shape on disk. Keeps only string customName/colorId fields (what every reader downstream
- * assumes, e.g. NetworkEditPopover's `customName?.trim()`) and drops anything else, entry by
- * entry, rather than discarding the whole file over one bad entry. */
-function sanitizeNetworkPreferences(parsed: unknown): NetworkPreferences {
- if (typeof parsed !== 'object' || parsed === null) return {}
-
- const result: NetworkPreferences = {}
- for (const [id, value] of Object.entries(parsed as Record<string, unknown>)) {
- if (typeof value !== 'object' || value === null) continue
- const { customName, colorId } = value as Record<string, unknown>
- const preference: NetworkPreference = {}
- if (typeof customName === 'string') preference.customName = customName
- if (typeof colorId === 'string') preference.colorId = colorId
- if (preference.customName || preference.colorId) result[id] = preference
- }
- return result
-}
-
-export async function loadNetworkPreferences(): Promise<NetworkPreferences> {
- 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 function saveNetworkPreference(
- id: string,
- patch: NetworkPreference
-): Promise<NetworkPreferences> {
- return updateJson(preferencesPath(), (parsed) => {
- const current = sanitizeNetworkPreferences(parsed)
- const merged: NetworkPreference = { ...current[id], ...patch }
- const next: NetworkPreferences = { ...current }
-
- 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 114e7ec..8442fc1 100644
--- a/src/main/settings.ts
+++ b/src/main/settings.ts
@@ -1,37 +1,95 @@
-import { join } from 'node:path'
+import { rm } from 'node:fs/promises'
+import { isAbsolute, join } from 'node:path'
import { app, nativeTheme } from 'electron'
-import type { ThemeSource } from '../shared/types'
+import { PRESET_STREAMS } from '../shared/plan'
+import type {
+ AppSettings,
+ NetworkPreference,
+ NetworkPreferences,
+ ThemeSource
+} from '../shared/types'
import { readJson, updateJson } from './jsonFile'
function settingsPath(): string {
return join(app.getPath('userData'), 'app-settings.json')
}
-interface AppSettings {
- themeSource?: ThemeSource
- dismissedUpdateVersion?: string
- streamsPerNetwork?: number
- destinationDir?: string
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
}
-function asSettings(parsed: unknown): AppSettings {
- return typeof parsed === 'object' && parsed !== null ? (parsed as AppSettings) : {}
+/** Keeps only string customName/colorId fields (what every reader downstream assumes, e.g.
+ * NetworkEditPopover's `customName?.trim()`), entry by entry, rather than discarding every
+ * network over one bad entry. An entry left with neither field is dropped, so resetting a
+ * network removes it from the file. */
+function sanitizeNetworkPreferences(parsed: unknown): NetworkPreferences {
+ if (!isRecord(parsed)) return {}
+
+ const result: NetworkPreferences = {}
+ for (const [id, value] of Object.entries(parsed)) {
+ if (!isRecord(value)) continue
+ const preference: NetworkPreference = {}
+ if (typeof value.customName === 'string') preference.customName = value.customName
+ if (typeof value.colorId === 'string') preference.colorId = value.colorId
+ if (preference.customName || preference.colorId) result[id] = preference
+ }
+ return result
+}
+
+/** Trusts nothing past "this is valid JSON" — the file may be hand-edited or from an older
+ * version, and a patch comes from the renderer. Every field is checked on its own, so one bad
+ * value only loses that value. An `undefined` field in a patch clears it. */
+function sanitizeSettings(parsed: unknown): AppSettings {
+ if (!isRecord(parsed)) return {}
+
+ const { themeSource, dismissedUpdateVersion, streamsPerNetwork, destinationDir } = parsed
+ const settings: AppSettings = {}
+ // 'system' was once an option — dropping it falls back to the OS appearance (loadThemeSource).
+ if (themeSource === 'light' || themeSource === 'dark') settings.themeSource = themeSource
+ if (typeof dismissedUpdateVersion === 'string') {
+ settings.dismissedUpdateVersion = dismissedUpdateVersion
+ }
+ if ((PRESET_STREAMS as readonly unknown[]).includes(streamsPerNetwork)) {
+ settings.streamsPerNetwork = streamsPerNetwork as number
+ }
+ if (typeof destinationDir === 'string' && isAbsolute(destinationDir)) {
+ settings.destinationDir = destinationDir
+ }
+ if (parsed.networkPreferences !== undefined) {
+ settings.networkPreferences = sanitizeNetworkPreferences(parsed.networkPreferences)
+ }
+ return settings
}
export async function loadSettings(): Promise<AppSettings> {
- return asSettings(await readJson(settingsPath()))
+ return sanitizeSettings(await readJson(settingsPath()))
}
-export async function saveSettings(patch: AppSettings): Promise<void> {
- await updateJson(settingsPath(), (current) => ({ ...asSettings(current), ...patch }))
+/** Merges `patch` over what's saved and returns the result as written. */
+export function saveSettings(patch: unknown): Promise<AppSettings> {
+ return updateJson(settingsPath(), (current) =>
+ sanitizeSettings({ ...sanitizeSettings(current), ...(isRecord(patch) ? patch : {}) })
+ )
}
export async function loadThemeSource(): Promise<ThemeSource> {
- const settings = await loadSettings()
- if (settings.themeSource === 'light' || settings.themeSource === 'dark') {
- return settings.themeSource
+ const { themeSource } = await loadSettings()
+ // First run — follow whatever the OS appearance is right now rather than a fixed theme.
+ return themeSource ?? (nativeTheme.shouldUseDarkColors ? 'dark' : 'light')
+}
+
+/** Network names/colors lived in their own network-preferences.json up to 1.0.0-rc.8. Folds
+ * that file into app-settings.json once, then deletes it (a corrupt one is just deleted). */
+export async function migrateLegacyNetworkPreferences(): Promise<void> {
+ const legacyPath = join(app.getPath('userData'), 'network-preferences.json')
+ const legacy = await readJson(legacyPath)
+ if (legacy !== undefined) {
+ await updateJson(settingsPath(), (current) => {
+ const settings = sanitizeSettings(current)
+ return settings.networkPreferences
+ ? settings
+ : { ...settings, networkPreferences: sanitizeNetworkPreferences(legacy) }
+ })
}
- // First run, or a pre-existing settings file from when 'system' was an option — fall back to
- // whatever the OS appearance is right now rather than defaulting to a fixed theme.
- return nativeTheme.shouldUseDarkColors ? 'dark' : 'light'
+ await rm(legacyPath, { force: true })
}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 2d65dbb..1b95972 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, InitialState, NetworkPreference, ThemeSource } from '../shared/types'
+import type { AppSettings, DownloadState, InitialState } 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
@@ -22,14 +22,8 @@ const plexoApi = {
pingInterfaces: () => invoke('pingInterfaces'),
deviceBindingSupported: () => invoke('deviceBindingSupported'),
openNetworkSettings: () => invoke('openNetworkSettings'),
- setNetworkPreference: (id: string, patch: NetworkPreference) =>
- invoke('setNetworkPreference', id, patch),
- getThemeSource: () => invoke('getThemeSource'),
- setThemeSource: (source: ThemeSource) => invoke('setThemeSource', source),
- setStreamsPerNetwork: (streamsPerNetwork: number) =>
- invoke('setStreamsPerNetwork', streamsPerNetwork),
+ updateSettings: (patch: AppSettings) => invoke('updateSettings', patch),
probeUrl: (url: string) => invoke('probeUrl', url),
- setDestinationDir: (dir: string) => invoke('setDestinationDir', dir),
chooseDestinationFolder: (defaultPath: string) => invoke('chooseDestinationFolder', defaultPath),
chooseSourceFile: () => invoke('chooseSourceFile'),
readClipboardText: () => invoke('readClipboardText'),
@@ -44,7 +38,6 @@ const plexoApi = {
cancelDownload: (downloadId: string) => invoke('cancelDownload', downloadId),
removeDownload: (downloadId: string) => invoke('removeDownload', downloadId),
checkForUpdate: () => invoke('checkForUpdate'),
- dismissUpdate: (version: string) => invoke('dismissUpdate', version),
onDownloadUpdated: (callback: (state: DownloadState) => void): (() => void) => {
const listener = (_event: IpcRendererEvent, state: DownloadState): void => callback(state)
diff --git a/src/renderer/src/components/NetworkEditPopover.tsx b/src/renderer/src/components/NetworkEditPopover.tsx
index 56402dc..1752a74 100644
--- a/src/renderer/src/components/NetworkEditPopover.tsx
+++ b/src/renderer/src/components/NetworkEditPopover.tsx
@@ -40,7 +40,7 @@ export function NetworkEditPopover({
// Re-picking the color it already had keeps it automatic instead of pinning it.
const colorId = draftColorId === visual.colorId ? preference?.colorId : draftColorId
if (customName !== preference?.customName || colorId !== preference?.colorId) {
- void setNetworkPreference(interfaceId, { customName, colorId })
+ setNetworkPreference(interfaceId, { customName, colorId })
}
}
diff --git a/src/renderer/src/components/ThemeToggle.tsx b/src/renderer/src/components/ThemeToggle.tsx
index 68a2a17..e05c036 100644
--- a/src/renderer/src/components/ThemeToggle.tsx
+++ b/src/renderer/src/components/ThemeToggle.tsx
@@ -41,7 +41,7 @@ export function ThemeToggle(): React.JSX.Element {
const current = OPTIONS.find((option) => option.id === themeSource) ?? OPTIONS[0]
const toggle = (): void => {
- void setThemeSource(current.id === 'light' ? 'dark' : 'light')
+ setThemeSource(current.id === 'light' ? 'dark' : 'light')
}
return (
diff --git a/src/renderer/src/screens/IdleScreen.tsx b/src/renderer/src/screens/IdleScreen.tsx
index 2170b81..a6d4628 100644
--- a/src/renderer/src/screens/IdleScreen.tsx
+++ b/src/renderer/src/screens/IdleScreen.tsx
@@ -37,7 +37,6 @@ export function IdleScreen(): React.JSX.Element {
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 url = useAppStore((store) => store.draftUrl)
const setUrl = useAppStore((store) => store.setDraftUrl)
@@ -108,7 +107,6 @@ export function IdleScreen(): React.JSX.Element {
selectedInterfaceIds.length > 0 &&
Boolean(destinationDir) &&
!starting
- const effectiveDestinationDir = destinationDir || downloadsDir
const footerParts = [
`${selectedInterfaceIds.length} ${selectedInterfaceIds.length === 1 ? 'network' : 'networks'} selected`
]
@@ -140,7 +138,7 @@ export function IdleScreen(): React.JSX.Element {
}
const handleBrowse = async (): Promise<void> => {
- const chosen = await window.plexo.chooseDestinationFolder(effectiveDestinationDir)
+ const chosen = await window.plexo.chooseDestinationFolder(destinationDir)
if (chosen) setDestinationDir(chosen)
}
@@ -246,7 +244,7 @@ export function IdleScreen(): React.JSX.Element {
<div className="flex h-9 items-center gap-[9px] rounded-[9px] border border-border px-3">
<div className={fieldLabelClass}>TO</div>
<div className="min-w-0 flex-1 truncate font-mono text-[12.5px] text-[var(--text-secondary)]">
- {toDisplayPath(effectiveDestinationDir, homeDir)}
+ {toDisplayPath(destinationDir, homeDir)}
</div>
<Button
type="button"
@@ -273,7 +271,7 @@ export function IdleScreen(): React.JSX.Element {
value={[String(chunksPerNetwork)]}
onValueChange={(values) => {
if (values.length === 0) return
- void setChunksPerNetwork(Number(values[0]))
+ 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 321ab1f..1fe00ba 100644
--- a/src/renderer/src/store/useAppStore.ts
+++ b/src/renderer/src/store/useAppStore.ts
@@ -1,4 +1,5 @@
import type {
+ AppSettings,
DownloadState,
NetworkInterfaceInfo,
NetworkPreference,
@@ -6,7 +7,6 @@ import type {
ThemeSource,
UpdateInfo
} from '@shared/types'
-import { PRESET_STREAMS } from '@shared/plan'
import { create } from 'zustand'
import { groupChunksByInterface } from '../utils/format'
@@ -57,9 +57,9 @@ interface AppStore {
loadInterfaces: () => Promise<void>
refreshLatencies: () => Promise<void>
- setNetworkPreference: (id: string, patch: NetworkPreference) => Promise<void>
- setThemeSource: (source: ThemeSource) => Promise<void>
- setStreamsPerNetwork: (streamsPerNetwork: number) => Promise<void>
+ setNetworkPreference: (id: string, patch: NetworkPreference) => void
+ setThemeSource: (source: ThemeSource) => void
+ setStreamsPerNetwork: (streamsPerNetwork: number) => void
checkForUpdate: () => Promise<void>
dismissUpdate: () => void
setCurrentDownload: (state: DownloadState) => void
@@ -70,9 +70,13 @@ interface AppStore {
// 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
-)
+
+/** Every setting changes optimistically: the store is updated first so the UI feels instant,
+ * then this saves it. The store stays the source of truth either way — a failed save just means
+ * the change isn't remembered next launch. */
+function persist(patch: AppSettings): void {
+ window.plexo.updateSettings(patch).catch(() => {})
+}
export const useAppStore = create<AppStore>((set, get) => ({
interfaces: [],
@@ -81,7 +85,7 @@ export const useAppStore = create<AppStore>((set, get) => ({
latencies: {},
networkPreferences: initial.networkPreferences,
themeSource: initial.themeSource,
- streamsPerNetwork: savedStreamsPerNetwork ?? 2,
+ streamsPerNetwork: initial.streamsPerNetwork ?? 2,
availableUpdate: null,
homeDir: initial.homeDir,
@@ -122,40 +126,24 @@ export const useAppStore = create<AppStore>((set, get) => ({
}
},
- 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).
- set((state) => ({
- networkPreferences: {
- ...state.networkPreferences,
- [id]: { ...state.networkPreferences[id], ...patch }
- }
- }))
- try {
- const networkPreferences = await window.plexo.setNetworkPreference(id, patch)
- set({ networkPreferences })
- } catch {
- // Leave the optimistic value in place — not persisted to disk, but still usable this session.
+ // An explicit `undefined` in `patch` clears that field; main drops an entry left with neither.
+ setNetworkPreference: (id, patch) => {
+ const networkPreferences = {
+ ...get().networkPreferences,
+ [id]: { ...get().networkPreferences[id], ...patch }
}
+ set({ networkPreferences })
+ persist({ networkPreferences })
},
- setThemeSource: async (themeSource) => {
- // Optimistic update, same as setNetworkPreference — the toggle should feel instant.
+ setThemeSource: (themeSource) => {
set({ themeSource })
- try {
- await window.plexo.setThemeSource(themeSource)
- } catch {
- // Leave the optimistic value in place — not persisted to disk, but still usable this session.
- }
+ persist({ themeSource })
},
- setStreamsPerNetwork: async (streamsPerNetwork) => {
+ setStreamsPerNetwork: (streamsPerNetwork) => {
set({ streamsPerNetwork })
- try {
- await window.plexo.setStreamsPerNetwork(streamsPerNetwork)
- } catch {
- // Leave the optimistic value in place — not persisted to disk, but still usable this session.
- }
+ persist({ streamsPerNetwork })
},
checkForUpdate: async () => {
@@ -172,7 +160,7 @@ export const useAppStore = create<AppStore>((set, get) => ({
if (!update) return
// Keeps the update visible as a quiet titlebar icon rather than clearing it outright.
set({ availableUpdate: { ...update, dismissed: true } })
- void window.plexo.dismissUpdate(update.version)
+ persist({ dismissedUpdateVersion: update.version })
},
setCurrentDownload: (download) => {
@@ -217,7 +205,6 @@ export const useAppStore = create<AppStore>((set, get) => ({
setDraftUrl: (draftUrl) => set({ draftUrl }),
setDestinationDir: (destinationDir) => {
set({ destinationDir })
- // Best-effort — a failed save just means the pick isn't remembered next launch.
- window.plexo.setDestinationDir(destinationDir).catch(() => {})
+ persist({ destinationDir })
}
}))
diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.ts
index 1cc8fe0..94ec2db 100644
--- a/src/shared/ipc-channels.ts
+++ b/src/shared/ipc-channels.ts
@@ -3,13 +3,9 @@ export const IpcChannels = {
pingInterfaces: 'network:ping-interfaces',
deviceBindingSupported: 'network:device-binding-supported',
openNetworkSettings: 'network:open-settings',
- setNetworkPreference: 'network:set-preference',
- getThemeSource: 'theme:get-source',
- setThemeSource: 'theme:set-source',
- setStreamsPerNetwork: 'streams:set-per-network',
probeUrl: 'download:probe',
getInitialState: 'app:get-initial-state',
- setDestinationDir: 'destination:set-dir',
+ updateSettings: 'app:update-settings',
chooseDestinationFolder: 'dialog:choose-destination-folder',
chooseSourceFile: 'dialog:choose-source-file',
readClipboardText: 'clipboard:read-text',
@@ -23,6 +19,5 @@ export const IpcChannels = {
removeDownload: 'download:remove',
downloadUpdated: 'download:updated',
toggleDevToolsPanel: 'dev:toggle-panel',
- checkForUpdate: 'update:check',
- dismissUpdate: 'update:dismiss'
+ checkForUpdate: 'update:check'
} as const
diff --git a/src/shared/ipc-contract.ts b/src/shared/ipc-contract.ts
index bae3bf3..2041e51 100644
--- a/src/shared/ipc-contract.ts
+++ b/src/shared/ipc-contract.ts
@@ -1,12 +1,10 @@
import type {
+ AppSettings,
DownloadState,
NetworkInterfaceInfo,
- NetworkPreference,
- NetworkPreferences,
ProbeResult,
StartDownloadRequest,
StartSimulatedDownloadRequest,
- ThemeSource,
UpdateInfo
} from './types'
@@ -19,15 +17,8 @@ export interface IpcContract {
pingInterfaces: { args: []; result: Record<string, number | null> }
deviceBindingSupported: { args: []; result: boolean }
openNetworkSettings: { args: []; result: void }
- setNetworkPreference: {
- args: [id: string, patch: NetworkPreference]
- result: NetworkPreferences
- }
- getThemeSource: { args: []; result: ThemeSource }
- setThemeSource: { args: [source: ThemeSource]; result: ThemeSource }
- setStreamsPerNetwork: { args: [streamsPerNetwork: number]; result: void }
+ updateSettings: { args: [patch: AppSettings]; result: void }
probeUrl: { args: [url: string]; result: ProbeResult }
- setDestinationDir: { args: [dir: string]; result: void }
chooseDestinationFolder: { args: [defaultPath: string]; result: string | null }
chooseSourceFile: { args: []; result: string | null }
readClipboardText: { args: []; result: string }
@@ -40,5 +31,4 @@ export interface IpcContract {
cancelDownload: { args: [id: string]; result: void }
removeDownload: { args: [id: string]; result: void }
checkForUpdate: { args: []; result: UpdateInfo | null }
- dismissUpdate: { args: [version: string]; result: void }
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 7e07625..08a7163 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -149,16 +149,25 @@ export interface UpdateInfo {
dismissed: boolean
}
-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
+/** What app-settings.json holds, and what the renderer sends to change it (merged over the saved
+ * values, `undefined` clearing one). A missing field was never set. */
+export interface AppSettings {
+ themeSource?: ThemeSource
+ dismissedUpdateVersion?: string
+ streamsPerNetwork?: number
+ /** The last destination folder picked. */
+ destinationDir?: string
+ /** User customizations (name/color) per network interface id. */
+ networkPreferences?: NetworkPreferences
}
/** 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 {
+export interface InitialState {
+ homeDir: string
+ downloadsDir: string
+ /** True in electron-vite's dev server, false in a packaged build — gates the dev tools panel. */
+ isDev: boolean
themeSource: ThemeSource
networkPreferences: NetworkPreferences
streamsPerNetwork?: number