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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
design+tech(D-S27..S30/D-S35..S39/AS-09): eine Zustandssprache, ein Installer-Automat
David51732e632263
diff --git a/src/components/onboarding/Onboarding.tsx b/src/components/onboarding/Onboarding.tsxindex e20a77c8..f9312093 100644--- a/src/components/onboarding/Onboarding.tsx+++ b/src/components/onboarding/Onboarding.tsx@@ -1,12 +1,12 @@-import { useState, useEffect, useRef } from 'react'+import { useState, useEffect, useRef, useReducer } from 'react'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 { Minus, Square, X as XIcon, ArrowRight, Download, Check, ChevronRight, Loader2, RefreshCw, ExternalLink, FolderOpen, Cpu, Image as ImageIcon } from 'lucide-react'import { useSettingsStore } from '../../stores/settingsStore'import { useProviderStore } from '../../stores/providerStore'import { ONBOARDING_MODELS, ONBOARDING_EMBED_MODEL } from '../../lib/constants'import { PROVIDER_PRESETS } from '../../api/providers/types'-import { ICON_SM } from '../ui/icon-size'+import { ICON_SM, ICON_LG } from '../ui/icon-size'import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-detector'import { detectProviderModelPath, startModelDownloadToPath } from '../../api/discover'import { useDownloadStore } from '../../stores/downloadStore'@@ -21,6 +21,10 @@ import { startBundledEngine, startBundledEmbed } from '../../api/engine'import { BUILTIN_BACKEND_ID, classifyOnboardingBackend, resolveOnboardingBackend } from '../../lib/onboarding-backend'import { version as currentVersion } from '../../../package.json'import { useReleaseNotesStore } from '../../stores/releaseNotesStore'+import { wizardProgress, workStepsFor, type Step } from './wizard-steps'+import {+ installerReducer, IDLE_INSTALLER, isRunning, isReady, elapsedSeconds, formatElapsed, lastLog,+} from './installer-state'// Bug (h): the dedicated 'theme' onboarding step was removed because users// kept ending up on Light by accident, and the project standard is "dark@@ -31,8 +35,10 @@ import { useReleaseNotesStore } from '../../stores/releaseNotesStore'// `nomic-embed-text` (~274 MB) before completing onboarding so Document// Chat / RAG works out of the box. The step shows a Skip button and// auto-skips entirely when the user already has any embedding model on disk.-type Step = 'welcome' | 'backends' | 'comfyui' | 'models' | 'embeddings' | 'done'-const STEP_ORDER: Step[] = ['welcome', 'backends', 'comfyui', 'models', 'embeddings', 'done']+// D-S35: `Step` und die Schrittfolge liegen jetzt in ./wizard-steps.ts —+// zusammen mit der Unterscheidung zwischen einem Bildschirm und einem+// Arbeitsschritt, die dieser Datei bisher fehlte. Der Typ wird hier+// re-exportiert, damit die 60 Fundstellen unten unveraendert bleiben.const isTauri = typeof window !== 'undefined' && !!(window as any).__TAURI_INTERNALS__/* ── Local backend info for the "nothing found" state ──────── */@@ -82,14 +88,14 @@ export function Onboarding() {// instead of "ComfyUI detected, Continue".const [comfyDetecting, setComfyDetecting] = useState(false)const [comfyFound, setComfyFound] = useState<{ found: boolean; path?: string; complete?: boolean } | null>(null)- const [comfyInstalling, setComfyInstalling] = useState(false)- const [comfyInstallLogs, setComfyInstallLogs] = useState<string[]>([])- const [comfyInstallError, setComfyInstallError] = useState('')+ // AS-09: hier standen acht `useState` fuer EINE Zustandsmaschine —+ // installing, logs, error, downloadProgress, downloadTotal, downloadSpeed+ // plus installStartTime und elapsed weiter unten. Dieselbe Maschine fuehrten+ // Ollama, LM Studio und der Python-Installer je noch einmal. Sie steht jetzt+ // in ./installer-state.ts, einmal und geprueft.+ const [comfyInstall, comfyDo] = useReducer(installerReducer, IDLE_INSTALLER)const [comfyPathInput, setComfyPathInput] = useState('')const [comfyReady, setComfyReady] = useState(false)- const [comfyDownloadProgress, setComfyDownloadProgress] = useState(0)- const [comfyDownloadTotal, setComfyDownloadTotal] = useState(0)- const [comfyDownloadSpeed, setComfyDownloadSpeed] = useState(0)// Bug #3 (ninjastic2008 v2.4.3): multi-install disambiguation. When// `detect_all_comfyui_installs` returns more than one hit the user picks// explicitly instead of LU auto-picking the first scan match. Picking@@ -109,12 +115,10 @@ export function Onboarding() {// pre-flight runs `python_check`; if Python is missing we kick off// `install_python` (winget Python.Python.3.12) and poll its status here// before re-firing `install_comfyui`.- const [pythonInstalling, setPythonInstalling] = useState(false)- const [pythonInstallLogs, setPythonInstallLogs] = useState<string[]>([])- const [pythonInstallError, setPythonInstallError] = useState('')- const [, setPythonReady] = useState(false)- const [pythonStartTime, setPythonStartTime] = useState<number | null>(null)- const [pythonElapsed, setPythonElapsed] = useState(0)+ // Dieselbe Maschine. `setPythonReady` war dabei ein Schreibzugriff ohne+ // Leser (`const [, setPythonReady]`) — im Reducer ist „fertig" eine Phase,+ // also gibt es den toten Halbzustand nicht mehr.+ const [pythonInstall, pythonDo] = useReducer(installerReducer, IDLE_INSTALLER)const [systemVRAM, setSystemVRAM] = useState<number | null>(null)// Default the active sub-tab to whichever category actually has entries.// The previous fixed 'uncensored' default broke the onboarding starter card@@ -129,33 +133,17 @@ export function Onboarding() {? 'uncensored': 'mainstream'const [modelSubTab, setModelSubTab] = useState<'uncensored' | 'mainstream'>(initialSubTab)- const [installStartTime, setInstallStartTime] = useState<number | null>(null)- const [elapsed, setElapsed] = useState(0)-- // Ollama install state- const [ollamaInstalling, setOllamaInstalling] = useState(false)- const [ollamaStatus, setOllamaStatus] = useState('')- const [ollamaProgress, setOllamaProgress] = useState(0)- const [ollamaTotal, setOllamaTotal] = useState(0)- const [ollamaSpeed, setOllamaSpeed] = useState(0)- const [ollamaLogs, setOllamaLogs] = useState<string[]>([])- const [ollamaError, setOllamaError] = useState('')- const [ollamaReady, setOllamaReady] = useState(false)- const [ollamaStartTime, setOllamaStartTime] = useState<number | null>(null)- const [ollamaElapsed, setOllamaElapsed] = useState(0)-- // LM Studio install state — same shape as Ollama; both can show their- // own progress card if the user picks both. In practice they pick one.- const [lmstudioInstalling, setLmstudioInstalling] = useState(false)- const [lmstudioStatus, setLmstudioStatus] = useState('')- const [lmstudioProgress, setLmstudioProgress] = useState(0)- const [lmstudioTotal, setLmstudioTotal] = useState(0)- const [lmstudioSpeed, setLmstudioSpeed] = useState(0)- const [lmstudioLogs, setLmstudioLogs] = useState<string[]>([])- const [lmstudioError, setLmstudioError] = useState('')- const [lmstudioReady, setLmstudioReady] = useState(false)- const [lmstudioStartTime, setLmstudioStartTime] = useState<number | null>(null)- const [lmstudioElapsed, setLmstudioElapsed] = useState(0)+ // Ollama und LM Studio — der Kommentar hier sagte es vorher selbst:+ // „same shape as Ollama". Zwanzig `useState` fuer zweimal dieselbe Maschine.+ const [ollama, ollamaDo] = useReducer(installerReducer, IDLE_INSTALLER)+ const [lmstudio, lmstudioDo] = useReducer(installerReducer, IDLE_INSTALLER)++ // Der EINE Takt fuer alle vier Anzeigen. `elapsed` war viermal ein eigener+ // `useState` mit einem eigenen `setInterval`, obwohl es nichts anderes ist+ // als `jetzt − startedAt`. Gespeichert wird jetzt nur noch das „jetzt",+ // gerechnet wird beim Rendern (elapsedSeconds in ./installer-state.ts).+ const [now, setNow] = useState(() => Date.now())+ const secondsOf = (startedAt: number | null) => elapsedSeconds(startedAt, now)// Set when LM Studio is installed on the box but its embedded server is// not currently listening on :1234. Surfaces a "Start LM Studio server"// primary action instead of pushing the user through a redundant 570 MB@@ -199,13 +187,13 @@ export function Onboarding() {const providers = useProviderStore.getState().providers// Decide which backend the download has to feed. selectedBackend (set in- // the backends step) is the strongest signal; ollamaReady covers the+ // the backends step) is the strongest signal; isReady(ollama) covers the// "we just installed Ollama in-app" path; final fallback is the first// detected backend, defaulting to ollama. The earlier code wrote a raw// .gguf into `~/.ollama/models` regardless — Ollama ignores files placed// there directly, which is the root cause of the "downloaded model// never appears" bug reported on Discord and GH discussion #35.- const targetBackend = resolveOnboardingBackend(selectedBackend, ollamaReady, detectedBackends)+ const targetBackend = resolveOnboardingBackend(selectedBackend, isReady(ollama), detectedBackends)const kind = classifyOnboardingBackend(targetBackend)const useBuiltinPath = kind === 'builtin'const useOllamaPath = kind === 'ollama'@@ -498,7 +486,7 @@ export function Onboarding() {// the bundled path too. Branching on isManagedBuiltinActive() dead-ended// LM Studio users on a machine that has no Ollama by explicit choice.const embedsViaBundled =- classifyOnboardingBackend(resolveOnboardingBackend(selectedBackend, ollamaReady, detectedBackends)) !== 'ollama'+ classifyOnboardingBackend(resolveOnboardingBackend(selectedBackend, isReady(ollama), detectedBackends)) !== 'ollama'// Probe whether an embedding model is already present. For the built-in// engine (P5) and openai-compat backends we scan the app models dir via@@ -598,35 +586,20 @@ export function Onboarding() {const showRecommendedBadge = existingModelCount === 0- // Elapsed timer for ComfyUI installation- useEffect(() => {- if (!installStartTime) return- const timer = setInterval(() => setElapsed(Math.floor((Date.now() - installStartTime) / 1000)), 1000)- return () => clearInterval(timer)- }, [installStartTime])-- // Elapsed timer for Ollama installation- useEffect(() => {- if (!ollamaStartTime) return- const timer = setInterval(() => setOllamaElapsed(Math.floor((Date.now() - ollamaStartTime) / 1000)), 1000)- return () => clearInterval(timer)- }, [ollamaStartTime])-- // Elapsed timer for LM Studio installation- useEffect(() => {- if (!lmstudioStartTime) return- const timer = setInterval(() => setLmstudioElapsed(Math.floor((Date.now() - lmstudioStartTime) / 1000)), 1000)- return () => clearInterval(timer)- }, [lmstudioStartTime])-- // Elapsed timer for Python installation (P14). winget pulls the Python- // 3.12 installer (~30 MB) and runs it silently; on a typical home- // connection this is ~30–60 s, but slow links can take a few minutes.+ // EIN Takt fuer alle vier Installer statt vier Intervallen (AS-09). Er+ // laeuft nur, solange ueberhaupt einer laeuft, und er speichert die Uhr,+ // nicht die vier daraus abgeleiteten Sekundenzaehler.+ //+ // Der Python-Fall ist der, der die Laufzeit ueberhaupt sichtbar macht+ // (P14): winget zieht den Python-3.12-Installer (~30 MB) und faehrt ihn+ // still durch — an einem normalen Anschluss 30–60 s, an einem langsamen+ // ein paar Minuten.+ const anyStartedAt = comfyInstall.startedAt ?? ollama.startedAt ?? lmstudio.startedAt ?? pythonInstall.startedAtuseEffect(() => {- if (!pythonStartTime) return- const timer = setInterval(() => setPythonElapsed(Math.floor((Date.now() - pythonStartTime) / 1000)), 1000)+ if (anyStartedAt === null) return+ const timer = setInterval(() => setNow(Date.now()), 1000)return () => clearInterval(timer)- }, [pythonStartTime])+ }, [anyStartedAt])/** Der Auto-Scan laeuft einmal pro Mount, sobald der comfyui-Schritt erreicht* ist. Ref statt State: der Wert steuert keinen Render, sondern verhindert@@ -678,10 +651,10 @@ export function Onboarding() {try {await backendCall('set_comfyui_path', { path: only.path })} catch (e) {- setComfyInstallError(withDetail(+ comfyDo({ type: 'warn', error: 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}@@ -715,14 +688,14 @@ export function Onboarding() {// 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('')+ comfyDo({ type: 'warn', error: '' })try {await backendCall('set_comfyui_path', { path: choice.path })} catch (e) {- setComfyInstallError(withDetail(+ comfyDo({ type: 'warn', error: 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 })@@ -743,18 +716,12 @@ export function Onboarding() {// Treat as "not available" and continue to install.}- setPythonInstalling(true)- setPythonInstallError('')- setPythonInstallLogs(['Installing Python 3.12 via winget…'])- setPythonStartTime(Date.now())- setPythonElapsed(0)+ pythonDo({ type: 'start', at: Date.now(), log: 'Installing Python 3.12 via winget…' })try {await backendCall('install_python')} catch (err) {- setPythonInstalling(false)- setPythonStartTime(null)- setPythonInstallError(err instanceof Error ? err.message : 'Python install failed to start')+ pythonDo({ type: 'fail', error: err instanceof Error ? err.message : 'Python install failed to start' })return false}@@ -762,19 +729,14 @@ export function Onboarding() {const poll = setInterval(async () => {try {const status: any = await backendCall('install_python_status')- setPythonInstallLogs(status.logs || [])+ pythonDo({ type: 'progress', status: status.status, logs: status.logs || [] })if (status.status === 'complete' || status.status === 'already_installed') {clearInterval(poll)- setPythonInstalling(false)- setPythonReady(true)- setPythonStartTime(null)+ pythonDo({ type: 'ready' })resolve(true)} else if (status.status === 'error') {clearInterval(poll)- setPythonInstalling(false)- setPythonStartTime(null)- const lastLog = status.logs?.[status.logs.length - 1] || ''- setPythonInstallError(withInstallerOutput('Installing Python did not finish.', lastLog))+ pythonDo({ type: 'fail', error: withInstallerOutput('Installing Python did not finish.', lastLog(status.logs)) })resolve(false)}} catch { /* keep polling */ }@@ -792,9 +754,17 @@ export function Onboarding() {: 0// Shared button styles- const primaryBtn = `mx-auto flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[0.7rem] font-medium transition-all ${- isDark ? 'bg-white text-black hover:bg-gray-200' : 'bg-gray-900 text-white hover:bg-gray-800'- }`+ //+ // D-S36: `primaryBtn` war `bg-white text-black hover:bg-gray-200` (dunkel)+ // bzw. `bg-gray-900 text-white hover:bg-gray-800` (hell). Der Hover machte+ // den Knopf also DUNKLER als seinen Ruhezustand — im Screenshot des Audits+ // liest Schritt 2 deshalb als deaktiviert. Das Rezept dafuer existiert seit+ // f336b91e genau einmal, in index.css als `.lu-primary`, und rechnet seinen+ // Kontrast nach (#a094f8 auf #111827 = 6.83:1 in Ruhe, #b1a6ff auf #111827+ // = 8.25:1 im Hover — der Hover wird HELLER, nicht dunkler). Er hatte das+ // Onboarding nur nie erreicht; AUDIT-COVERAGE fuehrt das unter D-A8 als+ // ausdruecklichen Rest. Kein eigenes Rezept hier, sondern jenes.+ const primaryBtn = 'lu-primary mx-auto flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[0.7rem] transition-all'const secondaryBtn = `mx-auto flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[0.7rem] font-medium transition-all ${isDark ? 'bg-white/10 text-white hover:bg-white/15' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`@@ -804,13 +774,22 @@ export function Onboarding() {const handleClose = async () => { const { getCurrentWindow } = await import('@tauri-apps/api/window'); getCurrentWindow().close() }const winBtn = 'inline-flex items-center justify-center w-[46px] h-8 transition-colors text-gray-400 hover:text-gray-200'- // Mac never visits 'comfyui' (see nextStepAfterBackends) — drop it from the- // dots too so the indicator doesn't show a step the user will never see.- const visibleStepOrder = isMacOS() ? STEP_ORDER.filter((s) => s !== 'comfyui') : STEP_ORDER- const stepIndex = visibleStepOrder.indexOf(step)+ // D-S35: Mac ueberspringt 'comfyui' (siehe nextStepAfterBackends). Der+ // Anzeiger zaehlt ausserdem nur noch die ARBEITSSCHRITTE — Willkommen ist+ // ein Titelbild, Fertig eine Bestaetigung. Die Rechnung dazu steht in+ // ./wizard-steps.ts und ist dort geprueft.+ const workSteps = workStepsFor(isMacOS())+ const progressNow = wizardProgress(step, isMacOS())return (- <div className={`h-screen w-screen flex items-center justify-center p-4 ${bgClass}`}>+ // D-S38: vorher `items-center` auf einem h-screen-Kasten PLUS ein+ // `fixed top-10`-Anzeiger. Die Punkte klebten damit an der Titelleiste+ // (y=46), der Inhalt hing in der Fenstermitte (y=340) — 294px Niemandsland+ // dazwischen, und die Punkte lasen als Teil des Fensterrahmens statt als+ // Teil des Assistenten. Jetzt steht der Anzeiger IM Fluss, direkt ueber+ // der Karte, und der Abstand ist der `gap` einer Spalte statt der Rest+ // einer Zentrierung.+ <div className={`h-screen w-screen flex flex-col items-center justify-center gap-5 p-4 ${bgClass}`}>{/* Drag region + window controls */}{isTauri && (<div data-tauri-drag-region className="fixed top-0 left-0 right-0 h-8 z-50 flex items-center justify-end select-none">@@ -820,11 +799,19 @@ export function Onboarding() {</div>)}- {/* Step indicator dots */}- <div className="fixed top-10 left-1/2 -translate-x-1/2 z-40 flex gap-1.5">- {visibleStepOrder.map((s, i) => (- <div key={s} className={`w-1.5 h-1.5 rounded-full transition-colors ${i <= stepIndex ? (isDark ? 'bg-white' : 'bg-gray-900') : (isDark ? 'bg-white/15' : 'bg-gray-300')}`} />- ))}+ {/* Step indicator — Punkte UND Text. Sechs anonyme Punkte konnten die+ Frage „wie viele noch?" nicht beantworten; „Step 2 of 4 · Model"+ kann es. Die Hoehe ist fest, damit ein Schrittwechsel die Karte+ darunter nicht verschiebt. */}+ <div className="h-8 flex flex-col items-center justify-end gap-1.5" aria-live="polite">+ {progressNow && (<>+ <div className="flex gap-1.5">+ {workSteps.map((s, i) => (+ <div key={s.step} className={`w-1.5 h-1.5 rounded-full transition-colors ${i < progressNow.filled ? (isDark ? 'bg-white' : 'bg-gray-900') : (isDark ? 'bg-white/15' : 'bg-gray-300')}`} />+ ))}+ </div>+ <p className={`text-[0.6rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>{progressNow.caption}</p>+ </>)}</div><AnimatePresence mode="wait">@@ -837,7 +824,22 @@ export function Onboarding() {animate={{ opacity: 1, y: 0 }}exit={{ opacity: 0, y: -20 }}>- <h1 className="text-base font-semibold">LU <span className="font-normal opacity-60">by LU Labs</span></h1>+ {/* D-S37: war `text-base` = 1rem — die Willkommens-Ueberschrift+ der App genau so gross wie ein Settings-Label. Soll laut Audit+ 28px/34px/600.+ Warum `1.5rem` und keine feste px-Zahl: die 28px des Audits+ sind eine MESSUNG am gerenderten Fenster, und das Wurzelmass+ der App wird gerade umgestellt (D-A3, anderes Paket). Beide+ Regime ergeben fuer 1.5rem dasselbe, weil 18,4 = 16 × 1,15:+ alt 1.5 × 18,4px = 27,6 gerenderte px+ neu 1.5 × 16px × --ui-scale 1,15 = 27,6 gerenderte px+ Zeilenhoehe 1,21 → 33,4px (Soll 34). Eine px-Angabe waere im+ neuen Regime durch `zoom` auf 32,2px gelaufen.+ Der Zusatz „by LU Labs" bleibt eine Stufe kleiner, damit die+ Groesse dem Namen gehoert und nicht der ganzen Zeile. */}+ <h1 className="text-[1.5rem] leading-[1.21] font-semibold tracking-tight">+ LU <span className="text-[0.75rem] font-normal opacity-60 align-middle">by LU Labs</span>+ </h1><p className={`text-[0.75rem] leading-relaxed ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>Private, local AI chat that works right away. No extra software to install. No servers, no tracking, everything stays on your machine.</p>@@ -975,7 +977,7 @@ export function Onboarding() {</p>{/* Ollama ready state */}- {ollamaReady && (+ {isReady(ollama) && (<div className={`p-3 rounded-lg border ${isDark ? 'bg-green-500/10 border-green-500/20' : 'bg-green-50 border-green-200'}`}><div className="flex items-center gap-2 justify-center"><Check size={14} className="text-green-400" />@@ -988,28 +990,26 @@ export function Onboarding() {Studio is on the box and just needs starting; pushingOllama in that situation is just noise and forces asecond 200 MB download. */}- {!ollamaInstalling && !ollamaReady && !lmstudioOfflineDetected && (+ {!isRunning(ollama) && !isReady(ollama) && !lmstudioOfflineDetected && (<buttononClick={async () => {- setOllamaInstalling(true)- setOllamaError('')- setOllamaStartTime(Date.now())- setOllamaElapsed(0)+ ollamaDo({ type: 'start', at: Date.now() })try {await backendCall('install_ollama')const poll = setInterval(async () => {try {const s: any = await backendCall('install_ollama_status')- setOllamaStatus(s.status || '')- setOllamaLogs(s.logs || [])- setOllamaProgress(s.download_progress || 0)- setOllamaTotal(s.download_total || 0)- setOllamaSpeed(s.download_speed || 0)+ ollamaDo({+ type: 'progress',+ status: s.status || '',+ logs: s.logs || [],+ received: s.download_progress || 0,+ total: s.download_total || 0,+ speed: s.download_speed || 0,+ })if (s.status === 'complete') {clearInterval(poll)- setOllamaInstalling(false)- setOllamaReady(true)- setOllamaStartTime(null)+ ollamaDo({ type: 'ready' })// Lock the model-download flow onto Ollama so// GGUFs go through `ollama pull` (which produces// a usable model) instead of a raw .gguf write@@ -1017,61 +1017,54 @@ export function Onboarding() {setSelectedBackend('ollama')} else if (s.status === 'error') {clearInterval(poll)- setOllamaInstalling(false)- setOllamaStartTime(null)- const lastLog = s.logs?.[s.logs.length - 1] || ''- setOllamaError(withInstallerOutput('Installing Ollama did not finish.', lastLog))+ ollamaDo({ type: 'fail', error: withInstallerOutput('Installing Ollama did not finish.', lastLog(s.logs)) })}} catch { /* keep polling */ }}, 1000)} catch (err) {- setOllamaInstalling(false)- setOllamaStartTime(null)- setOllamaError(err instanceof Error ? err.message : 'Installation failed')+ ollamaDo({ type: 'fail', error: err instanceof Error ? err.message : 'Installation failed' })}}}- className={`w-full flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg text-[0.7rem] font-medium transition-all ${- isDark ? 'bg-white text-black hover:bg-gray-200' : 'bg-gray-900 text-white hover:bg-gray-800'- }`}+ className="lu-primary w-full flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg text-[0.7rem] transition-all"><Download size={14} /> Install Ollama</button>)}{/* Install progress */}- {ollamaInstalling && (+ {isRunning(ollama) && (<div className={`p-3 rounded-lg border ${cardClass} text-left`}><div className="flex items-center justify-between mb-2"><div className="flex items-center gap-2"><Loader2 size={14} className="animate-spin text-blue-400" /><span className="text-[0.7rem] font-medium">- {ollamaStatus === 'downloading' ? 'Downloading Ollama...' :- ollamaStatus === 'installing' ? 'Installing Ollama...' :- ollamaStatus === 'starting' ? 'Starting Ollama...' :+ {ollama.status === 'downloading' ? 'Downloading Ollama...' :+ ollama.status === 'installing' ? 'Installing Ollama...' :+ ollama.status === 'starting' ? 'Starting Ollama...' :'Setting up Ollama...'}</span></div><span className={`text-[0.55rem] font-mono ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {Math.floor(ollamaElapsed / 60)}:{String(ollamaElapsed % 60).padStart(2, '0')}+ {formatElapsed(secondsOf(ollama.startedAt))}</span></div>{/* Download progress bar */}- {ollamaStatus === 'downloading' && ollamaTotal > 0 && (+ {ollama.status === 'downloading' && ollama.total > 0 && (<div className="space-y-1">- <ProgressBar progress={(ollamaProgress / ollamaTotal) * 100} />+ <ProgressBar progress={(ollama.received / ollama.total) * 100} /><div className="flex justify-between"><span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {formatBytes(ollamaProgress)} / {formatBytes(ollamaTotal)}+ {formatBytes(ollama.received)} / {formatBytes(ollama.total)}</span><span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {ollamaSpeed > 0 ? `${formatBytes(ollamaSpeed)}/s` : ''}+ {ollama.speed > 0 ? `${formatBytes(ollama.speed)}/s` : ''}</span></div></div>)}{/* Log lines */}<div className={`text-[0.55rem] font-mono mt-1 max-h-16 overflow-y-auto space-y-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {ollamaLogs.slice(-4).map((log, i) => (+ {ollama.logs.slice(-4).map((log, i) => (<p key={i}>{log}</p>))}</div>@@ -1079,12 +1072,12 @@ export function Onboarding() {)}{/* Error */}- {ollamaError && (- <p className="text-[0.65rem] text-red-400 whitespace-pre-line">{ollamaError}</p>+ {ollama.error && (+ <p className="text-[0.65rem] text-red-400 whitespace-pre-line">{ollama.error}</p>)}{/* LM Studio ready */}- {lmstudioReady && (+ {isReady(lmstudio) && (<div className={`p-3 rounded-lg border ${isDark ? 'bg-green-500/10 border-green-500/20' : 'bg-green-50 border-green-200'}`}><div className="flex items-center gap-2 justify-center"><Check size={14} className="text-green-400" />@@ -1100,28 +1093,26 @@ export function Onboarding() {command handle it; the Rust side detects the existinginstall and skips straight to bootstrap+server-startinstead of re-downloading. */}- {!lmstudioInstalling && !lmstudioReady && !ollamaInstalling && !ollamaReady && (+ {!isRunning(lmstudio) && !isReady(lmstudio) && !isRunning(ollama) && !isReady(ollama) && (<buttononClick={async () => {- setLmstudioInstalling(true)- setLmstudioError('')- setLmstudioStartTime(Date.now())- setLmstudioElapsed(0)+ lmstudioDo({ type: 'start', at: Date.now() })try {await backendCall('install_lmstudio')const poll = setInterval(async () => {try {const s: any = await backendCall('install_lmstudio_status')- setLmstudioStatus(s.status || '')- setLmstudioLogs(s.logs || [])- setLmstudioProgress(s.download_progress || 0)- setLmstudioTotal(s.download_total || 0)- setLmstudioSpeed(s.download_speed || 0)+ lmstudioDo({+ type: 'progress',+ status: s.status || '',+ logs: s.logs || [],+ received: s.download_progress || 0,+ total: s.download_total || 0,+ speed: s.download_speed || 0,+ })if (s.status === 'complete') {clearInterval(poll)- setLmstudioInstalling(false)- setLmstudioReady(true)- setLmstudioStartTime(null)+ lmstudioDo({ type: 'ready' })// Wire the OpenAI-compat provider to LM Studio so// /v1/chat/completions calls hit the right port,// and route GGUF downloads through the LM-Studio@@ -1136,23 +1127,18 @@ export function Onboarding() {})} else if (s.status === 'error') {clearInterval(poll)- setLmstudioInstalling(false)- setLmstudioStartTime(null)- const lastLog = s.logs?.[s.logs.length - 1] || ''- setLmstudioError(withInstallerOutput('Installing LM Studio did not finish.', lastLog))+ lmstudioDo({ type: 'fail', error: withInstallerOutput('Installing LM Studio did not finish.', lastLog(s.logs)) })}} catch { /* keep polling */ }}, 1000)} catch (err) {- setLmstudioInstalling(false)- setLmstudioStartTime(null)- setLmstudioError(err instanceof Error ? err.message : 'Installation failed')+ lmstudioDo({ type: 'fail', error: err instanceof Error ? err.message : 'Installation failed' })}}}- className={`w-full flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-[0.7rem] font-medium transition-all ${+ className={`w-full flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-[0.7rem] transition-all ${lmstudioOfflineDetected- ? (isDark ? 'bg-white text-black hover:bg-gray-200' : 'bg-gray-900 text-white hover:bg-gray-800')- : (isDark ? 'bg-white/10 text-white hover:bg-white/15' : 'bg-gray-100 text-gray-700 hover:bg-gray-200')+ ? 'lu-primary'+ : `font-medium ${isDark ? 'bg-white/10 text-white hover:bg-white/15' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}`}><Download size={14} />@@ -1163,47 +1149,47 @@ export function Onboarding() {)}{/* LM Studio install progress */}- {lmstudioInstalling && (+ {isRunning(lmstudio) && (<div className={`p-3 rounded-lg border ${cardClass} text-left`}><div className="flex items-center justify-between mb-2"><div className="flex items-center gap-2"><Loader2 size={14} className="animate-spin text-purple-400" /><span className="text-[0.7rem] font-medium">- {lmstudioStatus === 'downloading' ? 'Downloading LM Studio...' :- lmstudioStatus === 'installing' ? 'Installing LM Studio...' :- lmstudioStatus === 'starting' ? 'Starting LM Studio server...' :+ {lmstudio.status === 'downloading' ? 'Downloading LM Studio...' :+ lmstudio.status === 'installing' ? 'Installing LM Studio...' :+ lmstudio.status === 'starting' ? 'Starting LM Studio server...' :'Setting up LM Studio...'}</span></div><span className={`text-[0.55rem] font-mono ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {Math.floor(lmstudioElapsed / 60)}:{String(lmstudioElapsed % 60).padStart(2, '0')}+ {formatElapsed(secondsOf(lmstudio.startedAt))}</span></div>- {lmstudioStatus === 'downloading' && lmstudioTotal > 0 && (+ {lmstudio.status === 'downloading' && lmstudio.total > 0 && (<div className="space-y-1">- <ProgressBar progress={(lmstudioProgress / lmstudioTotal) * 100} />+ <ProgressBar progress={(lmstudio.received / lmstudio.total) * 100} /><div className="flex justify-between"><span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {formatBytes(lmstudioProgress)} / {formatBytes(lmstudioTotal)}+ {formatBytes(lmstudio.received)} / {formatBytes(lmstudio.total)}</span><span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {lmstudioSpeed > 0 ? `${formatBytes(lmstudioSpeed)}/s` : ''}+ {lmstudio.speed > 0 ? `${formatBytes(lmstudio.speed)}/s` : ''}</span></div></div>)}<div className={`text-[0.55rem] font-mono mt-1 max-h-16 overflow-y-auto space-y-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {lmstudioLogs.slice(-4).map((log, i) => (+ {lmstudio.logs.slice(-4).map((log, i) => (<p key={i}>{log}</p>))}</div></div>)}- {lmstudioError && (+ {lmstudio.error && (<p role="alert" className="text-[0.65rem] text-red-400 whitespace-pre-line">- {lmstudioError}- {lmstudioError.toLowerCase().includes('didn\'t come up') && (+ {lmstudio.error}+ {lmstudio.error.toLowerCase().includes('didn\'t come up') && (<button// Level (c): this button lives INSIDE the error it is// meant to clear, and the click wipes that error on the@@ -1212,12 +1198,14 @@ export function Onboarding() {// dud this file can produce. Put the outcome back into// the same line the button came from.onClick={() => {- setLmstudioError('')+ // `warn`, nicht `fail`: hier laeuft keine+ // Installation, es wird nur ein Server angestossen.+ lmstudioDo({ type: 'warn', error: '' })backendCall('start_lmstudio_server').catch((e) => {- setLmstudioError(withDetail(+ lmstudioDo({ type: 'warn', error: 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}`}@@ -1229,7 +1217,7 @@ export function Onboarding() {)}{/* Other alternatives collapsed */}- {!ollamaInstalling && !ollamaReady && (+ {!isRunning(ollama) && !isReady(ollama) && (<details className={`text-left ${isDark ? 'text-gray-400' : 'text-gray-500'}`}><summary className={`text-[0.6rem] cursor-pointer hover:underline ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>Other backends@@ -1260,17 +1248,17 @@ export function Onboarding() {)}<div className="flex items-center justify-center gap-2 pt-1">- {!ollamaInstalling && !lmstudioInstalling && !ollamaReady && !lmstudioReady && (+ {!isRunning(ollama) && !isRunning(lmstudio) && !isReady(ollama) && !isReady(lmstudio) && (<button onClick={runDetection} className={secondaryBtn}><RefreshCw size={12} /> Re-Scan</button>)}- {(ollamaReady || lmstudioReady || (!ollamaInstalling && !lmstudioInstalling)) && (+ {(isReady(ollama) || isReady(lmstudio) || (!isRunning(ollama) && !isRunning(lmstudio))) && (<buttononClick={() => setStep(nextStepAfterBackends())}- className={(ollamaReady || lmstudioReady) ? primaryBtn : `${secondaryBtn} opacity-60`}+ className={(isReady(ollama) || isReady(lmstudio)) ? primaryBtn : `${secondaryBtn} opacity-60`}>- {(ollamaReady || lmstudioReady) ? <>Continue <ArrowRight size={14} /></> : <>Skip for now <ChevronRight size={12} /></>}+ {(isReady(ollama) || isReady(lmstudio)) ? <>Continue <ArrowRight size={14} /></> : <>Skip for now <ChevronRight size={12} /></>}</button>)}</div>@@ -1292,7 +1280,15 @@ export function Onboarding() {animate={{ opacity: 1, y: 0 }}exit={{ opacity: 0, y: -20 }}>- <div className="w-3 h-3 rounded-full bg-purple-400 mx-auto" />+ {/* D-S39: hier stand ein nackter 13,8px-Punkt in `bg-purple-400`+ — im Screenshot des Audits nicht von einem fehlgeschlagenen+ Icon-Load zu unterscheiden. Jetzt das Zeichen, um das es auf+ diesem Schritt geht, auf der Leiterstufe ICON_LG (20px, siehe+ ui/icon-size.ts) in einer weichen Akzentflaeche — dieselbe+ Behandlung, die `Loader2` zwei Zeilen weiter unten bekommt. */}+ <div className="mx-auto w-9 h-9 rounded-full bg-lu-accent-soft flex items-center justify-center">+ <ImageIcon size={ICON_LG} className="text-lu-accent" />+ </div><h2 className="text-base font-semibold">Image & Video Generation</h2><p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>Generate images and videos right from the app. We'll set everything up for you.@@ -1360,7 +1356,7 @@ export function Onboarding() {{/* Found AND complete (a working install). The carcass caseis handled in the install-options block below. */}- {comfyFound?.found && comfyFound.complete !== false && !comfyInstalling && (+ {comfyFound?.found && comfyFound.complete !== false && !isRunning(comfyInstall) && (<div className={`p-3 rounded-lg border ${isDark ? 'bg-green-500/10 border-green-500/20' : 'bg-green-50 border-green-200'}`}><div className="flex items-center gap-2 justify-center"><Check size={14} className="text-green-400" />@@ -1374,7 +1370,7 @@ export function Onboarding() {P14: a found-but-incomplete dir is the ComfyUI carcass case;the same install button restarts the flow (Python pre-flight+ git pull + pip install). */}- {comfyFound && (!comfyFound.found || comfyFound.complete === false) && !comfyInstalling && !pythonInstalling && !comfyReady && (+ {comfyFound && (!comfyFound.found || comfyFound.complete === false) && !isRunning(comfyInstall) && !isRunning(pythonInstall) && !comfyReady && (<div className="space-y-2">{comfyFound.found && comfyFound.complete === false && (<div className={`p-2.5 rounded-lg border ${isDark ? 'bg-amber-500/10 border-amber-500/20' : 'bg-amber-50 border-amber-200'} text-left`}>@@ -1392,26 +1388,25 @@ export function Onboarding() {const pythonOk = await ensurePythonInstalled()if (!pythonOk) return- setComfyInstalling(true)- setComfyInstallError('')- setComfyInstallLogs(['Starting ComfyUI installation...'])- setInstallStartTime(Date.now())- setElapsed(0)+ comfyDo({ type: 'start', at: Date.now(), log: 'Starting ComfyUI installation...' })try {await backendCall('install_comfyui')// Poll installation statusconst poll = setInterval(async () => {try {const status: any = await backendCall('install_comfyui_status')- setComfyInstallLogs(status.logs || [])- setComfyDownloadProgress(status.download_progress || 0)- setComfyDownloadTotal(status.download_total || 0)- setComfyDownloadSpeed(status.download_speed || 0)+ comfyDo({+ type: 'progress',+ status: status.status,+ logs: status.logs || [],+ received: status.download_progress || 0,+ total: status.download_total || 0,+ speed: status.download_speed || 0,+ })if (status.status === 'complete' || status.status === 'done') {clearInterval(poll)- setComfyInstalling(false)+ comfyDo({ type: 'ready' })setComfyReady(true)- setInstallStartTime(null)// Auto-start ComfyUI.//// Level (b): the install DID finish, which is what@@ -1421,36 +1416,30 @@ export function Onboarding() {try {await backendCall('start_comfyui')} catch (e) {- setComfyInstallError(withDetail(+ // `warn`, nicht `fail`: die Installation IST+ // durch — nur der Start danach nicht.+ comfyDo({ type: 'warn', error: 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// again so they can retry or pick another drive.clearInterval(poll)- setComfyInstalling(false)- setInstallStartTime(null)- setComfyInstallError('Install cancelled.')+ comfyDo({ type: 'fail', error: 'Install cancelled.' })} else if (status.status === 'error') {clearInterval(poll)- setComfyInstalling(false)- setInstallStartTime(null)- const lastLog = status.logs?.[status.logs.length - 1] || ''- setComfyInstallError(withInstallerOutput('Installing ComfyUI did not finish.', lastLog))+ comfyDo({ type: 'fail', error: withInstallerOutput('Installing ComfyUI did not finish.', lastLog(status.logs)) })}} catch { /* keep polling */ }}, 2000)} catch (err) {- setComfyInstalling(false)- setComfyInstallError(err instanceof Error ? err.message : 'Installation failed')+ comfyDo({ type: 'fail', error: err instanceof Error ? err.message : 'Installation failed' })}}}- className={`w-full flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-[0.7rem] font-medium transition-all ${- isDark ? 'bg-white text-black hover:bg-gray-200' : 'bg-gray-900 text-white hover:bg-gray-800'- }`}+ className="lu-primary w-full flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-[0.7rem] transition-all"><Download size={14} /> Install ComfyUI (Recommended)</button>@@ -1494,13 +1483,13 @@ export function Onboarding() {try {await backendCall('start_comfyui')} catch (e) {- setComfyInstallError(withDetail(+ comfyDo({ type: 'warn', error: 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')+ comfyDo({ type: 'warn', error: err instanceof Error ? err.message : 'Invalid path' })}}}className={primaryBtn}@@ -1517,7 +1506,7 @@ export function Onboarding() {installer. Sits ABOVE the ComfyUI install card so the usercan see the dependency chain (Python → ComfyUI) when bothrun back-to-back from a single click. */}- {pythonInstalling && (+ {isRunning(pythonInstall) && (<div className={`p-3 rounded-lg border ${cardClass} text-left`}><div className="flex items-center justify-between mb-2"><div className="flex items-center gap-2">@@ -1525,40 +1514,40 @@ export function Onboarding() {<span className="text-[0.7rem] font-medium">Installing Python 3.12...</span></div><span className={`text-[0.55rem] font-mono ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {Math.floor(pythonElapsed / 60)}:{String(pythonElapsed % 60).padStart(2, '0')}+ {formatElapsed(secondsOf(pythonInstall.startedAt))}</span></div><p className={`text-[0.55rem] mb-2 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>ComfyUI needs Python to run pip. We're installing it via winget, about 30 MB and 30 to 60 s on a typical connection.</p><div className={`text-[0.55rem] font-mono max-h-24 overflow-y-auto space-y-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {pythonInstallLogs.slice(-6).map((log, i) => (+ {pythonInstall.logs.slice(-6).map((log, i) => (<p key={i}>{log}</p>))}</div></div>)}- {pythonInstallError && !pythonInstalling && (- <p className="text-[0.65rem] text-red-400 whitespace-pre-line">{pythonInstallError}</p>+ {pythonInstall.error && !isRunning(pythonInstall) && (+ <p className="text-[0.65rem] text-red-400 whitespace-pre-line">{pythonInstall.error}</p>)}{/* Installing progress */}- {comfyInstalling && (+ {isRunning(comfyInstall) && (<div className={`p-3 rounded-lg border ${cardClass} text-left`}><div className="flex items-center justify-between mb-2"><div className="flex items-center gap-2"><Loader2 size={14} className="animate-spin text-purple-400" /><span className="text-[0.7rem] font-medium">- {comfyInstallLogs.some(l => l.toLowerCase().includes('cancel')) ? 'Cancelling ComfyUI install…' : 'Installing ComfyUI...'}+ {comfyInstall.logs.some(l => l.toLowerCase().includes('cancel')) ? 'Cancelling ComfyUI install…' : 'Installing ComfyUI...'}</span></div><div className="flex items-center gap-2"><span className={`text-[0.55rem] font-mono ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {Math.floor(elapsed / 60)}:{String(elapsed % 60).padStart(2, '0')}+ {formatElapsed(secondsOf(comfyInstall.startedAt))}{/* Bug #1: rolling ETA from download bytes when known. */}- {comfyDownloadSpeed > 0 && comfyDownloadTotal > 0 && comfyDownloadProgress < comfyDownloadTotal && (() => {- const remaining = comfyDownloadTotal - comfyDownloadProgress- const etaSec = Math.round(remaining / Math.max(1, comfyDownloadSpeed))+ {comfyInstall.speed > 0 && comfyInstall.total > 0 && comfyInstall.received < comfyInstall.total && (() => {+ const remaining = comfyInstall.total - comfyInstall.received+ const etaSec = Math.round(remaining / Math.max(1, comfyInstall.speed))const m = Math.floor(etaSec / 60)const s = etaSec % 60return ` • ETA ${m}:${String(s).padStart(2, '0')}`@@ -1571,14 +1560,14 @@ export function Onboarding() {// 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('')+ comfyDo({ type: 'warn', error: '' })try {await backendCall('cancel_comfyui_install')} catch (e) {- setComfyInstallError(withDetail(+ comfyDo({ type: 'warn', error: 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 ${@@ -1593,27 +1582,27 @@ export function Onboarding() {</div></div>{/* Disk pressure warning (push from Rust side) */}- {comfyInstallLogs.some(l => l.startsWith('⚠')) && (+ {comfyInstall.logs.some(l => l.startsWith('⚠')) && (<div className={`text-[0.55rem] mb-2 px-2 py-1 rounded ${isDark ? 'bg-amber-500/10 text-amber-300' : 'bg-amber-50 text-amber-800'}`}>- {comfyInstallLogs.find(l => l.startsWith('⚠'))}+ {comfyInstall.logs.find(l => l.startsWith('⚠'))}</div>)}{/* Download progress bar (shown during download phase) */}- {comfyInstallLogs.some(l => l.includes('Downloading')) && comfyDownloadTotal > 0 && (+ {comfyInstall.logs.some(l => l.includes('Downloading')) && comfyInstall.total > 0 && (<div className="space-y-1 mb-2">- <ProgressBar progress={comfyDownloadTotal > 0 ? (comfyDownloadProgress / comfyDownloadTotal) * 100 : 0} />+ <ProgressBar progress={comfyInstall.total > 0 ? (comfyInstall.received / comfyInstall.total) * 100 : 0} /><div className="flex justify-between"><span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {formatBytes(comfyDownloadProgress)} / {formatBytes(comfyDownloadTotal)}+ {formatBytes(comfyInstall.received)} / {formatBytes(comfyInstall.total)}</span><span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {comfyDownloadSpeed > 0 ? `${formatBytes(comfyDownloadSpeed)}/s` : ''}+ {comfyInstall.speed > 0 ? `${formatBytes(comfyInstall.speed)}/s` : ''}</span></div></div>)}<div className={`text-[0.55rem] font-mono max-h-24 overflow-y-auto space-y-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {comfyInstallLogs.slice(-8).map((log, i) => (+ {comfyInstall.logs.slice(-8).map((log, i) => (<p key={i}>{log}</p>))}</div>@@ -1621,8 +1610,8 @@ export function Onboarding() {)}{/* Error */}- {comfyInstallError && (- <p role="alert" className="text-[0.65rem] text-red-400 whitespace-pre-line">{comfyInstallError}</p>+ {comfyInstall.error && (+ <p role="alert" className="text-[0.65rem] text-red-400 whitespace-pre-line">{comfyInstall.error}</p>)}{/* Ready state */}@@ -1647,7 +1636,7 @@ export function Onboarding() {Continue <ArrowRight size={14} /></button>)}- {!comfyInstalling && !pythonInstalling && (!comfyFound?.found || comfyFound.complete === false) && !comfyReady && (+ {!isRunning(comfyInstall) && !isRunning(pythonInstall) && (!comfyFound?.found || comfyFound.complete === false) && !comfyReady && (<><buttononClick={() => {@@ -1787,9 +1776,7 @@ export function Onboarding() {{selectedModels.length > 0 && !isDownloading ? (<buttononClick={handleDownloadSelected}- className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg text-[0.7rem] font-medium transition-all ${- isDark ? 'bg-white text-black hover:bg-gray-200' : 'bg-gray-900 text-white hover:bg-gray-800'- }`}+ className="lu-primary flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg text-[0.7rem] transition-all"><Download size={14} /> Install {selectedModels.length} model{selectedModels.length > 1 ? 's' : ''}</button>diff --git a/src/components/onboarding/__tests__/installer-state.test.ts b/src/components/onboarding/__tests__/installer-state.test.tsnew file mode 100644index 00000000..a6198b91--- /dev/null+++ b/src/components/onboarding/__tests__/installer-state.test.ts@@ -0,0 +1,216 @@+/**+ * Die eine Installer-Zustandsmaschine (AS-09) — und die Rechnung, dass die+ * Zerlegung wirklich eine ist.+ *+ * Zwei Teile:+ *+ * 1. `installerReducer` als Verhalten. Er ist rein, also ist das hier ein+ * echter Verhaltenstest, kein Quelltextabgleich. Geprueft sind vor allem+ * die drei Regeln, die vorher pro Installer als lose Zeilenfolge in+ * einem Klick-Handler standen und deshalb pro Installer anders sein+ * konnten — und teilweise waren.+ *+ * 2. Die BUCHFUEHRUNG. Eine Zerlegung, die 34 `useState` auf vier Dateien+ * verteilt, hat nichts gewonnen. Die Zahlen unten werden aus der Datei+ * gezaehlt, nicht behauptet, und sie sind eine Sperrklinke: sie duerfen+ * sinken, nicht steigen.+ *+ * Lauf: npx vitest run src/components/onboarding/__tests__/installer-state.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import {+ installerReducer,+ IDLE_INSTALLER,+ isRunning,+ isReady,+ elapsedSeconds,+ formatElapsed,+ lastLog,+ type InstallerState,+} from '../installer-state'++/**+ * Nur der Code. Die Zaehlungen und die Negativkontrollen unten duerfen nicht+ * an Kommentaren haengen, die die alten Namen zitieren, um die Aenderung zu+ * erklaeren.+ */+const codeOnly = (src: string) =>+ src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1')++const SRC = codeOnly(readFileSync(resolve(__dirname, '..', 'Onboarding.tsx'), 'utf8'))++/** Kurzschreibweise: eine Folge von Aktionen auf den Ruhezustand anwenden. */+const run = (...actions: Parameters<typeof installerReducer>[1][]): InstallerState =>+ actions.reduce(installerReducer, IDLE_INSTALLER)++describe('der Reducer: der Ablauf, den alle vier Installer teilen', () => {+ it('im Ruhezustand laeuft nichts und ist nichts fertig', () => {+ expect(isRunning(IDLE_INSTALLER)).toBe(false)+ expect(isReady(IDLE_INSTALLER)).toBe(false)+ expect(IDLE_INSTALLER.error).toBe('')+ expect(IDLE_INSTALLER.startedAt).toBeNull()+ })++ it('`start` merkt sich die Startzeit und nimmt die erste Logzeile an', () => {+ const s = run({ type: 'start', at: 1000, log: 'Installing Python 3.12 via winget…' })+ expect(isRunning(s)).toBe(true)+ expect(s.startedAt).toBe(1000)+ expect(s.logs).toEqual(['Installing Python 3.12 via winget…'])+ })++ it('`start` loescht den Fehler des vorigen Versuchs', () => {+ const s = run({ type: 'start', at: 1 }, { type: 'fail', error: 'boom' }, { type: 'start', at: 2 })+ expect(s.error).toBe('')+ expect(isRunning(s)).toBe(true)+ })++ it('`start` loescht auch Fortschritt und Logs des vorigen Versuchs', () => {+ // Das war vorher NICHT so: die vier Klick-Handler setzten beim Neustart+ // `installing`, `error`, `startTime` und `elapsed` zurueck — aber nicht+ // `status`, `logs`, `progress`, `total`, `speed`. Ein zweiter Anlauf+ // startete deshalb mit dem Fortschrittsbalken des ersten.+ const s = run(+ { type: 'start', at: 1 },+ { type: 'progress', status: 'downloading', logs: ['a', 'b'], received: 50, total: 100, speed: 10 },+ { type: 'fail', error: 'boom' },+ { type: 'start', at: 2 },+ )+ expect(s).toMatchObject({ status: '', logs: [], received: 0, total: 0, speed: 0 })+ })++ it('`progress` fuehrt nur die Felder nach, die der Tick wirklich brachte', () => {+ const s = run(+ { type: 'start', at: 0 },+ { type: 'progress', status: 'downloading', received: 10, total: 100 },+ { type: 'progress', received: 20 },+ )+ expect(s).toMatchObject({ status: 'downloading', received: 20, total: 100 })+ })++ it('ein `progress` NACH dem Ende aendert nichts mehr', () => {+ // Der Poll laeuft asynchron. Zwischen `clearInterval` und der letzten+ // Antwort kann noch ein Tick unterwegs sein; vorher hat der die Anzeige+ // einer fertigen Installation wieder auf „laeuft" gezogen.+ const done = run({ type: 'start', at: 0 }, { type: 'ready' })+ expect(installerReducer(done, { type: 'progress', status: 'downloading', received: 5 })).toBe(done)++ const failed = run({ type: 'start', at: 0 }, { type: 'fail', error: 'boom' })+ expect(installerReducer(failed, { type: 'progress', received: 5 })).toBe(failed)+ })++ it('`ready` und `fail` loeschen beide die Startzeit — sonst laeuft die Uhr weiter', () => {+ expect(run({ type: 'start', at: 5 }, { type: 'ready' }).startedAt).toBeNull()+ expect(run({ type: 'start', at: 5 }, { type: 'fail', error: 'x' }).startedAt).toBeNull()+ })++ it('`ready` loescht den Fehler, `fail` setzt ihn', () => {+ expect(run({ type: 'start', at: 0 }, { type: 'fail', error: 'x' }, { type: 'ready' }).error).toBe('')+ const f = run({ type: 'start', at: 0 }, { type: 'fail', error: 'did not finish' })+ expect(f.error).toBe('did not finish')+ expect(isRunning(f)).toBe(false)+ expect(isReady(f)).toBe(false)+ })++ it('`warn` meldet, ohne die Phase umzuwerfen — der ComfyUI-Fall', () => {+ // Installation durch, `start_comfyui` danach nicht: „failed" waere dafuer+ // die falsche Auskunft, die Installation IST gelungen.+ const s = run({ type: 'start', at: 0 }, { type: 'ready' }, { type: 'warn', error: 'installed but did not start' })+ expect(isReady(s)).toBe(true)+ expect(s.error).toBe('installed but did not start')+ // Und ein leerer String loescht die Meldung wieder.+ expect(installerReducer(s, { type: 'warn', error: '' }).error).toBe('')+ })++ it('`reset` fuehrt wirklich auf den Ruhezustand zurueck', () => {+ const s = run({ type: 'start', at: 9 }, { type: 'progress', received: 3 }, { type: 'reset' })+ expect(s).toEqual(IDLE_INSTALLER)+ })+})++describe('abgeleitet statt gespeichert: die Uhr', () => {+ it('vergangene Sekunden sind eine Subtraktion, kein Zustand', () => {+ expect(elapsedSeconds(10_000, 10_000)).toBe(0)+ expect(elapsedSeconds(10_000, 11_500)).toBe(1)+ expect(elapsedSeconds(10_000, 135_000)).toBe(125)+ })++ it('ohne Start ist nichts vergangen', () => {+ expect(elapsedSeconds(null, 999_999)).toBe(0)+ })++ it('nie negativ — der Takt kann eine Sekunde alt sein, wenn ein Lauf beginnt', () => {+ // Der gemeinsame Takt speichert `Date.now()` einmal pro Sekunde. Startet+ // ein Installer dazwischen, liegt `startedAt` hinter dem letzten Takt.+ expect(elapsedSeconds(11_000, 10_000)).toBe(0)+ })++ it('`m:ss` wie in allen vier Anzeigen vorher', () => {+ expect(formatElapsed(0)).toBe('0:00')+ expect(formatElapsed(9)).toBe('0:09')+ expect(formatElapsed(60)).toBe('1:00')+ expect(formatElapsed(125)).toBe('2:05')+ expect(formatElapsed(3_600)).toBe('60:00')+ })++ it('die letzte Logzeile, ohne die vier handgeschriebenen Kopien', () => {+ expect(lastLog(['a', 'b'])).toBe('b')+ expect(lastLog([])).toBe('')+ expect(lastLog(undefined)).toBe('')+ })+})++// ── Die Buchfuehrung ──────────────────────────────────────────────────────++describe('AS-09: die Zerlegung ist eine, keine Verschiebung', () => {+ const useStates = (SRC.match(/=\s*useState[<(]/g) ?? []).length+ const useReducers = (SRC.match(/=\s*useReducer\(/g) ?? []).length++ it('Onboarding.tsx haelt hoechstens 25 `useState` — vorher 58', () => {+ // Sperrklinke: die Zahl darf sinken, nicht steigen. 58 ist der Stand am+ // HEAD (`ed9d6e52`), den AUDIT-COVERAGE unter AS-09 mit „59" fuehrt —+ // der Audit zaehlt die Import-Zeile mit.+ expect(useStates).toBeLessThanOrEqual(25)+ })++ it('die vier Installer sind vier Reducer auf EINER Maschine', () => {+ expect(useReducers).toBe(4)+ for (const name of ['comfyInstall', 'pythonInstall', 'ollama', 'lmstudio']) {+ expect(SRC).toContain(`useReducer(installerReducer, IDLE_INSTALLER)`)+ expect(SRC, name).toContain(name)+ }+ })++ it('und die Maschine steht genau einmal, in einer eigenen Datei', () => {+ const machine = readFileSync(resolve(__dirname, '..', 'installer-state.ts'), 'utf8')+ expect((machine.match(/export function installerReducer/g) ?? [])).toHaveLength(1)+ // Keine zweite Kopie in der Komponente: die alten Feldnamen sind fort.+ for (const gone of [+ 'setOllamaInstalling', 'setLmstudioInstalling', 'setComfyInstalling', 'setPythonInstalling',+ 'setOllamaElapsed', 'setLmstudioElapsed', 'setPythonElapsed', 'setInstallStartTime',+ 'setPythonReady', 'setOllamaReady', 'setLmstudioReady',+ ]) {+ expect(SRC, gone).not.toContain(gone)+ }+ })++ it('EIN Takt statt vier Intervallen', () => {+ // Das Muster `setInterval(() => set<X>Elapsed(...))` gab es viermal.+ expect(SRC).not.toMatch(/setInterval\([^)]*Elapsed/)+ expect(SRC).toContain('const [now, setNow] = useState(() => Date.now())')+ expect(SRC).toContain('setInterval(() => setNow(Date.now()), 1000)')+ // Und er laeuft nur, wenn ueberhaupt etwas laeuft.+ expect(SRC).toContain('if (anyStartedAt === null) return')+ })++ it('NEGATIVKONTROLLE: die Schrittzahl allein waere keine Zerlegung gewesen', () => {+ // Der Audit verlangt „eine Zerlegung pro Schritt". Eine solche haette die+ // 34 Felder auf sechs Dateien verteilt und vier Kopien vier Kopien+ // gelassen. Was zaehlt, ist, dass die WIEDERHOLUNG weg ist: ein+ // Modul beschreibt vier Installer.+ const machine = readFileSync(resolve(__dirname, '..', 'installer-state.ts'), 'utf8')+ expect((machine.match(/^export (function|const|type|interface) /gm) ?? []).length).toBeGreaterThan(5)+ expect(useReducers).toBe(4)+ })+})diff --git a/src/components/onboarding/__tests__/onboarding-schritte-und-primaer.test.ts b/src/components/onboarding/__tests__/onboarding-schritte-und-primaer.test.tsnew file mode 100644index 00000000..ae6d5f34--- /dev/null+++ b/src/components/onboarding/__tests__/onboarding-schritte-und-primaer.test.ts@@ -0,0 +1,235 @@+/**+ * Onboarding: wie viele Schritte es sind, wie der Primaerknopf aussieht, wie+ * gross die Willkommens-Ueberschrift ist, wo die Fortschrittspunkte haengen+ * und was in Schritt 3 statt eines Icons stand.+ *+ * Deckt D-S35, D-S36, D-S37, D-S38 und D-S39 des Design-Audits.+ *+ * Zwei Sorten Zusicherung stehen hier nebeneinander, und der Unterschied ist+ * wichtig:+ *+ * — Die Schrittrechnung ist ECHTES Verhalten. `wizardProgress()` ist eine+ * reine Funktion, sie wird hier aufgerufen und ihr Ergebnis geprueft.+ * — Alles andere ist Quelltext- und Farbrechnung. Es gibt in diesem Projekt+ * keinen Renderer (`vitest.config.ts`: `environment: 'node'`, kein jsdom,+ * kein testing-library), also kann kein Test dieser Datei sagen, wie das+ * Fenster aussieht. Was er sagen kann: welche Regel gilt und was sie+ * rechnerisch bedeutet.+ *+ * Was ausdruecklich NICHT geprueft ist: die 294px aus D-S38. Die sind eine+ * Messung an gerendertem DOM; AUDIT-COVERAGE fuehrt D-S38 aus genau diesem+ * Grund als „nicht verifizierbar hier". Geprueft ist hier nur die URSACHE,+ * die das Audit benennt — `fixed top-10` plus zentrierter Inhalt.+ *+ * Lauf: npx vitest run src/components/onboarding/__tests__/onboarding-schritte-und-primaer.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { contrast, luminance } from '../../__tests__/wcag-contrast'+import { STEP_ORDER, WORK_STEPS, workStepsFor, wizardProgress } from '../wizard-steps'++const codeOnly = (src: string) =>+ src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1')++const SRC = codeOnly(readFileSync(resolve(__dirname, '..', 'Onboarding.tsx'), 'utf8'))+const CSS = readFileSync(resolve(__dirname, '..', '..', '..', 'index.css'), 'utf8')++const MAC = true+const WIN = false++// ── D-S35 — sechs Bildschirme, aber nicht sechs Aufgaben ──────────────────++describe('D-S35: der Anzeiger zaehlt Arbeitsschritte, nicht Bildschirme', () => {+ it('die Bildschirmliste ist unveraendert sechsteilig — daran wird nicht gelogen', () => {+ expect(STEP_ORDER).toEqual(['welcome', 'backends', 'comfyui', 'models', 'embeddings', 'done'])+ expect(STEP_ORDER).toHaveLength(6)+ })++ it('Willkommen und Fertig sind keine Arbeitsschritte', () => {+ const steps = WORK_STEPS.map((s) => s.step)+ expect(steps).not.toContain('welcome')+ expect(steps).not.toContain('done')+ expect(steps).toEqual(['backends', 'comfyui', 'models', 'embeddings'])+ })++ it('macOS hat wirklich drei, Windows und Linux vier', () => {+ expect(workStepsFor(MAC).map((s) => s.step)).toEqual(['backends', 'models', 'embeddings'])+ expect(workStepsFor(WIN)).toHaveLength(4)+ })++ it('das Titelbild bekommt keinen Fortschritt', () => {+ expect(wizardProgress('welcome', MAC)).toBeNull()+ expect(wizardProgress('welcome', WIN)).toBeNull()+ })++ it('jeder Arbeitsschritt sagt in Worten, der wievielte von wie vielen er ist', () => {+ expect(wizardProgress('backends', MAC)).toMatchObject({ position: 1, total: 3, filled: 1 })+ expect(wizardProgress('models', MAC)).toMatchObject({ position: 2, total: 3, filled: 2 })+ expect(wizardProgress('embeddings', MAC)).toMatchObject({ position: 3, total: 3, filled: 3 })+ expect(wizardProgress('backends', MAC)?.caption).toBe('Step 1 of 3 · Engine')+ expect(wizardProgress('comfyui', WIN)?.caption).toBe('Step 2 of 4 · Image & video')+ expect(wizardProgress('embeddings', WIN)?.caption).toBe('Step 4 of 4 · Documents')+ })++ it('der Abschluss faerbt alles voll und sagt es', () => {+ expect(wizardProgress('done', MAC)).toEqual({ position: null, total: 3, caption: 'Setup complete', filled: 3 })+ expect(wizardProgress('done', WIN)?.filled).toBe(4)+ })++ it('ein Schritt, den die Plattform ueberspringt, erzeugt keine falsche Zahl', () => {+ // ComfyUI existiert auf dem Mac nicht. Vorher waere das ein indexOf()+ // von -1 gewesen und haette alle Punkte leer gelassen.+ expect(wizardProgress('comfyui', MAC)).toBeNull()+ expect(wizardProgress('comfyui', WIN)?.position).toBe(2)+ })++ it('die Punkte im JSX haengen an den Arbeitsschritten, nicht mehr an STEP_ORDER', () => {+ expect(SRC).toContain('workStepsFor(isMacOS())')+ expect(SRC).toContain('wizardProgress(step, isMacOS())')+ expect(SRC).toContain('{workSteps.map((s, i) => (')+ expect(SRC).toContain('{progressNow.caption}')+ // Die alte Zaehlung ist weg: `visibleStepOrder` und `stepIndex` gab es+ // nur, um sechs Bildschirme als sechs Schritte zu zeichnen.+ expect(SRC).not.toContain('visibleStepOrder')+ expect(SRC).not.toContain('const stepIndex')+ })+})++// ── D-S36 — der Primaerknopf ──────────────────────────────────────────────++describe('D-S36: der Hover macht den Primaerknopf heller, nicht dunkler', () => {+ it('das Onboarding benutzt das vorhandene Rezept statt eines eigenen', () => {+ expect(SRC).toContain("const primaryBtn = 'lu-primary")+ // Und die vier weiteren Primaerknoepfe, die ihr Grau inline abgeschrieben+ // hatten, ebenfalls: Ollama, LM Studio (Server starten), ComfyUI,+ // „Install N models".+ expect((SRC.match(/lu-primary/g) ?? []).length).toBeGreaterThanOrEqual(5)+ })++ it('das Graphit-Rezept steht nirgends mehr in dieser Datei', () => {+ expect(SRC).not.toContain('bg-white text-black hover:bg-gray-200')+ expect(SRC).not.toContain('bg-gray-900 text-white hover:bg-gray-800')+ })++ it('das Rezept liegt weiterhin an EINER Stelle, in index.css', () => {+ expect((CSS.match(/^\.lu-primary\s*\{/gm) ?? [])).toHaveLength(1)+ expect(CSS).toMatch(/\.lu-primary:hover:not\(:disabled\)\s*\{/)+ })++ it('DER BEFUND, nachgerechnet: das alte Paar wurde im Hover dunkler', () => {+ // Dunkelmodus: Ruhe #ffffff, Hover #e5e7eb (gray-200).+ expect(luminance('#e5e7eb')).toBeLessThan(luminance('#ffffff'))+ // Hellmodus: Ruhe #111827 (gray-900), Hover #1f2937 (gray-800) — dort+ // wurde die Flaeche im Hover HELLER, also war die Bewegung in den beiden+ // Modi auch noch gegenlaeufig.+ expect(luminance('#1f2937')).toBeGreaterThan(luminance('#111827'))+ })++ it('DIE ABHILFE, nachgerechnet: der Akzent wird im Hover heller — in beiden Modi gleich', () => {+ const accent = CSS.match(/--color-lu-accent:\s*(#[0-9a-fA-F]{6})/)?.[1] ?? ''+ const hover = CSS.match(/--color-lu-accent-hover:\s*(#[0-9a-fA-F]{6})/)?.[1] ?? ''+ const onAccent = CSS.match(/--color-lu-on-accent:\s*(#[0-9a-fA-F]{6})/)?.[1] ?? ''+ expect([accent, hover, onAccent]).toEqual(['#a094f8', '#b1a6ff', '#111827'])+ expect(luminance(hover)).toBeGreaterThan(luminance(accent))+ // Und beide Zustaende bleiben lesbar: 6.83:1 bzw. 8.25:1.+ expect(contrast(accent, onAccent)).toBeCloseTo(6.83, 2)+ expect(contrast(hover, onAccent)).toBeCloseTo(8.25, 2)+ })++ it('die Sekundaerknoepfe bleiben sekundaer — sonst waere nur alles laut', () => {+ expect(SRC).toContain("const secondaryBtn = ")+ expect(SRC).not.toContain("const secondaryBtn = 'lu-primary")+ })+})++// ── D-S37 — die Willkommens-Ueberschrift ──────────────────────────────────++describe('D-S37: die H1 ist eine Ueberschrift, kein Label', () => {+ it('1.5rem / 1,21 / 600 — die Audit-Zahlen in einer Einheit, die mitskaliert', () => {+ expect(SRC).toContain('<h1 className="text-[1.5rem] leading-[1.21] font-semibold')+ })++ it('sie ist nicht mehr `text-base`', () => {+ expect(SRC).not.toContain('<h1 className="text-base font-semibold">')+ })++ /**+ * Das WIRKSAME Wurzelmass: Wurzel-`font-size` mal `--ui-scale`, denn der+ * Regler haengt als `zoom` an #root. Waehrend dieses Pakets lief die+ * D-A3-Umstellung parallel (18,4px ohne Regler → 16px mal 1,15); beide+ * Regime ergeben 18,4 gerenderte px, und genau deshalb steht die H1 in+ * rem und nicht in px. Ein `text-[28px]` waere im neuen Regime durch das+ * `zoom` auf 32,2px gelaufen.+ */+ function effectiveRootPx(): number {+ const root = Number(CSS.match(/html\s*\{[^}]*?font-size:\s*([\d.]+)px/s)?.[1])+ const scale = Number(CSS.match(/--ui-scale:\s*([\d.]+)/)?.[1] ?? 1)+ expect(Number.isFinite(root), 'Wurzel-font-size nicht gefunden').toBe(true)+ return root * scale+ }++ it('sie landet gerendert bei 27,6px — das Soll war 28', () => {+ const root = effectiveRootPx()+ expect(root).toBeCloseTo(18.4, 3)+ expect(1.5 * root).toBeCloseTo(27.6, 3)+ expect(Math.abs(1.5 * root - 28) / 28).toBeLessThan(0.02)+ // Zeilenhoehe: 1,21 × 27,6 = 33,4px, Soll 34.+ expect(Math.abs(1.21 * 1.5 * root - 34) / 34).toBeLessThan(0.02)+ })++ it('und ist damit gut die Haelfte groesser als das alte `text-base`', () => {+ // Der Befund im Verhaeltnis: 1rem war die Ueberschrift, 1rem ist auch+ // ein Settings-Label.+ expect(1.5).toBeGreaterThan(1)+ expect(1.5 * effectiveRootPx()).toBeGreaterThan(effectiveRootPx())+ })+})++// ── D-S38 — die Fortschrittspunkte ────────────────────────────────────────++describe('D-S38: die Punkte gehoeren zum Assistenten, nicht zur Titelleiste', () => {+ it('die Ursache aus dem Audit ist weg: kein `fixed top-10` mehr', () => {+ expect(SRC).not.toContain('fixed top-10')+ })++ it('Anzeiger und Karte stehen in EINER Spalte mit einem benannten Abstand', () => {+ expect(SRC).toContain('h-screen w-screen flex flex-col items-center justify-center gap-5 p-4')+ })++ it('der Anzeiger behaelt seine Hoehe, damit die Karte beim Schrittwechsel steht', () => {+ // Ohne feste Hoehe waechst der Block um die Textzeile, sobald der erste+ // Arbeitsschritt erreicht ist — und die Karte darunter springt.+ expect(SRC).toMatch(/<div className="h-8 flex flex-col items-center justify-end gap-1\.5"/)+ })++ it('der Fensterrahmen bleibt festgenagelt — nur er', () => {+ // `data-tauri-drag-region` MUSS fixed bleiben, das ist der Fensterbalken.+ expect(SRC).toContain('data-tauri-drag-region className="fixed top-0 left-0 right-0 h-8')+ expect((SRC.match(/className="fixed /g) ?? []).length).toBe(1)+ })+})++// ── D-S39 — der nackte Punkt ──────────────────────────────────────────────++describe('D-S39: Schritt 3 zeigt ein Zeichen statt eines Punktes', () => {+ it('der nackte Punkt ist weg', () => {+ expect(SRC).not.toContain('w-3 h-3 rounded-full bg-purple-400')+ })++ it('an seiner Stelle steht das Icon des Schrittes, auf einer Leiterstufe', () => {+ expect(SRC).toMatch(/<ImageIcon size=\{ICON_LG\} className="text-lu-accent" \/>/)+ expect(SRC).toContain("Image as ImageIcon")+ // Keine neue Icon-Groesse: ICON_LG ist die vorhandene 20er-Stufe. Die+ // Sperrklinke in src/components/__tests__/icon-leiter.test.ts zaehlt+ // distinkte numerische `size={n}` und darf nicht steigen.+ expect(SRC).not.toMatch(/<ImageIcon size=\{\d+\}/)+ })++ it('die Flaeche darunter ist dieselbe, die der Akzent sonst traegt', () => {+ expect(SRC).toContain('rounded-full bg-lu-accent-soft flex items-center justify-center')+ // Und der Akzent steht auf dem dunklen Grund des Onboardings fuer sich:+ // #a094f8 auf #202020 = 6.27:1.+ expect(contrast('#a094f8', '#202020')).toBeCloseTo(6.27, 2)+ })+})diff --git a/src/components/onboarding/installer-state.ts b/src/components/onboarding/installer-state.tsnew file mode 100644index 00000000..8bbb0c55--- /dev/null+++ b/src/components/onboarding/installer-state.ts@@ -0,0 +1,158 @@+/**+ * Die EINE Installer-Zustandsmaschine des Onboardings.+ *+ * ── Warum diese Datei existiert (AS-09) ───────────────────────────────────+ *+ * Der Technik-Audit fuehrt „Onboarding: 59 `useState` in einer Datei" und+ * verlangt eine Zerlegung „pro Schritt". Nachgezaehlt sind es 58 Aufrufe —+ * und die Verteilung ist der eigentliche Befund, nicht die Summe:+ *+ * Ollama 10 installing · status · progress · total · speed+ * LM Studio 10 logs · error · ready · startTime · elapsed+ * ComfyUI 8 dasselbe, unter anderen Namen+ * Python 6 dasselbe, ohne Fortschrittsbalken+ * ───────────────+ * 34 von 58 — vier Kopien EINER Zustandsmaschine+ *+ * Eine Zerlegung „pro Schritt" haette diese 34 auf vier Dateien verteilt und+ * damit nichts gewonnen: vier Kopien blieben vier Kopien, nur weiter+ * auseinander. Die Schnittlinie liegt nicht zwischen den Schritten, sondern+ * zwischen dem, was sich WIEDERHOLT, und dem, was einmalig ist. Hier steht+ * das Wiederholte, einmal, als reine Funktion — und damit auch als etwas,+ * das ohne DOM geprueft werden kann.+ *+ * Zwei Sorten Ersparnis stecken darin:+ *+ * 1. VIER KOPIEN → EINE. Aus 34 `useState` werden vier `useReducer`.+ * 2. ABGELEITET STATT GESPEICHERT. `elapsed` war viermal ein eigener+ * `useState` plus ein eigenes `setInterval`, obwohl es nichts anderes+ * ist als `jetzt − startedAt`. Es steht hier als Rechnung+ * (`elapsedSeconds`), nicht als Zustand.+ *+ * ── Was die Maschine kann ─────────────────────────────────────────────────+ *+ * Alle vier Installer folgen demselben Ablauf: Knopf gedrueckt → Tauri-Befehl+ * → sekuendliches Polling eines `*_status`-Endpunkts → `complete` oder+ * `error`. Genau das ist unten abgebildet, mit den Regeln, die vorher+ * verstreut in den Klick-Handlern standen:+ *+ * — Ein `progress` NACH dem Ende wird verworfen. Vorher konnte ein+ * Poll-Tick, der zwischen `clearInterval` und dem letzten `setState`+ * unterwegs war, den Fortschrittsbalken einer bereits fertigen+ * Installation wieder auf „laeuft" ziehen.+ * — `ready` und `fail` loeschen `startedAt`. Vorher war das eine eigene+ * Zeile pro Ausstiegspfad, und es gab sechs davon je Installer.+ * — `start` loescht den Fehler des vorigen Versuchs. Auch das war vorher+ * eine eigene Zeile, die genau einmal (im Python-Pfad) fehlte.+ */++/** Wo ein Installer steht. Vier Zustaende, nicht drei Boolesche. */+export type InstallerPhase = 'idle' | 'running' | 'ready' | 'failed'++export interface InstallerState {+ phase: InstallerPhase+ /** Der rohe `status`-String der Rust-Seite: 'downloading' | 'installing' | 'starting' | … */+ status: string+ logs: string[]+ /** Leerer String heisst „kein Fehler" — so lasen es die vier Vorlagen auch. */+ error: string+ /** Heruntergeladene Bytes. */+ received: number+ /** Gesamtbytes, 0 solange unbekannt. */+ total: number+ /** Bytes pro Sekunde. */+ speed: number+ /** `Date.now()` beim Start; `null`, sobald der Lauf vorbei ist. */+ startedAt: number | null+}++export const IDLE_INSTALLER: InstallerState = {+ phase: 'idle',+ status: '',+ logs: [],+ error: '',+ received: 0,+ total: 0,+ speed: 0,+ startedAt: null,+}++export type InstallerAction =+ /** Knopf gedrueckt. `at` ist die Startzeit, `log` eine optionale erste Zeile. */+ | { type: 'start'; at: number; log?: string }+ /** Ein Poll-Tick. Alle Felder optional — das Backend liefert nicht immer alle. */+ | { type: 'progress'; status?: string; logs?: string[]; received?: number; total?: number; speed?: number }+ /** `status === 'complete'`. */+ | { type: 'ready' }+ /** `status === 'error'`, ein geworfener Fehler, oder ein Abbruch. */+ | { type: 'fail'; error: string }+ /**+ * Eine Meldung, die die Phase NICHT umwirft. Der ComfyUI-Schritt braucht+ * das: die Installation ist durch, aber `start_comfyui` danach nicht — die+ * Installation ist trotzdem gelungen, und „failed" waere dafuer die+ * falsche Auskunft. Leerer String loescht die Meldung.+ */+ | { type: 'warn'; error: string }+ /** Zurueck auf Anfang (neuer Anlauf ohne laufenden Poll). */+ | { type: 'reset' }++export function installerReducer(state: InstallerState, action: InstallerAction): InstallerState {+ switch (action.type) {+ case 'start':+ return {+ ...IDLE_INSTALLER,+ phase: 'running',+ startedAt: action.at,+ logs: action.log ? [action.log] : [],+ }+ case 'progress':+ // Ein Tick, der nach dem Ende eintrifft, aendert nichts mehr. Der Poll+ // laeuft asynchron; zwischen `clearInterval` und dem letzten Ergebnis+ // kann noch eine Antwort unterwegs sein.+ if (state.phase !== 'running') return state+ return {+ ...state,+ status: action.status ?? state.status,+ logs: action.logs ?? state.logs,+ received: action.received ?? state.received,+ total: action.total ?? state.total,+ speed: action.speed ?? state.speed,+ }+ case 'ready':+ return { ...state, phase: 'ready', error: '', startedAt: null }+ case 'fail':+ return { ...state, phase: 'failed', error: action.error, startedAt: null }+ case 'warn':+ return { ...state, error: action.error }+ case 'reset':+ return IDLE_INSTALLER+ }+}++/** Laeuft gerade etwas? Ersetzt die vier `*Installing`-Flags. */+export const isRunning = (s: InstallerState): boolean => s.phase === 'running'++/** Fertig und benutzbar? Ersetzt die vier `*Ready`-Flags. */+export const isReady = (s: InstallerState): boolean => s.phase === 'ready'++/**+ * Vergangene Sekunden — die Rechnung, die vorher viermal als `useState` plus+ * `setInterval` gespeichert war. Nie negativ: `now` kommt aus einem Takt, der+ * eine Sekunde alt sein kann, und ein Start liegt dann in der „Zukunft".+ */+export function elapsedSeconds(startedAt: number | null, now: number): number {+ if (startedAt === null) return 0+ return Math.max(0, Math.floor((now - startedAt) / 1000))+}++/** `m:ss`, wie die vier Anzeigen es bisher jeweils selbst zusammengesetzt haben. */+export function formatElapsed(seconds: number): string {+ const s = Math.max(0, Math.floor(seconds))+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`+}++/**+ * Die letzte Logzeile — das, was die Fehlermeldungen der vier Installer als+ * „was hat das Installationsprogramm zuletzt gesagt" anhaengen.+ */+export const lastLog = (logs: string[] | undefined): string => logs?.[logs.length - 1] ?? ''diff --git a/src/components/onboarding/wizard-steps.ts b/src/components/onboarding/wizard-steps.tsnew file mode 100644index 00000000..ca43d794--- /dev/null+++ b/src/components/onboarding/wizard-steps.ts@@ -0,0 +1,93 @@+/**+ * Die Schrittfolge des Einrichtungsassistenten — als Daten und reine+ * Funktionen, nicht als 1920 Zeilen JSX.+ *+ * Warum es diese Datei gibt (Design-Audit D-S35): das Onboarding hat sechs+ * Eintraege in `STEP_ORDER` und zeigt sechs anonyme Punkte. Angekuendigt sind+ * drei. Der Audit haelt das ausdruecklich fest: „Die ‚Onboarding-Kuerze'+ * existiert nicht: es sind 6 Schritte."+ *+ * Was hier passiert, ist keine Umbenennung des Befundes, sondern eine+ * Unterscheidung, die im Code vorher nicht existierte: `welcome` ist ein+ * Titelbild mit einem Satz und einem Knopf, `done` eine Bestaetigung. Beides+ * sind keine Schritte, die jemand ERLEDIGT — sie stehen nur in derselben+ * Liste, weil dieselbe `step`-Variable auch den Bildschirm auswaehlt. Der+ * Fortschrittsanzeiger zaehlt ab jetzt die Arbeitsschritte:+ *+ * Windows/Linux Engine · Image & video · Model · Documents = 4+ * macOS Engine · Model · Documents = 3+ *+ * Auf dem Mac sind es damit wirklich drei. Auf Windows vier, und der+ * Anzeiger sagt es in Worten („Step 2 of 4") statt es in vier gleich grossen+ * Punkten zu verstecken. Die BILDSCHIRME sind unveraendert sechs: was hier+ * faellt, ist die Behauptung, es seien sechs Aufgaben.+ *+ * Alles hier ist rein und ohne React — deshalb pruefbar in einer Umgebung+ * ohne DOM (`vitest.config.ts`: `environment: 'node'`).+ */++export type Step = 'welcome' | 'backends' | 'comfyui' | 'models' | 'embeddings' | 'done'++/** Alle Bildschirme in ihrer Reihenfolge. Auswahlliste, kein Fortschritt. */+export const STEP_ORDER: Step[] = ['welcome', 'backends', 'comfyui', 'models', 'embeddings', 'done']++/**+ * Die Schritte, in denen der Nutzer etwas entscheidet oder installiert —+ * und ihre Beschriftung im Anzeiger. `welcome` und `done` fehlen hier mit+ * Absicht (siehe Kopf).+ */+export const WORK_STEPS: { step: Step; label: string }[] = [+ { step: 'backends', label: 'Engine' },+ { step: 'comfyui', label: 'Image & video' },+ { step: 'models', label: 'Model' },+ { step: 'embeddings', label: 'Documents' },+]++/**+ * Die Arbeitsschritte dieser Plattform. Auf macOS faellt ComfyUI weg —+ * `nextStepAfterBackends()` springt dort darueber hinweg, lokale Bild- und+ * Videoerzeugung laeuft auf Apple Silicon ausschliesslich ueber MLX.+ */+export function workStepsFor(skipComfyUI: boolean): { step: Step; label: string }[] {+ return skipComfyUI ? WORK_STEPS.filter((s) => s.step !== 'comfyui') : WORK_STEPS+}++/**+ * Was der Anzeiger ueber den aktuellen Bildschirm sagt.+ *+ * - `welcome` → `null`: das Titelbild bekommt keinen Fortschritt, weil es+ * keiner ist. (Und damit auch keine 294px Niemandsland+ * zwischen einem festgenagelten Anzeiger und dem Inhalt.)+ * - ein Arbeitsschritt → Position (1-basiert) und Gesamtzahl.+ * - `done` → alles voll, mit eigenem Text.+ */+export interface WizardProgress {+ /** 1-basierte Position, `null` auf dem Abschlussbildschirm. */+ position: number | null+ total: number+ /** Was unter den Punkten steht. */+ caption: string+ /** Wie viele Punkte gefuellt sind. */+ filled: number+}++export function wizardProgress(step: Step, skipComfyUI: boolean): WizardProgress | null {+ const steps = workStepsFor(skipComfyUI)+ const total = steps.length+ if (step === 'welcome') return null+ if (step === 'done') {+ return { position: null, total, caption: 'Setup complete', filled: total }+ }+ const at = steps.findIndex((s) => s.step === step)+ // Ein Schritt, den diese Plattform ueberspringt (comfyui auf dem Mac), darf+ // den Anzeiger nicht auf -1 setzen. Er kann hier nur ankommen, wenn jemand+ // die Weiche in nextStepAfterBackends() aendert und diese Liste vergisst;+ // dann ist „kein Anzeiger" das ehrlichere Ergebnis als eine falsche Zahl.+ if (at < 0) return null+ return {+ position: at + 1,+ total,+ caption: `Step ${at + 1} of ${total} · ${steps[at].label}`,+ filled: at + 1,+ }+}diff --git a/src/components/settings/InlineToggle.tsx b/src/components/settings/InlineToggle.tsxnew file mode 100644index 00000000..4f58c139--- /dev/null+++ b/src/components/settings/InlineToggle.tsx@@ -0,0 +1,28 @@+import type { ReactNode } from 'react'++/**+ * Der Zeilenschalter der Einstellungen. Er stand als lokale Funktion in+ * `SettingsPage.tsx` und wird jetzt von zwei Dateien gebraucht — der+ * ausgezogene Abschnitt `SpeechSettings.tsx` benutzt ihn viermal. Ein+ * Import zurueck in `SettingsPage.tsx` waere ein Zyklus gewesen, eine+ * zweite Kopie waere die naechste Divergenz. Also hierhin, einmal.+ */+export function InlineToggle({ label, enabled, onChange, icon }: { label: string; enabled: boolean; onChange: () => void; icon?: ReactNode }) {+ return (+ <div className="flex items-center justify-between py-0.5">+ <div className="flex items-center gap-1.5">+ {icon}+ <span className="text-[0.7rem] text-gray-700 dark:text-gray-400">{label}</span>+ </div>+ <button+ onClick={onChange}+ role="switch"+ aria-checked={enabled}+ aria-label={label}+ className={`relative w-7 h-3.5 rounded-full transition-colors ${enabled ? 'bg-green-500' : 'bg-gray-300 dark:bg-gray-700'}`}+ >+ <span className={`absolute top-0.5 left-0.5 w-2.5 h-2.5 rounded-full bg-white transition-transform ${enabled ? 'translate-x-3.5' : ''}`} />+ </button>+ </div>+ )+}diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 434756b2..19f518fb 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -1,48 +1,24 @@-import { useState, useEffect, useCallback, useRef, type ReactNode, type ChangeEvent } from 'react'+import { useState, useEffect, 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 { ArrowLeft, RotateCcw, Sun, Moon, Check, Loader2, Shield, ChevronRight, GraduationCap, Lock, Sliders, Plug, Bot, Phone, User, Download, AlertTriangle } 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 { sectionAnchorId, sectionsFor, type SettingsSectionFlags } from './settings-nav'import { useSettingsStore } from '../../stores/settingsStore'import { usePermissionStore } from '../../stores/permissionStore'import { useUIStore } from '../../stores/uiStore'import { SliderControl } from './SliderControl'+import { InlineToggle } from './InlineToggle'+import { SpeechSettings } from './SpeechSettings'import { LogFileSettings } from './LogFileSettings'import { PersonaPanel } from '../personas/PersonaPanel'import { AccountPanel } from '../auth/AccountPanel'import { useVoiceStore } from '../../stores/voiceStore'-import { checkWhisperAvailable, checkTtsAvailable, downloadPiperVoice, listInstalledPiperVoices } from '../../api/voice'import { downloadSuffix } from '../../lib/formatters'-// Curated local neural (Piper) voices the user can pick. Selecting one not yet-// on disk downloads it (~63 MB). Ids match rhasspy/piper-voices.-const PIPER_VOICES: { id: string; label: string }[] = [- { id: 'en_US-lessac-medium', label: 'Lessac, US, neutral' },- { id: 'en_US-amy-medium', label: 'Amy, US, female' },- { id: 'en_US-ryan-high', label: 'Ryan, US, male (high)' },- { id: 'en_US-hfc_female-medium', label: 'HFC, US, female' },- { id: 'en_GB-alba-medium', label: 'Alba, UK, female' },- { id: 'en_GB-northern_english_male-medium', label: 'Northern, UK, male' },-]--// MiniMax Speech-02 system voices for the hosted cloud TTS. The server route-// (/api/voice/tts) forwards the id verbatim as voice_id and only validates the-// character set; default is Wise_Woman.-const CLOUD_TTS_VOICES: { id: string; label: string }[] = [- { id: 'Wise_Woman', label: 'Wise Woman, default' },- { id: 'Calm_Woman', label: 'Calm Woman' },- { id: 'Lively_Girl', label: 'Lively Girl' },- { id: 'Lovely_Girl', label: 'Lovely Girl' },- { id: 'Sweet_Girl_2', label: 'Sweet Girl' },- { id: 'Friendly_Person', label: 'Friendly Person' },- { id: 'Deep_Voice_Man', label: 'Deep Voice Man' },- { id: 'Casual_Guy', label: 'Casual Guy' },- { id: 'Patient_Man', label: 'Patient Man' },- { id: 'Determined_Man', label: 'Determined Man' },- { id: 'Elegant_Man', label: 'Elegant Man' },- { id: 'Young_Knight', label: 'Young Knight' },-]+// AS-09: PIPER_VOICES und CLOUD_TTS_VOICES sind mit dem Abschnitt, der sie+// benutzt, nach ./SpeechSettings.tsx gezogen.import { useAgentModeStore } from '../../stores/agentModeStore'import { FEATURE_FLAGS } from '../../lib/constants'import { MemorySettings } from './MemorySettings'@@ -146,12 +122,20 @@ function Section({ title, children, defaultOpen = false }: { title: string; chilconst [open, setOpen] = useState(defaultOpen)const [animating, setAnimating] = useState(false)return (- <div className="border-b border-gray-100 dark:border-white/[0.04]">+ // D-S27: `id` + `scroll-mt` machen die Sektion zum Sprungziel der Rail.+ // Der Abstand nach oben haelt den Kopf unter dem klebenden Seitenkopf.+ <div id={sectionAnchorId(title)} className="scroll-mt-16 border-b border-gray-100 dark:border-white/[0.04]"><buttononClick={() => { setOpen(!open); setAnimating(true) }}className="w-full flex items-center justify-between py-2.5 group">- <span className="text-[0.65rem] font-semibold uppercase tracking-[0.15em] text-gray-600 dark:text-gray-500 group-hover:text-gray-800 dark:group-hover:text-gray-300 transition-colors">+ {/* D-S28: zwoelfmal 11,96px/600 uppercase gray-500 war kein Rang,+ sondern zwoelfmal dieselbe Betonung — und im Dunkelmodus mit+ 3.37:1 (gray-500 #6b7280 auf #202020) unter WCAG AA. Der Kopf ist+ jetzt eine echte Ueberschrift auf der Stufe darunter: 0.82rem =+ 15,1px bei 18,4px Wurzelmass, Satzstellung statt Versalien,+ 17.74:1 hell / 13.16:1 dunkel. Den Rang traegt die Rail. */}+ <span className="text-[0.82rem] font-semibold text-gray-900 dark:text-gray-200 group-hover:text-black dark:group-hover:text-white transition-colors">{title}</span><ChevronRight size={12} className={`text-gray-400 transition-transform duration-200 ${open ? 'rotate-90' : ''}`} />@@ -211,25 +195,6 @@ function Disclosure({ label, children, defaultOpen = false }: { label: string; c)}-// ── Inline Toggle ───────────────────────────────────────────────--function InlineToggle({ label, enabled, onChange, icon }: { label: string; enabled: boolean; onChange: () => void; icon?: ReactNode }) {- return (- <div className="flex items-center justify-between py-0.5">- <div className="flex items-center gap-1.5">- {icon}- <span className="text-[0.7rem] text-gray-700 dark:text-gray-400">{label}</span>- </div>- <button- onClick={onChange}- className={`relative w-7 h-3.5 rounded-full transition-colors ${enabled ? 'bg-green-500' : 'bg-gray-300 dark:bg-gray-700'}`}- >- <span className={`absolute top-0.5 left-0.5 w-2.5 h-2.5 rounded-full bg-white transition-transform ${enabled ? 'translate-x-3.5' : ''}`} />- </button>- </div>- )-}-// ── Workflow Section (inline, manages list/builder view) ────────function WorkflowSection() {@@ -1072,25 +1037,43 @@ function ResetSection({ tab }: { tab: SettingsTab }) {}return (- <div className="pt-3 pb-6 space-y-1.5">- <div className="flex items-center gap-3">- <button- onClick={() => handleClick('section')}- className={`flex items-center gap-1.5 text-[0.65rem] transition-colors ${- armed === 'section' ? 'text-red-400 font-medium' : 'text-gray-500 hover:text-red-400'- }`}- >- <RotateCcw size={11} />- {armed === 'section' ? `Click again to reset ${tabLabel}` : `Reset ${tabLabel} to defaults`}- </button>+ <div className="pt-3 pb-6 space-y-2.5">+ {/* D-S29: die beiden Reset-Aktionen sahen gleich aus — zwei graue+ Textlinks nebeneinander, von denen einer sehr viel mehr loescht.+ Die gefaehrlichere traegt jetzt eine eigene Form (umrandete+ Gefahrfarbe statt Textlink), eine eigene Zeile und einen Satz, der+ den Unterschied benennt. Gerechnet (WCAG 2.1): red-600 #dc2626 auf+ Weiss 4.83:1, red-400 #f87171 auf #202020 5.89:1 — Text UND Kante,+ also auch 1.4.11 (3:1) fuer die Umrandung erfuellt. Vorher stand+ "Reset all settings" im Dunkelmodus auf gray-600 = 2.16:1, war also+ ausgerechnet die unlesbarere der beiden.+ Der Textlink darueber bleibt Zeile fuer Zeile so, wie er war:+ src/lib/__tests__/reset-arming-is-visible.test.ts pinnt seine+ Klassen woertlich. */}+ <button+ onClick={() => handleClick('section')}+ className={`flex items-center gap-1.5 text-[0.65rem] transition-colors ${+ armed === 'section' ? 'text-red-400 font-medium' : 'text-gray-500 hover:text-red-400'+ }`}+ >+ <RotateCcw size={11} />+ {armed === 'section' ? `Click again to reset ${tabLabel}` : `Reset ${tabLabel} to defaults`}+ </button>+ <div className="flex items-start gap-2.5"><buttononClick={() => handleClick('all')}- className={`flex items-center gap-1.5 text-[0.6rem] transition-colors ${- armed === 'all' ? 'text-red-400 font-medium' : 'text-gray-600 dark:text-gray-600 hover:text-red-400'+ className={`shrink-0 inline-flex items-center gap-1.5 px-2 py-1 rounded-md border text-[0.6rem] transition-colors ${+ armed === 'all'+ ? 'bg-red-600 border-red-600 text-white font-medium'+ : 'border-red-600 text-red-600 hover:bg-red-600/10 dark:border-red-400 dark:text-red-400 dark:hover:bg-red-400/10'}`}>+ <AlertTriangle size={11} />{armed === 'all' ? 'Click again to reset everything' : 'Reset all settings'}</button>+ <p className="text-[0.55rem] text-gray-500 dark:text-gray-400 leading-snug pt-1">+ Every tab, not just {tabLabel}.+ </p></div>{done && (<div className="flex items-center gap-1.5 text-[0.6rem] text-emerald-500">@@ -1110,22 +1093,6 @@ export function SettingsPage() {// app-managed built-in engine (same gate as the send-path self-heal).const builtinManaged = useProviderStore((s) => !!s.providers.openai?.enabled && s.providers.openai?.managed === true)const { setView } = useUIStore()- const voiceSettings = useVoiceStore()- const [whisperStatus, setWhisperStatus] = useState<{ available: boolean; backend: string | null; error?: string } | null>(null)- const [whisperLoading, setWhisperLoading] = useState(true)- // §24.9 — in-app faster-whisper install. `installing` drives the spinner;- // `whisperInstallError` shows the last failure under the badge.- const [whisperInstalling, setWhisperInstalling] = useState(false)- const [whisperInstallError, setWhisperInstallError] = useState<string | null>(null)- // Neural TTS (Piper) install state — mirrors the whisper installer.- const [ttsStatus, setTtsStatus] = useState<{ available: boolean } | null>(null)- const [ttsLoading, setTtsLoading] = useState(true)- const [ttsInstalling, setTtsInstalling] = useState(false)- const [ttsInstallError, setTtsInstallError] = useState<string | null>(null)- // Piper voice picker state.- const [installedVoices, setInstalledVoices] = useState<string[]>([])- const [voiceBusy, setVoiceBusy] = useState(false)- const [voiceError, setVoiceError] = useState<string | null>(null)// Where the navigation that opened this page wanted to land. Read ONCE, at// mount, and held for this mount's whole life: `defaultOpen` below is an// initial value, so a focus that vanished from the store on the next render@@ -1151,181 +1118,110 @@ export function SettingsPage() {}, [tab])- // 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.- setSttAvailable(!!s.available)- })- .finally(() => setWhisperLoading(false))- }, [setSttAvailable])-- const refreshTts = useCallback(() => {- setTtsLoading(true)- // 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.- setTtsAvailable(!!s.available)- })- .finally(() => setTtsLoading(false))- }, [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.- const handleInstallWhisper = async () => {- if (whisperInstalling) return- setWhisperInstallError(null)- setWhisperInstalling(true)- try {- await backendCall('install_whisper')- // Poll install status until it leaves "installing" (cap ~10 min — a- // model download on a slow link can be lengthy; pip itself is quick).- const start = Date.now()- // eslint-disable-next-line no-constant-condition- while (true) {- await new Promise((r) => setTimeout(r, 2000))- let s: { status?: string; error?: string } = {}- try {- s = await backendCall<{ status?: string; error?: string }>('install_whisper_status')- } catch { /* transient — keep polling */ }- if (s.status === 'complete') break- if (s.status === 'error') {- setWhisperInstallError(withInstallerOutput('Installing speech to text did not finish.', s.error))- break- }- if (Date.now() - start > 600_000) {- setWhisperInstallError('Install is taking unusually long, check the logs / try again.')- break- }- }- } catch (e) {- setWhisperInstallError(e instanceof Error ? e.message : String(e))- } finally {- setWhisperInstalling(false)- await refreshWhisper()- }- }-- // Install Piper neural TTS (pip + voice download) the same end-user way as- // whisper, polling install_tts_status until done, then re-checking the badge.- const handleInstallTts = async () => {- if (ttsInstalling) return- setTtsInstallError(null)- setTtsInstalling(true)- try {- await backendCall('install_tts')- const start = Date.now()- // eslint-disable-next-line no-constant-condition- while (true) {- await new Promise((r) => setTimeout(r, 2000))- let s: { status?: string; error?: string } = {}- try {- s = await backendCall<{ status?: string; error?: string }>('install_tts_status')- } catch { /* transient — keep polling */ }- if (s.status === 'complete') break- if (s.status === 'error') {- setTtsInstallError(withInstallerOutput('Installing read aloud did not finish.', s.error))- break- }- if (Date.now() - start > 600_000) {- setTtsInstallError('Install is taking unusually long, check the logs / try again.')- break- }- }- } catch (e) {- setTtsInstallError(e instanceof Error ? e.message : String(e))- } finally {- setTtsInstalling(false)- await refreshTts()- }- }-- // Pick a Piper voice. If it isn't on disk yet, download it (~63 MB), then- // re-check the installed list + TTS availability. The selection is applied- // optimistically (so the dropdown reflects the pick) but REVERTED if the- // download fails — otherwise piperVoice pointed at a missing model and every- // read fell back to the Windows SAPI voice (#77, ElBiggus).- const handlePickVoice = async (id: string) => {- setVoiceError(null)- const prev = voiceSettings.piperVoice- voiceSettings.setPiperVoice(id)- if (installedVoices.includes(id)) return- setVoiceBusy(true)- try {- await downloadPiperVoice(id)- await refreshVoices()- await refreshTts()- } catch (e) {- voiceSettings.setPiperVoice(prev)- setVoiceError(e instanceof Error ? e.message : String(e))- } finally {- setVoiceBusy(false)- }+ // D-S27: die Bedingungen, unter denen einzelne Sektionen ueberhaupt+ // erscheinen, stehen ab hier EINMAL — die Rail liest sie ueber+ // sectionsFor(), das JSX weiter unten benutzt dieselben Ausdruecke.+ const sectionFlags: SettingsSectionFlags = {+ gpuPicker: !isMlxImageHost(),+ builtinExpert: builtinManaged,+ comfyui: !isMlxImageHost(),+ agentMode: FEATURE_FLAGS.AGENT_MODE,+ agentWorkflows: FEATURE_FLAGS.AGENT_WORKFLOWS,+ mediaTimeouts: settings.appMode !== 'cloud' && !isMlxImageHost(),}return (<div className="h-full overflow-y-auto scrollbar-thin">- <div className="max-w-lg mx-auto px-4 py-4">- {/* Header */}- <div className="flex items-center gap-2 mb-4">+ {/* D-S27 / D-S48: vorher `max-w-lg mx-auto` — eine 552px-Spalte, die in+ der Fenstermitte schwebte und bei 1600px links und rechts je ~524px+ Leere stehen liess. Die Zeilenlaenge war richtig, die Aufhaengung+ nicht. Jetzt: 200px-Rail links, Inhalt linksbuendig daneben, gedeckelt+ auf 640px (Soll des Audits). Die Rail erscheint ab `lg` (1024px+ Fensterbreite); darunter bleibt die waagerechte Tab-Leiste, weil+ 200 + 640 in einem 900px-Fenster mit Sidebar nicht nebeneinander+ passen — und bei 900px sah der Screen laut Audit ohnehin besser aus+ als bei 1600px. */}+ <div className="flex gap-6 px-4 py-4 lg:px-8">+ <nav+ aria-label="Settings sections"+ className="hidden lg:flex w-[200px] shrink-0 flex-col gap-4 sticky top-4 self-start max-h-[calc(100vh-6rem)] overflow-y-auto scrollbar-thin"+ >+ <div className="flex items-center gap-2">+ <button onClick={() => setView('chat')} className="p-1 rounded hover:bg-gray-200 dark:hover:bg-white/5 text-gray-500 hover:text-gray-900 dark:hover:text-white transition-colors" aria-label="Back to chat">+ <ArrowLeft size={16} />+ </button>+ {/* D-S28: die Spitze der Leiter. 1.15rem = 21,2px bei 18,4px+ Wurzelmass — eine Stufe der 12/13/15/17/21/28-Skala des+ Audits, und endlich groesser als ein Sektionskopf. */}+ <h1 className="text-[1.15rem] font-semibold leading-tight text-gray-900 dark:text-gray-100">Settings</h1>+ </div>++ <div className="flex flex-col gap-0.5">+ {SETTINGS_TABS.map(t => (+ <div key={t.id}>+ {/* D-S30: Zustand und Aktion trugen dieselbe Flaeche+ (`bg-gray-200 dark:bg-white/10` hier wie am Upload-Knopf).+ Der ausgewaehlte Tab spricht jetzt die Zustandssprache:+ Akzentflaeche + Akzentkante links. Aktionen behalten die+ neutrale graue Flaeche. Gerechnet: die Kante+ #8b7cf0 auf Weiss 3.37:1 und #a094f8 auf #202020 6.27:1 —+ beide ueber den 3:1 aus WCAG 1.4.11 fuer Nicht-Text. */}+ <button+ onClick={() => setTab(t.id)}+ aria-current={tab === t.id ? 'page' : undefined}+ className={`w-full inline-flex items-center gap-1.5 pl-2 pr-2.5 py-1.5 rounded-md text-[0.7rem] font-medium border-l-2 transition-colors ${+ tab === t.id+ ? 'bg-lu-accent-soft border-l-lu-accent-edge dark:border-l-lu-accent text-gray-900 dark:text-white'+ : 'border-l-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/[0.04]'+ }`}+ >+ {t.icon}+ {t.label}+ </button>+ {tab === t.id && (+ <ul className="mt-1 mb-1 ml-[0.6rem] border-l border-gray-200 dark:border-white/[0.08]">+ {sectionsFor(t.id, sectionFlags).map(title => (+ <li key={title}>+ <a+ href={`#${sectionAnchorId(title)}`}+ className="block pl-3 pr-1 py-[3px] text-[0.62rem] leading-snug text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"+ >+ {title}+ </a>+ </li>+ ))}+ </ul>+ )}+ </div>+ ))}+ </div>+ </nav>++ <div className="min-w-0 w-full max-w-[640px]">+ {/* Header — nur unterhalb von `lg`; ab da traegt die Rail Titel und+ Zurueck-Knopf. */}+ <div className="lg:hidden flex items-center gap-2 mb-4"><button onClick={() => setView('chat')} className="p-1 rounded hover:bg-gray-200 dark:hover:bg-white/5 text-gray-500 hover:text-gray-900 dark:hover:text-white transition-colors"><ArrowLeft size={16} /></button>- <h1 className="text-[0.8rem] font-semibold text-gray-800 dark:text-gray-200">Settings</h1>+ <h1 className="text-[1.15rem] font-semibold leading-tight text-gray-900 dark:text-gray-100">Settings</h1></div>{/* P5: top-level tabs. Sticky so the user can switch tabs from- anywhere in a long Section without scrolling back up. */}- <div className="sticky top-0 z-10 -mx-4 px-4 pb-2 mb-2 bg-white/80 dark:bg-[#202020]/80 backdrop-blur supports-[backdrop-filter]:bg-white/60 dark:supports-[backdrop-filter]:bg-[#202020]/60 border-b border-gray-100 dark:border-white/[0.06]">+ anywhere in a long Section without scrolling back up. Ab `lg`+ uebernimmt die Rail diese Aufgabe — zwei gleichzeitig sichtbare+ Navigationen fuer dieselbe Sache waeren genau der Befund, den+ D-S27 beschreibt. */}+ <div className="lg:hidden sticky top-0 z-10 -mx-4 px-4 pb-2 mb-2 bg-white/80 dark:bg-[#202020]/80 backdrop-blur supports-[backdrop-filter]:bg-white/60 dark:supports-[backdrop-filter]:bg-[#202020]/60 border-b border-gray-100 dark:border-white/[0.06]"><div className="flex items-center gap-1 overflow-x-auto scrollbar-thin">{SETTINGS_TABS.map(t => (<buttonkey={t.id}onClick={() => setTab(t.id)}+ aria-current={tab === t.id ? 'page' : undefined}className={`shrink-0 inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-[0.65rem] font-medium transition-colors ${tab === t.id- ? 'bg-gray-200 dark:bg-white/10 text-gray-900 dark:text-white'+ ? 'bg-lu-accent-soft ring-1 ring-lu-accent-edge dark:ring-lu-accent text-gray-900 dark:text-white': 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/[0.04]'}`}>@@ -1383,13 +1279,19 @@ export function SettingsPage() {</button></Section><Section title="Appearance">+ {/* D-S30, zweite Haelfte des Befundes: „Dark" (ein ZUSTAND) und+ „Upload" in AvatarSetting (eine AKTION) trugen beide+ `bg-gray-200 dark:bg-white/10`. Zustand spricht ab hier+ ueberall dieselbe Sprache wie der aktive Tab — Akzentflaeche+ mit Akzentkante — und die neutrale graue Flaeche bleibt den+ Aktionen. */}<div className="flex items-center justify-between"><span className="text-[0.7rem] text-gray-700 dark:text-gray-400">Theme</span><div className="flex gap-1"><buttononClick={() => updateSettings({ theme: 'light' })}className={`flex items-center gap-1 px-2 py-1 rounded text-[0.65rem] transition-colors ${- settings.theme === 'light' ? 'bg-gray-200 dark:bg-white/10 text-gray-900 dark:text-white' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'+ settings.theme === 'light' ? 'bg-lu-accent-soft ring-1 ring-lu-accent-edge dark:ring-lu-accent text-gray-900 dark:text-white' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}`}><Sun size={11} /> Light@@ -1397,7 +1299,7 @@ export function SettingsPage() {<buttononClick={() => updateSettings({ theme: 'dark' })}className={`flex items-center gap-1 px-2 py-1 rounded text-[0.65rem] transition-colors ${- settings.theme === 'dark' ? 'bg-gray-200 dark:bg-white/10 text-gray-900 dark:text-white' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'+ settings.theme === 'dark' ? 'bg-lu-accent-soft ring-1 ring-lu-accent-edge dark:ring-lu-accent text-gray-900 dark:text-white' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}`}><Moon size={11} /> Dark@@ -1718,178 +1620,7 @@ export function SettingsPage() {{/* ── Voice & Remote tab ────────────────────────── */}{tab === 'voice-remote' && (<><Section title="Speech" defaultOpen>- {settings.appMode === 'cloud' ? (<>- {/* Cloud mode: dictation + read-aloud are hosted on lu-labs.ai —- honest copy (audio leaves the machine, metered), no local- install buttons, and a picker for the hosted MiniMax voice. */}- <p className="text-[0.55rem] text-gray-500 leading-snug">- Cloud mode: dictation and read-aloud run on lu-labs.ai (hosted Whisper speech-to-text + MiniMax text-to-speech) and are metered against your credits. No local installs needed.- </p>- <InlineToggle label="Enable read-aloud" enabled={voiceSettings.ttsEnabled} onChange={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })} icon={<Volume2 size={11} className="text-gray-500" />} />- {voiceSettings.ttsEnabled && (- <InlineToggle label="Auto-read new responses" enabled={voiceSettings.autoReadAloud} onChange={() => voiceSettings.updateVoiceSettings({ autoReadAloud: !voiceSettings.autoReadAloud })} icon={<Volume2 size={11} className="text-gray-500" />} />- )}- <div className="flex items-center justify-between gap-2">- <span className="text-[0.7rem] text-gray-500">Voice</span>- <select- value={voiceSettings.cloudTtsVoice}- onChange={(e) => voiceSettings.updateVoiceSettings({ cloudTtsVoice: e.target.value })}- className="max-w-[210px] px-1.5 py-0.5 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 focus:outline-none"- >- {CLOUD_TTS_VOICES.map((v) => (- <option key={v.id} value={v.id}>{v.label}</option>- ))}- </select>- </div>- </>) : (<>- <p className="text-[0.55rem] text-gray-500 leading-snug">- Voice runs 100% locally, no cloud. Each engine is a one-time local install.- </p>-- {/* Speech-to-Text — faster-whisper (powers the microphone / dictation) */}- <div className="flex items-center gap-2 text-[0.65rem]">- <span className="flex items-center gap-1.5">- {whisperLoading- ? <Loader2 size={11} className="animate-spin text-gray-500" />- : whisperStatus?.available ? <Check size={11} className="text-green-500" /> : <X size={11} className="text-red-500" />}- <Mic size={11} className="text-gray-400" />- <span className="text-gray-700 dark:text-gray-200 font-medium">Speech-to-Text</span>- <span className="text-gray-500">faster-whisper</span>- </span>- {!whisperLoading && whisperStatus && !whisperStatus.available && (- <button- onClick={() => void handleInstallWhisper()}- disabled={whisperInstalling}- className="ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded text-[0.6rem] font-medium bg-blue-500/15 text-blue-400 border border-blue-500/30 hover:bg-blue-500/25 transition-colors disabled:opacity-50"- title="Download + install faster-whisper so the microphone works"- >- {whisperInstalling ? <Loader2 size={9} className="animate-spin" /> : <Download size={9} />}- {whisperInstalling ? 'Installing…' : 'Download & Install'}- </button>- )}- </div>- {whisperInstallError && (- <p className="text-[0.55rem] text-red-400/90 leading-snug">{whisperInstallError}</p>- )}- {!whisperLoading && whisperStatus && !whisperStatus.available && !whisperInstalling && !whisperInstallError && (- <p className="text-[0.55rem] text-gray-500 leading-snug">- Required for the microphone. Installs faster-whisper into LU's Python; first run also downloads a small model.- </p>- )}-- {/* Text-to-Speech, Piper neural (read responses aloud) */}- <div className="flex items-center gap-2 text-[0.65rem] pt-1">- <span className="flex items-center gap-1.5">- {ttsLoading- ? <Loader2 size={11} className="animate-spin text-gray-500" />- : ttsStatus?.available ? <Check size={11} className="text-green-500" /> : <X size={11} className="text-red-500" />}- <Volume2 size={11} className="text-gray-400" />- <span className="text-gray-700 dark:text-gray-200 font-medium">Text-to-Speech</span>- <span className="text-gray-500">Piper neural</span>- </span>- {!ttsLoading && ttsStatus && !ttsStatus.available && (- <button- onClick={() => void handleInstallTts()}- disabled={ttsInstalling}- className="ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded text-[0.6rem] font-medium bg-blue-500/15 text-blue-400 border border-blue-500/30 hover:bg-blue-500/25 transition-colors disabled:opacity-50"- title="Download + install Piper neural TTS + a voice (~63 MB)"- >- {ttsInstalling ? <Loader2 size={9} className="animate-spin" /> : <Download size={9} />}- {ttsInstalling ? 'Installing…' : 'Download & Install'}- </button>- )}- </div>- {ttsInstallError && (- <p className="text-[0.55rem] text-red-400/90 leading-snug">{ttsInstallError}</p>- )}- {/* #77: read-aloud silently fell back to the system voice while this- row showed a healthy green check — surface the recorded reason. */}- {voiceSettings.ttsMode === 'piper' && voiceSettings.ttsFallbackReason && (- <p className="text-[0.55rem] text-amber-400/90 leading-snug">- {voiceSettings.ttsFallbackReason} If an antivirus quarantined Piper, whitelist it or reinstall the voice below.- </p>- )}- {!ttsLoading && ttsStatus && !ttsStatus.available && !ttsInstalling && !ttsInstallError && (- <p className="text-[0.55rem] text-gray-500 leading-snug">- Required for read-aloud. Installs Piper + a neural voice locally (~63 MB).- </p>- )}-- <InlineToggle label="Enable read-aloud" enabled={voiceSettings.ttsEnabled} onChange={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })} icon={<Volume2 size={11} className="text-gray-500" />} />- {/* Auto-read is a SEPARATE opt-in (default OFF). The toggle above only- surfaces the per-message Speaker button; this one also reads each- finished response aloud (#77, ElBiggus, the old single toggle was- labelled "Read responses aloud" but never auto-read). */}- {voiceSettings.ttsEnabled && (- <InlineToggle label="Auto-read new responses" enabled={voiceSettings.autoReadAloud} onChange={() => voiceSettings.updateVoiceSettings({ autoReadAloud: !voiceSettings.autoReadAloud })} icon={<Volume2 size={11} className="text-gray-500" />} />- )}- {/* Neural voice picker (Piper), replaces the old Microsoft/browser- voices (David 2026-06-06). Picking one not yet on disk downloads- it (~63 MB). Browser-only rate/pitch knobs dropped, they didn't- apply to Piper. */}- <div className="flex items-center justify-between gap-2">- <span className="text-[0.7rem] text-gray-500 flex items-center gap-1">- Voice {voiceBusy && <Loader2 size={10} className="animate-spin text-gray-500" />}- </span>- <select- value={voiceSettings.piperVoice}- onChange={(e) => void handlePickVoice(e.target.value)}- disabled={voiceBusy}- className="max-w-[210px] px-1.5 py-0.5 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 focus:outline-none disabled:opacity-50"- >- {PIPER_VOICES.map((v) => (- <option key={v.id} value={v.id}>- {v.label}{installedVoices.includes(v.id) ? '' : ', download'}- </option>- ))}- </select>- </div>- {voiceBusy && <p className="text-[0.55rem] text-gray-500 leading-snug">Downloading voice (~63 MB)…</p>}- {voiceError && <p className="text-[0.55rem] text-red-400/90 leading-snug">{voiceError}</p>}-- {/* TTS engine — bundled Piper, or an external OpenAI-compatible HTTP- endpoint like Kokoro-FastAPI (GitHub #58). */}- <div className="flex items-center justify-between gap-2 pt-1">- <span className="text-[0.7rem] text-gray-500">Engine</span>- <div className="flex items-center gap-1 text-[0.6rem]">- {(['piper', 'external'] as const).map((m) => (- <button- key={m}- onClick={() => voiceSettings.updateVoiceSettings({ ttsMode: m })}- className={- 'px-2 py-0.5 rounded border transition-colors ' +- (voiceSettings.ttsMode === m- ? 'bg-gray-200 dark:bg-white/15 text-gray-900 dark:text-white border-gray-300 dark:border-white/20'- : 'text-gray-500 border-white/8 hover:text-gray-300')- }- >- {m === 'piper' ? 'Piper neural' : 'External HTTP'}- </button>- ))}- </div>- </div>- {voiceSettings.ttsMode === 'external' && (- <div className="space-y-1.5">- <input- value={voiceSettings.externalTtsUrl}- onChange={(e) => voiceSettings.updateVoiceSettings({ externalTtsUrl: e.target.value })}- placeholder="http://localhost:8880/v1/audio/speech"- spellCheck={false}- className="w-full px-2 py-1 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none focus:border-white/20"- />- <input- value={voiceSettings.externalTtsVoice}- onChange={(e) => voiceSettings.updateVoiceSettings({ externalTtsVoice: e.target.value })}- placeholder="voice name (e.g. af_bella, alloy)"- spellCheck={false}- className="w-full px-2 py-1 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none focus:border-white/20"- />- <p className="text-[0.55rem] text-gray-500 leading-snug">- Any OpenAI-compatible TTS endpoint (e.g. Kokoro-FastAPI). Used for read-aloud instead of Piper. Stays on your machine when the endpoint is local.- </p>- </div>- )}- </>)}+ <SpeechSettings /></Section><Section title="Remote Access">@@ -1904,6 +1635,7 @@ export function SettingsPage() {{/* ── Reset (GitHub #59: per-tab scope + confirm + feedback) ── */}<ResetSection tab={tab} />+ </div></div></div>)diff --git a/src/components/settings/SpeechSettings.tsx b/src/components/settings/SpeechSettings.tsxnew file mode 100644index 00000000..80269981--- /dev/null+++ b/src/components/settings/SpeechSettings.tsx@@ -0,0 +1,415 @@+import { useCallback, useEffect, useReducer, useState } from 'react'+import { Check, Download, Loader2, Mic, Volume2, X } from 'lucide-react'+import { withInstallerOutput } from '../../lib/error-text'+import { backendCall } from '../../api/backend'+import { useSettingsStore } from '../../stores/settingsStore'+import { useVoiceStore } from '../../stores/voiceStore'+import { checkWhisperAvailable, checkTtsAvailable, downloadPiperVoice, listInstalledPiperVoices } from '../../api/voice'+import { InlineToggle } from './InlineToggle'+import { initialProbe, makeProbeReducer, needsInstall, showsHint } from './probe-install'++/**+ * Der Abschnitt „Speech" der Einstellungen — Diktat (faster-whisper) und+ * Vorlesen (Piper), inklusive ihrer In-App-Installer.+ *+ * ── Warum diese Datei existiert (AS-09) ───────────────────────────────────+ *+ * Elf der dreizehn `useState` von `SettingsPage()` gehoerten diesem einen+ * Abschnitt, dazu drei `useCallback`, ein Mount-Effekt und drei Handler.+ * Zwei Dinge sind dabei schiefgelaufen, und beide werden hier geradegezogen:+ *+ * 1. Acht der elf waren ZWEIMAL DASSELBE — Probe, Ladeflagge,+ * Installationsflagge, Installationsfehler, einmal fuer STT und einmal+ * fuer TTS. Das steht jetzt in ./probe-install.ts, einmal.+ *+ * 2. Die drei Proben liefen im Mount-Effekt der SEITE. Wer die+ * Einstellungen auf „General" oeffnete, loeste drei Backend-Aufrufe fuer+ * einen Abschnitt aus, der gar nicht gerendert wurde. Als eigene+ * Komponente laeuft der Abschnitt, wenn er da ist — der Tab-Wechsel+ * montiert und demontiert ihn.+ *+ * Was NICHT verlorengeht: die Proben schreiben weiterhin `sttAvailable` /+ * `ttsAvailable` in den Voice-Store, damit Mikrofon- und Vorlesen-Knopf nach+ * einer In-App-Installation ohne Neustart aufwachen. Der Erststart probt+ * ohnehin schon in `App.tsx` — die Probe hier ist die Auffrischung nach der+ * Installation, und die passiert genau in diesem Abschnitt.+ */++interface WhisperProbe { available: boolean; backend: string | null; error?: string }+interface TtsProbe { available: boolean }++const whisperReducer = makeProbeReducer<WhisperProbe>()+const ttsReducer = makeProbeReducer<TtsProbe>()++// MiniMax Speech-02 system voices for the hosted cloud TTS. The server route+// (/api/voice/tts) forwards the id verbatim as voice_id and only validates the+// character set; default is Wise_Woman.+const CLOUD_TTS_VOICES: { id: string; label: string }[] = [+ { id: 'Wise_Woman', label: 'Wise Woman, default' },+ { id: 'Calm_Woman', label: 'Calm Woman' },+ { id: 'Lively_Girl', label: 'Lively Girl' },+ { id: 'Lovely_Girl', label: 'Lovely Girl' },+ { id: 'Sweet_Girl_2', label: 'Sweet Girl' },+ { id: 'Friendly_Person', label: 'Friendly Person' },+ { id: 'Deep_Voice_Man', label: 'Deep Voice Man' },+ { id: 'Casual_Guy', label: 'Casual Guy' },+ { id: 'Patient_Man', label: 'Patient Man' },+ { id: 'Determined_Man', label: 'Determined Man' },+ { id: 'Elegant_Man', label: 'Elegant Man' },+ { id: 'Young_Knight', label: 'Young Knight' },+]++// Curated local neural (Piper) voices the user can pick. Selecting one not yet+// on disk downloads it (~63 MB). Ids match rhasspy/piper-voices.+const PIPER_VOICES: { id: string; label: string }[] = [+ { id: 'en_US-lessac-medium', label: 'Lessac, US, neutral' },+ { id: 'en_US-amy-medium', label: 'Amy, US, female' },+ { id: 'en_US-ryan-high', label: 'Ryan, US, male (high)' },+ { id: 'en_US-hfc_female-medium', label: 'HFC, US, female' },+ { id: 'en_GB-alba-medium', label: 'Alba, UK, female' },+ { id: 'en_GB-northern_english_male-medium', label: 'Northern, UK, male' },+]++export function SpeechSettings() {+ const appMode = useSettingsStore((s) => s.settings.appMode)+ const voiceSettings = useVoiceStore()++ const [whisper, whisperDo] = useReducer(whisperReducer, initialProbe<WhisperProbe>())+ const [tts, ttsDo] = useReducer(ttsReducer, initialProbe<TtsProbe>())+ const [installedVoices, setInstalledVoices] = useState<string[]>([])+ const [voiceBusy, setVoiceBusy] = useState(false)+ const [voiceError, setVoiceError] = useState<string | null>(null)++ // 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(() => {+ whisperDo({ type: 'probing' })+ return checkWhisperAvailable()+ .then((s) => {+ whisperDo({ type: 'probed', probe: s })+ // Drive the mic button's availability from the same probe so it lights+ // up immediately after the in-app install — no restart needed.+ setSttAvailable(!!s.available)+ })+ .catch(() => whisperDo({ type: 'probeFailed' }))+ }, [setSttAvailable])++ const refreshTts = useCallback(() => {+ ttsDo({ type: 'probing' })+ // 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) => {+ ttsDo({ type: 'probed', probe: s })+ // Same as STT: drive the read-aloud button availability from this probe+ // so it lights up right after the in-app install.+ setTtsAvailable(!!s.available)+ })+ .catch(() => ttsDo({ type: 'probeFailed' }))+ }, [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.+ const handleInstallWhisper = async () => {+ if (whisper.installing) return+ whisperDo({ type: 'installStart' })+ try {+ await backendCall('install_whisper')+ // Poll install status until it leaves "installing" (cap ~10 min — a+ // model download on a slow link can be lengthy; pip itself is quick).+ const start = Date.now()+ // eslint-disable-next-line no-constant-condition+ while (true) {+ await new Promise((r) => setTimeout(r, 2000))+ let s: { status?: string; error?: string } = {}+ try {+ s = await backendCall<{ status?: string; error?: string }>('install_whisper_status')+ } catch { /* transient — keep polling */ }+ if (s.status === 'complete') break+ if (s.status === 'error') {+ whisperDo({ type: 'installFailed', error: withInstallerOutput('Installing speech to text did not finish.', s.error) })+ break+ }+ if (Date.now() - start > 600_000) {+ whisperDo({ type: 'installFailed', error: 'Install is taking unusually long, check the logs / try again.' })+ break+ }+ }+ } catch (e) {+ whisperDo({ type: 'installFailed', error: e instanceof Error ? e.message : String(e) })+ } finally {+ whisperDo({ type: 'installDone' })+ await refreshWhisper()+ }+ }++ // Install Piper neural TTS (pip + voice download) the same end-user way as+ // whisper, polling install_tts_status until done, then re-checking the badge.+ const handleInstallTts = async () => {+ if (tts.installing) return+ ttsDo({ type: 'installStart' })+ try {+ await backendCall('install_tts')+ const start = Date.now()+ // eslint-disable-next-line no-constant-condition+ while (true) {+ await new Promise((r) => setTimeout(r, 2000))+ let s: { status?: string; error?: string } = {}+ try {+ s = await backendCall<{ status?: string; error?: string }>('install_tts_status')+ } catch { /* transient — keep polling */ }+ if (s.status === 'complete') break+ if (s.status === 'error') {+ ttsDo({ type: 'installFailed', error: withInstallerOutput('Installing read aloud did not finish.', s.error) })+ break+ }+ if (Date.now() - start > 600_000) {+ ttsDo({ type: 'installFailed', error: 'Install is taking unusually long, check the logs / try again.' })+ break+ }+ }+ } catch (e) {+ ttsDo({ type: 'installFailed', error: e instanceof Error ? e.message : String(e) })+ } finally {+ ttsDo({ type: 'installDone' })+ await refreshTts()+ }+ }++ // Pick a Piper voice. If it isn't on disk yet, download it (~63 MB), then+ // re-check the installed list + TTS availability. The selection is applied+ // optimistically (so the dropdown reflects the pick) but REVERTED if the+ // download fails — otherwise piperVoice pointed at a missing model and every+ // read fell back to the Windows SAPI voice (#77, ElBiggus).+ const handlePickVoice = async (id: string) => {+ setVoiceError(null)+ const prev = voiceSettings.piperVoice+ voiceSettings.setPiperVoice(id)+ if (installedVoices.includes(id)) return+ setVoiceBusy(true)+ try {+ await downloadPiperVoice(id)+ await refreshVoices()+ await refreshTts()+ } catch (e) {+ voiceSettings.setPiperVoice(prev)+ setVoiceError(e instanceof Error ? e.message : String(e))+ } finally {+ setVoiceBusy(false)+ }+ }++ if (appMode === 'cloud') {+ return (<>+ {/* Cloud mode: dictation + read-aloud are hosted on lu-labs.ai —+ honest copy (audio leaves the machine, metered), no local+ install buttons, and a picker for the hosted MiniMax voice. */}+ <p className="text-[0.55rem] text-gray-500 leading-snug">+ Cloud mode: dictation and read-aloud run on lu-labs.ai (hosted Whisper speech-to-text + MiniMax text-to-speech) and are metered against your credits. No local installs needed.+ </p>+ <InlineToggle label="Enable read-aloud" enabled={voiceSettings.ttsEnabled} onChange={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })} icon={<Volume2 size={11} className="text-gray-500" />} />+ {voiceSettings.ttsEnabled && (+ <InlineToggle label="Auto-read new responses" enabled={voiceSettings.autoReadAloud} onChange={() => voiceSettings.updateVoiceSettings({ autoReadAloud: !voiceSettings.autoReadAloud })} icon={<Volume2 size={11} className="text-gray-500" />} />+ )}+ <div className="flex items-center justify-between gap-2">+ <span className="text-[0.7rem] text-gray-500">Voice</span>+ <select+ value={voiceSettings.cloudTtsVoice}+ onChange={(e) => voiceSettings.updateVoiceSettings({ cloudTtsVoice: e.target.value })}+ className="max-w-[210px] px-1.5 py-0.5 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 focus:outline-none"+ >+ {CLOUD_TTS_VOICES.map((v) => (+ <option key={v.id} value={v.id}>{v.label}</option>+ ))}+ </select>+ </div>+ </>)+ }++ return (<>+ <p className="text-[0.55rem] text-gray-500 leading-snug">+ Voice runs 100% locally, no cloud. Each engine is a one-time local install.+ </p>++ {/* Speech-to-Text — faster-whisper (powers the microphone / dictation) */}+ <div className="flex items-center gap-2 text-[0.65rem]">+ <span className="flex items-center gap-1.5">+ {whisper.loading+ ? <Loader2 size={11} className="animate-spin text-gray-500" />+ : whisper.probe?.available ? <Check size={11} className="text-green-500" /> : <X size={11} className="text-red-500" />}+ <Mic size={11} className="text-gray-400" />+ <span className="text-gray-700 dark:text-gray-200 font-medium">Speech-to-Text</span>+ <span className="text-gray-500">faster-whisper</span>+ </span>+ {needsInstall(whisper) && (+ <button+ onClick={() => void handleInstallWhisper()}+ disabled={whisper.installing}+ className="ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded text-[0.6rem] font-medium bg-blue-500/15 text-blue-400 border border-blue-500/30 hover:bg-blue-500/25 transition-colors disabled:opacity-50"+ title="Download + install faster-whisper so the microphone works"+ >+ {whisper.installing ? <Loader2 size={9} className="animate-spin" /> : <Download size={9} />}+ {whisper.installing ? 'Installing…' : 'Download & Install'}+ </button>+ )}+ </div>+ {whisper.installError && (+ <p className="text-[0.55rem] text-red-400/90 leading-snug">{whisper.installError}</p>+ )}+ {showsHint(whisper) && (+ <p className="text-[0.55rem] text-gray-500 leading-snug">+ Required for the microphone. Installs faster-whisper into LU's Python; first run also downloads a small model.+ </p>+ )}++ {/* Text-to-Speech, Piper neural (read responses aloud) */}+ <div className="flex items-center gap-2 text-[0.65rem] pt-1">+ <span className="flex items-center gap-1.5">+ {tts.loading+ ? <Loader2 size={11} className="animate-spin text-gray-500" />+ : tts.probe?.available ? <Check size={11} className="text-green-500" /> : <X size={11} className="text-red-500" />}+ <Volume2 size={11} className="text-gray-400" />+ <span className="text-gray-700 dark:text-gray-200 font-medium">Text-to-Speech</span>+ <span className="text-gray-500">Piper neural</span>+ </span>+ {needsInstall(tts) && (+ <button+ onClick={() => void handleInstallTts()}+ disabled={tts.installing}+ className="ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded text-[0.6rem] font-medium bg-blue-500/15 text-blue-400 border border-blue-500/30 hover:bg-blue-500/25 transition-colors disabled:opacity-50"+ title="Download + install Piper neural TTS + a voice (~63 MB)"+ >+ {tts.installing ? <Loader2 size={9} className="animate-spin" /> : <Download size={9} />}+ {tts.installing ? 'Installing…' : 'Download & Install'}+ </button>+ )}+ </div>+ {tts.installError && (+ <p className="text-[0.55rem] text-red-400/90 leading-snug">{tts.installError}</p>+ )}+ {/* #77: read-aloud silently fell back to the system voice while this+ row showed a healthy green check — surface the recorded reason. */}+ {voiceSettings.ttsMode === 'piper' && voiceSettings.ttsFallbackReason && (+ <p className="text-[0.55rem] text-amber-400/90 leading-snug">+ {voiceSettings.ttsFallbackReason} If an antivirus quarantined Piper, whitelist it or reinstall the voice below.+ </p>+ )}+ {showsHint(tts) && (+ <p className="text-[0.55rem] text-gray-500 leading-snug">+ Required for read-aloud. Installs Piper + a neural voice locally (~63 MB).+ </p>+ )}++ <InlineToggle label="Enable read-aloud" enabled={voiceSettings.ttsEnabled} onChange={() => voiceSettings.updateVoiceSettings({ ttsEnabled: !voiceSettings.ttsEnabled })} icon={<Volume2 size={11} className="text-gray-500" />} />+ {/* Auto-read is a SEPARATE opt-in (default OFF). The toggle above only+ surfaces the per-message Speaker button; this one also reads each+ finished response aloud (#77, ElBiggus, the old single toggle was+ labelled "Read responses aloud" but never auto-read). */}+ {voiceSettings.ttsEnabled && (+ <InlineToggle label="Auto-read new responses" enabled={voiceSettings.autoReadAloud} onChange={() => voiceSettings.updateVoiceSettings({ autoReadAloud: !voiceSettings.autoReadAloud })} icon={<Volume2 size={11} className="text-gray-500" />} />+ )}+ {/* Neural voice picker (Piper), replaces the old Microsoft/browser+ voices (David 2026-06-06). Picking one not yet on disk downloads+ it (~63 MB). Browser-only rate/pitch knobs dropped, they didn't+ apply to Piper. */}+ <div className="flex items-center justify-between gap-2">+ <span className="text-[0.7rem] text-gray-500 flex items-center gap-1">+ Voice {voiceBusy && <Loader2 size={10} className="animate-spin text-gray-500" />}+ </span>+ <select+ value={voiceSettings.piperVoice}+ onChange={(e) => void handlePickVoice(e.target.value)}+ disabled={voiceBusy}+ className="max-w-[210px] px-1.5 py-0.5 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 focus:outline-none disabled:opacity-50"+ >+ {PIPER_VOICES.map((v) => (+ <option key={v.id} value={v.id}>+ {v.label}{installedVoices.includes(v.id) ? '' : ', download'}+ </option>+ ))}+ </select>+ </div>+ {voiceBusy && <p className="text-[0.55rem] text-gray-500 leading-snug">Downloading voice (~63 MB)…</p>}+ {voiceError && <p className="text-[0.55rem] text-red-400/90 leading-snug">{voiceError}</p>}++ {/* TTS engine — bundled Piper, or an external OpenAI-compatible HTTP+ endpoint like Kokoro-FastAPI (GitHub #58). */}+ <div className="flex items-center justify-between gap-2 pt-1">+ <span className="text-[0.7rem] text-gray-500">Engine</span>+ <div className="flex items-center gap-1 text-[0.6rem]">+ {(['piper', 'external'] as const).map((m) => (+ <button+ key={m}+ onClick={() => voiceSettings.updateVoiceSettings({ ttsMode: m })}+ aria-pressed={voiceSettings.ttsMode === m}+ className={+ // D-S30: der gewaehlte Motor ist ein ZUSTAND und trug bisher+ // dieselbe graue Flaeche wie jede Aktion auf dem Bildschirm.+ // Dieselbe Akzentsprache wie der aktive Tab und der gewaehlte+ // Theme-Knopf.+ 'px-2 py-0.5 rounded border transition-colors ' ++ (voiceSettings.ttsMode === m+ ? 'bg-lu-accent-soft text-gray-900 dark:text-white border-lu-accent-edge dark:border-lu-accent'+ : 'text-gray-500 border-white/8 hover:text-gray-300')+ }+ >+ {m === 'piper' ? 'Piper neural' : 'External HTTP'}+ </button>+ ))}+ </div>+ </div>+ {voiceSettings.ttsMode === 'external' && (+ <div className="space-y-1.5">+ <input+ value={voiceSettings.externalTtsUrl}+ onChange={(e) => voiceSettings.updateVoiceSettings({ externalTtsUrl: e.target.value })}+ placeholder="http://localhost:8880/v1/audio/speech"+ spellCheck={false}+ className="w-full px-2 py-1 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none focus:border-white/20"+ />+ <input+ value={voiceSettings.externalTtsVoice}+ onChange={(e) => voiceSettings.updateVoiceSettings({ externalTtsVoice: e.target.value })}+ placeholder="voice name (e.g. af_bella, alloy)"+ spellCheck={false}+ className="w-full px-2 py-1 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none focus:border-white/20"+ />+ <p className="text-[0.55rem] text-gray-500 leading-snug">+ Any OpenAI-compatible TTS endpoint (e.g. Kokoro-FastAPI). Used for read-aloud instead of Piper. Stays on your machine when the endpoint is local.+ </p>+ </div>+ )}+ </>)+}diff --git a/src/components/settings/__tests__/settings-rail-und-rang.test.ts b/src/components/settings/__tests__/settings-rail-und-rang.test.tsnew file mode 100644index 00000000..bd907dee--- /dev/null+++ b/src/components/settings/__tests__/settings-rail-und-rang.test.ts@@ -0,0 +1,372 @@+/**+ * Settings: die Rail, der Rang der Ueberschriften, die zwei Reset-Aktionen+ * und der Unterschied zwischen Zustand und Aktion.+ *+ * Deckt D-S27, D-S28, D-S29, D-S30 und D-S48 des Design-Audits.+ *+ * Warum als Quelltext- und Rechen-Test und nicht als Sichtpruefung: die+ * Testumgebung ist `environment: 'node'` (vitest.config.ts), es gibt kein DOM+ * und keinen Renderer im Projekt. Was sich OHNE DOM pruefen laesst, ist+ * (a) die Struktur, um die es geht — Rail vorhanden, Spalte nicht mehr+ * freischwebend, Sprungziele decken die Sektionen — und (b) die+ * Kontrastwerte, die dabei behauptet werden. Die werden hier AUSGERECHNET,+ * aus derselben Rechnung, die `primary-recipe.test.ts` benutzt, nicht+ * abgeschrieben.+ *+ * Was hier NICHT geprueft werden kann: wie breit die Spalte im laufenden+ * Fenster wirklich wird und wo die Fortschrittsanker beim Klick landen. Das+ * braucht ein gerendertes Fenster; die 294px/524px-Messungen des Audits sind+ * genau deshalb dort als „nicht verifizierbar hier" gefuehrt.+ *+ * Lauf: npx vitest run src/components/settings/__tests__/settings-rail-und-rang.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { contrast, over } from '../../__tests__/wcag-contrast'+import { sectionAnchorId, sectionsFor, type SettingsSectionFlags } from '../settings-nav'+import type { SettingsTab } from '../../../lib/settings-reset'++/**+ * Nur der Code, ohne Kommentare. Die Zusicherungen unten sind teils+ * NEGATIV ("dieser Klassenname kommt nicht mehr vor") — und ein Kommentar,+ * der den alten Wert zitiert, um die Aenderung zu erklaeren, waere sonst+ * ausgerechnet das, was den Test rot faerbt. Dieselbe Vorsichtsmassnahme+ * wie in src/components/layout/__tests__/listen-ladezustaende.test.ts.+ */+const codeOnly = (src: string) =>+ src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1')++const SRC = codeOnly(readFileSync(resolve(__dirname, '..', 'SettingsPage.tsx'), 'utf8'))+const CSS = readFileSync(resolve(__dirname, '..', '..', '..', 'index.css'), 'utf8')++/** Die Palettenwerte, die in den Klassen unten wirklich stehen. */+const PAL = {+ white: '#ffffff',+ appDark: '#202020', // die Flaeche, auf der Settings im Dunkelmodus liegt+ gray200: '#e5e7eb',+ gray400: '#9ca3af',+ gray500: '#6b7280',+ gray900: '#111827',+ red400: '#f87171',+ red600: '#dc2626',+ accent: '#a094f8',+ accentEdge: '#8b7cf0',+}++// ── D-S27 / D-S48 — die Spalte haengt an etwas ────────────────────────────++describe('D-S27 / D-S48: die Inhaltsspalte schwebt nicht mehr frei', () => {+ it('`max-w-lg mx-auto` ist weg — das WAR die freischwebende Spalte', () => {+ expect(SRC).not.toContain('max-w-lg mx-auto')+ })++ it('es gibt eine 200px-Rail und eine auf 640px gedeckelte Inhaltsspalte', () => {+ // Die beiden Zahlen des Audit-Solls: „200px-Rail links mit den Sektionen,+ // 640px Content daneben, linksbuendig".+ expect(SRC).toMatch(/w-\[200px\]/)+ expect(SRC).toMatch(/max-w-\[640px\]/)+ })++ it('die Rail ist eine benannte Navigation und klebt beim Scrollen', () => {+ const rail = SRC.match(/<nav[\s\S]*?>/)?.[0] ?? ''+ expect(rail).toContain('aria-label="Settings sections"')+ expect(rail).toContain('sticky')+ })++ it('unter `lg` bleibt genau EINE Navigation stehen, nicht zwei', () => {+ // Die Rail erscheint ab lg, die waagerechte Tableiste verschwindet dort.+ // Beides gleichzeitig sichtbar waere zwei Navigationen fuer dieselbe+ // Sache — der Befund, den D-S27 an anderer Stelle beschreibt.+ expect(SRC).toMatch(/hidden lg:flex w-\[200px\]/)+ expect(SRC).toMatch(/lg:hidden sticky top-0/)+ })++ it('der aktive Tab ist als solcher ausgezeichnet, nicht nur eingefaerbt', () => {+ expect((SRC.match(/aria-current=\{tab === t\.id \? 'page' : undefined\}/g) ?? []).length).toBe(2)+ })+})++// ── Die Rail zeigt auf das, was wirklich da ist ───────────────────────────++const TABS: SettingsTab[] = ['general', 'backends', 'agent', 'voice-remote']+const ALL_ON: SettingsSectionFlags = {+ gpuPicker: true, builtinExpert: true, comfyui: true, agentMode: true, agentWorkflows: true,+ mediaTimeouts: true,+}+const ALL_OFF: SettingsSectionFlags = {+ gpuPicker: false, builtinExpert: false, comfyui: false, agentMode: false, agentWorkflows: false,+ mediaTimeouts: false,+}++/** Der JSX-Zweig eines Tabs, von seinem Guard bis zum naechsten. */+function branch(tab: SettingsTab): string {+ const marks = TABS.map((t) => `{tab === '${t}' && (<>`)+ const start = SRC.indexOf(`{tab === '${tab}' && (<>`)+ expect(start, `Der Zweig fuer '${tab}' fehlt in SettingsPage.tsx`).toBeGreaterThan(-1)+ const ends = marks+ .map((m) => SRC.indexOf(m, start + 1))+ .filter((i) => i > start)+ const reset = SRC.indexOf('<ResetSection tab={tab} />')+ const end = Math.min(...[...ends, reset].filter((i) => i > start))+ return SRC.slice(start, end)+}++/** Die `<Section title="…">`-Literale eines Zweigs, in Renderreihenfolge. */+function renderedTitles(tab: SettingsTab): string[] {+ let text = branch(tab)+ // `<UpdateSection />` ist eine eigene Funktion mit einer eigenen Section+ // darin. Sie an ihrer Einbaustelle aufzuloesen ist die einzige+ // Sonderregel hier — ohne sie faehrt der Vergleich unten gegen eine+ // Sektion, die es sehr wohl gibt.+ const update = SRC.slice(SRC.indexOf('function UpdateSection()'))+ const updateTitles = [...update.matchAll(/<Section title="([^"]+)"/g)].map((m) => m[1])+ text = text.replace('<UpdateSection />', updateTitles.map((t) => `<Section title="${t}"`).join('\n'))+ return [...text.matchAll(/<Section title="([^"]+)"/g)].map((m) => m[1])+}++describe('die Rail und der Inhalt koennen nicht auseinanderlaufen', () => {+ it.each(TABS)('%s: die Rail kennt genau die Sektionen, die der Zweig rendert', (tab) => {+ const inJsx = new Set(renderedTitles(tab))+ // Die Vereinigung ueber beide Flag-Belegungen ist genau die Menge, die im+ // Quelltext steht: ComfyUI UND Local Media, Hardware, der Expertenblock,+ // die Agent-Sektionen hinter ihren Feature-Flags.+ const inRail = new Set([...sectionsFor(tab, ALL_ON), ...sectionsFor(tab, ALL_OFF)])+ expect(inJsx).toEqual(inRail)+ })++ /**+ * Die Sektionen eines Zweigs, die im JSX hinter einer Bedingung stehen.+ * Gemessen wird der Abstand zwischen dem SCHLIESSENDEN `</Section>` davor+ * (bzw. dem Zweiganfang) und dem oeffnenden Tag: nur was dort steht, ist+ * ein Guard fuer genau diese Sektion. Bedingungen INNERHALB der+ * vorangehenden Sektion zaehlen nicht — daran ist die erste, naive Fassung+ * dieser Pruefung gescheitert.+ */+ function guardedTitles(tab: SettingsTab): Set<string> {+ const seg = branch(tab).replace(/^\{tab === '[a-z-]+' && \(<>/, '')+ const out = new Set<string>()+ for (const m of seg.matchAll(/<Section title="([^"]+)"/g)) {+ const before = seg.slice(0, m.index)+ const lastClose = before.lastIndexOf('</Section>')+ const gap = before.slice(lastClose < 0 ? 0 : lastClose + '</Section>'.length)+ if (/&& \(|\? \(|: \(/.test(gap)) out.add(m[1])+ }+ return out+ }++ it.each(TABS)('%s: was im JSX eine Bedingung hat, hat sie auch in der Rail', (tab) => {+ // Der eigentliche Fehler, den diese Sperrklinke faengt: eine Sektion, die+ // im JSX hinter `settings.appMode !== 'cloud' && !isMlxImageHost()` haengt,+ // in der Rail aber unbedingt gelistet ist — die Rail bietet dann einen+ // Sprung an, den es nicht gibt. Genau das ist mir beim ersten Anlauf+ // passiert und im laufenden Fenster aufgefallen, nicht hier.+ const guarded = guardedTitles(tab)+ // „Immer da" heisst: bei JEDER Flag-Belegung in der Liste. Der Schnitt,+ // nicht eine der beiden Belegungen — ComfyUI und Local Media sind die+ // zwei Zweige EINES Ternaers, jeder einzeln bedingt, das Paar zusammen+ // unbedingt.+ const off = new Set(sectionsFor(tab, ALL_OFF))+ const always = new Set(sectionsFor(tab, ALL_ON).filter((t) => off.has(t)))+ for (const title of guarded) {+ expect(always.has(title), `"${title}" steht im JSX hinter einer Bedingung, in der Rail aber unbedingt`).toBe(false)+ }+ for (const title of sectionsFor(tab, ALL_ON)) {+ if (always.has(title)) {+ expect(guarded.has(title), `"${title}" ist in der Rail unbedingt, im JSX aber bedingt`).toBe(false)+ }+ }+ })++ it.each(TABS)('%s: und in derselben Reihenfolge', (tab) => {+ const order = renderedTitles(tab)+ const rail = sectionsFor(tab, ALL_ON)+ expect(rail.map((t) => order.indexOf(t))).toEqual([...rail.map((t) => order.indexOf(t))].sort((a, b) => a - b))+ expect(rail.every((t) => order.includes(t))).toBe(true)+ })++ it('der Ankername wird an EINER Stelle abgeleitet, von Section wie von der Rail', () => {+ expect(SRC).toContain('id={sectionAnchorId(title)}')+ expect(SRC).toContain('href={`#${sectionAnchorId(title)}`}')+ })++ it('kein Tab erzeugt zwei Sektionen mit demselben Anker', () => {+ for (const tab of TABS) {+ const ids = sectionsFor(tab, ALL_ON).map(sectionAnchorId)+ expect(new Set(ids).size, tab).toBe(ids.length)+ }+ })++ it('der Anker ist ein brauchbarer Fragmentname, auch fuer Titel mit Sonderzeichen', () => {+ expect(sectionAnchorId('ComfyUI (Image & Video)')).toBe('set-comfyui-image-video')+ expect(sectionAnchorId('Image / Video Generation Timeouts')).toBe('set-image-video-generation-timeouts')+ expect(sectionAnchorId('Speech')).toBe('set-speech')+ for (const tab of TABS) {+ for (const id of sectionsFor(tab, ALL_ON).map(sectionAnchorId)) {+ expect(id, id).toMatch(/^set-[a-z0-9-]+$/)+ expect(id.endsWith('-')).toBe(false)+ }+ }+ })+})++// ── D-S28 — Rang statt zwoelfmal derselben Betonung ───────────────────────++describe('D-S28: die Sektionskoepfe haben einen Rang bekommen', () => {+ it('die Versalien-plus-Sperrung-Behandlung ist weg', () => {+ expect(SRC).not.toContain('tracking-[0.15em]')+ const head = SRC.match(/<span className="text-\[0\.82rem\][^"]*">\s*\{title\}/)?.[0] ?? ''+ expect(head, 'Der Sektionskopf traegt nicht mehr die 0.82rem-Stufe').not.toBe('')+ expect(head).not.toContain('uppercase')+ })++ it('es gibt drei Stufen statt einer: H1 > Sektionskopf > Fliesstext', () => {+ // Gerechnet gegen das WIRKSAME Wurzelmass, nicht gegen eine abgeschriebene+ // Zahl: Wurzel-`font-size` mal `--ui-scale`, falls es den Regler gibt (er+ // haengt als `zoom` an #root). Waehrend dieses Pakets stellte D-A3+ // parallel von „18,4px, kein Regler" auf „16px mal 1,15" um und wieder+ // zurueck; beide Regime ergeben 18,4 gerenderte px. Genau deshalb stehen+ // die Stufen unten in rem und nicht in px.+ const rootDecl = Number(CSS.match(/html\s*\{[^}]*?font-size:\s*([\d.]+)px/s)?.[1])+ const scale = Number(CSS.match(/--ui-scale:\s*([\d.]+)/)?.[1] ?? 1)+ const root = rootDecl * scale+ expect(root).toBeCloseTo(18.4, 3)+ const px = (rem: number) => rem * root+ expect(px(1.15)).toBeCloseTo(21.16, 2)+ expect(px(0.82)).toBeCloseTo(15.09, 2)+ expect(px(0.7)).toBeCloseTo(12.88, 2)+ expect(px(1.15)).toBeGreaterThan(px(0.82))+ expect(px(0.82)).toBeGreaterThan(px(0.7))+ // Und die Stufen stehen wirklich in der Datei.+ expect(SRC).toContain('text-[1.15rem] font-semibold')+ expect(SRC).toContain('text-[0.82rem] font-semibold')+ })++ it('die H1 ist nicht mehr so gross wie ein Sektionskopf', () => {+ // Der Befund im Kleinen: vorher H1 `text-[0.8rem]` gegen Sektionskopf+ // `text-[0.65rem]` — zwei Stufen, die im Fenster als eine lesen.+ expect(SRC).not.toContain('text-[0.8rem] font-semibold text-gray-800 dark:text-gray-200">Settings')+ })++ it('der Kopf erreicht in BEIDEN Modi WCAG AA — vorher im Dunkelmodus nicht', () => {+ // Gerechnet, nicht behauptet:+ // alt gray-500 #6b7280 auf #202020 = 3.37:1 → unter AA (4.5:1)+ // neu gray-200 #e5e7eb auf #202020 = 13.16:1+ // neu gray-900 #111827 auf #ffffff = 17.74:1+ expect(contrast(PAL.gray500, PAL.appDark)).toBeCloseTo(3.37, 2)+ expect(contrast(PAL.gray500, PAL.appDark)).toBeLessThan(4.5)+ expect(contrast(PAL.gray200, PAL.appDark)).toBeGreaterThanOrEqual(4.5)+ expect(contrast(PAL.gray900, PAL.white)).toBeGreaterThanOrEqual(4.5)+ expect(SRC).toContain('text-gray-900 dark:text-gray-200 group-hover:text-black')+ })+})++// ── D-S29 — zwei verschieden gefaehrliche Aktionen ────────────────────────++describe('D-S29: die gefaehrlichere Reset-Aktion sieht anders aus', () => {+ const resetBlock = () => {+ const at = SRC.indexOf('function ResetSection(')+ const end = SRC.indexOf('\nexport function SettingsPage()')+ return SRC.slice(at, end)+ }++ it('sie ist keine zweite Textzeile mehr, sondern ein umrandeter Knopf', () => {+ const block = resetBlock()+ expect(block).toContain("border-red-600 text-red-600 hover:bg-red-600/10 dark:border-red-400 dark:text-red-400")+ // Das alte, fast unsichtbare Grau ist weg.+ expect(block).not.toContain("text-gray-600 dark:text-gray-600 hover:text-red-400")+ })++ it('und sie sagt, was „alle" bedeutet', () => {+ expect(resetBlock()).toContain('Every tab, not just {tabLabel}.')+ })++ it('die beiden Knoepfe tragen NICHT mehr dieselben Klassen', () => {+ const block = resetBlock()+ const scoped = block.match(/armed === 'section' \? '([^']*)' : '([^']*)'/)+ const all = block.match(/armed === 'all'\s*\n?\s*\? '([^']*)'\s*\n?\s*: '([^']*)'/)+ expect(scoped, 'Der Zweig fuer die tab-weite Aktion fehlt').not.toBeNull()+ expect(all, 'Der Zweig fuer die App-weite Aktion fehlt').not.toBeNull()+ expect(all?.[2]).not.toBe(scoped?.[2])+ })++ it('die Gefahrfarbe traegt Text UND Kante durch WCAG', () => {+ // Text: AA braucht 4.5:1. Kante: 1.4.11 (Nicht-Text) braucht 3:1.+ // red-600 #dc2626 auf Weiss = 4.83:1, red-400 #f87171 auf #202020 = 5.89:1.+ expect(contrast(PAL.red600, PAL.white)).toBeCloseTo(4.83, 2)+ expect(contrast(PAL.red400, PAL.appDark)).toBeCloseTo(5.89, 2)+ expect(contrast(PAL.red600, PAL.white)).toBeGreaterThanOrEqual(4.5)+ expect(contrast(PAL.red400, PAL.appDark)).toBeGreaterThanOrEqual(4.5)+ // Der scharf gestellte Zustand ist eine gefuellte Flaeche: Weiss auf+ // red-600 = 4.83:1, dieselbe Rechnung von der anderen Seite.+ expect(contrast(PAL.white, PAL.red600)).toBeGreaterThanOrEqual(4.5)+ expect(SRC).toContain("'bg-red-600 border-red-600 text-white font-medium'")+ })++ it('NEGATIVKONTROLLE: das alte Grau war im Dunkelmodus unlesbar — 2.16:1', () => {+ // gray-600 #4b5563 auf #202020. Genau das trug bisher die Aktion, die+ // ALLES zuruecksetzt: die gefaehrlichere war die unlesbarere.+ expect(contrast('#4b5563', PAL.appDark)).toBeCloseTo(2.16, 2)+ })++ it('NEGATIVKONTROLLE: der Arm-Mechanismus ist unangetastet', () => {+ // Die Optik zu aendern darf die Zwei-Klick-Bestaetigung nicht anfassen.+ const block = resetBlock()+ expect(block).toContain("if (armed !== which) {")+ expect(block).toContain('setTimeout(() => setArmed(null), 4000)')+ expect(block).toContain("armed === 'all' ? 'Click again to reset everything' : 'Reset all settings'")+ })+})++// ── D-S30 — Zustand ist nicht Aktion ──────────────────────────────────────++describe('D-S30: Zustand und Aktion tragen nicht mehr dieselbe Flaeche', () => {+ it('der aktive Tab traegt die Akzentflaeche, nicht die Aktionsflaeche', () => {+ expect(SRC).toMatch(/tab === t\.id\s*\n?\s*\? 'bg-lu-accent-soft/)+ // `bg-gray-200 dark:bg-white/10` als AUSGEWAEHLT-Markierung ist weg.+ expect(SRC).not.toContain("? 'bg-gray-200 dark:bg-white/10 text-gray-900 dark:text-white'")+ })++ it('der gewaehlte Theme-Knopf spricht dieselbe Zustandssprache', () => {+ for (const t of ['light', 'dark']) {+ expect(SRC).toContain(`settings.theme === '${t}' ? 'bg-lu-accent-soft ring-1 ring-lu-accent-edge dark:ring-lu-accent`)+ }+ })++ it('die Aktion behaelt die neutrale graue Flaeche — sonst waere nur getauscht', () => {+ // „Upload" in AvatarSetting ist der Aktionsknopf aus dem Befund. Er sieht+ // aus wie vorher; verschoben hat sich der ZUSTAND.+ const avatar = SRC.slice(SRC.indexOf('function AvatarSetting()'), SRC.indexOf('function Section('))+ expect(avatar).toContain('bg-gray-200 dark:bg-white/10')+ expect(avatar).not.toContain('bg-lu-accent-soft')+ })++ it('die Zustandskante erfuellt 1.4.11 in beiden Modi', () => {+ // Die Flaeche selbst ist absichtlich blass (rgba(160,148,248,.14) ueber+ // Weiss = 1.12:1) — die Kante traegt die Unterscheidbarkeit.+ expect(contrast(over(PAL.accent, PAL.white, 0.14), PAL.white)).toBeLessThan(1.5)+ expect(contrast(PAL.accentEdge, PAL.white)).toBeCloseTo(3.37, 2)+ expect(contrast(PAL.accent, PAL.appDark)).toBeCloseTo(6.27, 2)+ expect(contrast(PAL.accentEdge, PAL.white)).toBeGreaterThanOrEqual(3)+ expect(contrast(PAL.accent, PAL.appDark)).toBeGreaterThanOrEqual(3)+ })++ it('und der Text auf der Zustandsflaeche bleibt lesbar', () => {+ // gray-900 auf der hellen Akzentflaeche, Weiss auf der dunklen.+ expect(contrast(PAL.gray900, over(PAL.accent, PAL.white, 0.14))).toBeGreaterThanOrEqual(4.5)+ expect(contrast(PAL.white, over(PAL.accent, PAL.appDark, 0.14))).toBeGreaterThanOrEqual(4.5)+ })++ it('OFFEN, ausdruecklich: der tab-weite Reset-Link bleibt im Dunkelmodus bei 3.37:1', () => {+ // `text-gray-500` ohne dark:-Gegenstueck. Die Klasse ist in+ // src/lib/__tests__/reset-arming-is-visible.test.ts woertlich gepinnt+ // (fremde Datei, nicht Teil dieses Pakets) — sie hier zu aendern hiesse,+ // jenen Test zu brechen oder zu entschaerfen. Der Wert steht deshalb als+ // gemessene, offene Luecke da, nicht als stille.+ expect(SRC).toContain("'text-gray-500 hover:text-red-400'")+ expect(contrast(PAL.gray500, PAL.appDark)).toBeLessThan(4.5)+ expect(contrast(PAL.gray500, PAL.white)).toBeGreaterThanOrEqual(4.5)+ // Der neue Hinweistext daneben ist dagegen in beiden Modi lesbar.+ expect(contrast(PAL.gray400, PAL.appDark)).toBeGreaterThanOrEqual(4.5)+ })+})diff --git a/src/components/settings/__tests__/speech-abschnitt-und-probe.test.ts b/src/components/settings/__tests__/speech-abschnitt-und-probe.test.tsnew file mode 100644index 00000000..8140403f--- /dev/null+++ b/src/components/settings/__tests__/speech-abschnitt-und-probe.test.ts@@ -0,0 +1,178 @@+/**+ * AS-09, Settings-Haelfte: der Abschnitt „Speech" als eigene Komponente und+ * die eine Probe-und-Installier-Maschine hinter STT und TTS.+ *+ * Wie in der Onboarding-Haelfte zwei Sorten Zusicherung:+ *+ * — `makeProbeReducer` ist rein, also ist der erste Block echtes Verhalten.+ * — Der zweite Block ist Buchfuehrung am Quelltext, mit Sperrklinken:+ * die Zahlen duerfen sinken, nicht steigen.+ *+ * Was hier NICHT bewiesen wird: dass der Abschnitt im Fenster gleich+ * aussieht wie vorher. Das Projekt hat keinen Renderer (`environment:+ * 'node'`), der Vergleich lief von Hand am laufenden Dev-Server.+ *+ * Lauf: npx vitest run src/components/settings/__tests__/speech-abschnitt-und-probe.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { initialProbe, makeProbeReducer, needsInstall, showsHint, type ProbeInstall } from '../probe-install'++const codeOnly = (src: string) =>+ src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1')++const read = (rel: string) => codeOnly(readFileSync(resolve(__dirname, '..', rel), 'utf8'))+const PAGE = read('SettingsPage.tsx')+const SPEECH = read('SpeechSettings.tsx')++interface Probe { available: boolean }+const reducer = makeProbeReducer<Probe>()+const run = (...actions: Parameters<typeof reducer>[1][]): ProbeInstall<Probe> =>+ actions.reduce(reducer, initialProbe<Probe>())++describe('die Probe-und-Installier-Maschine', () => {+ it('faengt ladend an — ein rotes Kreuz vor dem ersten Ergebnis waere gelogen', () => {+ const s = initialProbe<Probe>()+ expect(s).toEqual({ probe: null, loading: true, installing: false, installError: null })+ // Und solange nichts vorliegt, wird auch kein Installationsknopf angeboten.+ expect(needsInstall(s)).toBe(false)+ expect(showsHint(s)).toBe(false)+ })++ it('eine Probe, die etwas findet, bietet keine Installation an', () => {+ const s = run({ type: 'probed', probe: { available: true } })+ expect(s.loading).toBe(false)+ expect(needsInstall(s)).toBe(false)+ })++ it('eine Probe, die nichts findet, bietet sie an — mit Erklaerzeile', () => {+ const s = run({ type: 'probed', probe: { available: false } })+ expect(needsInstall(s)).toBe(true)+ expect(showsHint(s)).toBe(true)+ })++ it('waehrend der Installation bleibt der Knopf, die Erklaerzeile geht', () => {+ const s = run({ type: 'probed', probe: { available: false } }, { type: 'installStart' })+ expect(needsInstall(s)).toBe(true)+ expect(showsHint(s)).toBe(false)+ })++ it('ein Installationsfehler ersetzt die Erklaerzeile', () => {+ const s = run(+ { type: 'probed', probe: { available: false } },+ { type: 'installStart' },+ { type: 'installFailed', error: 'pip exit 1' },+ { type: 'installDone' },+ )+ expect(s.installError).toBe('pip exit 1')+ expect(s.installing).toBe(false)+ expect(showsHint(s)).toBe(false)+ })++ it('ein neuer Anlauf loescht den Fehler des vorigen', () => {+ const s = run(+ { type: 'installStart' },+ { type: 'installFailed', error: 'pip exit 1' },+ { type: 'installDone' },+ { type: 'installStart' },+ )+ expect(s.installError).toBeNull()+ expect(s.installing).toBe(true)+ })++ it('eine gescheiterte Probe laesst den letzten bekannten Stand stehen', () => {+ // Genau wie vorher: `setStatus` stand im `.then`, `setLoading(false)` im+ // `.finally`. Ein Fehlschlag hat den Status nicht auf null gesetzt.+ const s = run({ type: 'probed', probe: { available: true } }, { type: 'probing' }, { type: 'probeFailed' })+ expect(s.probe).toEqual({ available: true })+ expect(s.loading).toBe(false)+ })++ it('`installDone` sagt nichts ueber Erfolg — das sagt die Probe danach', () => {+ // Der `finally`-Block der beiden Handler feuert auf JEDEM Weg und stoesst+ // danach die Probe an. Die Phase „fertig installiert" gibt es hier+ // bewusst nicht: ob etwas da ist, weiss nur die Probe.+ const s = run({ type: 'installStart' }, { type: 'installDone' })+ expect(s.installing).toBe(false)+ expect(s.probe).toBeNull()+ })+})++describe('AS-09: der Abschnitt ist ausgezogen, nicht nur verschoben', () => {+ it('SettingsPage() haelt hoechstens 2 eigene `useState` — vorher 13', () => {+ // Sperrklinke. Die 13 waren: whisperStatus/Loading/Installing/InstallError,+ // ttsStatus/Loading/Installing/InstallError, installedVoices, voiceBusy,+ // voiceError, entryFocus, tab. Elf davon gehoerten dem Speech-Abschnitt.+ const body = PAGE.slice(PAGE.indexOf('export function SettingsPage()'), PAGE.indexOf('\nfunction UpdateSection()'))+ expect((body.match(/=\s*useState[<(]/g) ?? []).length).toBeLessThanOrEqual(2)+ })++ it('die acht doppelt gefuehrten Felder sind eine Maschine, zweimal benutzt', () => {+ expect((SPEECH.match(/=\s*useReducer\(/g) ?? []).length).toBe(2)+ expect(SPEECH).toContain('makeProbeReducer<WhisperProbe>()')+ expect(SPEECH).toContain('makeProbeReducer<TtsProbe>()')+ // Und die alten acht Namen gibt es nirgends mehr.+ for (const gone of [+ 'whisperStatus', 'whisperLoading', 'whisperInstalling', 'whisperInstallError',+ 'ttsStatus', 'ttsLoading', 'ttsInstalling', 'ttsInstallError',+ ]) {+ expect(PAGE, gone).not.toContain(gone)+ expect(SPEECH, gone).not.toContain(gone)+ }+ })++ it('die Proben laufen im Abschnitt, nicht beim Oeffnen der Seite', () => {+ // DAS ist der Gewinn, der nicht in der Zahl steckt: der Mount-Effekt mit+ // den drei Backend-Aufrufen stand in SettingsPage() und lief bei JEDEM+ // Oeffnen der Einstellungen — auch auf „General", wo der Abschnitt gar+ // nicht gerendert wird.+ expect(PAGE).not.toContain('checkWhisperAvailable')+ expect(PAGE).not.toContain('listInstalledPiperVoices')+ expect(SPEECH).toContain('void refreshWhisper()')+ expect(SPEECH).toContain('void refreshTts()')+ expect(SPEECH).toContain('void refreshVoices()')+ // Und der Abschnitt haengt wirklich nur am Voice-Tab.+ const voiceBranch = PAGE.slice(PAGE.indexOf("{tab === 'voice-remote' && (<>"), PAGE.indexOf('<ResetSection tab={tab} />'))+ expect(voiceBranch).toContain('<SpeechSettings />')+ expect((PAGE.match(/<SpeechSettings \/>/g) ?? []).length).toBe(1)+ })++ it('SettingsPage abonniert nicht mehr den GANZEN Voice-Store', () => {+ // `const voiceSettings = useVoiceStore()` ohne Selektor liess die ganze+ // Seite bei jedem Schreibvorgang im Voice-Store neu rendern — auch beim+ // Tippen in ein Feld eines anderen Tabs.+ expect(PAGE).not.toContain('const voiceSettings = useVoiceStore()')+ expect(PAGE).toContain('useVoiceStore((s) => s.resetVoiceDefaults)')+ })++ it('der Zeilenschalter steht einmal, nicht zweimal', () => {+ const toggle = read('InlineToggle.tsx')+ expect((toggle.match(/export function InlineToggle/g) ?? [])).toHaveLength(1)+ expect(PAGE).not.toMatch(/function InlineToggle\(/)+ expect(SPEECH).not.toMatch(/function InlineToggle\(/)+ expect(PAGE).toContain("import { InlineToggle } from './InlineToggle'")+ expect(SPEECH).toContain("import { InlineToggle } from './InlineToggle'")+ })++ it('die Stimmenlisten stehen bei dem Abschnitt, der sie benutzt', () => {+ expect(PAGE).not.toContain('PIPER_VOICES')+ expect(PAGE).not.toContain('CLOUD_TTS_VOICES')+ expect(SPEECH).toContain('const PIPER_VOICES')+ expect(SPEECH).toContain('const CLOUD_TTS_VOICES')+ })++ it('NEGATIVKONTROLLE: die Auffrischung nach der Installation ist NICHT weggefallen', () => {+ // Die Proben schreiben weiterhin in den Voice-Store, sonst wachte der+ // Mikrofonknopf nach einer In-App-Installation erst beim Neustart auf.+ expect(SPEECH).toContain('setSttAvailable(!!s.available)')+ expect(SPEECH).toContain('setTtsAvailable(!!s.available)')+ expect(SPEECH).toContain('await refreshWhisper()')+ expect(SPEECH).toContain('await refreshTts()')+ })++ it('D-S30 gilt auch hier: der gewaehlte Motor ist kein Aktionsknopf', () => {+ expect(SPEECH).toContain('bg-lu-accent-soft text-gray-900 dark:text-white border-lu-accent-edge dark:border-lu-accent')+ expect(SPEECH).not.toContain('bg-gray-200 dark:bg-white/15 text-gray-900 dark:text-white border-gray-300')+ })+})diff --git a/src/components/settings/probe-install.ts b/src/components/settings/probe-install.tsnew file mode 100644index 00000000..32ecd3f7--- /dev/null+++ b/src/components/settings/probe-install.ts@@ -0,0 +1,100 @@+/**+ * „Ist es da? Und wenn nicht, installier es." — die Zustandsmaschine hinter+ * Speech-to-Text und Text-to-Speech in den Einstellungen.+ *+ * ── Warum diese Datei existiert (AS-09, zweite Haelfte) ───────────────────+ *+ * `SettingsPage.tsx` ist, anders als `Onboarding.tsx`, laengst zerlegt: neun+ * Komponenten in einer Datei, die groesste (`ComfyUISettings`) mit 16+ * `useState`, die Wurzel `SettingsPage()` mit 13. Von diesen 13 gehoerten+ * elf einem einzigen Abschnitt — „Speech" — und acht davon waren zweimal+ * dasselbe:+ *+ * whisperStatus · whisperLoading · whisperInstalling · whisperInstallError+ * ttsStatus · ttsLoading · ttsInstalling · ttsInstallError+ *+ * Also wieder kein Zaehlproblem, sondern eine Wiederholung. Hier steht sie+ * einmal, ueber dem Typ der jeweiligen Probe generisch, und ohne React —+ * damit pruefbar in einer Umgebung ohne DOM.+ *+ * Der zweite Gewinn liegt nicht in der Zahl: die drei Proben (`whisper`,+ * `tts`, Stimmenliste) liefen im Mount-Effekt von `SettingsPage` und damit+ * bei JEDEM Oeffnen der Einstellungen — auch auf dem Tab „General", wo der+ * Abschnitt gar nicht gerendert wird. Mit dem Abschnitt als eigener+ * Komponente laufen sie, wenn er auf dem Bildschirm ist.+ */++/** Ergebnis einer Verfuegbarkeitsprobe plus der Zustand ihrer Installation. */+export interface ProbeInstall<T> {+ /** Das Probenergebnis, `null` solange nichts vorliegt. */+ probe: T | null+ /** Die Probe laeuft gerade. */+ loading: boolean+ /** Die Installation laeuft gerade. */+ installing: boolean+ /** Letzter Installationsfehler, `null` wenn keiner. */+ installError: string | null+}++export type ProbeAction<T> =+ /** Probe angestossen. */+ | { type: 'probing' }+ /** Probe zurueck. */+ | { type: 'probed'; probe: T }+ /**+ * Probe fehlgeschlagen. Das Ergebnis bleibt, was es war — genau wie+ * vorher, wo `setStatus` im `.then` stand und `setLoading(false)` im+ * `.finally`: ein Fehlschlag liess den letzten bekannten Stand stehen.+ */+ | { type: 'probeFailed' }+ /** Installation angestossen; loescht den Fehler des vorigen Versuchs. */+ | { type: 'installStart' }+ /** Installation gescheitert (die Probe danach laeuft trotzdem). */+ | { type: 'installFailed'; error: string }+ /** Installationslauf beendet — erfolgreich oder nicht; die Probe entscheidet. */+ | { type: 'installDone' }++export function initialProbe<T>(): ProbeInstall<T> {+ // `loading: true` ist der Ausgangszustand, nicht `false`: die Probe wird im+ // selben Zug angestossen, in dem die Komponente entsteht, und ein kurzes+ // rotes Kreuz vor dem ersten Ergebnis waere eine Falschaussage.+ return { probe: null, loading: true, installing: false, installError: null }+}++/**+ * Erzeugt den Reducer fuer einen konkreten Probentyp. Die Fabrik existiert+ * nur, damit die Aufrufstelle `useReducer(whisperReducer, initialProbe())`+ * schreiben kann, ohne eine generische Funktion casten zu muessen.+ */+export function makeProbeReducer<T>() {+ return function probeInstallReducer(state: ProbeInstall<T>, action: ProbeAction<T>): ProbeInstall<T> {+ switch (action.type) {+ case 'probing':+ return { ...state, loading: true }+ case 'probed':+ return { ...state, loading: false, probe: action.probe }+ case 'probeFailed':+ return { ...state, loading: false }+ case 'installStart':+ return { ...state, installing: true, installError: null }+ case 'installFailed':+ return { ...state, installError: action.error }+ case 'installDone':+ return { ...state, installing: false }+ }+ }+}++/**+ * „Der Knopf ‚Herunterladen und installieren' gehoert hierhin." — die+ * Bedingung, die im JSX viermal als `!loading && probe && !probe.available`+ * ausgeschrieben stand.+ */+export function needsInstall(s: ProbeInstall<{ available: boolean }>): boolean {+ return !s.loading && s.probe !== null && !s.probe.available+}++/** „Die Erklaerzeile darunter gehoert hierhin." */+export function showsHint(s: ProbeInstall<{ available: boolean }>): boolean {+ return needsInstall(s) && !s.installing && s.installError === null+}diff --git a/src/components/settings/settings-nav.ts b/src/components/settings/settings-nav.tsnew file mode 100644index 00000000..82ecf4b5--- /dev/null+++ b/src/components/settings/settings-nav.ts@@ -0,0 +1,108 @@+/**+ * Die Navigationsstruktur der Einstellungen — als Daten, nicht als JSX.+ *+ * Warum es diese Datei gibt (Design-Audit D-S27 / D-S48): die Inhaltsspalte+ * stand auf `max-w-lg mx-auto` und schwebte damit in der Fenstermitte; nach+ * oben skalierte der Screen gar nicht, weil es nichts gab, was den gewonnenen+ * Platz benutzen konnte. Das Soll des Audits ist eine 200px-Rail links mit den+ * Sektionen und die Inhaltsspalte linksbuendig daneben. Eine Rail braucht eine+ * Liste — und diese Liste darf nicht neben dem JSX her leben, sonst zeigt sie+ * irgendwann auf Sektionen, die es nicht mehr gibt.+ *+ * Deshalb zwei Dinge hier:+ *+ * 1. `sectionAnchorId()` ist die EINE Ableitung Titel → Ankername. Die+ * `<Section>`-Komponente setzt damit ihr `id`, die Rail baut damit ihr+ * Sprungziel. Zwei Kopien derselben Slug-Regel waeren genau der Zustand,+ * in dem ein Sprungziel still ins Leere zeigt.+ *+ * 2. `sectionsFor()` ist die Reihenfolge der Sektionen je Tab, abhaengig von+ * denselben Bedingungen, die im JSX die Sektion ueberhaupt rendern. Die+ * Bedingungen kommen als Flags herein, damit diese Funktion rein bleibt+ * und geprueft werden kann, ohne die Plattform zu kennen.+ *+ * Gegen das Auseinanderlaufen von Liste und JSX steht eine Sperrklinke im+ * Test (`__tests__/settings-rail-und-rang.test.ts`): er liest die+ * `<Section title="…">`-Literale aus SettingsPage.tsx je Tab-Zweig und+ * vergleicht sie mit dem, was hier steht. Wer eine Sektion hinzufuegt und die+ * Rail vergisst, faellt dort durch.+ */+import type { SettingsTab } from '../../lib/settings-reset'++/**+ * Titel → DOM-`id`. Kleinbuchstaben, alles Nicht-Alphanumerische wird zu+ * einem Bindestrich, das Praefix haelt die ids aus dem globalen id-Raum der+ * App heraus ("Speech" ist ein zu naheliegender Name, um ihn unpraefixiert zu+ * vergeben).+ */+export function sectionAnchorId(title: string): string {+ return `set-${title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`+}++/**+ * Die Bedingungen, unter denen einzelne Sektionen ueberhaupt gerendert+ * werden. Genau die Ausdruecke, die im JSX vor der Sektion stehen — hier+ * benannt, damit Rail und Inhalt dieselbe Wahrheit lesen.+ */+export interface SettingsSectionFlags {+ /** `!isMlxImageHost()` — der GPU-Picker ist auf Apple Silicon durchweg ein No-op. */+ gpuPicker: boolean+ /** `builtinManaged` — der Expertenblock existiert nur, wenn der openai-Slot die eigene Engine IST. */+ builtinExpert: boolean+ /** `!isMlxImageHost()` — Windows/Linux bekommen ComfyUI, der Mac an derselben Stelle MLX. */+ comfyui: boolean+ /** `FEATURE_FLAGS.AGENT_MODE` */+ agentMode: boolean+ /** `FEATURE_FLAGS.AGENT_WORKFLOWS` */+ agentWorkflows: boolean+ /**+ * `settings.appMode !== 'cloud' && !isMlxImageHost()` — die+ * ComfyUI-Zeitgrenzen. Zwei Bedingungen, nicht eine: im Cloud-Modus gelten+ * serverseitige Grenzen, und die MLX-Pipeline des Macs hat ihre eigene.+ * Diese Bedingung hat mich beim ersten Anlauf erwischt — die Rail bot einen+ * Sprung an, den der Inhalt nicht hatte. Der Beweis dafuer, dass die+ * Sperrklinke im Test noetig ist.+ */+ mediaTimeouts: boolean+}++/**+ * Die Sektionen eines Tabs, in Renderreihenfolge. Leere Eintraege fallen+ * heraus, damit die Rail keine Sprungziele anbietet, die im Inhalt fehlen.+ */+export function sectionsFor(tab: SettingsTab, flags: SettingsSectionFlags): string[] {+ switch (tab) {+ case 'general':+ return [+ 'LU Cloud Account',+ 'Cloud API Keys',+ 'Appearance',+ 'Generation',+ ...(flags.gpuPicker ? ['Hardware (GPU picker)'] : []),+ 'Import from other chatbots',+ 'Chat Backup',+ ...(flags.mediaTimeouts ? ['Image / Video Generation Timeouts'] : []),+ 'Privacy',+ 'Onboarding',+ 'Updates',+ 'Troubleshoot',+ ]+ case 'backends':+ return [+ 'Providers',+ 'Model Storage',+ ...(flags.builtinExpert ? ['Built-in Engine (expert)'] : []),+ flags.comfyui ? 'ComfyUI (Image & Video)' : 'Local Media (Apple MLX)',+ ]+ case 'agent':+ return [+ 'Personas',+ 'Memory',+ ...(flags.agentMode ? ['Agent Permissions'] : []),+ ...(flags.agentWorkflows ? ['Agent Workflows'] : []),+ ...(flags.agentMode ? ['MCP Servers', 'Coding Agent', 'Search Provider'] : []),+ ]+ case 'voice-remote':+ return ['Speech', 'Remote Access']+ }+}