Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

tech+design: react-hooks auf 0, und 22 stumme catch-Bloecke eingeordnet

David9a52f7124d6c
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index 6e771f38..045059f3 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -30,6 +30,7 @@ import { idbStorage } from '../../lib/idbStorage'
import { STORE_KEYS, IDB_STORE_KEYS, backupStoresIfChanged, flushSyncStoreBackup } from '../../lib/store-backup'
import { idbKeysToRestore, mayReloadForIdbRestore } from '../../lib/idb-restore'
import { log } from '../../lib/logger'
+import { withDetail } from '../../lib/error-text'
import { pickForMode } from '../../lib/active-model-mode'
import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts'
import { useCloudAuth } from '../../hooks/useCloudAuth'
@@ -93,6 +94,10 @@ export function AppShell() {
const isComparing = useCompareStore((s) => s.isComparing)
const onboardingDone = useSettingsStore((s) => s.settings.onboardingDone)
const [restoring, setRestoring] = useState(false)
+ // The one failure in this file the user has to be told about: a post-update
+ // store restore that threw. Shown as a dismissible line in the shell, next
+ // to the other shell-level notices.
+ const [restoreError, setRestoreError] = useState<string | null>(null)
const [detectedBackends, setDetectedBackends] = useState<DetectedBackend[]>([])
const [showSelector, setShowSelector] = useState(false)
@@ -193,6 +198,15 @@ export function AppShell() {
// (switch OR launch-in-cloud); local mode is a no-op.
useEffect(() => {
if (!isTauri() || appMode !== 'cloud') return
+ // Level (a): silent on purpose, both of them. These free memory the user
+ // is no longer using; they are not the switch itself, which has already
+ // happened by the time they run. The LM Studio one in particular REJECTS
+ // by design on every machine without LM Studio installed
+ // ("lms CLI not found", install.rs:3511) — reporting that would put an
+ // error in front of the majority of users every time they go to Cloud,
+ // about a program they never installed. If a model really does stay
+ // resident, it shows up where the user can act on it: the backend panel
+ // in Settings.
backendCall('offload_local_models').catch(() => {})
backendCall('lmstudio_unload_model', { model: '--all' }).catch(() => {})
}, [appMode])
@@ -203,6 +217,11 @@ export function AppShell() {
// re-opened Settings. Desktop-only — the web build has no local ComfyUI.
useEffect(() => {
if (!isTauri()) return
+ // Level (a): silent on purpose. This mirrors a stored preference into the
+ // backend on every boot, with no user standing in front of it — and it
+ // runs on machines that have no ComfyUI at all. The setting itself is
+ // safe either way: it is persisted, this effect re-fires on the next
+ // launch, and Settings → ComfyUI shows the mode actually in force.
backendCall('set_comfy_gpu_mode', { mode: settings.comfyGpuMode || 'auto' }).catch(() => {})
}, [settings.comfyGpuMode])
@@ -369,7 +388,24 @@ export function AppShell() {
}
}
}
- } catch {}
+ } catch (e) {
+ // Level (b): the user finds out, the app carries on. This is the
+ // post-update restore. Reaching here means the backup could not be
+ // read or was not valid JSON — NOT "there is no backup", which
+ // returns null and lands in step 3 below without throwing. So the
+ // app is about to come up looking empty after an update, and
+ // without this line that reads as "the update ate my chats".
+ //
+ // Not blocking: there is nothing to block. The restore is over, and
+ // holding the app hostage behind a dialog would only add a wall in
+ // front of the chats that DID survive.
+ setRestoreError(
+ withDetail(
+ 'Your chats and settings could not be restored after the update. Nothing was deleted — the backup is still in the app data folder. Close LU and reopen it to try again; if it stays empty, keep that folder before reinstalling.',
+ e,
+ ),
+ )
+ }
// 3. No backup available — at least recover onboarding from marker file
if (markerExists) {
@@ -467,6 +503,11 @@ export function AppShell() {
if (Object.keys(memVectors).length > 0) {
;(snapshot as Record<string, unknown>)[MEMORY_VECTORS_BACKUP_KEY] = memVectors
}
+ // Level (a): silent on purpose. This is the 30 s background backup
+ // loop; a missed write is retried on the next tick and nothing the
+ // user did just failed. Swallowed HERE rather than in the outer
+ // catch so a failed write still stamps ragLastRun and keeps the
+ // 30 s spacing instead of hot-retrying.
await backendCall('backup_rag_chunks', { data: JSON.stringify(snapshot) }).catch(() => {})
ragLastRun = Date.now()
} catch { /* best-effort */ }
@@ -479,6 +520,11 @@ export function AppShell() {
// them onboardingDone is false, and the missing marker is intentional.
backendCall<boolean>('is_onboarding_done').catch(() => false).then((markerExists) => {
if (!markerExists && useSettingsStore.getState().settings.onboardingDone) {
+ // Level (a): silent on purpose. Nobody asked for this — it is a
+ // one-time migration that writes a recovery marker. It re-runs on
+ // every launch until it succeeds, and the thing it protects (not
+ // re-running onboarding after an NSIS update) is already covered by
+ // the persisted store on this machine.
backendCall('set_onboarding_done').catch(() => {})
}
})
@@ -580,6 +626,13 @@ export function AppShell() {
const { setOllamaBase } = await import('../../api/backend')
setOllamaBase(next)
if (isTauri()) {
+ // Level (a): silent on purpose. setOllamaBase() on the line above has
+ // already applied the new host to everything the user can see; this
+ // only mirrors it into Rust's config.json. The providerStore is
+ // persisted and wins on the next boot anyway (see the comment on the
+ // hydration path below), and this subscription re-fires on the next
+ // edit. Reporting from inside a store subscription would also mean
+ // an error with no control anywhere near it.
backendCall('set_ollama_host', { host: next }).catch(() => {})
}
})
@@ -845,6 +898,19 @@ export function AppShell() {
<Titlebar />
<Header />
<StaleModelsBanner />
+ {restoreError && (
+ <div className="mx-2 mt-2 flex items-start gap-2 rounded-lg border border-red-500/20 bg-red-500/[0.06] px-3 py-2">
+ <p role="alert" className="flex-1 text-[0.65rem] leading-snug text-red-500 dark:text-red-400 whitespace-pre-line">
+ {restoreError}
+ </p>
+ <button
+ onClick={() => setRestoreError(null)}
+ className="shrink-0 text-[0.6rem] text-red-500/70 hover:text-red-400 transition-colors"
+ >
+ Dismiss
+ </button>
+ </div>
+ )}
<StorageQuotaToast />
<div className="flex-1 flex overflow-hidden gap-2 p-2">
{!isComparing && <Sidebar />}
diff --git a/src/components/onboarding/Onboarding.tsx b/src/components/onboarding/Onboarding.tsx
index 53295cee..22685025 100644
--- a/src/components/onboarding/Onboarding.tsx
+++ b/src/components/onboarding/Onboarding.tsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef } from 'react'
-import { withInstallerOutput } from '../../lib/error-text'
+import { withInstallerOutput, withDetail } from '../../lib/error-text'
import { motion, AnimatePresence } from 'framer-motion'
import { Minus, Square, X as XIcon, ArrowRight, Download, Check, ChevronRight, Loader2, RefreshCw, ExternalLink, FolderOpen, Cpu } from 'lucide-react'
import { useSettingsStore } from '../../stores/settingsStore'
@@ -349,7 +349,14 @@ export function Onboarding() {
// an upgrade never runs this wizard, so its flag stays null and it gets the
// notes. This is the ONLY place that stamps without showing anything.
useReleaseNotesStore.getState().markNotesSeen(currentVersion)
- // Persist to filesystem so NSIS updates don't reset onboarding
+ // Persist to filesystem so NSIS updates don't reset onboarding.
+ //
+ // Level (a): silent on purpose. updateSettings() above is what actually
+ // ends the wizard, and it is persisted. This only writes the recovery
+ // marker, which AppShell re-writes on any later boot where it is missing
+ // (the migration next to `is_onboarding_done`). So a failure here heals
+ // itself, and reporting it would put an error on the last screen of a
+ // setup that succeeded.
if (isTauri) backendCall('set_onboarding_done').catch(() => {})
}
@@ -425,7 +432,13 @@ export function Onboarding() {
setDetecting(false)
}
- // Detect system VRAM for model filtering
+ // Detect system VRAM for model filtering.
+ //
+ // Level (a): silent on purpose. systemVRAM is only ever read as
+ // `if (systemVRAM && m.vramGB > systemVRAM) return false`, so a failed
+ // probe means the recommendation list is not narrowed — the user sees MORE
+ // models, not fewer, and every card still states its own VRAM need. There
+ // is no action to offer, and nothing was lost.
useEffect(() => { getSystemVRAM().then(v => setSystemVRAM(v)).catch(() => {}) }, [])
// Count CHAT-CAPABLE models the user already has installed. Used to skip
@@ -655,7 +668,20 @@ export function Onboarding() {
setComfyFound({ found: true, path: only.path, complete: only.complete })
if (only.complete) setComfyReady(true)
// Persist the auto-pick so process.rs uses it on start_comfyui.
- try { await backendCall('set_comfyui_path', { path: only.path }) } catch {}
+ //
+ // Level (b): the user finds out, the wizard carries on. Nobody
+ // clicked anything here — the single install was auto-picked — but
+ // if the path does not stick, the panel above says "found" while
+ // start_comfyui will look somewhere else entirely, and the failure
+ // then surfaces minutes later with no visible cause.
+ try {
+ await backendCall('set_comfyui_path', { path: only.path })
+ } catch (e) {
+ setComfyInstallError(withDetail(
+ `LU found ComfyUI at ${only.path} but could not save that location. Starting it may not work; set the path by hand below.`,
+ e,
+ ))
+ }
return
}
// Zero matches — fall back to legacy find_comfyui (env var, config
@@ -683,7 +709,21 @@ export function Onboarding() {
// chosen path is persisted via set_comfyui_path so start_comfyui hits it
// without further user intervention.
const pickComfyInstall = async (choice: ComfyInstallChoice) => {
- try { await backendCall('set_comfyui_path', { path: choice.path }) } catch {}
+ // Level (c): the user picked one of several installs and this call is the
+ // whole point of that click — without it the pick is not recorded anywhere
+ // and start_comfyui keeps using the old one. The lines below close the
+ // dialog and report "found", so a swallowed failure here leaves the wizard
+ // confidently showing a choice that was never made.
+ setComfyInstallError('')
+ try {
+ await backendCall('set_comfyui_path', { path: choice.path })
+ } catch (e) {
+ setComfyInstallError(withDetail(
+ `Could not switch ComfyUI to ${choice.path}. LU will keep using the location it had — try the pick again, or enter the path by hand below.`,
+ e,
+ ))
+ return
+ }
setComfyFound({ found: true, path: choice.path, complete: choice.complete })
if (choice.complete) setComfyReady(true)
setComfyChoices([])
@@ -1160,11 +1200,25 @@ export function Onboarding() {
)}
{lmstudioError && (
- <p className="text-[0.65rem] text-red-400 whitespace-pre-line">
+ <p role="alert" className="text-[0.65rem] text-red-400 whitespace-pre-line">
{lmstudioError}
{lmstudioError.toLowerCase().includes('didn\'t come up') && (
<button
- onClick={() => { backendCall('start_lmstudio_server').catch(() => {}); setLmstudioError('') }}
+ // Level (c): this button lives INSIDE the error it is
+ // meant to clear, and the click wipes that error on the
+ // spot. Swallowing the failure meant the message
+ // vanished and nothing replaced it — the one shape of
+ // dud this file can produce. Put the outcome back into
+ // the same line the button came from.
+ onClick={() => {
+ setLmstudioError('')
+ backendCall('start_lmstudio_server').catch((e) => {
+ setLmstudioError(withDetail(
+ 'The LM Studio server did not start. Open LM Studio and start its local server from the Developer tab, then continue here.',
+ e,
+ ))
+ })
+ }}
className={`block mt-1 ${secondaryBtn}`}
>
Start LM Studio server
@@ -1357,8 +1411,20 @@ export function Onboarding() {
setComfyInstalling(false)
setComfyReady(true)
setInstallStartTime(null)
- // Auto-start ComfyUI
- try { await backendCall('start_comfyui') } catch {}
+ // Auto-start ComfyUI.
+ //
+ // Level (b): the install DID finish, which is what
+ // this step was for, so the wizard moves on to its
+ // ready state either way. But "ready" would then be
+ // claiming something that is not running, so say so.
+ try {
+ await backendCall('start_comfyui')
+ } catch (e) {
+ setComfyInstallError(withDetail(
+ 'ComfyUI is installed but did not start. You can start it from Settings → ComfyUI later; the rest of the setup is unaffected.',
+ e,
+ ))
+ }
} else if (status.status === 'cancelled') {
// Bug #1: install cancelled by user, close the
// progress card and surface the install options
@@ -1419,7 +1485,19 @@ export function Onboarding() {
try {
await backendCall('set_comfyui_path', { path: comfyPathInput.trim() })
setComfyReady(true)
- try { await backendCall('start_comfyui') } catch {}
+ // Level (b): the path — the thing the user typed —
+ // was saved, so this stays out of the outer catch and
+ // `ready` stands. Only the convenience auto-start
+ // failed, and that is worth one line rather than
+ // undoing a save that worked.
+ try {
+ await backendCall('start_comfyui')
+ } catch (e) {
+ setComfyInstallError(withDetail(
+ 'The path was saved, but ComfyUI did not start from it. Check that the folder holds a complete ComfyUI install, then start it from Settings → ComfyUI.',
+ e,
+ ))
+ }
} catch (err) {
setComfyInstallError(err instanceof Error ? err.message : 'Invalid path')
}
@@ -1488,7 +1566,19 @@ export function Onboarding() {
{/* Cancel button (Bug #1 — techx69) */}
<button
onClick={async () => {
- try { await backendCall('cancel_comfyui_install') } catch {}
+ // Level (c): Cancel is the only way out of a multi-GB
+ // download. If the call fails the progress bar keeps
+ // filling and the button looks broken — and the user is
+ // still paying for the bandwidth.
+ setComfyInstallError('')
+ try {
+ await backendCall('cancel_comfyui_install')
+ } catch (e) {
+ setComfyInstallError(withDetail(
+ 'The install could not be cancelled and is still running. Try Cancel once more; if it keeps going, closing LU stops the download.',
+ e,
+ ))
+ }
}}
className={`text-[0.55rem] px-1.5 py-[1px] rounded border transition-colors ${
isDark
@@ -1531,7 +1621,7 @@ export function Onboarding() {
{/* Error */}
{comfyInstallError && (
- <p className="text-[0.65rem] text-red-400 whitespace-pre-line">{comfyInstallError}</p>
+ <p role="alert" className="text-[0.65rem] text-red-400 whitespace-pre-line">{comfyInstallError}</p>
)}
{/* Ready state */}
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 45b54381..22309bd3 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -1,8 +1,9 @@
-import { useState, useEffect, useRef, type ReactNode, type ChangeEvent } from 'react'
-import { withInstallerOutput } from '../../lib/error-text'
+import { useState, useEffect, useCallback, useRef, type ReactNode, type ChangeEvent } from 'react'
+import { withInstallerOutput, withDetail } from '../../lib/error-text'
import { ArrowLeft, RotateCcw, Sun, Moon, Volume2, Check, X, Loader2, Shield, ChevronRight, GraduationCap, Lock, Sliders, Plug, Bot, Phone, User, Download, Mic } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import { SETTINGS_TAB_RESET_KEYS, type SettingsTab } from '../../lib/settings-reset'
+import { armedScopeFor, type ResetArm, type ResetArmScope } from '../../lib/reset-arming'
import { useSettingsStore } from '../../stores/settingsStore'
import { usePermissionStore } from '../../stores/permissionStore'
import { useUIStore } from '../../stores/uiStore'
@@ -259,13 +260,20 @@ function HfDownloadPathSetting() {
const override = useSettingsStore(s => s.settings.hfDownloadPathOverride)
const updateSettings = useSettingsStore(s => s.updateSettings)
const [draft, setDraft] = useState(override)
+ const [pickError, setPickError] = useState<string | null>(null)
useEffect(() => { setDraft(override) }, [override])
async function pickFolder() {
+ setPickError(null)
try {
const chosen = await backendCall<string | null>('pick_folder')
if (chosen) { setDraft(chosen); updateSettings({ hfDownloadPathOverride: chosen }) }
- } catch {}
+ } catch (e) {
+ // Level (c): the click was meant to CHANGE the download path and did
+ // not. Cancelling the dialog returns null and is not an error, so
+ // anything landing here really failed to open the picker.
+ setPickError(withDetail('The folder picker did not open. Type or paste the path into the field instead.', e))
+ }
}
return (
@@ -297,6 +305,11 @@ function HfDownloadPathSetting() {
</button>
)}
</div>
+ {pickError && (
+ <p role="alert" className="text-[0.55rem] text-red-500 dark:text-red-400 leading-snug whitespace-pre-line">
+ {pickError}
+ </p>
+ )}
</div>
)
}
@@ -403,6 +416,7 @@ function ComfyUISettings() {
const [pathSuccess, setPathSuccess] = useState(false)
const [customPort, setCustomPort] = useState('')
const [portSuccess, setPortSuccess] = useState(false)
+ const [portError, setPortError] = useState('')
const [customHost, setCustomHost] = useState('')
const [hostError, setHostError] = useState('')
const [hostSuccess, setHostSuccess] = useState(false)
@@ -426,7 +440,13 @@ function ComfyUISettings() {
if (typeof s?.port === 'number' && s.port > 0) setComfyPort(s.port)
if (typeof s?.host === 'string' && s.host.trim()) setComfyHost(s.host)
}
- } catch {}
+ } catch {
+ // Level (a): silent on purpose. This is the 5 s status poll below, and
+ // a failed probe simply means the panel keeps showing the last known
+ // state until the next tick. Every USER action in this panel (start,
+ // stop, install, set port) reports its own failure; a poll that missed
+ // one beat is not something to interrupt anyone about.
+ }
if (!cancelled) setLoading(false)
}
check()
@@ -493,11 +513,17 @@ function ComfyUISettings() {
}
const handleStop = async () => {
+ setStartError('')
try {
const { backendCall } = await import('../../api/backend')
await backendCall('stop_comfyui')
setStatus(prev => prev ? { ...prev, running: false } : null)
- } catch {}
+ } catch (e) {
+ // Level (c): a stop that failed leaves the panel showing "running", which
+ // is the truth — but without this line the button reads as a dud. Same
+ // channel as the start failure, right under the same pair of buttons.
+ setStartError(withDetail('ComfyUI did not stop. It may still be running — try again, or close it in its own window.', e))
+ }
}
const handleSetPath = async () => {
@@ -536,7 +562,7 @@ function ComfyUISettings() {
</div>
{startError && (
- <pre className="whitespace-pre-wrap break-words text-[0.55rem] leading-relaxed text-red-400 bg-red-500/[0.06] border border-red-500/20 rounded p-2 max-h-40 overflow-y-auto">
+ <pre role="alert" className="whitespace-pre-wrap break-words text-[0.55rem] leading-relaxed text-red-400 bg-red-500/[0.06] border border-red-500/20 rounded p-2 max-h-40 overflow-y-auto">
{startError}
</pre>
)}
@@ -627,13 +653,19 @@ function ComfyUISettings() {
onClick={async () => {
const port = parseInt(customPort)
if (!port || port < 1 || port > 65535) return
+ setPortError('')
try {
const { backendCall, setComfyPort } = await import('../../api/backend')
await backendCall('set_comfyui_port', { port })
setComfyPort(port)
setPortSuccess(true)
setTimeout(() => setPortSuccess(false), 3000)
- } catch {}
+ } catch (e) {
+ // Level (c): the port was NOT saved. Without this the button
+ // just fails to produce the green "Port saved" line, which is
+ // indistinguishable from a slow save.
+ setPortError(withDetail('The port was not saved. Pick a free port and try again.', e))
+ }
}}
disabled={!customPort || parseInt(customPort) === (status?.port || 8188)}
className="px-2 py-1 rounded text-[0.6rem] bg-purple-500/10 text-purple-400 hover:bg-purple-500/20 transition-colors disabled:opacity-30"
@@ -642,6 +674,11 @@ function ComfyUISettings() {
</button>
</div>
{portSuccess && <p className="text-[0.55rem] text-green-400">Port saved. Restart ComfyUI to apply.</p>}
+ {portError && (
+ <p role="alert" className="text-[0.55rem] text-red-500 dark:text-red-400 leading-snug whitespace-pre-line">
+ {portError}
+ </p>
+ )}
</div>
{/* Controls, local host only (can't manage a remote process) */}
@@ -979,16 +1016,21 @@ function ResetSection({ tab }: { tab: SettingsTab }) {
const resetSettings = useSettingsStore((s) => s.resetSettings)
const resetVoiceDefaults = useVoiceStore((s) => s.resetVoiceDefaults)
const resetPermissions = usePermissionStore((s) => s.resetToDefaults)
- const [armed, setArmed] = useState<'section' | 'all' | null>(null)
+ // The arm records the tab it was made on, so "still armed?" is a question
+ // that can be answered while rendering. Switching tabs while armed must
+ // disarm — otherwise a click armed on General would confirm-fire on Agent —
+ // and armedScopeFor() is that rule (src/lib/reset-arming.ts). It replaces a
+ // `useEffect(..., [tab])` that disarmed one render too late.
+ const [arm, setArm] = useState<ResetArm<SettingsTab>>(null)
+ const armed = armedScopeFor(arm, tab)
+ const setArmed = (which: ResetArmScope | null) =>
+ setArm(which === null ? null : { scope: which, tab })
const [done, setDone] = useState<string | null>(null)
const armTimer = useRef<number | null>(null)
const doneTimer = useRef<number | null>(null)
const tabLabel = SETTINGS_TABS.find((t) => t.id === tab)?.label ?? 'section'
- // Switching tabs while armed must disarm — otherwise a click armed on
- // General would confirm-fire on Agent.
- useEffect(() => { setArmed(null) }, [tab])
useEffect(() => () => {
if (armTimer.current) window.clearTimeout(armTimer.current)
if (doneTimer.current) window.clearTimeout(doneTimer.current)
@@ -1094,42 +1136,74 @@ export function SettingsPage() {
})
useEffect(() => {
if (typeof window !== 'undefined') {
- try { window.localStorage.setItem(SETTINGS_TAB_KEY, tab) } catch {}
+ // Level (a): silent on purpose. This only remembers which tab was open
+ // for the next visit. If storage is full or blocked (private window),
+ // Settings opens on General next time — a convenience lost, not an
+ // action failed, and nothing the user could act on.
+ try { window.localStorage.setItem(SETTINGS_TAB_KEY, tab) } catch { /* see above */ }
}
}, [tab])
- const refreshWhisper = () => {
+ // The three probes are stabilised with useCallback ON PURPOSE, not for
+ // speed: the mount effect below has to list them as dependencies, and a
+ // function rebuilt on every render would re-run the effect on every render.
+ // `voiceSettings` is `useVoiceStore()` — the WHOLE store, so it changes on
+ // every store write, including the writes these probes make themselves.
+ // Reaching for the actions through selectors instead keeps the closures
+ // pinned to values that never change: zustand defines its actions once in
+ // create(), so setSttAvailable/setTtsAvailable are the same references for
+ // the life of the store.
+ const setSttAvailable = useVoiceStore((s) => s.setSttAvailable)
+ const setTtsAvailable = useVoiceStore((s) => s.setTtsAvailable)
+
+ const refreshWhisper = useCallback(() => {
setWhisperLoading(true)
return checkWhisperAvailable()
.then((s) => {
setWhisperStatus(s)
// Drive the mic button's availability from the same probe so it lights
// up immediately after the in-app install — no restart needed.
- voiceSettings.setSttAvailable(!!s.available)
+ setSttAvailable(!!s.available)
})
.finally(() => setWhisperLoading(false))
- }
+ }, [setSttAvailable])
- const refreshTts = () => {
+ const refreshTts = useCallback(() => {
setTtsLoading(true)
- return checkTtsAvailable(voiceSettings.piperVoice)
+ // Read the voice at call time rather than closing over it. It is what
+ // every caller already means — handlePickVoice sets the new voice and
+ // then asks "is TTS available now?", which is a question about the NEW
+ // voice — and it keeps this callback free of a dependency that changes.
+ return checkTtsAvailable(useVoiceStore.getState().piperVoice)
.then((s) => {
setTtsStatus(s)
// Same as STT: drive the read-aloud button availability from this probe
// so it lights up right after the in-app install.
- voiceSettings.setTtsAvailable(!!s.available)
+ setTtsAvailable(!!s.available)
})
.finally(() => setTtsLoading(false))
- }
-
- const refreshVoices = () => listInstalledPiperVoices().then(setInstalledVoices).catch(() => {})
+ }, [setTtsAvailable])
+
+ const refreshVoices = useCallback(
+ () =>
+ listInstalledPiperVoices()
+ .then(setInstalledVoices)
+ // Level (a): silent on purpose. This only fills the voice DROPDOWN. If
+ // the list cannot be read the dropdown stays on its last contents and
+ // every real action here — picking a voice, downloading one — reports
+ // its own failure through setVoiceError below. A second message for
+ // "the list did not refresh" would be noise on a screen that already
+ // says what went wrong.
+ .catch(() => {}),
+ [],
+ )
useEffect(() => {
void refreshWhisper()
void refreshTts()
void refreshVoices()
- }, [])
+ }, [refreshWhisper, refreshTts, refreshVoices])
// §24.9 — kick off the faster-whisper install, poll its status, then
// re-check availability so the badge flips ✗ → ✓ without a restart.
@@ -1472,8 +1546,19 @@ export function SettingsPage() {
</div>
<button
onClick={async () => {
+ // The line above is what actually re-runs the wizard: AppShell
+ // gates it on settings.onboardingDone, and that store is
+ // persisted, so it survives the reload below. The backend call
+ // only clears the marker FILE, which is read in one place —
+ // the NSIS-update recovery in AppShell, and only when the
+ // store itself was lost.
+ //
+ // Level (a): silent on purpose. The visible action succeeds
+ // either way, and the reload on the next line would wipe any
+ // message before it could be read. A stale marker costs
+ // nothing until a store-loss recovery, which re-writes it.
useSettingsStore.getState().updateSettings({ onboardingDone: false })
- try { await backendCall('set_onboarding_done', { done: false }) } catch {}
+ try { await backendCall('set_onboarding_done', { done: false }) } catch { /* see above */ }
window.location.reload()
}}
className="ml-3 shrink-0 px-2.5 py-1 rounded-md text-[0.6rem] font-medium bg-white dark:bg-white/10 text-gray-800 dark:text-white hover:bg-gray-100 dark:hover:bg-white/15 border border-gray-200 dark:border-white/15 transition-colors"
diff --git a/src/lib/__tests__/reset-arming-is-visible.test.ts b/src/lib/__tests__/reset-arming-is-visible.test.ts
index e27da60b..1e31375b 100644
--- a/src/lib/__tests__/reset-arming-is-visible.test.ts
+++ b/src/lib/__tests__/reset-arming-is-visible.test.ts
@@ -20,6 +20,7 @@
* Run: npx vitest run src/lib/__tests__/reset-arming-is-visible.test.ts
*/
import { describe, it, expect } from 'vitest'
+import { armedScopeFor } from '../reset-arming'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
@@ -63,7 +64,31 @@ describe('an armed button is never lying in wait', () => {
})
it('and a tab switch disarms it, so General cannot fire on Agent', () => {
- expect(settingsPage).toMatch(/useEffect\(\(\) => \{ setArmed\(null\) \}, \[tab\]\)/)
+ // This used to pin the effect that did it: useEffect(() => { setArmed(null) }, [tab]).
+ // The effect is gone (it disarmed one render late, and React 19's
+ // set-state-in-effect rule is right about that); the rule now lives in
+ // armedScopeFor(), tested as behaviour just below. What stays pinned here
+ // is that SettingsPage reads `armed` THROUGH that rule and never keeps a
+ // raw armed flag that a tab switch could miss.
+ expect(settingsPage).toMatch(/const armed = armedScopeFor\(arm, tab\)/)
+ expect(settingsPage).not.toMatch(/useState<'section' \| 'all' \| null>/)
+ })
+})
+
+describe('armedScopeFor: an arm is only live on the tab it was made on', () => {
+ it('is armed on the tab the click happened on', () => {
+ expect(armedScopeFor({ scope: 'section', tab: 'general' }, 'general')).toBe('section')
+ expect(armedScopeFor({ scope: 'all', tab: 'general' }, 'general')).toBe('all')
+ })
+
+ it('is NOT armed on any other tab — General cannot fire on Agent', () => {
+ expect(armedScopeFor({ scope: 'section', tab: 'general' }, 'agent')).toBeNull()
+ expect(armedScopeFor({ scope: 'all', tab: 'general' }, 'backends')).toBeNull()
+ })
+
+ it('coming back to the tab does not re-arm a stale click either', () => {
+ // The 4 s timer clears the arm outright; nothing else can resurrect it.
+ expect(armedScopeFor(null, 'general')).toBeNull()
})
})
diff --git a/src/lib/reset-arming.ts b/src/lib/reset-arming.ts
new file mode 100644
index 00000000..7a1c2724
--- /dev/null
+++ b/src/lib/reset-arming.ts
@@ -0,0 +1,30 @@
+/**
+ * The one rule behind the arm-then-confirm reset button, as a plain function.
+ *
+ * "Reset <tab> to defaults" needs two clicks: the first arms, the second
+ * fires. An arm that survives a tab switch would be a trap — a click armed on
+ * General would confirm-fire on Agent. So an arm is only ever live on the tab
+ * it was made on.
+ *
+ * This used to be an effect (`useEffect(() => setArmed(null), [tab])`), which
+ * meant the disarm happened one render LATE: the render right after a tab
+ * switch still saw the old tab as armed. Recording the tab alongside the arm
+ * and comparing at render time removes both the effect and that one-frame
+ * window.
+ */
+
+/** Which reset the armed click would fire. */
+export type ResetArmScope = 'section' | 'all'
+
+/** An arm remembers what it would do AND where it was made. */
+export type ResetArm<Tab extends string = string> = { scope: ResetArmScope; tab: Tab } | null
+
+/**
+ * The scope the button is armed for on `tab` — `null` on every other tab.
+ *
+ * Pure: given the same arm and tab it always answers the same, which is what
+ * lets the component derive `armed` while rendering instead of syncing it.
+ */
+export function armedScopeFor<Tab extends string>(arm: ResetArm<Tab>, tab: Tab): ResetArmScope | null {
+ return arm && arm.tab === tab ? arm.scope : null
+}