Skip to content

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

tech(W-T3/KF-14b) + design(D-S39): Onboarding.tsx zerlegt — 1909 -> 343, und der Doppelname ist weg

David184d022d1ae0
diff --git a/src/components/onboarding/BackendsStep.tsx b/src/components/onboarding/BackendsStep.tsx
new file mode 100644
index 00000000..4e1117d6
--- /dev/null
+++ b/src/components/onboarding/BackendsStep.tsx
@@ -0,0 +1,500 @@
+/**
+ * Schritt „Engine": was auf dieser Maschine schon laeuft, und was LU
+ * stattdessen selbst installieren kann.
+ *
+ * Warum es dieses Modul gibt: alles, was dieser Bildschirm an EIGENEM Zustand
+ * hat, liest niemand sonst — die zwei Installationsablaeufe (Ollama, LM Studio)
+ * mit ihren Pollschleifen, die Liste der zwoelf bekannten Backends samt ihren
+ * Standardports, und die zwei Zweige „gefunden" / „nichts gefunden". Das sind
+ * rund vierhundert Zeilen, die in der Wurzel des Assistenten nur lagen, weil
+ * sie dort entstanden sind.
+ *
+ * Was NICHT hier liegt, obwohl es hier gezeichnet wird:
+ * • Das Scan-Ergebnis (`useBackendScan`) — fuenf Bildschirme lesen es.
+ * • Die Installer-Maschinen (`useInstallerFleet`) — ComfyUI und Python
+ * laufen auf derselben, und alle vier teilen sich EINEN Takt.
+ * • `selectBackendAndContinue` — das ist die Weiche des Assistenten, nicht
+ * die dieses Bildschirms: sie schreibt den Provider-Store und entscheidet,
+ * welcher Schritt als naechster kommt.
+ * Der Schnitt liegt also genau dort, wo der Zustand aufhoert, geteilt zu sein.
+ */
+import { Loader2, Check, Download, RefreshCw, ArrowRight, ChevronRight, ExternalLink, Cpu } from 'lucide-react'
+import { withInstallerOutput, withDetail } from '../../lib/error-text'
+import { useProviderStore } from '../../stores/providerStore'
+import { BUILTIN_BACKEND_ID } from '../../lib/onboarding-backend'
+import { ProgressBar } from '../ui/ProgressBar'
+import { backendCall, openExternal } from '../../api/backend'
+import { formatBytes } from '../../lib/formatters'
+import { isRunning, isReady, formatElapsed, lastLog, type InstallerStatusResponse } from './installer-state'
+import type { Step } from './wizard-steps'
+import type { OnboardingSkin } from './onboarding-skin'
+import type { BackendScan } from './use-backend-scan'
+import type { InstallerFleet } from './use-installer-fleet'
+
+/* ── Local backend info for the "nothing found" state ──────── */
+interface LocalBackendInfo {
+ id: string
+ name: string
+ description: string
+ url: string // Download / homepage URL
+ port: number
+}
+
+const LOCAL_BACKENDS: LocalBackendInfo[] = [
+ { id: 'ollama', name: 'Ollama', description: 'Easiest setup. CLI + API. Huge model library.', url: 'https://ollama.com/', port: 11434 },
+ { id: 'lmstudio', name: 'LM Studio', description: 'GUI app with built-in chat. One-click model download.', url: 'https://lmstudio.ai/', port: 1234 },
+ { id: 'jan', name: 'Jan', description: 'Open-source desktop app. Simple UI, offline-first.', url: 'https://jan.ai/', port: 1337 },
+ { id: 'gpt4all', name: 'GPT4All', description: 'Desktop app by Nomic. CPU-friendly, no GPU needed.', url: 'https://www.nomic.ai/gpt4all', port: 4891 },
+ { id: 'koboldcpp', name: 'KoboldCpp', description: 'Single executable. GGUF models, GPU + CPU hybrid.', url: 'https://github.com/LostRuins/koboldcpp', port: 5001 },
+ { id: 'llamacpp', name: 'llama.cpp', description: 'Minimal C++ inference. Low-level, maximum control.', url: 'https://github.com/ggerganov/llama.cpp', port: 8080 },
+ { id: 'vllm', name: 'vLLM', description: 'High-throughput serving. Best for multi-GPU setups.', url: 'https://github.com/vllm-project/vllm', port: 8000 },
+ { id: 'localai', name: 'LocalAI', description: 'Drop-in OpenAI replacement. Supports text, image, audio.', url: 'https://localai.io/', port: 8080 },
+ { id: 'oobabooga', name: 'text-generation-webui', description: 'Feature-rich web UI. Extensive model format support.', url: 'https://github.com/oobabooga/text-generation-webui', port: 5000 },
+ { id: 'tabbyapi', name: 'TabbyAPI', description: 'ExLlamaV2-based. Fast inference with EXL2 quants.', url: 'https://github.com/theroyallab/tabbyAPI', port: 5000 },
+ { id: 'aphrodite', name: 'Aphrodite', description: 'vLLM fork with extras. SillyTavern compatible.', url: 'https://github.com/PygmalionAI/aphrodite-engine', port: 2242 },
+ { id: 'sglang', name: 'SGLang', description: 'Structured generation. Optimized for complex prompts.', url: 'https://github.com/sgl-project/sglang', port: 30000 },
+]
+
+interface BackendsStepProps {
+ skin: OnboardingSkin
+ scan: BackendScan
+ fleet: InstallerFleet
+ setStep: (step: Step) => void
+ nextStepAfterBackends: () => Step
+ selectBackendAndContinue: () => void
+}
+
+export function BackendsStep({ skin, scan, fleet, setStep, nextStepAfterBackends, selectBackendAndContinue }: BackendsStepProps) {
+ const { isDark, cardClass, primaryBtn, secondaryBtn } = skin
+ const {
+ detectedBackends, detecting, selectedBackend, setSelectedBackend,
+ lmstudioOfflineDetected, lmstudioModelCount, runDetection,
+ } = scan
+ const { ollama, ollamaDo, lmstudio, lmstudioDo, secondsOf } = fleet
+ const { setProviderConfig } = useProviderStore()
+
+ return (
+ <>
+ {detecting ? (
+ <>
+ <Loader2 size={18} className="mx-auto animate-spin text-gray-400" />
+ <h2 className="text-base font-semibold">Scanning for local backends...</h2>
+ <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
+ Checking {LOCAL_BACKENDS.length} backends on their default ports.
+ </p>
+ </>
+ ) : (
+ <>
+ {/* Built-in engine — the 2.5.7 default. Runs locally, nothing to
+ install. Detected/installable external engines move under the
+ Advanced disclosure below (kept, just no longer required). */}
+ <h2 className="text-base font-semibold">Ready to chat</h2>
+ <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
+ LU runs its own engine on your machine. Nothing to install. Pick a starter model next.
+ </p>
+
+ <button
+ onClick={() => setSelectedBackend(BUILTIN_BACKEND_ID)}
+ className={`w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-lg border text-left transition-colors ${
+ selectedBackend === BUILTIN_BACKEND_ID
+ ? isDark ? 'bg-white/10 border-white/20' : 'bg-gray-100 border-gray-900'
+ : isDark ? 'border-white/10 hover:border-white/20' : 'border-gray-200 hover:border-gray-400'
+ }`}
+ >
+ <Cpu size={16} className={selectedBackend === BUILTIN_BACKEND_ID ? (isDark ? 'text-white' : 'text-gray-900') : 'text-gray-500'} />
+ <div className="flex-1 min-w-0">
+ <p className="text-[0.72rem] font-medium">Built-in Engine</p>
+ <p className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>Runs on your machine · nothing to install</p>
+ </div>
+ {selectedBackend === BUILTIN_BACKEND_ID && <Check size={14} className="text-green-400 shrink-0" />}
+ </button>
+
+ <div className="flex items-center justify-center gap-2 pt-1">
+ <button onClick={selectBackendAndContinue} className={primaryBtn}>
+ Continue <ArrowRight size={14} />
+ </button>
+ </div>
+
+ {/* Advanced: connect to a detected engine or install another one.
+ All the existing Ollama/LM-Studio detection + install UI lives
+ here now — available, but off the critical path. */}
+ <details className="text-left pt-1">
+ <summary className={`text-[0.6rem] cursor-pointer hover:underline text-center list-none ${isDark ? 'text-gray-500 hover:text-gray-300' : 'text-gray-400 hover:text-gray-600'}`}>
+ Use another engine (Ollama, LM Studio…)
+ </summary>
+ <div className="mt-3 space-y-4 text-center">
+ {detectedBackends.length > 0 ? (
+ /* ── Backends found ──────────────────────────────── */
+ <>
+ <h2 className="text-base font-semibold">
+ {detectedBackends.length} backend{detectedBackends.length > 1 ? 's' : ''} detected
+ </h2>
+ <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
+ {detectedBackends.length === 1
+ ? `${detectedBackends[0].name} is running. Select it to connect.`
+ : 'Select which backend to use as your primary. You can add more in Settings.'}
+ </p>
+
+ <div className="space-y-1.5 text-left">
+ {detectedBackends.map(b => (
+ <button
+ key={b.id}
+ onClick={() => setSelectedBackend(b.id)}
+ className={`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg border text-left transition-colors ${
+ selectedBackend === b.id
+ ? isDark ? 'bg-white/10 border-white/20' : 'bg-gray-100 border-gray-900'
+ : isDark ? 'border-white/10 hover:border-white/20' : 'border-gray-200 hover:border-gray-400'
+ }`}
+ >
+ <div className={`w-1.5 h-1.5 rounded-full shrink-0 ${
+ selectedBackend === b.id ? 'bg-green-500' : 'bg-gray-500'
+ }`} />
+ <div>
+ <p className="text-[0.7rem] font-medium">{b.name}</p>
+ <p className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'} font-mono`}>localhost:{b.port}</p>
+ </div>
+ </button>
+ ))}
+ </div>
+
+ <div className="flex items-center justify-center gap-2 pt-1">
+ <button onClick={runDetection} className={secondaryBtn} title="Scan again">
+ <RefreshCw size={12} /> Re-Scan
+ </button>
+ {/* Punkt 2: dieser Knopf hiess ebenfalls „Continue" — genau wie der
+ eine Bildschirm weiter oben, der mit der eingebauten Maschine
+ weitermacht. Beide rufen `selectBackendAndContinue`; der
+ Unterschied ist, WOMIT weitergemacht wird, und der stand in
+ keinem der beiden Namen.
+
+ Zwei Folgen, eine sichtbar, eine nicht: ein Screenreader hoerte
+ auf dem aufgeklappten Schritt zweimal dasselbe Wort ohne
+ Unterschied, und `getByRole('button', { name: /Continue/i })`
+ loeste bei offener Klappe auf ZWEI Elemente auf. Playwright
+ WIEDERHOLT eine strict-mode-Verletzung im Klick bis zum Timeout,
+ statt sofort zu scheitern — der Fehler sah deshalb aus wie 60 s
+ Warten an einem Knopf, der weder deaktiviert noch animiert ist.
+ Bei zugeklappter Klappe filtert Playwright den verborgenen weg,
+ deshalb war die Suite gruen und der Fall trotzdem scharf.
+
+ Der Name sagt jetzt, was er tut: WEITER MIT DIESER Maschine,
+ der oben ausgewaehlten aus der Liste darueber. Der Wortlaut
+ greift die Klappe auf, die darueber steht („Use another
+ engine…"): erst „eine andere Maschine", dann „diese hier". */}
+ <button
+ onClick={selectBackendAndContinue}
+ className={primaryBtn}
+ >
+ Use this engine <ArrowRight size={14} />
+ </button>
+ </div>
+ </>
+ ) : (
+ /* ── No backends found — install Ollama in-app ─────── */
+ <>
+ <h2 className="text-base font-semibold">
+ {lmstudioOfflineDetected ? 'LM Studio detected' : 'No local backend detected'}
+ </h2>
+ <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
+ {lmstudioOfflineDetected
+ ? (lmstudioModelCount > 0
+ ? `LM Studio is installed (${lmstudioModelCount} model${lmstudioModelCount === 1 ? '' : 's'} detected) but its server isn't currently running. Start it to use LM Studio as your backend, no re-install needed.`
+ : "LM Studio is installed but its server isn't currently running. Start it to use LM Studio as your backend, no re-install needed.")
+ : "You need a local AI backend to chat. We'll install Ollama for you, it's the easiest to set up."}
+ </p>
+
+ {/* Ollama ready state */}
+ {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" />
+ <span className="text-[0.7rem] font-medium">Ollama is ready!</span>
+ </div>
+ </div>
+ )}
+
+ {/* Ollama install button — hidden when we already know LM
+ Studio is on the box and just needs starting; pushing
+ Ollama in that situation is just noise and forces a
+ second 200 MB download. */}
+ {!isRunning(ollama) && !isReady(ollama) && !lmstudioOfflineDetected && (
+ <button
+ onClick={async () => {
+ ollamaDo({ type: 'start', at: Date.now() })
+ try {
+ await backendCall('install_ollama')
+ const poll = setInterval(async () => {
+ try {
+ const s = await backendCall<InstallerStatusResponse>('install_ollama_status')
+ 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)
+ 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
+ // (which Ollama then can't see).
+ setSelectedBackend('ollama')
+ } else if (s.status === 'error') {
+ clearInterval(poll)
+ ollamaDo({ type: 'fail', error: withInstallerOutput('Installing Ollama did not finish.', lastLog(s.logs)) })
+ }
+ } catch { /* keep polling */ }
+ }, 1000)
+ } catch (err) {
+ ollamaDo({ type: 'fail', error: err instanceof Error ? err.message : 'Installation failed' })
+ }
+ }}
+ 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 */}
+ {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">
+ {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'}`}>
+ {formatElapsed(secondsOf(ollama.startedAt))}
+ </span>
+ </div>
+ {/* Download progress bar */}
+ {ollama.status === 'downloading' && ollama.total > 0 && (
+ <div className="space-y-1">
+ <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(ollama.received)} / {formatBytes(ollama.total)}
+ </span>
+ <span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
+ {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'}`}>
+ {ollama.logs.slice(-4).map((log, i) => (
+ <p key={i}>{log}</p>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Error */}
+ {ollama.error && (
+ <p className="text-[0.65rem] text-red-400 whitespace-pre-line">{ollama.error}</p>
+ )}
+
+ {/* LM Studio ready */}
+ {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" />
+ <span className="text-[0.7rem] font-medium">LM Studio is ready (server on :1234)</span>
+ </div>
+ </div>
+ )}
+
+ {/* LM Studio install — alt path. Hidden once any installer is
+ running so two heavy downloads don't kick off at once.
+ When `lmstudioOfflineDetected` is set we re-label this
+ button as the primary action and let the same Tauri
+ command handle it; the Rust side detects the existing
+ install and skips straight to bootstrap+server-start
+ instead of re-downloading. */}
+ {!isRunning(lmstudio) && !isReady(lmstudio) && !isRunning(ollama) && !isReady(ollama) && (
+ <button
+ onClick={async () => {
+ lmstudioDo({ type: 'start', at: Date.now() })
+ try {
+ await backendCall('install_lmstudio')
+ const poll = setInterval(async () => {
+ try {
+ const s = await backendCall<InstallerStatusResponse>('install_lmstudio_status')
+ 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)
+ 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
+ // <user>/<repo>/<file>.gguf nesting.
+ setSelectedBackend('lmstudio')
+ setProviderConfig('openai', {
+ enabled: true,
+ name: 'LM Studio',
+ baseUrl: 'http://localhost:1234/v1',
+ isLocal: true,
+ managed: false,
+ })
+ } else if (s.status === 'error') {
+ clearInterval(poll)
+ lmstudioDo({ type: 'fail', error: withInstallerOutput('Installing LM Studio did not finish.', lastLog(s.logs)) })
+ }
+ } catch { /* keep polling */ }
+ }, 1000)
+ } catch (err) {
+ 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] transition-all ${
+ lmstudioOfflineDetected
+ ? '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} />
+ {lmstudioOfflineDetected
+ ? 'Start LM Studio server'
+ : 'Or install LM Studio (GUI app, ~570 MB)'}
+ </button>
+ )}
+
+ {/* LM Studio install progress */}
+ {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">
+ {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'}`}>
+ {formatElapsed(secondsOf(lmstudio.startedAt))}
+ </span>
+ </div>
+ {lmstudio.status === 'downloading' && lmstudio.total > 0 && (
+ <div className="space-y-1">
+ <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(lmstudio.received)} / {formatBytes(lmstudio.total)}
+ </span>
+ <span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
+ {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'}`}>
+ {lmstudio.logs.slice(-4).map((log, i) => (
+ <p key={i}>{log}</p>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {lmstudio.error && (
+ <p role="alert" className="text-[0.65rem] text-red-400 whitespace-pre-line">
+ {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
+ // spot. Swallowing the failure meant the message
+ // vanished and nothing replaced it — the one shape of
+ // dud this file can produce. Put the outcome back into
+ // the same line the button came from.
+ onClick={() => {
+ // `warn`, nicht `fail`: hier laeuft keine
+ // Installation, es wird nur ein Server angestossen.
+ lmstudioDo({ type: 'warn', error: '' })
+ backendCall('start_lmstudio_server').catch((e) => {
+ 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}`}
+ >
+ Start LM Studio server
+ </button>
+ )}
+ </p>
+ )}
+
+ {/* Other alternatives collapsed */}
+ {!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
+ </summary>
+ <div className="space-y-1 mt-2 max-h-[30vh] overflow-y-auto scrollbar-thin pr-1">
+ {LOCAL_BACKENDS.filter(b => b.id !== 'ollama' && b.id !== 'lmstudio').map(b => (
+ <button
+ key={b.id}
+ onClick={() => openExternal(b.url)}
+ className={`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg border transition-colors group text-left ${
+ isDark
+ ? 'border-white/[0.06] hover:border-white/15 hover:bg-white/[0.03]'
+ : 'border-gray-200 hover:border-gray-400 hover:bg-gray-50'
+ }`}
+ >
+ <div className={`w-1.5 h-1.5 rounded-full shrink-0 ${isDark ? 'bg-gray-600' : 'bg-gray-300'}`} />
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-1.5">
+ <p className="text-[0.65rem] font-medium">{b.name}</p>
+ <ExternalLink size={10} className={`opacity-0 group-hover:opacity-100 transition-opacity ${isDark ? 'text-gray-500' : 'text-gray-400'}`} />
+ </div>
+ <p className={`text-[0.5rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>{b.description}</p>
+ </div>
+ </button>
+ ))}
+ </div>
+ </details>
+ )}
+
+ <div className="flex items-center justify-center gap-2 pt-1">
+ {!isRunning(ollama) && !isRunning(lmstudio) && !isReady(ollama) && !isReady(lmstudio) && (
+ <button onClick={runDetection} className={secondaryBtn}>
+ <RefreshCw size={12} /> Re-Scan
+ </button>
+ )}
+ {(isReady(ollama) || isReady(lmstudio) || (!isRunning(ollama) && !isRunning(lmstudio))) && (
+ <button
+ onClick={() => setStep(nextStepAfterBackends())}
+ className={(isReady(ollama) || isReady(lmstudio)) ? primaryBtn : `${secondaryBtn} opacity-60`}
+ >
+ {(isReady(ollama) || isReady(lmstudio)) ? <>Continue <ArrowRight size={14} /></> : <>Skip for now <ChevronRight size={12} /></>}
+ </button>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ </details>
+ </>
+ )}
+ </>
+ )
+}
diff --git a/src/components/onboarding/ComfyStep.tsx b/src/components/onboarding/ComfyStep.tsx
new file mode 100644
index 00000000..7b6e7aba
--- /dev/null
+++ b/src/components/onboarding/ComfyStep.tsx
@@ -0,0 +1,632 @@
+/**
+ * Schritt „Image & video": ComfyUI finden, auswaehlen oder installieren —
+ * und, wenn noetig, vorher Python.
+ *
+ * Warum es dieses Modul gibt: dieser Bildschirm haelt sechs Zustaende, die
+ * KEIN anderer Bildschirm liest — der Auto-Scan, sein Ergebnis, die
+ * Mehrfach-Install-Auswahl (Bug #3), der handeingetragene Pfad, das
+ * „bereit"-Flag und die Wiedereintrittssperre des Scans. Nach aussen gibt er
+ * genau eine Nachricht: `setStep('models')`. Ein geschlossenerer Schnitt ist
+ * in dieser Datei nicht zu haben.
+ *
+ * Was er sich trotzdem teilt: die beiden Installer-Maschinen (ComfyUI und
+ * Python) kommen aus `useInstallerFleet`, nicht von hier. Sie muessen dort
+ * liegen, weil sie sich mit Ollama und LM Studio EINEN Takt teilen — vier
+ * Anzeigen, eine Uhr (AS-09). Faenge dieser Schritt seine eigenen an, waeren
+ * es wieder zwei Uhren.
+ *
+ * `step` faehrt als Prop mit, obwohl dieses Bauteil nur auf diesem Schritt
+ * gezeichnet wird: der Auto-Scan-Effekt haengt daran, und er steht hier
+ * unveraendert. Waehrend die Karte ausblendet, ist sie noch montiert und
+ * `step` steht schon auf dem naechsten — die Bedingung im Effekt ist also
+ * nicht ueberfluessig, sie ist genau fuer diesen Moment da.
+ */
+import { useEffect, useRef, useState } from 'react'
+import { Loader2, Check, Download, RefreshCw, ArrowRight, ChevronRight, FolderOpen, Image as ImageIcon } from 'lucide-react'
+import { withInstallerOutput, withDetail } from '../../lib/error-text'
+import { ICON_LG } from '../ui/icon-size'
+import { ProgressBar } from '../ui/ProgressBar'
+import { backendCall, isMacOS } from '../../api/backend'
+import { formatBytes } from '../../lib/formatters'
+import { isRunning, formatElapsed, lastLog, type InstallerStatusResponse } from './installer-state'
+import type { Step } from './wizard-steps'
+import type { OnboardingSkin } from './onboarding-skin'
+import type { InstallerFleet } from './use-installer-fleet'
+
+interface ComfyStepProps {
+ skin: OnboardingSkin
+ fleet: InstallerFleet
+ step: Step
+ setStep: (step: Step) => void
+}
+
+export function ComfyStep({ skin, fleet, step, setStep }: ComfyStepProps) {
+ const { isDark, cardClass, primaryBtn, secondaryBtn } = skin
+ const { comfyInstall, comfyDo, pythonInstall, pythonDo, secondsOf } = fleet
+
+ // ComfyUI step state. `comfyFound.complete` distinguishes a working
+ // install from a half-cloned carcass — see is_comfyui_install_complete in
+ // process.rs. UI uses `complete:false` to surface a Re-install option
+ // instead of "ComfyUI detected, Continue".
+ // Der Scan laeuft ab dem ERSTEN Bild, nicht erst ab dem zweiten. Vorher
+ // stand hier `useState(false)` und einen Effekt weiter unten ein
+ // `setComfyDetecting(true)` — ein zweiter Render fuer eine Aussage, die
+ // beim Montieren schon feststand, denn dieses Bauteil existiert genau
+ // dann, wenn der Schritt erreicht ist. Solange alles in einer
+ // 1909-Zeilen-Funktion lag, hat der Compiler hinter
+ // `react-hooks/set-state-in-effect` diese Funktion nicht gelesen und
+ // geschwiegen; klein genug, meldet er sie. Die Bedingung ist dieselbe
+ // geblieben, die auch der Effekt fuehrt: auf dem Mac wird hier nichts
+ // gesucht (harte Regel — Bild/Video ist dort MLX, nie ComfyUI).
+ const [comfyDetecting, setComfyDetecting] = useState(() => !isMacOS())
+ const [comfyFound, setComfyFound] = useState<{ found: boolean; path?: string; complete?: boolean } | null>(null)
+
+ const [comfyPathInput, setComfyPathInput] = useState('')
+ const [comfyReady, setComfyReady] = useState(false)
+ // 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
+ // the wrong install caused "ComfyUI loaded endlessly" because their
+ // manual install's `python_embeded` was incompatible with our default
+ // System-Python launcher.
+ type ComfyInstallChoice = {
+ path: string
+ complete: boolean
+ has_embedded_python: boolean
+ source: string
+ }
+ const [comfyChoices, setComfyChoices] = useState<ComfyInstallChoice[]>([])
+
+ /** Der Auto-Scan laeuft einmal pro Mount, sobald der comfyui-Schritt erreicht
+ * ist. Ref statt State: der Wert steuert keinen Render, sondern verhindert
+ * nur den Wiedereintritt in den Effekt. */
+ const comfyAutoDetectStarted = useRef(false)
+
+ // Auto-detect ComfyUI when entering the comfyui step. We mark the install
+ // as "ready" (=> Continue button) only when both `found` AND `complete`
+ // are true. A `found && !complete` carcass (P14) keeps the install option
+ // visible so the user can re-trigger and let LU rebuild torch/deps.
+ useEffect(() => {
+ // Belt-and-suspenders: nextStepAfterBackends() already routes macOS
+ // straight past this step, so `step` should never actually be 'comfyui'
+ // there — but never auto-detect/install ComfyUI on Mac regardless (hard
+ // rule: Mac local image/video is MLX only).
+ if (step === 'comfyui' && !isMacOS() && !comfyAutoDetectStarted.current) {
+ // Die Wiedereintritts-Sperre steckte bisher in `!comfyFound &&
+ // !comfyDetecting`. Als Dependencies notiert waeren genau diese beiden
+ // eine Endlosschleife: der Mehrfach-Install-Zweig setzt `comfyFound`
+ // absichtlich wieder auf null und `finally` setzt `comfyDetecting` auf
+ // false — der Effekt haette sich damit selbst nachgetriggert und den
+ // Backend-Scan in Dauerschleife gefahren. Die Sperre ist Lauf-Zustand,
+ // kein Render-Zustand, und liegt deshalb in einer Ref.
+ comfyAutoDetectStarted.current = true
+ // First: enumerate ALL installs (Bug #3). When >1 we show a picker
+ // BEFORE auto-picking — preventing the ninjastic2008 trap where LU
+ // detected their manual install while they wanted the empty placeholder
+ // path. `find_comfyui` is the auto-pick fallback for the single-install
+ // case, which keeps the existing happy-path behaviour intact.
+ backendCall<ComfyInstallChoice[]>('detect_all_comfyui_installs')
+ .then(async installs => {
+ if (Array.isArray(installs) && installs.length > 1) {
+ setComfyChoices(installs)
+ setComfyFound(null)
+ return
+ }
+ if (Array.isArray(installs) && installs.length === 1) {
+ const only = installs[0]
+ setComfyFound({ found: true, path: only.path, complete: only.complete })
+ if (only.complete) setComfyReady(true)
+ // Persist the auto-pick so process.rs uses it on start_comfyui.
+ //
+ // Level (b): the user finds out, the wizard carries on. Nobody
+ // clicked anything here — the single install was auto-picked — but
+ // if the path does not stick, the panel above says "found" while
+ // start_comfyui will look somewhere else entirely, and the failure
+ // then surfaces minutes later with no visible cause.
+ try {
+ await backendCall('set_comfyui_path', { path: only.path })
+ } catch (e) {
+ 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
+ }
+ // Zero matches — fall back to legacy find_comfyui (env var, config
+ // file overrides that aren't on the scan list).
+ const legacy = await backendCall<{ found: boolean; path?: string; complete?: boolean }>('find_comfyui')
+ setComfyFound(legacy)
+ if (legacy.found && legacy.complete !== false) setComfyReady(true)
+ })
+ .catch(async () => {
+ // Older builds without detect_all_comfyui_installs — degrade
+ // gracefully to the previous single-pick API.
+ try {
+ const legacy = await backendCall<{ found: boolean; path?: string; complete?: boolean }>('find_comfyui')
+ setComfyFound(legacy)
+ if (legacy.found && legacy.complete !== false) setComfyReady(true)
+ } catch {
+ setComfyFound({ found: false, complete: false })
+ }
+ })
+ .finally(() => setComfyDetecting(false))
+ }
+ // `comfyDo` ist der Dispatch eines `useReducer` und hat eine stabile
+ // Identitaet — er steht hier, weil die Regel ihn sehen will, und er kann
+ // den Effekt nicht nachtriggern.
+ }, [step, comfyDo])
+
+ // Pick one of the multiple installs from the disambiguation dialog. The
+ // chosen path is persisted via set_comfyui_path so start_comfyui hits it
+ // without further user intervention.
+ const pickComfyInstall = async (choice: ComfyInstallChoice) => {
+ // Level (c): the user picked one of several installs and this call is the
+ // whole point of that click — without it the pick is not recorded anywhere
+ // and start_comfyui keeps using the old one. The lines below close the
+ // dialog and report "found", so a swallowed failure here leaves the wizard
+ // confidently showing a choice that was never made.
+ comfyDo({ type: 'warn', error: '' })
+ try {
+ await backendCall('set_comfyui_path', { path: choice.path })
+ } catch (e) {
+ 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 })
+ if (choice.complete) setComfyReady(true)
+ setComfyChoices([])
+ }
+
+ // P14 pre-flight: ensure Python is on the box before triggering ComfyUI's
+ // pip install. On fresh Windows, `python` is the Microsoft Store stub
+ // and pip silently exit-1's, leaving a carcass on disk and a
+ // "not responding" message in the UI. Returns true once Python is ready.
+ // If Python is already installed, this is a no-op single round trip.
+ const ensurePythonInstalled = async (): Promise<boolean> => {
+ try {
+ const probe = await backendCall<{ available: boolean; path?: string | null }>('python_check')
+ if (probe?.available) return true
+ } catch {
+ // Treat as "not available" and continue to install.
+ }
+
+ pythonDo({ type: 'start', at: Date.now(), log: 'Installing Python 3.12 via winget…' })
+
+ try {
+ await backendCall('install_python')
+ } catch (err) {
+ pythonDo({ type: 'fail', error: err instanceof Error ? err.message : 'Python install failed to start' })
+ return false
+ }
+
+ return await new Promise<boolean>((resolve) => {
+ const poll = setInterval(async () => {
+ try {
+ const status = await backendCall<InstallerStatusResponse>('install_python_status')
+ pythonDo({ type: 'progress', status: status.status, logs: status.logs || [] })
+ if (status.status === 'complete' || status.status === 'already_installed') {
+ clearInterval(poll)
+ pythonDo({ type: 'ready' })
+ resolve(true)
+ } else if (status.status === 'error') {
+ clearInterval(poll)
+ pythonDo({ type: 'fail', error: withInstallerOutput('Installing Python did not finish.', lastLog(status.logs)) })
+ resolve(false)
+ }
+ } catch { /* keep polling */ }
+ }, 2000)
+ })
+ }
+
+ return (
+ <>
+ {/* 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.
+ </p>
+
+ {/* Auto-detecting */}
+ {comfyDetecting && (
+ <div className="flex items-center justify-center gap-2">
+ <Loader2 size={14} className="animate-spin text-gray-400" />
+ <span className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>Looking for ComfyUI...</span>
+ </div>
+ )}
+
+ {/* Bug #3: multi-install picker. When the scan found more than
+ one ComfyUI directory, LU asks the user explicitly rather
+ than guessing. Each option shows whether it's complete and
+ whether it ships its own python_embeded — both matter for
+ start_comfyui's launcher decision. */}
+ {!comfyDetecting && comfyChoices.length > 1 && !comfyFound && (
+ <div className="space-y-2 text-left">
+ <div className={`p-2.5 rounded-lg border ${isDark ? 'bg-amber-500/10 border-amber-500/20' : 'bg-amber-50 border-amber-200'}`}>
+ <p className={`text-[0.7rem] font-medium ${isDark ? 'text-amber-200' : 'text-amber-800'}`}>
+ Multiple ComfyUI installs detected
+ </p>
+ <p className={`text-[0.6rem] mt-0.5 ${isDark ? 'text-amber-300/80' : 'text-amber-700'}`}>
+ Pick the one you want LU to use. We'll remember your choice, and you can change it later in Settings → ComfyUI.
+ </p>
+ </div>
+ <div className="space-y-1.5 max-h-44 overflow-y-auto">
+ {comfyChoices.map((c) => (
+ <button
+ key={c.path}
+ onClick={() => pickComfyInstall(c)}
+ className={`w-full text-left px-3 py-2 rounded-lg border transition-colors ${
+ isDark ? 'border-white/[0.08] hover:bg-white/[0.04]' : 'border-gray-200 hover:bg-gray-50'
+ }`}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <span className={`text-[0.65rem] font-mono truncate ${isDark ? 'text-gray-200' : 'text-gray-800'}`}>{c.path}</span>
+ <span className={`text-[0.5rem] px-1.5 py-[1px] rounded shrink-0 ${
+ c.complete
+ ? (isDark ? 'bg-green-500/15 text-green-400' : 'bg-green-100 text-green-700')
+ : (isDark ? 'bg-amber-500/15 text-amber-300' : 'bg-amber-100 text-amber-700')
+ }`}>
+ {c.complete ? 'ready' : 'needs setup'}
+ </span>
+ </div>
+ <div className={`flex items-center gap-2 mt-0.5 text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-500'}`}>
+ <span>found via {c.source}</span>
+ {c.has_embedded_python && (
+ <span className={isDark ? 'text-blue-300' : 'text-blue-600'}>• bundles python_embeded</span>
+ )}
+ </div>
+ </button>
+ ))}
+ </div>
+ <button
+ onClick={() => { setComfyChoices([]); setComfyFound({ found: false, complete: false }) }}
+ className={`text-[0.55rem] ${isDark ? 'text-gray-500 hover:text-gray-300' : 'text-gray-500 hover:text-gray-700'} underline`}
+ >
+ None of these, let me install a fresh one
+ </button>
+ </div>
+ )}
+
+ {/* Found AND complete (a working install). The carcass case
+ is handled in the install-options block below. */}
+ {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" />
+ <span className="text-[0.7rem] font-medium">ComfyUI detected</span>
+ </div>
+ <p className={`text-[0.55rem] font-mono mt-1 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>{comfyFound.path}</p>
+ </div>
+ )}
+
+ {/* Not found OR found-but-incomplete — install options.
+ 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) && !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`}>
+ <p className={`text-[0.6rem] ${isDark ? 'text-amber-300' : 'text-amber-800'}`}>
+ Found a previous ComfyUI install at <code className="font-mono">{comfyFound.path}</code> but it's missing PyTorch, looks like a previous install was interrupted. Click below to finish it.
+ </p>
+ </div>
+ )}
+ <button
+ onClick={async () => {
+ // P14 pre-flight, install Python first if missing,
+ // then proceed with the original ComfyUI flow. Both
+ // progress cards animate from this single click; the
+ // user never has to interact mid-flight.
+ const pythonOk = await ensurePythonInstalled()
+ if (!pythonOk) return
+
+ comfyDo({ type: 'start', at: Date.now(), log: 'Starting ComfyUI installation...' })
+ try {
+ await backendCall('install_comfyui')
+ // Poll installation status
+ const poll = setInterval(async () => {
+ try {
+ const status = await backendCall<InstallerStatusResponse>('install_comfyui_status')
+ 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)
+ comfyDo({ type: 'ready' })
+ setComfyReady(true)
+ // Auto-start ComfyUI.
+ //
+ // Level (b): the install DID finish, which is what
+ // this step was for, so the wizard moves on to its
+ // ready state either way. But "ready" would then be
+ // claiming something that is not running, so say so.
+ try {
+ await backendCall('start_comfyui')
+ } catch (e) {
+ // `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)
+ comfyDo({ type: 'fail', error: 'Install cancelled.' })
+ } else if (status.status === 'error') {
+ clearInterval(poll)
+ comfyDo({ type: 'fail', error: withInstallerOutput('Installing ComfyUI did not finish.', lastLog(status.logs)) })
+ }
+ } catch { /* keep polling */ }
+ }, 2000)
+ } catch (err) {
+ comfyDo({ type: 'fail', error: err instanceof Error ? err.message : 'Installation failed' })
+ }
+ }}
+ 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>
+ <button
+ onClick={() => {
+ const input = document.createElement('input')
+ input.type = 'text'
+ // Show path input inline
+ setComfyPathInput('')
+ setComfyFound({ found: false })
+ }}
+ // D-S39, zweite Haelfte („vier Buttons in vier Behandlungen"):
+ // dieser Knopf trug die Sekundaerbehandlung und stellte seine
+ // Geometrie daneben per `style` wieder um — Breite und Ausrichtung
+ // kamen aus einem Inline-Stil, waehrend sein Nachbar
+ // („Install ComfyUI") genau dasselbe mit `w-full` und
+ // `justify-center` sagt. Ein Knopf, dessen Form aus einer zweiten
+ // Quelle kommt, ist eine eigene Behandlung, auch wenn er zufaellig
+ // gleich aussieht. Jetzt dieselbe Vokabel wie der Nachbar, nur in
+ // der leisen Rolle — er ist die Nebenaktion und bleibt es.
+ className={`${secondaryBtn} w-full justify-center`}
+ >
+ <FolderOpen size={14} /> I already have ComfyUI
+ </button>
+
+ {/* Manual path input */}
+ {comfyPathInput !== undefined && (
+ <div className="flex gap-1.5">
+ <input
+ type="text"
+ value={comfyPathInput}
+ onChange={e => setComfyPathInput(e.target.value)}
+ placeholder="C:\ComfyUI"
+ className={`flex-1 px-2 py-1.5 rounded-lg border text-[0.65rem] font-mono ${
+ isDark ? 'bg-black border-white/10 text-white' : 'bg-white border-gray-300 text-gray-900'
+ }`}
+ />
+ <button
+ onClick={async () => {
+ if (!comfyPathInput.trim()) return
+ try {
+ await backendCall('set_comfyui_path', { path: comfyPathInput.trim() })
+ setComfyReady(true)
+ // Level (b): the path — the thing the user typed —
+ // was saved, so this stays out of the outer catch and
+ // `ready` stands. Only the convenience auto-start
+ // failed, and that is worth one line rather than
+ // undoing a save that worked.
+ try {
+ await backendCall('start_comfyui')
+ } catch (e) {
+ 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) {
+ comfyDo({ type: 'warn', error: err instanceof Error ? err.message : 'Invalid path' })
+ }
+ }}
+ className={primaryBtn}
+ >
+ Connect
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* P14: Python install progress card. Animates while winget
+ pulls Python.Python.3.12 (~30 MB) and runs the silent
+ installer. Sits ABOVE the ComfyUI install card so the user
+ can see the dependency chain (Python → ComfyUI) when both
+ run back-to-back from a single click. */}
+ {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">
+ <Loader2 size={14} className="animate-spin text-purple-400" />
+ <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'}`}>
+ {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'}`}>
+ {pythonInstall.logs.slice(-6).map((log, i) => (
+ <p key={i}>{log}</p>
+ ))}
+ </div>
+ </div>
+ )}
+ {pythonInstall.error && !isRunning(pythonInstall) && (
+ <p className="text-[0.65rem] text-red-400 whitespace-pre-line">{pythonInstall.error}</p>
+ )}
+
+ {/* Installing progress */}
+ {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">
+ {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'}`}>
+ {formatElapsed(secondsOf(comfyInstall.startedAt))}
+ {/* Bug #1: rolling ETA from download bytes when known. */}
+ {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 % 60
+ return ` • ETA ${m}:${String(s).padStart(2, '0')}`
+ })()}
+ </span>
+ {/* Cancel button (Bug #1 — techx69) */}
+ <button
+ onClick={async () => {
+ // Level (c): Cancel is the only way out of a multi-GB
+ // download. If the call fails the progress bar keeps
+ // filling and the button looks broken — and the user is
+ // still paying for the bandwidth.
+ comfyDo({ type: 'warn', error: '' })
+ try {
+ await backendCall('cancel_comfyui_install')
+ } catch (e) {
+ 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,
+ ) })
+ }
+ }}
+ // D-S39, zweite Haelfte: die vierte Behandlung. Dieser Knopf
+ // hatte sein eigenes Rezept — 8,8px Schrift, 1px senkrechtes
+ // Polster, eigener Radius, rote Kante — und war damit weder
+ // primaer noch sekundaer, sondern ein Einzelstueck mit einer
+ // Trefferflaeche von rund elf Pixeln Hoehe.
+ //
+ // Er traegt jetzt `.lu-control` aus index.css, das neutrale
+ // Rezept des Hauses, mit `data-active` fuer den sichtbaren
+ // Behaelter. Das ist keine Erfindung fuer diesen Knopf,
+ // sondern GENAU die Entscheidung, die dieses Haus fuer Stop
+ // in der Prompt-Zeile schon getroffen und dort aufgeschrieben
+ // hat: „Rot heisst in dieser App an rund hundert Stellen
+ // kaputt oder wird geloescht". Abbrechen ist der normale
+ // Ausgang aus einem laufenden Vorgang, nicht dessen Defekt —
+ // dieselbe Rolle wie Stop, also dieselbe Behandlung.
+ // Auffindbar bleibt er ueber den Behaelter, nicht ueber die
+ // Fehlerfarbe, und er bekommt nebenbei die 26px des Hauses
+ // statt seiner elf.
+ data-active="true"
+ className="lu-control"
+ title="Cancel ComfyUI install"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ {/* Disk pressure warning (push from Rust side) */}
+ {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'}`}>
+ {comfyInstall.logs.find(l => l.startsWith('⚠'))}
+ </div>
+ )}
+ {/* Download progress bar (shown during download phase) */}
+ {comfyInstall.logs.some(l => l.includes('Downloading')) && comfyInstall.total > 0 && (
+ <div className="space-y-1 mb-2">
+ <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(comfyInstall.received)} / {formatBytes(comfyInstall.total)}
+ </span>
+ <span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
+ {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'}`}>
+ {comfyInstall.logs.slice(-8).map((log, i) => (
+ <p key={i}>{log}</p>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Error */}
+ {comfyInstall.error && (
+ <p role="alert" className="text-[0.65rem] text-red-400 whitespace-pre-line">{comfyInstall.error}</p>
+ )}
+
+ {/* Ready state */}
+ {comfyReady && (
+ <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" />
+ <span className="text-[0.7rem] font-medium">ComfyUI is ready</span>
+ </div>
+ </div>
+ )}
+
+ <div className="flex items-center justify-center gap-2 pt-1">
+ {/* Continue only when ComfyUI is actually usable. A
+ found-but-incomplete carcass shouldn't qualify — that
+ install will fail at first generation. */}
+ {((comfyFound?.found && comfyFound.complete !== false) || comfyReady) && (
+ <button
+ onClick={() => setStep('models')}
+ className={primaryBtn}
+ >
+ Continue <ArrowRight size={14} />
+ </button>
+ )}
+ {!isRunning(comfyInstall) && !isRunning(pythonInstall) && (!comfyFound?.found || comfyFound.complete === false) && !comfyReady && (
+ <>
+ <button
+ onClick={() => {
+ setComfyDetecting(true)
+ setComfyFound(null)
+ backendCall<{ found: boolean; path?: string; complete?: boolean }>('find_comfyui')
+ .then(result => { setComfyFound(result); if (result.found && result.complete !== false) setComfyReady(true) })
+ .catch(() => setComfyFound({ found: false, complete: false }))
+ .finally(() => setComfyDetecting(false))
+ }}
+ className={secondaryBtn}
+ >
+ <RefreshCw size={12} /> Re-Scan
+ </button>
+ <button
+ onClick={() => setStep('models')}
+ className={`${secondaryBtn} opacity-60`}
+ >
+ Skip for now <ChevronRight size={12} />
+ </button>
+ </>
+ )}
+ </div>
+ </>
+ )
+}
diff --git a/src/components/onboarding/EmbeddingsStep.tsx b/src/components/onboarding/EmbeddingsStep.tsx
new file mode 100644
index 00000000..bff4e691
--- /dev/null
+++ b/src/components/onboarding/EmbeddingsStep.tsx
@@ -0,0 +1,248 @@
+/**
+ * Schritt „Documents": das kleine Einbettungsmodell fuer Dokumenten-Chat.
+ *
+ * Warum es dieses Modul gibt: die fuenf Zustaende dieses Bildschirms (laeuft,
+ * fertig, Fehler, Fortschritt, „hat der Nutzer schon eins?") liest nach ihm
+ * niemand mehr — er gibt nach aussen nur `setStep('done')`. Er ist damit,
+ * neben dem ComfyUI-Schritt, der zweite wirklich geschlossene Schnitt in
+ * diesem Assistenten.
+ *
+ * Die eine Frage, die er NICHT selbst beantworten kann, ist `embedsViaBundled`:
+ * ob die Einbettungen ueber den mitgelieferten Server oder ueber Ollama
+ * laufen, haengt an der Maschine, die im Backend-Schritt gewaehlt wurde. Die
+ * kommt aus `useBackendScan`, und `isReady(ollama)` aus der Installer-Flotte —
+ * beides Zustand der Schale, hier nur gelesen.
+ *
+ * Warum das Warten auf den Download aus `./wait-for-download` kommt und nicht
+ * hier steht: der Modellschritt braucht dasselbe, aus demselben Grund (erst
+ * wenn die Datei ganz da ist, darf ein Server darauf starten).
+ *
+ * `step` faehrt als Prop mit: der Effekt, der nach einem vorhandenen
+ * Einbettungsmodell sucht, haengt daran und steht hier unveraendert.
+ */
+import { useState, useEffect } from 'react'
+import { Check, Download, ArrowRight, ChevronRight } from 'lucide-react'
+import { ONBOARDING_EMBED_MODEL } from '../../lib/constants'
+import { useDownloadStore } from '../../stores/downloadStore'
+import { detectProviderModelPath, startModelDownloadToPath } from '../../api/discover'
+import { pullModelTauri, checkConnection as checkOllama } from '../../api/ollama'
+import { startBundledEmbed } from '../../api/engine'
+import { backendCall } from '../../api/backend'
+import { BUILTIN_BACKEND_ID, classifyOnboardingBackend, resolveOnboardingBackend } from '../../lib/onboarding-backend'
+import { ProgressBar } from '../ui/ProgressBar'
+import { formatBytes } from '../../lib/formatters'
+import { isReady } from './installer-state'
+import { awaitDownloadComplete } from './wait-for-download'
+import { isTauri } from './onboarding-host'
+import type { Step } from './wizard-steps'
+import type { OnboardingSkin } from './onboarding-skin'
+import type { BackendScan } from './use-backend-scan'
+import type { InstallerFleet } from './use-installer-fleet'
+
+interface EmbeddingsStepProps {
+ skin: OnboardingSkin
+ scan: BackendScan
+ fleet: InstallerFleet
+ step: Step
+ setStep: (step: Step) => void
+}
+
+export function EmbeddingsStep({ skin, scan, fleet, step, setStep }: EmbeddingsStepProps) {
+ const { isDark, cardClass, primaryBtn, secondaryBtn } = skin
+ const { selectedBackend, detectedBackends } = scan
+ const { ollama } = fleet
+ const dlStore = useDownloadStore
+
+ // ── nomic-embed-text install state (GH #45, leonsk29 2026-05-23) ─────
+ // The Document Chat / RAG feature needs an embedding model. We default
+ // to `nomic-embed-text` — small (~274 MB), broadly supported. The step
+ // auto-skips when the user already has any embedding model installed
+ // (covers LM Studio users who came in via that backend with their own
+ // embedding model, and Ollama users who already pulled one).
+ const [embeddingsPulling, setEmbeddingsPulling] = useState(false)
+ const [embeddingsPulled, setEmbeddingsPulled] = useState(false)
+ const [embeddingsError, setEmbeddingsError] = useState<string | null>(null)
+ const [embeddingsProgress, setEmbeddingsProgress] = useState<{ completed: number; total: number }>({ completed: 0, total: 0 })
+ const [embeddingsAlreadyHave, setEmbeddingsAlreadyHave] = useState<boolean | null>(null)
+
+ // Embeddings route on the CHOSEN backend, not isManagedBuiltinActive():
+ // rag.ts only ever queries the bundled embeddings server or Ollama — never
+ // an LM-Studio-style /v1/embeddings — so openai-compat backends must take
+ // 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, 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
+ // list_bundled_models; only Ollama lists its pulled models. Either way we
+ // match anything with `embed`/`bge`/`nomic` in the name (same heuristic
+ // used elsewhere).
+ useEffect(() => {
+ if (step !== 'embeddings') return
+ let cancelled = false
+ const isEmbed = (name: string) => {
+ const lower = (name || '').toLowerCase()
+ return lower.includes('embed') || lower.includes('bge-') || lower.includes('nomic')
+ }
+ const probe = embedsViaBundled
+ ? import('../../api/engine').then(({ listBundledModels }) =>
+ listBundledModels().then(models => models.some(m => isEmbed(m.name))))
+ : import('../../api/ollama').then(({ listModels }) =>
+ listModels().then(models => models.some(m => isEmbed(m.name))))
+ probe
+ .then(hasEmbedding => { if (!cancelled) setEmbeddingsAlreadyHave(hasEmbedding) })
+ .catch(() => { if (!cancelled) setEmbeddingsAlreadyHave(false) })
+ return () => { cancelled = true }
+ }, [step, embedsViaBundled])
+
+ const handlePullEmbeddings = async () => {
+ if (!isTauri) {
+ setEmbeddingsError('Embedding install requires the desktop app. Running in a browser preview.')
+ return
+ }
+ setEmbeddingsPulling(true)
+ setEmbeddingsError(null)
+ setEmbeddingsProgress({ completed: 0, total: 0 })
+
+ // P5: bundled-engine path — download the embedding GGUF flat into the app
+ // models dir and boot the embeddings server on it. No Ollama involved, so
+ // Document-Chat/RAG works on a fresh install with zero external provider.
+ // Taken for the built-in engine AND openai-compat backends (LM Studio
+ // etc.) — see embedsViaBundled above.
+ if (embedsViaBundled) {
+ try {
+ const destDir = await detectProviderModelPath(BUILTIN_BACKEND_ID)
+ if (!destDir) throw new Error('Could not resolve the built-in models directory.')
+ const { downloadUrl, filename, sizeGB } = ONBOARDING_EMBED_MODEL
+ dlStore.getState().setMeta(filename, downloadUrl, 'gguf', destDir)
+ const expectedBytes = sizeGB ? Math.round(sizeGB * 1_073_741_824) : undefined
+ await startModelDownloadToPath(downloadUrl, destDir, filename, expectedBytes)
+ dlStore.getState().startPolling()
+ // Mirror the store's completed/total into the step's progress UI.
+ const unsub = useDownloadStore.subscribe(s => {
+ const d = s.downloads[filename]
+ if (d) setEmbeddingsProgress({ completed: d.progress || 0, total: d.total || 0 })
+ })
+ try {
+ await awaitDownloadComplete(filename)
+ } finally {
+ unsub()
+ }
+ await startBundledEmbed(`${destDir}/${filename}`)
+ setEmbeddingsPulled(true)
+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))
+ } catch (e) {
+ setEmbeddingsError(`Embedding setup failed: ${e instanceof Error ? e.message : String(e)}`)
+ } finally {
+ setEmbeddingsPulling(false)
+ }
+ return
+ }
+
+ try {
+ // Make sure ollama is reachable before kicking off the pull.
+ let ok = await checkOllama()
+ if (!ok) {
+ try { await backendCall('start_ollama') } catch { /* fall through */ }
+ for (let i = 0; i < 20 && !ok; i++) {
+ await new Promise(r => setTimeout(r, 250))
+ ok = await checkOllama()
+ }
+ }
+ if (!ok) {
+ setEmbeddingsError('Cannot reach Ollama (localhost:11434). Start Ollama and retry.')
+ setEmbeddingsPulling(false)
+ return
+ }
+ const { promise } = pullModelTauri('nomic-embed-text', (p) => {
+ setEmbeddingsProgress({ completed: p.completed || 0, total: p.total || 0 })
+ })
+ await promise
+ setEmbeddingsPulled(true)
+ // Same refresh event chat/picker components listen on.
+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))
+ } catch (e) {
+ setEmbeddingsError(`Pull failed: ${e instanceof Error ? e.message : String(e)}`)
+ } finally {
+ setEmbeddingsPulling(false)
+ }
+ }
+
+ return (
+ <>
+ <div className="text-center mb-2">
+ <h2 className="text-base font-semibold mb-1">Document Chat (optional)</h2>
+ <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
+ Drop a PDF, Word doc, or text file into chat and the model can answer questions about it. Needs a small embedding model.
+ </p>
+ </div>
+
+ {embeddingsAlreadyHave === true && !embeddingsPulled && (
+ <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" />
+ <span className="text-[0.7rem] font-medium">Embedding model already installed, Document Chat is ready.</span>
+ </div>
+ </div>
+ )}
+
+ {embeddingsAlreadyHave !== true && (
+ <div className={`p-3 rounded-lg border ${cardClass}`}>
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex-1 min-w-0">
+ <p className="text-[0.7rem] font-medium">nomic-embed-text</p>
+ <p className={`text-[0.6rem] mt-0.5 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
+ Standard embedding model from Nomic AI. Used purely on-device to chunk and retrieve your documents, never sent anywhere.
+ </p>
+ <p className={`text-[0.55rem] mt-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
+ {embedsViaBundled ? '84 MB · bundled engine, runs on any CPU' : '274 MB · runs on any CPU'}
+ </p>
+ </div>
+ </div>
+
+ {embeddingsPulling && (
+ <div className="mt-2.5 space-y-1">
+ <ProgressBar progress={embeddingsProgress.total > 0 ? (embeddingsProgress.completed / embeddingsProgress.total) * 100 : 0} />
+ <p className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
+ {embeddingsProgress.total > 0
+ ? `${formatBytes(embeddingsProgress.completed)} / ${formatBytes(embeddingsProgress.total)}`
+ : 'Starting…'}
+ </p>
+ </div>
+ )}
+
+ {embeddingsPulled && (
+ <div className="mt-2.5 flex items-center gap-2 text-[0.65rem] text-green-400">
+ <Check size={12} /> Installed. Document Chat is ready.
+ </div>
+ )}
+
+ {embeddingsError && (
+ <p className="text-[0.6rem] text-red-400 mt-2">{embeddingsError}</p>
+ )}
+ </div>
+ )}
+
+ <div className="flex items-center gap-2 pt-1">
+ {embeddingsAlreadyHave !== true && !embeddingsPulled && !embeddingsPulling && (
+ <button onClick={handlePullEmbeddings} className={primaryBtn} style={{ flex: 1 }}>
+ <Download size={14} /> Install nomic-embed-text ({embedsViaBundled ? '84 MB' : '274 MB'})
+ </button>
+ )}
+ <button
+ onClick={() => setStep('done')}
+ disabled={embeddingsPulling}
+ className={`${secondaryBtn} ${embeddingsPulling ? 'opacity-40 cursor-not-allowed' : ''}`}
+ style={{ flex: embeddingsAlreadyHave === true || embeddingsPulled ? 1 : undefined }}
+ >
+ {embeddingsAlreadyHave === true || embeddingsPulled ? (
+ <>Continue <ArrowRight size={14} /></>
+ ) : (
+ <>Skip for now <ChevronRight size={14} /></>
+ )}
+ </button>
+ </div>
+ </>
+ )
+}
diff --git a/src/components/onboarding/ModelsStep.tsx b/src/components/onboarding/ModelsStep.tsx
new file mode 100644
index 00000000..f9a99c49
--- /dev/null
+++ b/src/components/onboarding/ModelsStep.tsx
@@ -0,0 +1,418 @@
+/**
+ * Schritt „Model": ein Startermodell aussuchen und es dorthin schreiben, wo
+ * die gewaehlte Maschine es auch findet.
+ *
+ * Warum es dieses Modul gibt: die Auswahl, der laufende Pull, der HF-Pfad,
+ * der Fehlertext, die Unterreiter und die VRAM-Schranke sind Zustand, den
+ * nach diesem Bildschirm niemand mehr anfasst. Was ihn ueberlebt, ist genau
+ * EINE Liste — `pulledModels`, weil der Schlussbildschirm sie zaehlt („2
+ * models installed"). Sie liegt deshalb in der Schale und kommt als Prop
+ * herein; alles andere bleibt hier.
+ *
+ * Der Kern des Bildschirms ist nicht die Kachelliste, sondern
+ * `handleDownloadSelected`: dieselbe GGUF geht je nach gewaehlter Maschine
+ * drei verschiedene Wege (Ollama-Pull, flach in den App-Ordner mit
+ * anschliessendem Motorstart, oder `<user>/<repo>/`-Verschachtelung fuer LM
+ * Studio). Welche Maschine das ist, weiss der Scan (`useBackendScan`) — nicht
+ * dieser Schritt.
+ *
+ * `step` faehrt als Prop mit: die beiden Effekte, die die installierten
+ * Modelle zaehlen und den Schritt gegebenenfalls ueberspringen, haengen daran
+ * und stehen hier unveraendert.
+ */
+import { useState, useEffect } from 'react'
+import { Check, Download, ChevronRight } from 'lucide-react'
+import { ONBOARDING_MODELS } from '../../lib/constants'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useProviderStore } from '../../stores/providerStore'
+import { useDownloadStore } from '../../stores/downloadStore'
+import { detectProviderModelPath, startModelDownloadToPath } from '../../api/discover'
+import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir } from '../../lib/hf-to-provider'
+import { pullModelTauri, checkConnection as checkOllama } from '../../api/ollama'
+import { startBundledEngine } from '../../api/engine'
+import { backendCall } from '../../api/backend'
+import { getSystemVRAM } from '../../api/comfyui'
+import { BUILTIN_BACKEND_ID, classifyOnboardingBackend, resolveOnboardingBackend } from '../../lib/onboarding-backend'
+import { ProgressBar } from '../ui/ProgressBar'
+import { formatBytes } from '../../lib/formatters'
+import { isReady } from './installer-state'
+import { awaitDownloadComplete } from './wait-for-download'
+import { isTauri } from './onboarding-host'
+import type { Step } from './wizard-steps'
+import type { OnboardingSkin } from './onboarding-skin'
+import type { BackendScan } from './use-backend-scan'
+import type { InstallerFleet } from './use-installer-fleet'
+
+interface ModelsStepProps {
+ skin: OnboardingSkin
+ scan: BackendScan
+ fleet: InstallerFleet
+ step: Step
+ setStep: (step: Step) => void
+ /** Ueberlebt diesen Schritt: der Schlussbildschirm zaehlt sie. */
+ pulledModels: string[]
+ setPulledModels: (update: (prev: string[]) => string[]) => void
+}
+
+export function ModelsStep({ skin, scan, fleet, step, setStep, pulledModels, setPulledModels }: ModelsStepProps) {
+ const { isDark, cardClass, secondaryBtn } = skin
+ const { selectedBackend, detectedBackends } = scan
+ const { ollama } = fleet
+ const downloads = useDownloadStore(s => s.downloads)
+ const dlStore = useDownloadStore
+
+ const [selectedModels, setSelectedModels] = useState<string[]>([])
+ const [pullingModel, setPullingModel] = useState<string | null>(null)
+ const [hfModelPath, setHfModelPath] = useState<string | null>(null)
+ const [downloadError, setDownloadError] = useState<string | null>(null)
+ 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
+ // entirely once P4 trimmed ONBOARDING_MODELS down to a single mainstream
+ // entry (Qwen 2.5 0.5B): the tab switcher hides itself when only one
+ // category is populated, but the filter at render time still rejected every
+ // mainstream model — leaving the user on an empty list with only "Skip for
+ // now". This computed initial value keeps the switcher useful when both
+ // categories grow back, while making the single-entry case actually show
+ // the entry.
+ const initialSubTab: 'uncensored' | 'mainstream' = ONBOARDING_MODELS.some(m => m.uncensored)
+ ? 'uncensored'
+ : 'mainstream'
+ const [modelSubTab, setModelSubTab] = useState<'uncensored' | 'mainstream'>(initialSubTab)
+
+ const toggleModel = (name: string) => {
+ setSelectedModels((prev) =>
+ prev.includes(name) ? prev.filter((m) => m !== name) : [...prev, name]
+ )
+ }
+
+ const handleDownloadSelected = async () => {
+ setDownloadError(null)
+ const providers = useProviderStore.getState().providers
+
+ // Decide which backend the download has to feed. selectedBackend (set in
+ // 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, isReady(ollama), detectedBackends)
+ const kind = classifyOnboardingBackend(targetBackend)
+ const useBuiltinPath = kind === 'builtin'
+ const useOllamaPath = kind === 'ollama'
+
+ // Sanity-check / auto-start Ollama before pulling. The pull command will
+ // otherwise spin in "connecting" with no actionable error if the daemon
+ // isn't reachable.
+ if (useOllamaPath && isTauri) {
+ let ok = await checkOllama()
+ if (!ok) {
+ try { await backendCall('start_ollama') } catch { /* fall through to retry loop */ }
+ for (let i = 0; i < 20 && !ok; i++) {
+ await new Promise(r => setTimeout(r, 250))
+ ok = await checkOllama()
+ }
+ }
+ if (!ok) {
+ setDownloadError('Cannot reach Ollama (localhost:11434). Open the Ollama app or run `ollama serve`, then retry.')
+ return
+ }
+ }
+
+ // Direct-write providers (built-in engine, LM Studio etc.) need a base dir.
+ // The built-in engine has a dedicated, app-owned models dir resolved by the
+ // Rust side (detect_model_path("builtin")); other OpenAI-compat providers
+ // reuse the LM-Studio-style detection / user override.
+ let destDir: string | null = null
+ if (useBuiltinPath) {
+ destDir = await detectProviderModelPath(BUILTIN_BACKEND_ID)
+ if (!destDir) {
+ setDownloadError('Could not create the built-in engine model folder. Check app permissions and retry.')
+ return
+ }
+ } else if (!useOllamaPath) {
+ const settingsOverride = useSettingsStore.getState().settings.hfDownloadPathOverride?.trim() || ''
+ destDir = settingsOverride || hfModelPath || (await detectProviderModelPath(providers.openai?.name || 'LM Studio'))
+ if (!destDir) {
+ setDownloadError('Could not determine model directory. Please check app permissions, or set a custom path in Settings → Models.')
+ return
+ }
+ setHfModelPath(destDir)
+ }
+
+ for (const name of selectedModels) {
+ if (pulledModels.includes(name)) continue
+ const model = ONBOARDING_MODELS.find(m => m.name === name)
+ if (!model?.downloadUrl || !model?.filename) continue
+
+ setPullingModel(name)
+ try {
+ if (useOllamaPath) {
+ // Ollama: HF URL → `hf.co/<user>/<repo>:<quant>` → /api/pull. Ollama
+ // materialises the GGUF into its own blob+manifest store; the file
+ // appears in `ollama list` (and therefore in our model manager) the
+ // moment the pull finishes — no separate scanner involved.
+ const ollamaRef = hfUrlToOllamaRef(model.downloadUrl, model.filename)
+ if (!ollamaRef) {
+ setDownloadError(`Cannot derive an Ollama reference for ${model.label}. Try LM Studio instead.`)
+ continue
+ }
+
+ // Seed an entry in the download store so the existing onboarding
+ // progress UI keeps working. Translation from PullProgress (Ollama)
+ // → DownloadProgress (LU) below.
+ dlStore.getState().setMeta(model.filename, model.downloadUrl, 'ollama')
+ useDownloadStore.setState(s => ({
+ downloads: {
+ ...s.downloads,
+ [model.filename!]: {
+ progress: 0, total: 0, speed: 0,
+ filename: model.filename!,
+ status: 'connecting',
+ },
+ },
+ }))
+
+ const { promise } = pullModelTauri(ollamaRef, (p) => {
+ const total = p.total || 0
+ const completed = p.completed || 0
+ const status = (p.status || '').toLowerCase()
+ const isComplete = status.includes('success') || status === 'complete'
+ useDownloadStore.setState(s => ({
+ downloads: {
+ ...s.downloads,
+ [model.filename!]: {
+ progress: completed, total,
+ speed: 0,
+ filename: model.filename!,
+ status: isComplete ? 'complete' : 'downloading',
+ },
+ },
+ }))
+ })
+ await promise
+ // Mark complete in case the final progress event didn't include
+ // a "success" status string (Ollama varies between versions).
+ useDownloadStore.getState().markComplete(model.filename)
+ } else if (useBuiltinPath) {
+ // Built-in engine: write the GGUF flat into the app models dir, wait
+ // for it to finish, then boot llama-server on it. Unlike LM Studio
+ // there's no <user>/<repo> nesting — list_bundled_models scans the
+ // dir directly. We await completion here (not fire-and-forget) so the
+ // engine starts on a fully-downloaded file and the first chat works.
+ dlStore.getState().setMeta(model.filename, model.downloadUrl, 'gguf', destDir!)
+ const expectedBytes = model.sizeGB ? Math.round(model.sizeGB * 1_073_741_824) : undefined
+ await startModelDownloadToPath(model.downloadUrl, destDir!, model.filename, expectedBytes)
+ dlStore.getState().startPolling()
+ await awaitDownloadComplete(model.filename)
+ try {
+ await startBundledEngine(`${destDir}/${model.filename}`)
+ } catch (e) {
+ setDownloadError(`Model downloaded, but the built-in engine failed to start: ${e instanceof Error ? e.message : String(e)}`)
+ }
+ } else {
+ // LM Studio etc.: nest under <user>/<repo>/ so the scanner finds
+ // it. A bare .gguf in the model root is silently ignored by LM
+ // Studio's library — the second half of the same Discord bug.
+ const subdir = hfUrlToLmStudioSubdir(model.downloadUrl)
+ const targetDir = subdir ? `${destDir}/${subdir}` : destDir!
+ dlStore.getState().setMeta(model.filename, model.downloadUrl, 'gguf', targetDir)
+ const expectedBytes = model.sizeGB ? Math.round(model.sizeGB * 1_073_741_824) : undefined
+ await startModelDownloadToPath(model.downloadUrl, targetDir, model.filename, expectedBytes)
+ dlStore.getState().startPolling()
+ }
+ setPulledModels(prev => [...prev, name])
+ } catch (e) {
+ setDownloadError(`Download failed for ${model.label}: ${e instanceof Error ? e.message : String(e)}`)
+ }
+ }
+ setPullingModel(null)
+ // Tell the rest of the app the model list changed — Model Manager,
+ // Chat picker, etc. listen for this and re-fetch.
+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))
+ setStep('embeddings')
+ }
+
+ // Detect system VRAM for model filtering.
+ //
+ // Level (a): silent on purpose. systemVRAM is only ever read as
+ // `if (systemVRAM && m.vramGB > systemVRAM) return false`, so a failed
+ // probe means the recommendation list is not narrowed — the user sees MORE
+ // models, not fewer, and every card still states its own VRAM need. There
+ // is no action to offer, and nothing was lost.
+ useEffect(() => { getSystemVRAM().then(v => setSystemVRAM(v)).catch(() => {}) }, [])
+
+ // Count CHAT-CAPABLE models the user already has installed. Used to skip
+ // the model-picker step when they're not a fresh install — a reinstaller /
+ // upgrader doesn't need a starter rec.
+ //
+ // Embedding-only models (LM Studio's default `nomic-embed-text-v1.5`,
+ // `bge-*`, anything with `embed` in the name) are excluded because they
+ // can't drive a chat. Without this filter, a fresh LM Studio install
+ // looked like "user already has 1 model" and auto-skipped the starter
+ // card — which is exactly the noob trap we're trying to remove.
+ const [existingModelCount, setExistingModelCount] = useState<number | null>(null)
+ useEffect(() => {
+ if (step !== 'models') return
+ let cancelled = false
+ import('../../api/ollama').then(({ listModels }) =>
+ listModels()
+ .then(models => {
+ const chatCapable = models.filter(m => {
+ const lower = (m.name || '').toLowerCase()
+ return !lower.includes('embed') && !lower.includes('bge-') && !lower.includes('nomic')
+ })
+ if (!cancelled) setExistingModelCount(chatCapable.length)
+ })
+ .catch(() => { if (!cancelled) setExistingModelCount(0) })
+ )
+ return () => { cancelled = true }
+ }, [step])
+
+ // Auto-skip the model step when the user already has installed models
+ // (P4 LU-Aufgaben: "Nur wenn der User noch gar kein Modell installiert hat.
+ // Sonst nirgendwo mehr 'Recommended'-Empfehlungen"). null = still loading,
+ // 0 = fresh, >0 = experienced — only the first two should see the picker.
+ // Experienced users still progress to the embedding step (separate skip).
+ useEffect(() => {
+ if (step === 'models' && existingModelCount !== null && existingModelCount > 0) {
+ setStep('embeddings')
+ }
+ // `setStep` ist der Setter eines `useState` aus der Schale, also stabil;
+ // er steht hier fuer die Regel und triggert den Effekt nicht nach.
+ }, [step, existingModelCount, setStep])
+
+ const showRecommendedBadge = existingModelCount === 0
+
+ // GGUF download progress from downloadStore
+ const currentModel = pullingModel ? ONBOARDING_MODELS.find(m => m.name === pullingModel) : null
+ const currentDownload = currentModel?.filename ? downloads[currentModel.filename] : null
+ const isDownloading = !!pullingModel
+ const progress =
+ currentDownload?.total && currentDownload?.progress
+ ? (currentDownload.progress / currentDownload.total) * 100
+ : 0
+
+ return (
+ <>
+ <div className="text-center mb-3">
+ <h2 className="text-base font-semibold mb-1">Pick a starter model</h2>
+ <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
+ One small model to get you running. You can browse and install more from the Models tab once you're in.
+ </p>
+ </div>
+
+ {/* Unfiltered / Mainstream tabs, only meaningful when both
+ categories have entries. With the curated single-starter list
+ (P4) the tabs are hidden; reintroduce only if the list grows. */}
+ {ONBOARDING_MODELS.some(m => m.uncensored) && ONBOARDING_MODELS.some(m => !m.uncensored) && (
+ <div className="flex gap-4 justify-center">
+ <button onClick={() => setModelSubTab('uncensored')} className={`flex items-center gap-2 transition-all ${modelSubTab === 'uncensored' ? 'opacity-100' : 'opacity-40 hover:opacity-70'}`}>
+ <div className={`w-1 h-4 rounded-full ${modelSubTab === 'uncensored' ? 'bg-red-500' : 'bg-red-500/50'}`} />
+ <span className="text-[0.65rem] font-semibold uppercase tracking-wider">Unfiltered</span>
+ </button>
+ <button onClick={() => setModelSubTab('mainstream')} className={`flex items-center gap-2 transition-all ${modelSubTab === 'mainstream' ? 'opacity-100' : 'opacity-40 hover:opacity-70'}`}>
+ <div className={`w-1 h-4 rounded-full ${modelSubTab === 'mainstream' ? 'bg-blue-500' : 'bg-blue-500/50'}`} />
+ <span className="text-[0.65rem] font-semibold uppercase tracking-wider">Mainstream</span>
+ </button>
+ </div>
+ )}
+
+ {isDownloading && pullingModel && (
+ <div className={`p-2.5 rounded-lg border ${cardClass}`}>
+ <div className="flex items-center justify-between mb-1">
+ <p className="text-[0.7rem]">
+ Downloading <span className="font-mono font-medium">{currentModel?.label || pullingModel}</span>...
+ </p>
+ </div>
+ <p className={`text-[0.6rem] mb-1.5 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>{currentDownload?.status || 'Starting...'}</p>
+ {currentDownload?.total ? (
+ <>
+ <ProgressBar progress={progress} />
+ <p className={`text-[0.55rem] mt-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
+ {formatBytes(currentDownload.progress)} / {formatBytes(currentDownload.total)}
+ {progress > 0 && <span className="ml-1.5 text-blue-400">{Math.round(progress)}%</span>}
+ </p>
+ </>
+ ) : null}
+ </div>
+ )}
+ {downloadError && (
+ <p className={`text-[0.65rem] text-red-400 text-center`}>{downloadError}</p>
+ )}
+
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-[50vh] overflow-y-auto scrollbar-thin pr-1">
+ {ONBOARDING_MODELS.filter(m => {
+ // Filter by tab
+ if (modelSubTab === 'uncensored' && !m.uncensored) return false
+ if (modelSubTab === 'mainstream' && m.uncensored) return false
+ // Filter by VRAM if known
+ if (systemVRAM && m.vramGB > systemVRAM) return false
+ return true
+ }).map((model) => {
+ const selected = selectedModels.includes(model.name)
+ const pulled = pulledModels.includes(model.name) || (model.filename ? downloads[model.filename]?.status === 'complete' : false)
+ return (
+ <button
+ key={model.name}
+ onClick={() => !pulled && !isDownloading && toggleModel(model.name)}
+ disabled={pulled || isDownloading}
+ className={`text-left p-2.5 rounded-lg border transition-colors ${
+ pulled
+ ? isDark ? 'bg-green-500/10 border-green-500/30' : 'bg-green-50 border-green-300'
+ : selected
+ ? isDark ? 'bg-white/10 border-white/30' : 'bg-gray-100 border-gray-900'
+ : isDark ? 'border-white/10 hover:border-white/20' : 'border-gray-200 hover:border-gray-400'
+ } ${isDownloading ? 'opacity-60' : ''}`}
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div>
+ <div className="flex items-center gap-1.5">
+ <span className="font-medium text-[0.7rem]">{model.label}</span>
+ {model.recommended && showRecommendedBadge && (
+ <span className={`text-[0.5rem] px-1 py-0.5 rounded ${isDark ? 'bg-white/10 text-gray-300' : 'bg-gray-200 text-gray-600'}`}>
+ Recommended
+ </span>
+ )}
+ </div>
+ <p className={`text-[0.6rem] mt-0.5 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>{model.description}</p>
+ <p className={`text-[0.55rem] mt-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
+ {model.size} · VRAM: {model.vram}
+ </p>
+ </div>
+ {pulled ? (
+ <Check size={14} className="text-green-400 shrink-0 mt-0.5" />
+ ) : selected ? (
+ <div className={`w-4 h-4 rounded flex items-center justify-center shrink-0 mt-0.5 ${isDark ? 'bg-white' : 'bg-gray-900'}`}>
+ <Check size={10} className={isDark ? 'text-black' : 'text-white'} />
+ </div>
+ ) : (
+ <div className={`w-4 h-4 rounded border shrink-0 mt-0.5 ${isDark ? 'border-white/20' : 'border-gray-300'}`} />
+ )}
+ </div>
+ </button>
+ )
+ })}
+ </div>
+
+ <div className="flex items-center gap-2 pt-1">
+ {selectedModels.length > 0 && !isDownloading ? (
+ <button
+ onClick={handleDownloadSelected}
+ 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>
+ ) : !isDownloading ? (
+ <button
+ onClick={() => setStep('embeddings')}
+ className={`flex-1 flex items-center justify-center gap-1.5 ${secondaryBtn}`}
+ >
+ Skip for now <ChevronRight size={14} />
+ </button>
+ ) : null}
+ </div>
+ </>
+ )
+}
diff --git a/src/components/onboarding/Onboarding.tsx b/src/components/onboarding/Onboarding.tsx
index 04a7e10c..498d3d1b 100644
--- a/src/components/onboarding/Onboarding.tsx
+++ b/src/components/onboarding/Onboarding.tsx
@@ -1,32 +1,72 @@
-import { useState, useEffect, useRef, useReducer } from 'react'
-import { withInstallerOutput, withDetail } from '../../lib/error-text'
+/**
+ * Der Assistent beim ersten Start — die SCHALE.
+ *
+ * ── Warum diese Datei nur noch die Schale ist (W-T3) ──────────────────────
+ *
+ * Hier standen 1909 Zeilen: sechs Bildschirme, vier Installationsablaeufe,
+ * drei Download-Wege und der Fensterrahmen, alles in einer Funktion. Die
+ * Zerlegung folgt NICHT der Bildschirmfolge und nicht der Zeilenzahl, sondern
+ * der Frage, welcher Zustand ueber einen Bildschirm hinaus gelesen wird:
+ *
+ * ./use-backend-scan.ts Der Scan und die gewaehlte Maschine. FUENF
+ * Bildschirme lesen ihn, zwei schreiben ihn —
+ * also gehoert er ueber die Schritte, nicht in
+ * einen von ihnen.
+ * ./use-installer-fleet.ts Die vier Installer und ihr EINER Takt. Sie
+ * verteilen sich auf zwei Bildschirme, teilen
+ * aber eine Uhr (AS-09); eine Zerlegung „pro
+ * Schritt" haette daraus wieder zwei Uhren
+ * gemacht.
+ * ./onboarding-skin.ts Die zwei Knopf-Behandlungen und die zwei
+ * Flaechen. Fuenf Dateien zeichnen sie; fuenf
+ * Kopien waeren fuenf Rezepte (D-S36).
+ * ./wait-for-download.ts Das Einzige, was sich Modell- und
+ * Einbettungsschritt teilen: erst wenn die Datei
+ * ganz da ist, darf ein Server darauf starten.
+ * ./onboarding-host.ts Desktop-Fenster oder Browser-Vorschau. Drei
+ * Dateien fragen; das Praedikat steht einmal.
+ *
+ * Was danach uebrig blieb, ist genau das, was ein Assistent ist: welcher
+ * Bildschirm gerade dran ist, was der Nutzer bis hierher gewaehlt hat, der
+ * Fensterrahmen, der Fortschrittsanzeiger — und die zwei Bildschirme, die
+ * keinen eigenen Zustand haben (Willkommen, Fertig). Die vier
+ * ARBEITSSCHRITTE liegen je in einer eigenen Datei:
+ * ./BackendsStep.tsx · ./ComfyStep.tsx · ./ModelsStep.tsx ·
+ * ./EmbeddingsStep.tsx.
+ *
+ * Die `motion.div` samt Schluessel und Ein-/Ausblendung bleibt hier, um jeden
+ * Schritt herum: der UEBERGANG zwischen Bildschirmen gehoert dem Assistenten,
+ * nicht dem Bildschirm. Die Schritte liefern ein Fragment — das DOM ist
+ * dadurch dasselbe wie vorher, `space-y-*` der Karte greift unveraendert.
+ *
+ * ── Die zwei Weichen, die hier bleiben mussten ────────────────────────────
+ *
+ * `nextStepAfterBackends` und `selectBackendAndContinue` sehen aus wie
+ * Backend-Schritt und sind es nicht: die erste entscheidet, welcher
+ * Bildschirm als naechster kommt, die zweite schreibt den Provider-Store und
+ * ruft dann die erste. Beides ist Routenwahl des Assistenten.
+ */
+import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
-import { Minus, Square, X as XIcon, ArrowRight, Download, Check, ChevronRight, Loader2, RefreshCw, ExternalLink, FolderOpen, Cpu, Image as ImageIcon } from 'lucide-react'
+import { Minus, Square, X as XIcon, ArrowRight } 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, 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'
-import { ProgressBar } from '../ui/ProgressBar'
-import { openExternal, isMacOS } from '../../api/backend'
-import { formatBytes } from '../../lib/formatters'
-import { backendCall } from '../../api/backend'
-import { getSystemVRAM } from '../../api/comfyui'
-import { pullModelTauri, checkConnection as checkOllama } from '../../api/ollama'
-import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir } from '../../lib/hf-to-provider'
-import { startBundledEngine, startBundledEmbed } from '../../api/engine'
-import { BUILTIN_BACKEND_ID, classifyOnboardingBackend, resolveOnboardingBackend } from '../../lib/onboarding-backend'
+import { ICON_SM } from '../ui/icon-size'
+import { isMacOS, backendCall } from '../../api/backend'
+import { BUILTIN_BACKEND_ID } 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,
- type InstallerStatusResponse,
-} from './installer-state'
-import type { LmStudioServerStatus } from '../models/ModelSelector'
+import { onboardingSkin } from './onboarding-skin'
+import { useBackendScan } from './use-backend-scan'
+import { useInstallerFleet } from './use-installer-fleet'
+import { isTauri } from './onboarding-host'
+import { BackendsStep } from './BackendsStep'
+import { ComfyStep } from './ComfyStep'
+import { ModelsStep } from './ModelsStep'
+import { EmbeddingsStep } from './EmbeddingsStep'
+
// Bug (h): the dedicated 'theme' onboarding step was removed because users
// kept ending up on Light by accident, and the project standard is "dark
@@ -41,296 +81,24 @@ import type { LmStudioServerStatus } from '../models/ModelSelector'
// 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.__TAURI_INTERNALS__
-
-/* ── Local backend info for the "nothing found" state ──────── */
-interface LocalBackendInfo {
- id: string
- name: string
- description: string
- url: string // Download / homepage URL
- port: number
-}
-
-const LOCAL_BACKENDS: LocalBackendInfo[] = [
- { id: 'ollama', name: 'Ollama', description: 'Easiest setup. CLI + API. Huge model library.', url: 'https://ollama.com/', port: 11434 },
- { id: 'lmstudio', name: 'LM Studio', description: 'GUI app with built-in chat. One-click model download.', url: 'https://lmstudio.ai/', port: 1234 },
- { id: 'jan', name: 'Jan', description: 'Open-source desktop app. Simple UI, offline-first.', url: 'https://jan.ai/', port: 1337 },
- { id: 'gpt4all', name: 'GPT4All', description: 'Desktop app by Nomic. CPU-friendly, no GPU needed.', url: 'https://www.nomic.ai/gpt4all', port: 4891 },
- { id: 'koboldcpp', name: 'KoboldCpp', description: 'Single executable. GGUF models, GPU + CPU hybrid.', url: 'https://github.com/LostRuins/koboldcpp', port: 5001 },
- { id: 'llamacpp', name: 'llama.cpp', description: 'Minimal C++ inference. Low-level, maximum control.', url: 'https://github.com/ggerganov/llama.cpp', port: 8080 },
- { id: 'vllm', name: 'vLLM', description: 'High-throughput serving. Best for multi-GPU setups.', url: 'https://github.com/vllm-project/vllm', port: 8000 },
- { id: 'localai', name: 'LocalAI', description: 'Drop-in OpenAI replacement. Supports text, image, audio.', url: 'https://localai.io/', port: 8080 },
- { id: 'oobabooga', name: 'text-generation-webui', description: 'Feature-rich web UI. Extensive model format support.', url: 'https://github.com/oobabooga/text-generation-webui', port: 5000 },
- { id: 'tabbyapi', name: 'TabbyAPI', description: 'ExLlamaV2-based. Fast inference with EXL2 quants.', url: 'https://github.com/theroyallab/tabbyAPI', port: 5000 },
- { id: 'aphrodite', name: 'Aphrodite', description: 'vLLM fork with extras. SillyTavern compatible.', url: 'https://github.com/PygmalionAI/aphrodite-engine', port: 2242 },
- { id: 'sglang', name: 'SGLang', description: 'Structured generation. Optimized for complex prompts.', url: 'https://github.com/sgl-project/sglang', port: 30000 },
-]
export function Onboarding() {
const [step, setStep] = useState<Step>('welcome')
- const [selectedModels, setSelectedModels] = useState<string[]>([])
- const { settings, updateSettings } = useSettingsStore()
- const downloads = useDownloadStore(s => s.downloads)
- const dlStore = useDownloadStore
- const [pullingModel, setPullingModel] = useState<string | null>(null)
+ // Ueberlebt den Modellschritt: der Schlussbildschirm zaehlt, was
+ // heruntergeladen wurde. Deshalb steht die Liste hier und nicht dort.
const [pulledModels, setPulledModels] = useState<string[]>([])
- const [hfModelPath, setHfModelPath] = useState<string | null>(null)
- const [downloadError, setDownloadError] = useState<string | null>(null)
- const [detectedBackends, setDetectedBackends] = useState<DetectedBackend[]>([])
- const [detecting, setDetecting] = useState(false)
- // 2.5.7: the built-in engine is the pre-selected default — a fresh install
- // needs nothing installed. Detected Ollama/LM Studio are offered as Advanced.
- const [selectedBackend, setSelectedBackend] = useState<string>(BUILTIN_BACKEND_ID)
+ const { settings, updateSettings } = useSettingsStore()
const { setProviderConfig } = useProviderStore()
- // ComfyUI step state. `comfyFound.complete` distinguishes a working
- // install from a half-cloned carcass — see is_comfyui_install_complete in
- // process.rs. UI uses `complete:false` to surface a Re-install option
- // instead of "ComfyUI detected, Continue".
- const [comfyDetecting, setComfyDetecting] = useState(false)
- const [comfyFound, setComfyFound] = useState<{ found: boolean; path?: string; complete?: boolean } | null>(null)
- // 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)
- // 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
- // the wrong install caused "ComfyUI loaded endlessly" because their
- // manual install's `python_embeded` was incompatible with our default
- // System-Python launcher.
- type ComfyInstallChoice = {
- path: string
- complete: boolean
- has_embedded_python: boolean
- source: string
- }
- const [comfyChoices, setComfyChoices] = useState<ComfyInstallChoice[]>([])
-
- // P14: Python install state. On a fresh Windows box `python` is the
- // Microsoft Store stub which exit-1's `pip install`. The ComfyUI install
- // 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`.
- // 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
- // entirely once P4 trimmed ONBOARDING_MODELS down to a single mainstream
- // entry (Qwen 2.5 0.5B): the tab switcher hides itself when only one
- // category is populated, but the filter at render time still rejected every
- // mainstream model — leaving the user on an empty list with only "Skip for
- // now". This computed initial value keeps the switcher useful when both
- // categories grow back, while making the single-entry case actually show
- // the entry.
- const initialSubTab: 'uncensored' | 'mainstream' = ONBOARDING_MODELS.some(m => m.uncensored)
- ? 'uncensored'
- : 'mainstream'
- const [modelSubTab, setModelSubTab] = useState<'uncensored' | 'mainstream'>(initialSubTab)
- // 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
- // re-install. The install_lmstudio Tauri command is idempotent — it
- // detects the existing install and skips straight to bootstrap+server
- // start — so we route through the same code path either way; only the
- // UI labelling differs.
- const [lmstudioOfflineDetected, setLmstudioOfflineDetected] = useState(false)
- // Soft-detect: GGUFs in ~/.lmstudio/models/ even when we can't locate
- // lms.exe. Set when techx69-style users have LM Studio installed
- // system-wide (C:\Program Files\LM Studio) and the Rust path scan misses
- // it, but the canonical models dir is populated anyway. We surface a
- // "Start LM Studio server" CTA either way — the model count gives a
- // confidence cue in the offline-detected card.
- const [lmstudioModelCount, setLmstudioModelCount] = useState(0)
-
const isDark = settings.theme === 'dark'
- const bgClass = isDark ? 'bg-[#202020] text-white' : 'bg-white text-gray-900'
- const cardClass = isDark ? 'bg-[#202020] border-white/[0.08]' : 'bg-gray-50 border-gray-200'
-
- const toggleModel = (name: string) => {
- setSelectedModels((prev) =>
- prev.includes(name) ? prev.filter((m) => m !== name) : [...prev, name]
- )
- }
-
- // Resolve once the download store reports the file finished (or errored).
- // Used by the built-in engine path, which must not boot llama-server until
- // the GGUF is fully on disk. Polls the same store the progress UI renders.
- const awaitDownloadComplete = (filename: string) =>
- new Promise<void>((resolve, reject) => {
- const poll = setInterval(() => {
- const d = useDownloadStore.getState().downloads[filename]
- if (d?.status === 'complete') { clearInterval(poll); resolve() }
- else if (d?.status === 'error') { clearInterval(poll); reject(new Error(d.error || 'Download failed')) }
- }, 500)
- })
-
- const handleDownloadSelected = async () => {
- setDownloadError(null)
- const providers = useProviderStore.getState().providers
+ const skin = onboardingSkin(isDark)
+ const { bgClass, primaryBtn } = skin
- // Decide which backend the download has to feed. selectedBackend (set in
- // 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, isReady(ollama), detectedBackends)
- const kind = classifyOnboardingBackend(targetBackend)
- const useBuiltinPath = kind === 'builtin'
- const useOllamaPath = kind === 'ollama'
-
- // Sanity-check / auto-start Ollama before pulling. The pull command will
- // otherwise spin in "connecting" with no actionable error if the daemon
- // isn't reachable.
- if (useOllamaPath && isTauri) {
- let ok = await checkOllama()
- if (!ok) {
- try { await backendCall('start_ollama') } catch { /* fall through to retry loop */ }
- for (let i = 0; i < 20 && !ok; i++) {
- await new Promise(r => setTimeout(r, 250))
- ok = await checkOllama()
- }
- }
- if (!ok) {
- setDownloadError('Cannot reach Ollama (localhost:11434). Open the Ollama app or run `ollama serve`, then retry.')
- return
- }
- }
-
- // Direct-write providers (built-in engine, LM Studio etc.) need a base dir.
- // The built-in engine has a dedicated, app-owned models dir resolved by the
- // Rust side (detect_model_path("builtin")); other OpenAI-compat providers
- // reuse the LM-Studio-style detection / user override.
- let destDir: string | null = null
- if (useBuiltinPath) {
- destDir = await detectProviderModelPath(BUILTIN_BACKEND_ID)
- if (!destDir) {
- setDownloadError('Could not create the built-in engine model folder. Check app permissions and retry.')
- return
- }
- } else if (!useOllamaPath) {
- const settingsOverride = useSettingsStore.getState().settings.hfDownloadPathOverride?.trim() || ''
- destDir = settingsOverride || hfModelPath || (await detectProviderModelPath(providers.openai?.name || 'LM Studio'))
- if (!destDir) {
- setDownloadError('Could not determine model directory. Please check app permissions, or set a custom path in Settings → Models.')
- return
- }
- setHfModelPath(destDir)
- }
-
- for (const name of selectedModels) {
- if (pulledModels.includes(name)) continue
- const model = ONBOARDING_MODELS.find(m => m.name === name)
- if (!model?.downloadUrl || !model?.filename) continue
-
- setPullingModel(name)
- try {
- if (useOllamaPath) {
- // Ollama: HF URL → `hf.co/<user>/<repo>:<quant>` → /api/pull. Ollama
- // materialises the GGUF into its own blob+manifest store; the file
- // appears in `ollama list` (and therefore in our model manager) the
- // moment the pull finishes — no separate scanner involved.
- const ollamaRef = hfUrlToOllamaRef(model.downloadUrl, model.filename)
- if (!ollamaRef) {
- setDownloadError(`Cannot derive an Ollama reference for ${model.label}. Try LM Studio instead.`)
- continue
- }
-
- // Seed an entry in the download store so the existing onboarding
- // progress UI keeps working. Translation from PullProgress (Ollama)
- // → DownloadProgress (LU) below.
- dlStore.getState().setMeta(model.filename, model.downloadUrl, 'ollama')
- useDownloadStore.setState(s => ({
- downloads: {
- ...s.downloads,
- [model.filename!]: {
- progress: 0, total: 0, speed: 0,
- filename: model.filename!,
- status: 'connecting',
- },
- },
- }))
-
- const { promise } = pullModelTauri(ollamaRef, (p) => {
- const total = p.total || 0
- const completed = p.completed || 0
- const status = (p.status || '').toLowerCase()
- const isComplete = status.includes('success') || status === 'complete'
- useDownloadStore.setState(s => ({
- downloads: {
- ...s.downloads,
- [model.filename!]: {
- progress: completed, total,
- speed: 0,
- filename: model.filename!,
- status: isComplete ? 'complete' : 'downloading',
- },
- },
- }))
- })
- await promise
- // Mark complete in case the final progress event didn't include
- // a "success" status string (Ollama varies between versions).
- useDownloadStore.getState().markComplete(model.filename)
- } else if (useBuiltinPath) {
- // Built-in engine: write the GGUF flat into the app models dir, wait
- // for it to finish, then boot llama-server on it. Unlike LM Studio
- // there's no <user>/<repo> nesting — list_bundled_models scans the
- // dir directly. We await completion here (not fire-and-forget) so the
- // engine starts on a fully-downloaded file and the first chat works.
- dlStore.getState().setMeta(model.filename, model.downloadUrl, 'gguf', destDir!)
- const expectedBytes = model.sizeGB ? Math.round(model.sizeGB * 1_073_741_824) : undefined
- await startModelDownloadToPath(model.downloadUrl, destDir!, model.filename, expectedBytes)
- dlStore.getState().startPolling()
- await awaitDownloadComplete(model.filename)
- try {
- await startBundledEngine(`${destDir}/${model.filename}`)
- } catch (e) {
- setDownloadError(`Model downloaded, but the built-in engine failed to start: ${e instanceof Error ? e.message : String(e)}`)
- }
- } else {
- // LM Studio etc.: nest under <user>/<repo>/ so the scanner finds
- // it. A bare .gguf in the model root is silently ignored by LM
- // Studio's library — the second half of the same Discord bug.
- const subdir = hfUrlToLmStudioSubdir(model.downloadUrl)
- const targetDir = subdir ? `${destDir}/${subdir}` : destDir!
- dlStore.getState().setMeta(model.filename, model.downloadUrl, 'gguf', targetDir)
- const expectedBytes = model.sizeGB ? Math.round(model.sizeGB * 1_073_741_824) : undefined
- await startModelDownloadToPath(model.downloadUrl, targetDir, model.filename, expectedBytes)
- dlStore.getState().startPolling()
- }
- setPulledModels(prev => [...prev, name])
- } catch (e) {
- setDownloadError(`Download failed for ${model.label}: ${e instanceof Error ? e.message : String(e)}`)
- }
- }
- setPullingModel(null)
- // Tell the rest of the app the model list changed — Model Manager,
- // Chat picker, etc. listen for this and re-fetch.
- window.dispatchEvent(new CustomEvent('lu-models-refresh'))
- setStep('embeddings')
- }
+ // Der geteilte Kern: welche Maschine gefunden und welche gewaehlt wurde,
+ // und die vier Installer mit ihrem einen Takt.
+ const scan = useBackendScan()
+ const fleet = useInstallerFleet()
+ const { selectedBackend, detectedBackends, runDetection } = scan
const finish = () => {
updateSettings({ onboardingDone: true })
@@ -387,390 +155,6 @@ export function Onboarding() {
setStep(nextStepAfterBackends())
}
- /* ── Scan for backends ──────────────────────────────────── */
- const runDetection = async () => {
- setDetecting(true)
- setLmstudioOfflineDetected(false)
- setLmstudioModelCount(0)
- const backends = await detectLocalBackends()
- setDetectedBackends(backends)
- if (backends.length > 0 && !selectedBackend) {
- setSelectedBackend(backends[0].id)
- } else if (backends.length === 0 && isTauri) {
- // No live backend on any well-known port. Before we push the user
- // through a 570 MB LM-Studio re-install, ask the Rust side whether
- // LM Studio is actually present on disk — its embedded server may
- // just be turned off. lmstudio_server_status is cheap (a single
- // reqwest probe + a path check) and was added in the same sweep
- // that introduced this branch.
- //
- // v2.4.4 (Bug #2): the status payload now also includes
- // `models_detected` / `model_count` — set by scanning
- // ~/.lmstudio/models/ for GGUF files. We treat that as a strong
- // soft-detect signal: if the user has models in the canonical dir,
- // they obviously *have* LM Studio, regardless of whether our path
- // scan turned up lms.exe (techx69's system-wide install reproed this).
- try {
- const status = await backendCall<LmStudioServerStatus>('lmstudio_server_status')
- const offline = status?.lms_present && !status?.running
- const softDetect = status?.models_detected && !status?.running
- if (offline || softDetect) {
- setLmstudioOfflineDetected(true)
- setLmstudioModelCount(Number(status?.model_count) || 0)
- }
- } catch { /* command unavailable — ignore */ }
- }
- setDetecting(false)
- }
-
- // Detect system VRAM for model filtering.
- //
- // Level (a): silent on purpose. systemVRAM is only ever read as
- // `if (systemVRAM && m.vramGB > systemVRAM) return false`, so a failed
- // probe means the recommendation list is not narrowed — the user sees MORE
- // models, not fewer, and every card still states its own VRAM need. There
- // is no action to offer, and nothing was lost.
- useEffect(() => { getSystemVRAM().then(v => setSystemVRAM(v)).catch(() => {}) }, [])
-
- // Count CHAT-CAPABLE models the user already has installed. Used to skip
- // the model-picker step when they're not a fresh install — a reinstaller /
- // upgrader doesn't need a starter rec.
- //
- // Embedding-only models (LM Studio's default `nomic-embed-text-v1.5`,
- // `bge-*`, anything with `embed` in the name) are excluded because they
- // can't drive a chat. Without this filter, a fresh LM Studio install
- // looked like "user already has 1 model" and auto-skipped the starter
- // card — which is exactly the noob trap we're trying to remove.
- const [existingModelCount, setExistingModelCount] = useState<number | null>(null)
- useEffect(() => {
- if (step !== 'models') return
- let cancelled = false
- import('../../api/ollama').then(({ listModels }) =>
- listModels()
- .then(models => {
- const chatCapable = models.filter(m => {
- const lower = (m.name || '').toLowerCase()
- return !lower.includes('embed') && !lower.includes('bge-') && !lower.includes('nomic')
- })
- if (!cancelled) setExistingModelCount(chatCapable.length)
- })
- .catch(() => { if (!cancelled) setExistingModelCount(0) })
- )
- return () => { cancelled = true }
- }, [step])
-
- // Auto-skip the model step when the user already has installed models
- // (P4 LU-Aufgaben: "Nur wenn der User noch gar kein Modell installiert hat.
- // Sonst nirgendwo mehr 'Recommended'-Empfehlungen"). null = still loading,
- // 0 = fresh, >0 = experienced — only the first two should see the picker.
- // Experienced users still progress to the embedding step (separate skip).
- useEffect(() => {
- if (step === 'models' && existingModelCount !== null && existingModelCount > 0) {
- setStep('embeddings')
- }
- }, [step, existingModelCount])
-
- // ── nomic-embed-text install state (GH #45, leonsk29 2026-05-23) ─────
- // The Document Chat / RAG feature needs an embedding model. We default
- // to `nomic-embed-text` — small (~274 MB), broadly supported. The step
- // auto-skips when the user already has any embedding model installed
- // (covers LM Studio users who came in via that backend with their own
- // embedding model, and Ollama users who already pulled one).
- const [embeddingsPulling, setEmbeddingsPulling] = useState(false)
- const [embeddingsPulled, setEmbeddingsPulled] = useState(false)
- const [embeddingsError, setEmbeddingsError] = useState<string | null>(null)
- const [embeddingsProgress, setEmbeddingsProgress] = useState<{ completed: number; total: number }>({ completed: 0, total: 0 })
- const [embeddingsAlreadyHave, setEmbeddingsAlreadyHave] = useState<boolean | null>(null)
-
- // Embeddings route on the CHOSEN backend, not isManagedBuiltinActive():
- // rag.ts only ever queries the bundled embeddings server or Ollama — never
- // an LM-Studio-style /v1/embeddings — so openai-compat backends must take
- // 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, 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
- // list_bundled_models; only Ollama lists its pulled models. Either way we
- // match anything with `embed`/`bge`/`nomic` in the name (same heuristic
- // used elsewhere).
- useEffect(() => {
- if (step !== 'embeddings') return
- let cancelled = false
- const isEmbed = (name: string) => {
- const lower = (name || '').toLowerCase()
- return lower.includes('embed') || lower.includes('bge-') || lower.includes('nomic')
- }
- const probe = embedsViaBundled
- ? import('../../api/engine').then(({ listBundledModels }) =>
- listBundledModels().then(models => models.some(m => isEmbed(m.name))))
- : import('../../api/ollama').then(({ listModels }) =>
- listModels().then(models => models.some(m => isEmbed(m.name))))
- probe
- .then(hasEmbedding => { if (!cancelled) setEmbeddingsAlreadyHave(hasEmbedding) })
- .catch(() => { if (!cancelled) setEmbeddingsAlreadyHave(false) })
- return () => { cancelled = true }
- }, [step, embedsViaBundled])
-
- const handlePullEmbeddings = async () => {
- if (!isTauri) {
- setEmbeddingsError('Embedding install requires the desktop app. Running in a browser preview.')
- return
- }
- setEmbeddingsPulling(true)
- setEmbeddingsError(null)
- setEmbeddingsProgress({ completed: 0, total: 0 })
-
- // P5: bundled-engine path — download the embedding GGUF flat into the app
- // models dir and boot the embeddings server on it. No Ollama involved, so
- // Document-Chat/RAG works on a fresh install with zero external provider.
- // Taken for the built-in engine AND openai-compat backends (LM Studio
- // etc.) — see embedsViaBundled above.
- if (embedsViaBundled) {
- try {
- const destDir = await detectProviderModelPath(BUILTIN_BACKEND_ID)
- if (!destDir) throw new Error('Could not resolve the built-in models directory.')
- const { downloadUrl, filename, sizeGB } = ONBOARDING_EMBED_MODEL
- dlStore.getState().setMeta(filename, downloadUrl, 'gguf', destDir)
- const expectedBytes = sizeGB ? Math.round(sizeGB * 1_073_741_824) : undefined
- await startModelDownloadToPath(downloadUrl, destDir, filename, expectedBytes)
- dlStore.getState().startPolling()
- // Mirror the store's completed/total into the step's progress UI.
- const unsub = useDownloadStore.subscribe(s => {
- const d = s.downloads[filename]
- if (d) setEmbeddingsProgress({ completed: d.progress || 0, total: d.total || 0 })
- })
- try {
- await awaitDownloadComplete(filename)
- } finally {
- unsub()
- }
- await startBundledEmbed(`${destDir}/${filename}`)
- setEmbeddingsPulled(true)
- window.dispatchEvent(new CustomEvent('lu-models-refresh'))
- } catch (e) {
- setEmbeddingsError(`Embedding setup failed: ${e instanceof Error ? e.message : String(e)}`)
- } finally {
- setEmbeddingsPulling(false)
- }
- return
- }
-
- try {
- // Make sure ollama is reachable before kicking off the pull.
- let ok = await checkOllama()
- if (!ok) {
- try { await backendCall('start_ollama') } catch { /* fall through */ }
- for (let i = 0; i < 20 && !ok; i++) {
- await new Promise(r => setTimeout(r, 250))
- ok = await checkOllama()
- }
- }
- if (!ok) {
- setEmbeddingsError('Cannot reach Ollama (localhost:11434). Start Ollama and retry.')
- setEmbeddingsPulling(false)
- return
- }
- const { promise } = pullModelTauri('nomic-embed-text', (p) => {
- setEmbeddingsProgress({ completed: p.completed || 0, total: p.total || 0 })
- })
- await promise
- setEmbeddingsPulled(true)
- // Same refresh event chat/picker components listen on.
- window.dispatchEvent(new CustomEvent('lu-models-refresh'))
- } catch (e) {
- setEmbeddingsError(`Pull failed: ${e instanceof Error ? e.message : String(e)}`)
- } finally {
- setEmbeddingsPulling(false)
- }
- }
-
- const showRecommendedBadge = existingModelCount === 0
-
- // 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.startedAt
- useEffect(() => {
- if (anyStartedAt === null) return
- const timer = setInterval(() => setNow(Date.now()), 1000)
- return () => clearInterval(timer)
- }, [anyStartedAt])
-
- /** Der Auto-Scan laeuft einmal pro Mount, sobald der comfyui-Schritt erreicht
- * ist. Ref statt State: der Wert steuert keinen Render, sondern verhindert
- * nur den Wiedereintritt in den Effekt. */
- const comfyAutoDetectStarted = useRef(false)
-
- // Auto-detect ComfyUI when entering the comfyui step. We mark the install
- // as "ready" (=> Continue button) only when both `found` AND `complete`
- // are true. A `found && !complete` carcass (P14) keeps the install option
- // visible so the user can re-trigger and let LU rebuild torch/deps.
- useEffect(() => {
- // Belt-and-suspenders: nextStepAfterBackends() already routes macOS
- // straight past this step, so `step` should never actually be 'comfyui'
- // there — but never auto-detect/install ComfyUI on Mac regardless (hard
- // rule: Mac local image/video is MLX only).
- if (step === 'comfyui' && !isMacOS() && !comfyAutoDetectStarted.current) {
- // Die Wiedereintritts-Sperre steckte bisher in `!comfyFound &&
- // !comfyDetecting`. Als Dependencies notiert waeren genau diese beiden
- // eine Endlosschleife: der Mehrfach-Install-Zweig setzt `comfyFound`
- // absichtlich wieder auf null und `finally` setzt `comfyDetecting` auf
- // false — der Effekt haette sich damit selbst nachgetriggert und den
- // Backend-Scan in Dauerschleife gefahren. Die Sperre ist Lauf-Zustand,
- // kein Render-Zustand, und liegt deshalb in einer Ref.
- comfyAutoDetectStarted.current = true
- setComfyDetecting(true)
- // First: enumerate ALL installs (Bug #3). When >1 we show a picker
- // BEFORE auto-picking — preventing the ninjastic2008 trap where LU
- // detected their manual install while they wanted the empty placeholder
- // path. `find_comfyui` is the auto-pick fallback for the single-install
- // case, which keeps the existing happy-path behaviour intact.
- backendCall<ComfyInstallChoice[]>('detect_all_comfyui_installs')
- .then(async installs => {
- if (Array.isArray(installs) && installs.length > 1) {
- setComfyChoices(installs)
- setComfyFound(null)
- return
- }
- if (Array.isArray(installs) && installs.length === 1) {
- const only = installs[0]
- setComfyFound({ found: true, path: only.path, complete: only.complete })
- if (only.complete) setComfyReady(true)
- // Persist the auto-pick so process.rs uses it on start_comfyui.
- //
- // Level (b): the user finds out, the wizard carries on. Nobody
- // clicked anything here — the single install was auto-picked — but
- // if the path does not stick, the panel above says "found" while
- // start_comfyui will look somewhere else entirely, and the failure
- // then surfaces minutes later with no visible cause.
- try {
- await backendCall('set_comfyui_path', { path: only.path })
- } catch (e) {
- 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
- }
- // Zero matches — fall back to legacy find_comfyui (env var, config
- // file overrides that aren't on the scan list).
- const legacy = await backendCall<{ found: boolean; path?: string; complete?: boolean }>('find_comfyui')
- setComfyFound(legacy)
- if (legacy.found && legacy.complete !== false) setComfyReady(true)
- })
- .catch(async () => {
- // Older builds without detect_all_comfyui_installs — degrade
- // gracefully to the previous single-pick API.
- try {
- const legacy = await backendCall<{ found: boolean; path?: string; complete?: boolean }>('find_comfyui')
- setComfyFound(legacy)
- if (legacy.found && legacy.complete !== false) setComfyReady(true)
- } catch {
- setComfyFound({ found: false, complete: false })
- }
- })
- .finally(() => setComfyDetecting(false))
- }
- }, [step])
-
- // Pick one of the multiple installs from the disambiguation dialog. The
- // chosen path is persisted via set_comfyui_path so start_comfyui hits it
- // without further user intervention.
- const pickComfyInstall = async (choice: ComfyInstallChoice) => {
- // Level (c): the user picked one of several installs and this call is the
- // whole point of that click — without it the pick is not recorded anywhere
- // and start_comfyui keeps using the old one. The lines below close the
- // dialog and report "found", so a swallowed failure here leaves the wizard
- // confidently showing a choice that was never made.
- comfyDo({ type: 'warn', error: '' })
- try {
- await backendCall('set_comfyui_path', { path: choice.path })
- } catch (e) {
- 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 })
- if (choice.complete) setComfyReady(true)
- setComfyChoices([])
- }
-
- // P14 pre-flight: ensure Python is on the box before triggering ComfyUI's
- // pip install. On fresh Windows, `python` is the Microsoft Store stub
- // and pip silently exit-1's, leaving a carcass on disk and a
- // "not responding" message in the UI. Returns true once Python is ready.
- // If Python is already installed, this is a no-op single round trip.
- const ensurePythonInstalled = async (): Promise<boolean> => {
- try {
- const probe = await backendCall<{ available: boolean; path?: string | null }>('python_check')
- if (probe?.available) return true
- } catch {
- // Treat as "not available" and continue to install.
- }
-
- pythonDo({ type: 'start', at: Date.now(), log: 'Installing Python 3.12 via winget…' })
-
- try {
- await backendCall('install_python')
- } catch (err) {
- pythonDo({ type: 'fail', error: err instanceof Error ? err.message : 'Python install failed to start' })
- return false
- }
-
- return await new Promise<boolean>((resolve) => {
- const poll = setInterval(async () => {
- try {
- const status = await backendCall<InstallerStatusResponse>('install_python_status')
- pythonDo({ type: 'progress', status: status.status, logs: status.logs || [] })
- if (status.status === 'complete' || status.status === 'already_installed') {
- clearInterval(poll)
- pythonDo({ type: 'ready' })
- resolve(true)
- } else if (status.status === 'error') {
- clearInterval(poll)
- pythonDo({ type: 'fail', error: withInstallerOutput('Installing Python did not finish.', lastLog(status.logs)) })
- resolve(false)
- }
- } catch { /* keep polling */ }
- }, 2000)
- })
- }
-
- // GGUF download progress from downloadStore
- const currentModel = pullingModel ? ONBOARDING_MODELS.find(m => m.name === pullingModel) : null
- const currentDownload = currentModel?.filename ? downloads[currentModel.filename] : null
- const isDownloading = !!pullingModel
- const progress =
- currentDownload?.total && currentDownload?.progress
- ? (currentDownload.progress / currentDownload.total) * 100
- : 0
-
- // Shared button styles
- //
- // 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-colors ${
- isDark ? 'bg-white/10 text-white hover:bg-white/15' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
- }`
-
const handleMinimize = async () => { const { getCurrentWindow } = await import('@tauri-apps/api/window'); getCurrentWindow().minimize() }
const handleMaximize = async () => { const { getCurrentWindow } = await import('@tauri-apps/api/window'); getCurrentWindow().toggleMaximize() }
const handleClose = async () => { const { getCurrentWindow } = await import('@tauri-apps/api/window'); getCurrentWindow().close() }
@@ -870,406 +254,14 @@ export function Onboarding() {
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
>
- {detecting ? (
- <>
- <Loader2 size={18} className="mx-auto animate-spin text-gray-400" />
- <h2 className="text-base font-semibold">Scanning for local backends...</h2>
- <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
- Checking {LOCAL_BACKENDS.length} backends on their default ports.
- </p>
- </>
- ) : (
- <>
- {/* Built-in engine — the 2.5.7 default. Runs locally, nothing to
- install. Detected/installable external engines move under the
- Advanced disclosure below (kept, just no longer required). */}
- <h2 className="text-base font-semibold">Ready to chat</h2>
- <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
- LU runs its own engine on your machine. Nothing to install. Pick a starter model next.
- </p>
-
- <button
- onClick={() => setSelectedBackend(BUILTIN_BACKEND_ID)}
- className={`w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-lg border text-left transition-colors ${
- selectedBackend === BUILTIN_BACKEND_ID
- ? isDark ? 'bg-white/10 border-white/20' : 'bg-gray-100 border-gray-900'
- : isDark ? 'border-white/10 hover:border-white/20' : 'border-gray-200 hover:border-gray-400'
- }`}
- >
- <Cpu size={16} className={selectedBackend === BUILTIN_BACKEND_ID ? (isDark ? 'text-white' : 'text-gray-900') : 'text-gray-500'} />
- <div className="flex-1 min-w-0">
- <p className="text-[0.72rem] font-medium">Built-in Engine</p>
- <p className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>Runs on your machine · nothing to install</p>
- </div>
- {selectedBackend === BUILTIN_BACKEND_ID && <Check size={14} className="text-green-400 shrink-0" />}
- </button>
-
- <div className="flex items-center justify-center gap-2 pt-1">
- <button onClick={selectBackendAndContinue} className={primaryBtn}>
- Continue <ArrowRight size={14} />
- </button>
- </div>
-
- {/* Advanced: connect to a detected engine or install another one.
- All the existing Ollama/LM-Studio detection + install UI lives
- here now — available, but off the critical path. */}
- <details className="text-left pt-1">
- <summary className={`text-[0.6rem] cursor-pointer hover:underline text-center list-none ${isDark ? 'text-gray-500 hover:text-gray-300' : 'text-gray-400 hover:text-gray-600'}`}>
- Use another engine (Ollama, LM Studio…)
- </summary>
- <div className="mt-3 space-y-4 text-center">
- {detectedBackends.length > 0 ? (
- /* ── Backends found ──────────────────────────────── */
- <>
- <h2 className="text-base font-semibold">
- {detectedBackends.length} backend{detectedBackends.length > 1 ? 's' : ''} detected
- </h2>
- <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
- {detectedBackends.length === 1
- ? `${detectedBackends[0].name} is running. Select it to connect.`
- : 'Select which backend to use as your primary. You can add more in Settings.'}
- </p>
-
- <div className="space-y-1.5 text-left">
- {detectedBackends.map(b => (
- <button
- key={b.id}
- onClick={() => setSelectedBackend(b.id)}
- className={`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg border text-left transition-colors ${
- selectedBackend === b.id
- ? isDark ? 'bg-white/10 border-white/20' : 'bg-gray-100 border-gray-900'
- : isDark ? 'border-white/10 hover:border-white/20' : 'border-gray-200 hover:border-gray-400'
- }`}
- >
- <div className={`w-1.5 h-1.5 rounded-full shrink-0 ${
- selectedBackend === b.id ? 'bg-green-500' : 'bg-gray-500'
- }`} />
- <div>
- <p className="text-[0.7rem] font-medium">{b.name}</p>
- <p className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'} font-mono`}>localhost:{b.port}</p>
- </div>
- </button>
- ))}
- </div>
-
- <div className="flex items-center justify-center gap-2 pt-1">
- <button onClick={runDetection} className={secondaryBtn} title="Scan again">
- <RefreshCw size={12} /> Re-Scan
- </button>
- <button
- onClick={selectBackendAndContinue}
- className={primaryBtn}
- >
- Continue <ArrowRight size={14} />
- </button>
- </div>
- </>
- ) : (
- /* ── No backends found — install Ollama in-app ─────── */
- <>
- <h2 className="text-base font-semibold">
- {lmstudioOfflineDetected ? 'LM Studio detected' : 'No local backend detected'}
- </h2>
- <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
- {lmstudioOfflineDetected
- ? (lmstudioModelCount > 0
- ? `LM Studio is installed (${lmstudioModelCount} model${lmstudioModelCount === 1 ? '' : 's'} detected) but its server isn't currently running. Start it to use LM Studio as your backend, no re-install needed.`
- : "LM Studio is installed but its server isn't currently running. Start it to use LM Studio as your backend, no re-install needed.")
- : "You need a local AI backend to chat. We'll install Ollama for you, it's the easiest to set up."}
- </p>
-
- {/* Ollama ready state */}
- {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" />
- <span className="text-[0.7rem] font-medium">Ollama is ready!</span>
- </div>
- </div>
- )}
-
- {/* Ollama install button — hidden when we already know LM
- Studio is on the box and just needs starting; pushing
- Ollama in that situation is just noise and forces a
- second 200 MB download. */}
- {!isRunning(ollama) && !isReady(ollama) && !lmstudioOfflineDetected && (
- <button
- onClick={async () => {
- ollamaDo({ type: 'start', at: Date.now() })
- try {
- await backendCall('install_ollama')
- const poll = setInterval(async () => {
- try {
- const s = await backendCall<InstallerStatusResponse>('install_ollama_status')
- 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)
- 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
- // (which Ollama then can't see).
- setSelectedBackend('ollama')
- } else if (s.status === 'error') {
- clearInterval(poll)
- ollamaDo({ type: 'fail', error: withInstallerOutput('Installing Ollama did not finish.', lastLog(s.logs)) })
- }
- } catch { /* keep polling */ }
- }, 1000)
- } catch (err) {
- ollamaDo({ type: 'fail', error: err instanceof Error ? err.message : 'Installation failed' })
- }
- }}
- 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 */}
- {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">
- {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'}`}>
- {formatElapsed(secondsOf(ollama.startedAt))}
- </span>
- </div>
- {/* Download progress bar */}
- {ollama.status === 'downloading' && ollama.total > 0 && (
- <div className="space-y-1">
- <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(ollama.received)} / {formatBytes(ollama.total)}
- </span>
- <span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
- {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'}`}>
- {ollama.logs.slice(-4).map((log, i) => (
- <p key={i}>{log}</p>
- ))}
- </div>
- </div>
- )}
-
- {/* Error */}
- {ollama.error && (
- <p className="text-[0.65rem] text-red-400 whitespace-pre-line">{ollama.error}</p>
- )}
-
- {/* LM Studio ready */}
- {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" />
- <span className="text-[0.7rem] font-medium">LM Studio is ready (server on :1234)</span>
- </div>
- </div>
- )}
-
- {/* LM Studio install — alt path. Hidden once any installer is
- running so two heavy downloads don't kick off at once.
- When `lmstudioOfflineDetected` is set we re-label this
- button as the primary action and let the same Tauri
- command handle it; the Rust side detects the existing
- install and skips straight to bootstrap+server-start
- instead of re-downloading. */}
- {!isRunning(lmstudio) && !isReady(lmstudio) && !isRunning(ollama) && !isReady(ollama) && (
- <button
- onClick={async () => {
- lmstudioDo({ type: 'start', at: Date.now() })
- try {
- await backendCall('install_lmstudio')
- const poll = setInterval(async () => {
- try {
- const s = await backendCall<InstallerStatusResponse>('install_lmstudio_status')
- 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)
- 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
- // <user>/<repo>/<file>.gguf nesting.
- setSelectedBackend('lmstudio')
- setProviderConfig('openai', {
- enabled: true,
- name: 'LM Studio',
- baseUrl: 'http://localhost:1234/v1',
- isLocal: true,
- managed: false,
- })
- } else if (s.status === 'error') {
- clearInterval(poll)
- lmstudioDo({ type: 'fail', error: withInstallerOutput('Installing LM Studio did not finish.', lastLog(s.logs)) })
- }
- } catch { /* keep polling */ }
- }, 1000)
- } catch (err) {
- 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] transition-all ${
- lmstudioOfflineDetected
- ? '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} />
- {lmstudioOfflineDetected
- ? 'Start LM Studio server'
- : 'Or install LM Studio (GUI app, ~570 MB)'}
- </button>
- )}
-
- {/* LM Studio install progress */}
- {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">
- {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'}`}>
- {formatElapsed(secondsOf(lmstudio.startedAt))}
- </span>
- </div>
- {lmstudio.status === 'downloading' && lmstudio.total > 0 && (
- <div className="space-y-1">
- <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(lmstudio.received)} / {formatBytes(lmstudio.total)}
- </span>
- <span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
- {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'}`}>
- {lmstudio.logs.slice(-4).map((log, i) => (
- <p key={i}>{log}</p>
- ))}
- </div>
- </div>
- )}
-
- {lmstudio.error && (
- <p role="alert" className="text-[0.65rem] text-red-400 whitespace-pre-line">
- {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
- // spot. Swallowing the failure meant the message
- // vanished and nothing replaced it — the one shape of
- // dud this file can produce. Put the outcome back into
- // the same line the button came from.
- onClick={() => {
- // `warn`, nicht `fail`: hier laeuft keine
- // Installation, es wird nur ein Server angestossen.
- lmstudioDo({ type: 'warn', error: '' })
- backendCall('start_lmstudio_server').catch((e) => {
- 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}`}
- >
- Start LM Studio server
- </button>
- )}
- </p>
- )}
-
- {/* Other alternatives collapsed */}
- {!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
- </summary>
- <div className="space-y-1 mt-2 max-h-[30vh] overflow-y-auto scrollbar-thin pr-1">
- {LOCAL_BACKENDS.filter(b => b.id !== 'ollama' && b.id !== 'lmstudio').map(b => (
- <button
- key={b.id}
- onClick={() => openExternal(b.url)}
- className={`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg border transition-colors group text-left ${
- isDark
- ? 'border-white/[0.06] hover:border-white/15 hover:bg-white/[0.03]'
- : 'border-gray-200 hover:border-gray-400 hover:bg-gray-50'
- }`}
- >
- <div className={`w-1.5 h-1.5 rounded-full shrink-0 ${isDark ? 'bg-gray-600' : 'bg-gray-300'}`} />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-1.5">
- <p className="text-[0.65rem] font-medium">{b.name}</p>
- <ExternalLink size={10} className={`opacity-0 group-hover:opacity-100 transition-opacity ${isDark ? 'text-gray-500' : 'text-gray-400'}`} />
- </div>
- <p className={`text-[0.5rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>{b.description}</p>
- </div>
- </button>
- ))}
- </div>
- </details>
- )}
-
- <div className="flex items-center justify-center gap-2 pt-1">
- {!isRunning(ollama) && !isRunning(lmstudio) && !isReady(ollama) && !isReady(lmstudio) && (
- <button onClick={runDetection} className={secondaryBtn}>
- <RefreshCw size={12} /> Re-Scan
- </button>
- )}
- {(isReady(ollama) || isReady(lmstudio) || (!isRunning(ollama) && !isRunning(lmstudio))) && (
- <button
- onClick={() => setStep(nextStepAfterBackends())}
- className={(isReady(ollama) || isReady(lmstudio)) ? primaryBtn : `${secondaryBtn} opacity-60`}
- >
- {(isReady(ollama) || isReady(lmstudio)) ? <>Continue <ArrowRight size={14} /></> : <>Skip for now <ChevronRight size={12} /></>}
- </button>
- )}
- </div>
- </>
- )}
- </div>
- </details>
- </>
- )}
+ <BackendsStep
+ skin={skin}
+ scan={scan}
+ fleet={fleet}
+ setStep={setStep}
+ nextStepAfterBackends={nextStepAfterBackends}
+ selectBackendAndContinue={selectBackendAndContinue}
+ />
</motion.div>
)}
@@ -1282,386 +274,7 @@ export function Onboarding() {
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
>
- {/* 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.
- </p>
-
- {/* Auto-detecting */}
- {comfyDetecting && (
- <div className="flex items-center justify-center gap-2">
- <Loader2 size={14} className="animate-spin text-gray-400" />
- <span className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>Looking for ComfyUI...</span>
- </div>
- )}
-
- {/* Bug #3: multi-install picker. When the scan found more than
- one ComfyUI directory, LU asks the user explicitly rather
- than guessing. Each option shows whether it's complete and
- whether it ships its own python_embeded — both matter for
- start_comfyui's launcher decision. */}
- {!comfyDetecting && comfyChoices.length > 1 && !comfyFound && (
- <div className="space-y-2 text-left">
- <div className={`p-2.5 rounded-lg border ${isDark ? 'bg-amber-500/10 border-amber-500/20' : 'bg-amber-50 border-amber-200'}`}>
- <p className={`text-[0.7rem] font-medium ${isDark ? 'text-amber-200' : 'text-amber-800'}`}>
- Multiple ComfyUI installs detected
- </p>
- <p className={`text-[0.6rem] mt-0.5 ${isDark ? 'text-amber-300/80' : 'text-amber-700'}`}>
- Pick the one you want LU to use. We'll remember your choice, and you can change it later in Settings → ComfyUI.
- </p>
- </div>
- <div className="space-y-1.5 max-h-44 overflow-y-auto">
- {comfyChoices.map((c) => (
- <button
- key={c.path}
- onClick={() => pickComfyInstall(c)}
- className={`w-full text-left px-3 py-2 rounded-lg border transition-colors ${
- isDark ? 'border-white/[0.08] hover:bg-white/[0.04]' : 'border-gray-200 hover:bg-gray-50'
- }`}
- >
- <div className="flex items-center justify-between gap-2">
- <span className={`text-[0.65rem] font-mono truncate ${isDark ? 'text-gray-200' : 'text-gray-800'}`}>{c.path}</span>
- <span className={`text-[0.5rem] px-1.5 py-[1px] rounded shrink-0 ${
- c.complete
- ? (isDark ? 'bg-green-500/15 text-green-400' : 'bg-green-100 text-green-700')
- : (isDark ? 'bg-amber-500/15 text-amber-300' : 'bg-amber-100 text-amber-700')
- }`}>
- {c.complete ? 'ready' : 'needs setup'}
- </span>
- </div>
- <div className={`flex items-center gap-2 mt-0.5 text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-500'}`}>
- <span>found via {c.source}</span>
- {c.has_embedded_python && (
- <span className={isDark ? 'text-blue-300' : 'text-blue-600'}>• bundles python_embeded</span>
- )}
- </div>
- </button>
- ))}
- </div>
- <button
- onClick={() => { setComfyChoices([]); setComfyFound({ found: false, complete: false }) }}
- className={`text-[0.55rem] ${isDark ? 'text-gray-500 hover:text-gray-300' : 'text-gray-500 hover:text-gray-700'} underline`}
- >
- None of these, let me install a fresh one
- </button>
- </div>
- )}
-
- {/* Found AND complete (a working install). The carcass case
- is handled in the install-options block below. */}
- {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" />
- <span className="text-[0.7rem] font-medium">ComfyUI detected</span>
- </div>
- <p className={`text-[0.55rem] font-mono mt-1 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>{comfyFound.path}</p>
- </div>
- )}
-
- {/* Not found OR found-but-incomplete — install options.
- 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) && !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`}>
- <p className={`text-[0.6rem] ${isDark ? 'text-amber-300' : 'text-amber-800'}`}>
- Found a previous ComfyUI install at <code className="font-mono">{comfyFound.path}</code> but it's missing PyTorch, looks like a previous install was interrupted. Click below to finish it.
- </p>
- </div>
- )}
- <button
- onClick={async () => {
- // P14 pre-flight, install Python first if missing,
- // then proceed with the original ComfyUI flow. Both
- // progress cards animate from this single click; the
- // user never has to interact mid-flight.
- const pythonOk = await ensurePythonInstalled()
- if (!pythonOk) return
-
- comfyDo({ type: 'start', at: Date.now(), log: 'Starting ComfyUI installation...' })
- try {
- await backendCall('install_comfyui')
- // Poll installation status
- const poll = setInterval(async () => {
- try {
- const status = await backendCall<InstallerStatusResponse>('install_comfyui_status')
- 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)
- comfyDo({ type: 'ready' })
- setComfyReady(true)
- // Auto-start ComfyUI.
- //
- // Level (b): the install DID finish, which is what
- // this step was for, so the wizard moves on to its
- // ready state either way. But "ready" would then be
- // claiming something that is not running, so say so.
- try {
- await backendCall('start_comfyui')
- } catch (e) {
- // `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)
- comfyDo({ type: 'fail', error: 'Install cancelled.' })
- } else if (status.status === 'error') {
- clearInterval(poll)
- comfyDo({ type: 'fail', error: withInstallerOutput('Installing ComfyUI did not finish.', lastLog(status.logs)) })
- }
- } catch { /* keep polling */ }
- }, 2000)
- } catch (err) {
- comfyDo({ type: 'fail', error: err instanceof Error ? err.message : 'Installation failed' })
- }
- }}
- 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>
- <button
- onClick={() => {
- const input = document.createElement('input')
- input.type = 'text'
- // Show path input inline
- setComfyPathInput('')
- setComfyFound({ found: false })
- }}
- className={secondaryBtn}
- style={{ width: '100%', justifyContent: 'center' }}
- >
- <FolderOpen size={14} /> I already have ComfyUI
- </button>
-
- {/* Manual path input */}
- {comfyPathInput !== undefined && (
- <div className="flex gap-1.5">
- <input
- type="text"
- value={comfyPathInput}
- onChange={e => setComfyPathInput(e.target.value)}
- placeholder="C:\ComfyUI"
- className={`flex-1 px-2 py-1.5 rounded-lg border text-[0.65rem] font-mono ${
- isDark ? 'bg-black border-white/10 text-white' : 'bg-white border-gray-300 text-gray-900'
- }`}
- />
- <button
- onClick={async () => {
- if (!comfyPathInput.trim()) return
- try {
- await backendCall('set_comfyui_path', { path: comfyPathInput.trim() })
- setComfyReady(true)
- // Level (b): the path — the thing the user typed —
- // was saved, so this stays out of the outer catch and
- // `ready` stands. Only the convenience auto-start
- // failed, and that is worth one line rather than
- // undoing a save that worked.
- try {
- await backendCall('start_comfyui')
- } catch (e) {
- 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) {
- comfyDo({ type: 'warn', error: err instanceof Error ? err.message : 'Invalid path' })
- }
- }}
- className={primaryBtn}
- >
- Connect
- </button>
- </div>
- )}
- </div>
- )}
-
- {/* P14: Python install progress card. Animates while winget
- pulls Python.Python.3.12 (~30 MB) and runs the silent
- installer. Sits ABOVE the ComfyUI install card so the user
- can see the dependency chain (Python → ComfyUI) when both
- run back-to-back from a single click. */}
- {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">
- <Loader2 size={14} className="animate-spin text-purple-400" />
- <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'}`}>
- {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'}`}>
- {pythonInstall.logs.slice(-6).map((log, i) => (
- <p key={i}>{log}</p>
- ))}
- </div>
- </div>
- )}
- {pythonInstall.error && !isRunning(pythonInstall) && (
- <p className="text-[0.65rem] text-red-400 whitespace-pre-line">{pythonInstall.error}</p>
- )}
-
- {/* Installing progress */}
- {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">
- {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'}`}>
- {formatElapsed(secondsOf(comfyInstall.startedAt))}
- {/* Bug #1: rolling ETA from download bytes when known. */}
- {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 % 60
- return ` • ETA ${m}:${String(s).padStart(2, '0')}`
- })()}
- </span>
- {/* Cancel button (Bug #1 — techx69) */}
- <button
- onClick={async () => {
- // Level (c): Cancel is the only way out of a multi-GB
- // download. If the call fails the progress bar keeps
- // filling and the button looks broken — and the user is
- // still paying for the bandwidth.
- comfyDo({ type: 'warn', error: '' })
- try {
- await backendCall('cancel_comfyui_install')
- } catch (e) {
- 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 ${
- isDark
- ? 'border-red-500/40 text-red-300 hover:bg-red-500/10'
- : 'border-red-300 text-red-600 hover:bg-red-50'
- }`}
- title="Cancel ComfyUI install"
- >
- Cancel
- </button>
- </div>
- </div>
- {/* Disk pressure warning (push from Rust side) */}
- {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'}`}>
- {comfyInstall.logs.find(l => l.startsWith('⚠'))}
- </div>
- )}
- {/* Download progress bar (shown during download phase) */}
- {comfyInstall.logs.some(l => l.includes('Downloading')) && comfyInstall.total > 0 && (
- <div className="space-y-1 mb-2">
- <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(comfyInstall.received)} / {formatBytes(comfyInstall.total)}
- </span>
- <span className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
- {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'}`}>
- {comfyInstall.logs.slice(-8).map((log, i) => (
- <p key={i}>{log}</p>
- ))}
- </div>
- </div>
- )}
-
- {/* Error */}
- {comfyInstall.error && (
- <p role="alert" className="text-[0.65rem] text-red-400 whitespace-pre-line">{comfyInstall.error}</p>
- )}
-
- {/* Ready state */}
- {comfyReady && (
- <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" />
- <span className="text-[0.7rem] font-medium">ComfyUI is ready</span>
- </div>
- </div>
- )}
-
- <div className="flex items-center justify-center gap-2 pt-1">
- {/* Continue only when ComfyUI is actually usable. A
- found-but-incomplete carcass shouldn't qualify — that
- install will fail at first generation. */}
- {((comfyFound?.found && comfyFound.complete !== false) || comfyReady) && (
- <button
- onClick={() => setStep('models')}
- className={primaryBtn}
- >
- Continue <ArrowRight size={14} />
- </button>
- )}
- {!isRunning(comfyInstall) && !isRunning(pythonInstall) && (!comfyFound?.found || comfyFound.complete === false) && !comfyReady && (
- <>
- <button
- onClick={() => {
- setComfyDetecting(true)
- setComfyFound(null)
- backendCall<{ found: boolean; path?: string; complete?: boolean }>('find_comfyui')
- .then(result => { setComfyFound(result); if (result.found && result.complete !== false) setComfyReady(true) })
- .catch(() => setComfyFound({ found: false, complete: false }))
- .finally(() => setComfyDetecting(false))
- }}
- className={secondaryBtn}
- >
- <RefreshCw size={12} /> Re-Scan
- </button>
- <button
- onClick={() => setStep('models')}
- className={`${secondaryBtn} opacity-60`}
- >
- Skip for now <ChevronRight size={12} />
- </button>
- </>
- )}
- </div>
+ <ComfyStep skin={skin} fleet={fleet} step={step} setStep={setStep} />
</motion.div>
)}
@@ -1674,123 +287,15 @@ export function Onboarding() {
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
>
- <div className="text-center mb-3">
- <h2 className="text-base font-semibold mb-1">Pick a starter model</h2>
- <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
- One small model to get you running. You can browse and install more from the Models tab once you're in.
- </p>
- </div>
-
- {/* Unfiltered / Mainstream tabs, only meaningful when both
- categories have entries. With the curated single-starter list
- (P4) the tabs are hidden; reintroduce only if the list grows. */}
- {ONBOARDING_MODELS.some(m => m.uncensored) && ONBOARDING_MODELS.some(m => !m.uncensored) && (
- <div className="flex gap-4 justify-center">
- <button onClick={() => setModelSubTab('uncensored')} className={`flex items-center gap-2 transition-all ${modelSubTab === 'uncensored' ? 'opacity-100' : 'opacity-40 hover:opacity-70'}`}>
- <div className={`w-1 h-4 rounded-full ${modelSubTab === 'uncensored' ? 'bg-red-500' : 'bg-red-500/50'}`} />
- <span className="text-[0.65rem] font-semibold uppercase tracking-wider">Unfiltered</span>
- </button>
- <button onClick={() => setModelSubTab('mainstream')} className={`flex items-center gap-2 transition-all ${modelSubTab === 'mainstream' ? 'opacity-100' : 'opacity-40 hover:opacity-70'}`}>
- <div className={`w-1 h-4 rounded-full ${modelSubTab === 'mainstream' ? 'bg-blue-500' : 'bg-blue-500/50'}`} />
- <span className="text-[0.65rem] font-semibold uppercase tracking-wider">Mainstream</span>
- </button>
- </div>
- )}
-
- {isDownloading && pullingModel && (
- <div className={`p-2.5 rounded-lg border ${cardClass}`}>
- <div className="flex items-center justify-between mb-1">
- <p className="text-[0.7rem]">
- Downloading <span className="font-mono font-medium">{currentModel?.label || pullingModel}</span>...
- </p>
- </div>
- <p className={`text-[0.6rem] mb-1.5 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>{currentDownload?.status || 'Starting...'}</p>
- {currentDownload?.total ? (
- <>
- <ProgressBar progress={progress} />
- <p className={`text-[0.55rem] mt-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
- {formatBytes(currentDownload.progress)} / {formatBytes(currentDownload.total)}
- {progress > 0 && <span className="ml-1.5 text-blue-400">{Math.round(progress)}%</span>}
- </p>
- </>
- ) : null}
- </div>
- )}
- {downloadError && (
- <p className={`text-[0.65rem] text-red-400 text-center`}>{downloadError}</p>
- )}
-
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-[50vh] overflow-y-auto scrollbar-thin pr-1">
- {ONBOARDING_MODELS.filter(m => {
- // Filter by tab
- if (modelSubTab === 'uncensored' && !m.uncensored) return false
- if (modelSubTab === 'mainstream' && m.uncensored) return false
- // Filter by VRAM if known
- if (systemVRAM && m.vramGB > systemVRAM) return false
- return true
- }).map((model) => {
- const selected = selectedModels.includes(model.name)
- const pulled = pulledModels.includes(model.name) || (model.filename ? downloads[model.filename]?.status === 'complete' : false)
- return (
- <button
- key={model.name}
- onClick={() => !pulled && !isDownloading && toggleModel(model.name)}
- disabled={pulled || isDownloading}
- className={`text-left p-2.5 rounded-lg border transition-colors ${
- pulled
- ? isDark ? 'bg-green-500/10 border-green-500/30' : 'bg-green-50 border-green-300'
- : selected
- ? isDark ? 'bg-white/10 border-white/30' : 'bg-gray-100 border-gray-900'
- : isDark ? 'border-white/10 hover:border-white/20' : 'border-gray-200 hover:border-gray-400'
- } ${isDownloading ? 'opacity-60' : ''}`}
- >
- <div className="flex items-start justify-between gap-2">
- <div>
- <div className="flex items-center gap-1.5">
- <span className="font-medium text-[0.7rem]">{model.label}</span>
- {model.recommended && showRecommendedBadge && (
- <span className={`text-[0.5rem] px-1 py-0.5 rounded ${isDark ? 'bg-white/10 text-gray-300' : 'bg-gray-200 text-gray-600'}`}>
- Recommended
- </span>
- )}
- </div>
- <p className={`text-[0.6rem] mt-0.5 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>{model.description}</p>
- <p className={`text-[0.55rem] mt-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
- {model.size} · VRAM: {model.vram}
- </p>
- </div>
- {pulled ? (
- <Check size={14} className="text-green-400 shrink-0 mt-0.5" />
- ) : selected ? (
- <div className={`w-4 h-4 rounded flex items-center justify-center shrink-0 mt-0.5 ${isDark ? 'bg-white' : 'bg-gray-900'}`}>
- <Check size={10} className={isDark ? 'text-black' : 'text-white'} />
- </div>
- ) : (
- <div className={`w-4 h-4 rounded border shrink-0 mt-0.5 ${isDark ? 'border-white/20' : 'border-gray-300'}`} />
- )}
- </div>
- </button>
- )
- })}
- </div>
-
- <div className="flex items-center gap-2 pt-1">
- {selectedModels.length > 0 && !isDownloading ? (
- <button
- onClick={handleDownloadSelected}
- 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>
- ) : !isDownloading ? (
- <button
- onClick={() => setStep('embeddings')}
- className={`flex-1 flex items-center justify-center gap-1.5 ${secondaryBtn}`}
- >
- Skip for now <ChevronRight size={14} />
- </button>
- ) : null}
- </div>
+ <ModelsStep
+ skin={skin}
+ scan={scan}
+ fleet={fleet}
+ step={step}
+ setStep={setStep}
+ pulledModels={pulledModels}
+ setPulledModels={setPulledModels}
+ />
</motion.div>
)}
@@ -1803,78 +308,7 @@ export function Onboarding() {
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
>
- <div className="text-center mb-2">
- <h2 className="text-base font-semibold mb-1">Document Chat (optional)</h2>
- <p className={`text-[0.7rem] ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
- Drop a PDF, Word doc, or text file into chat and the model can answer questions about it. Needs a small embedding model.
- </p>
- </div>
-
- {embeddingsAlreadyHave === true && !embeddingsPulled && (
- <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" />
- <span className="text-[0.7rem] font-medium">Embedding model already installed, Document Chat is ready.</span>
- </div>
- </div>
- )}
-
- {embeddingsAlreadyHave !== true && (
- <div className={`p-3 rounded-lg border ${cardClass}`}>
- <div className="flex items-start justify-between gap-2">
- <div className="flex-1 min-w-0">
- <p className="text-[0.7rem] font-medium">nomic-embed-text</p>
- <p className={`text-[0.6rem] mt-0.5 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
- Standard embedding model from Nomic AI. Used purely on-device to chunk and retrieve your documents, never sent anywhere.
- </p>
- <p className={`text-[0.55rem] mt-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
- {embedsViaBundled ? '84 MB · bundled engine, runs on any CPU' : '274 MB · runs on any CPU'}
- </p>
- </div>
- </div>
-
- {embeddingsPulling && (
- <div className="mt-2.5 space-y-1">
- <ProgressBar progress={embeddingsProgress.total > 0 ? (embeddingsProgress.completed / embeddingsProgress.total) * 100 : 0} />
- <p className={`text-[0.55rem] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
- {embeddingsProgress.total > 0
- ? `${formatBytes(embeddingsProgress.completed)} / ${formatBytes(embeddingsProgress.total)}`
- : 'Starting…'}
- </p>
- </div>
- )}
-
- {embeddingsPulled && (
- <div className="mt-2.5 flex items-center gap-2 text-[0.65rem] text-green-400">
- <Check size={12} /> Installed. Document Chat is ready.
- </div>
- )}
-
- {embeddingsError && (
- <p className="text-[0.6rem] text-red-400 mt-2">{embeddingsError}</p>
- )}
- </div>
- )}
-
- <div className="flex items-center gap-2 pt-1">
- {embeddingsAlreadyHave !== true && !embeddingsPulled && !embeddingsPulling && (
- <button onClick={handlePullEmbeddings} className={primaryBtn} style={{ flex: 1 }}>
- <Download size={14} /> Install nomic-embed-text ({embedsViaBundled ? '84 MB' : '274 MB'})
- </button>
- )}
- <button
- onClick={() => setStep('done')}
- disabled={embeddingsPulling}
- className={`${secondaryBtn} ${embeddingsPulling ? 'opacity-40 cursor-not-allowed' : ''}`}
- style={{ flex: embeddingsAlreadyHave === true || embeddingsPulled ? 1 : undefined }}
- >
- {embeddingsAlreadyHave === true || embeddingsPulled ? (
- <>Continue <ArrowRight size={14} /></>
- ) : (
- <>Skip for now <ChevronRight size={14} /></>
- )}
- </button>
- </div>
+ <EmbeddingsStep skin={skin} scan={scan} fleet={fleet} step={step} setStep={setStep} />
</motion.div>
)}
diff --git a/src/components/onboarding/__tests__/installer-state.test.ts b/src/components/onboarding/__tests__/installer-state.test.ts
index a6198b91..4cec3bcb 100644
--- a/src/components/onboarding/__tests__/installer-state.test.ts
+++ b/src/components/onboarding/__tests__/installer-state.test.ts
@@ -15,10 +15,24 @@
* gezaehlt, nicht behauptet, und sie sind eine Sperrklinke: sie duerfen
* sinken, nicht steigen.
*
+ * ── Warum hier jetzt ein ORDNER gezaehlt wird und nicht eine Datei ────────
+ *
+ * Der Assistent ist mit W-T3 aus `Onboarding.tsx` in mehrere Module
+ * zerfallen. Wuerde die Sperrklinke weiter nur `Onboarding.tsx` zaehlen,
+ * waere sie ab diesem Tag wertlos: sie ginge von 25 auf 2 und liesse sich
+ * kuenftig durch jedes Verschieben unterlaufen. Gezaehlt wird deshalb der
+ * ganze Assistent — und damit die Zahl nicht still weglaufen kann, wenn
+ * jemand eine Datei dazulegt, prueft ein eigener Fall, dass die Liste unten
+ * WIRKLICH alle Dateien des Ordners abdeckt.
+ *
+ * `BackendSelector.tsx` liegt im selben Ordner und gehoert nicht dazu: es ist
+ * die Backend-Auswahl der EINSTELLUNGEN, nicht ein Schritt des Assistenten.
+ * Es stand nie in den 58 und steht auch jetzt nicht in den 25.
+ *
* Lauf: npx vitest run src/components/onboarding/__tests__/installer-state.test.ts
*/
import { describe, it, expect } from 'vitest'
-import { readFileSync } from 'node:fs'
+import { readFileSync, readdirSync } from 'node:fs'
import { resolve } from 'node:path'
import {
installerReducer,
@@ -39,7 +53,33 @@ import {
const codeOnly = (src: string) =>
src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1')
-const SRC = codeOnly(readFileSync(resolve(__dirname, '..', 'Onboarding.tsx'), 'utf8'))
+const DIR = resolve(__dirname, '..')
+const lies = (name: string) => codeOnly(readFileSync(resolve(DIR, name), 'utf8'))
+
+/** Die Dateien, aus denen der Assistent nach der Zerlegung besteht. */
+const ASSISTENT = [
+ 'Onboarding.tsx',
+ 'BackendsStep.tsx',
+ 'ComfyStep.tsx',
+ 'ModelsStep.tsx',
+ 'EmbeddingsStep.tsx',
+ 'use-backend-scan.ts',
+ 'use-installer-fleet.ts',
+ 'onboarding-skin.ts',
+ 'onboarding-host.ts',
+ 'wait-for-download.ts',
+ 'installer-state.ts',
+ 'wizard-steps.ts',
+]
+
+/** Liegt im selben Ordner, ist aber kein Schritt des Assistenten. */
+const NICHT_DER_ASSISTENT = ['BackendSelector.tsx']
+
+/** Der ganze Assistent als ein Text — die Sperrklinke zaehlt darauf. */
+const SRC = ASSISTENT.map(lies).join('\n')
+
+/** Die Flotte allein: dort, wo die vier Installer verdrahtet sind. */
+const FLOTTE = lies('use-installer-fleet.ts')
/** Kurzschreibweise: eine Folge von Aktionen auf den Ruhezustand anwenden. */
const run = (...actions: Parameters<typeof installerReducer>[1][]): InstallerState =>
@@ -167,19 +207,37 @@ 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', () => {
+ it('der ganze Assistent haelt hoechstens 25 `useState` — vorher 58 in EINER Datei', () => {
// 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.
+ //
+ // Nach W-T3 zaehlt diese Zeile den ORDNER, nicht mehr die eine Datei.
+ // Genau das ist der Punkt: die Zerlegung durfte die 25 verteilen, nicht
+ // vermehren. Sie hat sie verteilt — 25 vorher, 25 nachher.
expect(useStates).toBeLessThanOrEqual(25)
})
- it('die vier Installer sind vier Reducer auf EINER Maschine', () => {
+ it('die Liste oben deckt den Ordner wirklich ab — sonst zaehlt die Sperrklinke ins Leere', () => {
+ // Ohne diesen Fall waere die Zerlegung selbst das Schlupfloch: eine
+ // sechste Schrittdatei, in der Liste vergessen, brächte beliebig viele
+ // `useState` mit, ohne dass oben die Zahl steigt.
+ const imOrdner = readdirSync(DIR).filter((n) => /\.tsx?$/.test(n)).sort()
+ expect(imOrdner).toEqual([...ASSISTENT, ...NICHT_DER_ASSISTENT].sort())
+ })
+
+ it('die vier Installer sind vier Reducer auf EINER Maschine — und in EINER Datei', () => {
expect(useReducers).toBe(4)
for (const name of ['comfyInstall', 'pythonInstall', 'ollama', 'lmstudio']) {
expect(SRC).toContain(`useReducer(installerReducer, IDLE_INSTALLER)`)
expect(SRC, name).toContain(name)
}
+ // Schaerfer als vorher, und das ist der Ertrag der Zerlegung: alle vier
+ // stehen zusammen in `use-installer-fleet.ts`. Waeren sie auf die
+ // Schritte verteilt, teilten sie sich zwangslaeufig auch keinen Takt
+ // mehr — Ollama/LM Studio zeichnet der Backend-Schritt, ComfyUI/Python
+ // der ComfyUI-Schritt, und keiner sieht die Startzeit des anderen.
+ expect((FLOTTE.match(/=\s*useReducer\(/g) ?? []).length).toBe(4)
})
it('und die Maschine steht genau einmal, in einer eigenen Datei', () => {
diff --git a/src/components/onboarding/__tests__/onboarding-schritte-und-primaer.test.ts b/src/components/onboarding/__tests__/onboarding-schritte-und-primaer.test.ts
index ae6d5f34..879d546f 100644
--- a/src/components/onboarding/__tests__/onboarding-schritte-und-primaer.test.ts
+++ b/src/components/onboarding/__tests__/onboarding-schritte-und-primaer.test.ts
@@ -32,7 +32,32 @@ import { STEP_ORDER, WORK_STEPS, workStepsFor, wizardProgress } from '../wizard-
const codeOnly = (src: string) =>
src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1')
-const SRC = codeOnly(readFileSync(resolve(__dirname, '..', 'Onboarding.tsx'), 'utf8'))
+/**
+ * Zwei Heuhaufen, und der Unterschied ist die halbe Aussage dieses Tests.
+ *
+ * Seit W-T3 ist der Assistent kein Einzelstueck mehr: die SCHALE haelt den
+ * Rahmen (Fensterbalken, Fortschrittsanzeiger, Willkommen, Fertig), die vier
+ * Arbeitsschritte liegen daneben, und die gemeinsame Formsprache steht in
+ * `onboarding-skin.ts`.
+ *
+ * SRC — nur die Schale. Alles, was der RAHMEN behauptet, muss dort stehen
+ * und nirgends sonst: D-S37 (die H1), D-S38 (eine Spalte, ein fester
+ * Anzeiger, genau ein `fixed`), D-S35 (die Schrittrechnung).
+ * ALL — der ganze Assistent. Alles, was eine VOKABEL ist, gilt ueberall:
+ * das Primaerrezept, die Negativkontrollen, das Icon aus D-S39.
+ *
+ * Waere alles gegen ALL geprueft, koennte der Fensterbalken in einen Schritt
+ * wandern und der Test bliebe gruen. Waere alles gegen SRC geprueft, waere
+ * er seit der Zerlegung fast leer.
+ */
+const DIR = resolve(__dirname, '..')
+const SRC = codeOnly(readFileSync(resolve(DIR, 'Onboarding.tsx'), 'utf8'))
+const ALL = [
+ 'Onboarding.tsx', 'BackendsStep.tsx', 'ComfyStep.tsx', 'ModelsStep.tsx',
+ 'EmbeddingsStep.tsx', 'onboarding-skin.ts', 'use-backend-scan.ts',
+ 'use-installer-fleet.ts', 'onboarding-host.ts', 'wait-for-download.ts',
+ 'wizard-steps.ts', 'installer-state.ts',
+].map((n) => codeOnly(readFileSync(resolve(DIR, n), 'utf8'))).join('\n')
const CSS = readFileSync(resolve(__dirname, '..', '..', '..', 'index.css'), 'utf8')
const MAC = true
@@ -91,8 +116,8 @@ describe('D-S35: der Anzeiger zaehlt Arbeitsschritte, nicht Bildschirme', () =>
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')
+ expect(ALL).not.toContain('visibleStepOrder')
+ expect(ALL).not.toContain('const stepIndex')
})
})
@@ -100,16 +125,16 @@ describe('D-S35: der Anzeiger zaehlt Arbeitsschritte, nicht Bildschirme', () =>
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")
+ expect(ALL).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)
+ expect((ALL.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')
+ expect(ALL).not.toContain('bg-white text-black hover:bg-gray-200')
+ expect(ALL).not.toContain('bg-gray-900 text-white hover:bg-gray-800')
})
it('das Rezept liegt weiterhin an EINER Stelle, in index.css', () => {
@@ -138,8 +163,8 @@ describe('D-S36: der Hover macht den Primaerknopf heller, nicht dunkler', () =>
})
it('die Sekundaerknoepfe bleiben sekundaer — sonst waere nur alles laut', () => {
- expect(SRC).toContain("const secondaryBtn = ")
- expect(SRC).not.toContain("const secondaryBtn = 'lu-primary")
+ expect(ALL).toContain("const secondaryBtn = ")
+ expect(ALL).not.toContain("const secondaryBtn = 'lu-primary")
})
})
@@ -190,7 +215,7 @@ describe('D-S37: die H1 ist eine Ueberschrift, kein Label', () => {
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')
+ expect(ALL).not.toContain('fixed top-10')
})
it('Anzeiger und Karte stehen in EINER Spalte mit einem benannten Abstand', () => {
@@ -206,7 +231,7 @@ describe('D-S38: die Punkte gehoeren zum Assistenten, nicht zur Titelleiste', ()
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)
+ expect((ALL.match(/className="fixed /g) ?? []).length).toBe(1)
})
})
@@ -214,22 +239,136 @@ describe('D-S38: die Punkte gehoeren zum Assistenten, nicht zur Titelleiste', ()
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')
+ expect(ALL).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")
+ expect(ALL).toMatch(/<ImageIcon size=\{ICON_LG\} className="text-lu-accent" \/>/)
+ expect(ALL).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+\}/)
+ expect(ALL).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')
+ expect(ALL).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)
})
})
+
+// ── D-S39, zweite Haelfte — „vier Buttons in vier Behandlungen" ───────────
+//
+// Der Audit-Bullet hatte zwei Teile. Der erste (das Icon oben) war erledigt,
+// der zweite nicht: auf DEM Bildschirm, den D-S39 benennt, standen vier
+// Knoepfe in vier Behandlungen. Zwei liefen bereits ueber `.lu-primary`
+// (`Install ComfyUI`, `Connect`), zwei nicht:
+//
+// „I already have ComfyUI" Sekundaerrezept fuer die Farbe, aber Breite und
+// Ausrichtung aus einem INLINE-STIL — die Form kam
+// aus einer zweiten Quelle.
+// „Cancel" ein Einzelstueck: 8,8px Schrift, 1px senkrechtes
+// Polster, eigener Radius, rote Kante.
+//
+// Beide sind jetzt auf vorhandenen Rezepten, ohne eine neue Farbe und ohne
+// eine neue Klasse: der eine auf der Sekundaerbehandlung dieser Datei, der
+// andere auf `.lu-control` aus index.css.
+
+describe('D-S39 (2): die vier Knoepfe des ComfyUI-Schrittes tragen zwei Rezepte', () => {
+ const COMFY = codeOnly(readFileSync(resolve(DIR, 'ComfyStep.tsx'), 'utf8'))
+
+ /** Die className-Kette jedes `<button>` im Abschnitt, in Reihenfolge. */
+ function buttonClassNames(region: string): string[] {
+ const out: string[] = []
+ for (const m of region.matchAll(/<button\b/g)) {
+ const tagStart = m.index
+ const at = region.indexOf('className=', tagStart)
+ if (at < 0) continue
+ let i = at + 'className='.length
+ if (region[i] === '"' || region[i] === "'") {
+ const quote = region[i]
+ out.push(region.slice(i + 1, region.indexOf(quote, i + 1)))
+ } else if (region[i] === '{') {
+ let depth = 0
+ const start = i
+ for (; i < region.length; i++) {
+ if (region[i] === '{') depth++
+ else if (region[i] === '}' && --depth === 0) break
+ }
+ out.push(region.slice(start + 1, i))
+ }
+ }
+ return out
+ }
+
+ const KNOEPFE = buttonClassNames(COMFY)
+
+ it('der Abschnitt wird wirklich gelesen — sonst prueft alles unten nichts', () => {
+ expect(COMFY.length).toBeGreaterThan(2000)
+ // Neun `<button>`: die beiden Listenformen (Install-Auswahl, „None of
+ // these"), die vier aus dem Audit-Bullet und die drei der Fusszeile
+ // (Re-Scan, Skip for now, Continue).
+ expect(KNOEPFE).toHaveLength(9)
+ })
+
+ it('die zwei, die schon auf dem Rezept liefen, laufen weiter darauf', () => {
+ expect(COMFY).toContain('className="lu-primary w-full flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-[0.7rem] transition-all"')
+ expect(COMFY).toMatch(/className=\{primaryBtn\}\s*>\s*\n\s*Connect/)
+ })
+
+ it('„I already have ComfyUI" holt seine Form nicht mehr aus einem Inline-Stil', () => {
+ expect(COMFY).toContain('className={`${secondaryBtn} w-full justify-center`}')
+ // Die zweite Quelle ist weg — nicht nur hier, im ganzen Assistenten.
+ expect(ALL).not.toContain("style={{ width: '100%', justifyContent: 'center' }}")
+ // Und die Vokabel ist die seines Nachbarn, keine neue: derselbe
+ // Install-Knopf darueber sagt Breite und Ausrichtung genauso.
+ expect(COMFY).toContain('lu-primary w-full flex items-center justify-center')
+ })
+
+ it('„Cancel" traegt das neutrale Hausrezept, nicht mehr sein eigenes', () => {
+ expect(COMFY).toContain('data-active="true"')
+ expect(COMFY).toContain('className="lu-control"')
+ // Das Einzelstueck ist fort: eigene Schriftgroesse, eigenes Polster,
+ // eigener Radius, eigene Kante.
+ expect(ALL).not.toContain('text-[0.55rem] px-1.5 py-[1px] rounded border transition-colors')
+ expect(ALL).not.toContain('border-red-500/40 text-red-300 hover:bg-red-500/10')
+ expect(ALL).not.toContain('border-red-300 text-red-600 hover:bg-red-50')
+ })
+
+ it('`.lu-control` ist nicht hier erfunden, sondern das Rezept aus index.css', () => {
+ expect((CSS.match(/^\.lu-control\s*\{/gm) ?? [])).toHaveLength(1)
+ // `data-active` ist dort ein echter Zustand, keine Dekoration.
+ expect(CSS).toMatch(/\.lu-control:not\(\.lu-primary\)\[data-active='true'\]/)
+ })
+
+ it('DIE BEGRUENDUNG, nachgerechnet: neutral ist hier nicht die leisere Wahl', () => {
+ // index.css schreibt fuer Stop auf, warum ein Ausstieg aus einem
+ // LAUFENDEN Vorgang neutral bleibt und nicht rot wird — „Rot heisst in
+ // dieser App kaputt oder wird geloescht". Abbrechen einer Installation
+ // ist dieselbe Rolle. Die Zahlen sagen dazu, dass die Umstellung nichts
+ // an Lesbarkeit kostet:
+ // dunkel #9ca3af auf der Karte #202020
+ // hell #4b5563 auf der Karte #f9fafb
+ expect(contrast('#9ca3af', '#202020')).toBeCloseTo(6.42, 2)
+ expect(contrast('#4b5563', '#f9fafb')).toBeCloseTo(7.23, 2)
+ // Der hellere der beiden alten Zustaende lag bei 4.62:1, also knapp
+ // ueber AA — die neutrale Fassung ist in beiden Modi deutlicher.
+ expect(contrast('#dc2626', '#f9fafb')).toBeCloseTo(4.62, 2)
+ expect(contrast('#4b5563', '#f9fafb')).toBeGreaterThan(contrast('#dc2626', '#f9fafb'))
+ })
+
+ it('NEGATIVKONTROLLE: der Schritt hat dadurch keine dritte Behandlung bekommen', () => {
+ // Jeder Knopf traegt eins der vier bekannten Rezepte — ausser den zwei,
+ // die keine Knoepfe im Sinne der Formsprache sind und deshalb hier
+ // namentlich stehen: die Zeilen der Install-Auswahl (eine Liste) und
+ // „None of these…" (ein Textlink).
+ const fremd = KNOEPFE.filter((c) =>
+ !/primaryBtn|secondaryBtn|lu-primary|lu-control/.test(c),
+ )
+ expect(fremd).toHaveLength(2)
+ expect(fremd[0]).toContain('w-full text-left px-3 py-2 rounded-lg border')
+ expect(fremd[1]).toContain('underline')
+ })
+})
diff --git a/src/components/onboarding/onboarding-host.ts b/src/components/onboarding/onboarding-host.ts
new file mode 100644
index 00000000..47d20f37
--- /dev/null
+++ b/src/components/onboarding/onboarding-host.ts
@@ -0,0 +1,20 @@
+/**
+ * Laeuft der Assistent im Desktop-Fenster oder in einer Browser-Vorschau?
+ *
+ * Warum das ein eigenes Modul ist und keine drei Kopien: nach der Zerlegung
+ * fragen DREI Dateien danach — die Schale (Fensterknoepfe, `set_onboarding_done`
+ * am Ende), der Modellschritt (Ollama vor dem Pull anwerfen) und der
+ * Einbettungsschritt (der Pull braucht die Desktop-App). Drei Kopien EINES
+ * Praedikats sind genau das Muster, das AS-09 aus dieser Datei geraeumt hat.
+ *
+ * Warum NICHT `isTauri()` aus `api/backend.ts`: das ist ein anderes Praedikat.
+ * Jenes akzeptiert zusaetzlich das alte Tauri-v1-Global `__TAURI__`; der
+ * Assistent hat seit jeher nur auf `__TAURI_INTERNALS__` geprueft. Die beiden
+ * gegeneinander zu tauschen waere eine Verhaltensaenderung, keine Aufraeumung —
+ * also bleibt hier der strenge v2-Test stehen, und dieser Kommentar sagt, dass
+ * der Unterschied bekannt ist und nicht uebersehen wurde.
+ *
+ * Einmal beim Laden ausgewertet, nicht pro Aufruf: so stand es vorher auch,
+ * und ein Fenster wechselt seinen Wirt nicht mitten im Assistenten.
+ */
+export const isTauri = typeof window !== 'undefined' && !!window.__TAURI_INTERNALS__
diff --git a/src/components/onboarding/onboarding-skin.ts b/src/components/onboarding/onboarding-skin.ts
new file mode 100644
index 00000000..b26e182b
--- /dev/null
+++ b/src/components/onboarding/onboarding-skin.ts
@@ -0,0 +1,56 @@
+/**
+ * Die Formsprache des Assistenten: zwei Knopf-Behandlungen und zwei Flaechen.
+ *
+ * Warum es dieses Modul gibt: nach der Zerlegung zeichnen FUENF Dateien
+ * dieselben Knoepfe — die Schale (Willkommen, Fertig) und die vier Schritte.
+ * Ein Rezept, das in fuenf Dateien je einmal dasteht, ist kein Rezept mehr,
+ * sondern fuenf Rezepte, die heute noch zufaellig gleich aussehen. Genau
+ * diesen Zerfall hat D-S36 in dieser Komponente vorgefunden: der Primaerknopf
+ * hatte sein eigenes Graustufen-Paar, waehrend `.lu-primary` in `index.css`
+ * schon lange danebenlag.
+ *
+ * Was hier NICHT steht: eine neue Farbe, ein neues Rezept, eine neue Zahl.
+ * `primaryBtn` traegt `.lu-primary` aus `index.css` und legt nur die Geometrie
+ * dazu, die dieser Bildschirm braucht. Die Sekundaerbehandlung bleibt
+ * ausdruecklich sekundaer — sonst waere alles gleich laut, und der Assistent
+ * haette wieder keinen Vorschlag.
+ *
+ * `isDark` faehrt hier mit, obwohl es keine Klasse ist: es ist die EINE
+ * Entscheidung, aus der alle vier Zeichenketten fallen, und die Schritte
+ * rechnen daraus noch ihre eigenen Zweige. Zweimal dasselbe aus dem Store zu
+ * lesen waere zwei Abonnements fuer eine Frage.
+ */
+
+export interface OnboardingSkin {
+ /** Dunkelmodus? Die Schritte leiten daraus ihre eigenen Zweige ab. */
+ isDark: boolean
+ /** Der Vollbild-Grund, auf dem der Assistent steht. */
+ bgClass: string
+ /** Die ruhige Karte: Installationsfortschritt, Modellkarte, nomic-Karte. */
+ cardClass: string
+ /** Die eine betonte Aktion eines Bildschirms. */
+ primaryBtn: string
+ /** Alles, was daneben steht: Re-Scan, Skip, „I already have …". */
+ secondaryBtn: string
+}
+
+export function onboardingSkin(isDark: boolean): OnboardingSkin {
+ const bgClass = isDark ? 'bg-[#202020] text-white' : 'bg-white text-gray-900'
+ const cardClass = isDark ? 'bg-[#202020] border-white/[0.08]' : 'bg-gray-50 border-gray-200'
+
+ // 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-colors ${
+ isDark ? 'bg-white/10 text-white hover:bg-white/15' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
+ }`
+
+ return { isDark, bgClass, cardClass, primaryBtn, secondaryBtn }
+}
diff --git a/src/components/onboarding/use-backend-scan.ts b/src/components/onboarding/use-backend-scan.ts
new file mode 100644
index 00000000..6fd9a653
--- /dev/null
+++ b/src/components/onboarding/use-backend-scan.ts
@@ -0,0 +1,112 @@
+/**
+ * Welche Maschine der Assistent nachher anspricht — der geteilte Kern des
+ * ganzen Assistenten.
+ *
+ * Warum es dieses Modul gibt: das Ergebnis des Port-Scans ist der einzige
+ * Zustand, den FUENF der sechs Bildschirme anfassen, und zwei von ihnen
+ * schreiben ihn:
+ *
+ * Willkommen startet den Scan beim Weiterklicken
+ * Backends zeichnet ihn, laesst waehlen, scannt neu
+ * Modelle entscheidet daran, WOHIN eine GGUF geschrieben wird
+ * (Ollama-Pull, App-Ordner, LM-Studio-Verschachtelung)
+ * Einbettungen entscheidet daran, welcher Embeddings-Weg genommen wird
+ * Fertig nennt den verbundenen Backend beim Namen
+ *
+ * Genau deshalb steht er NICHT im Backend-Schritt, obwohl er dort gezeichnet
+ * wird: ein Schritt, der den Zustand von vier anderen haelt, ist kein Schritt,
+ * sondern die Schale mit einer Tarnkappe. Er steht hier, oberhalb der
+ * Schritte, und wird ihnen gereicht.
+ *
+ * Was der Schritt dagegen SELBST behaelt: `detecting` faerbt nur seinen
+ * eigenen Bildschirm — es steht trotzdem hier, weil `runDetection` es setzt
+ * und die Funktion von zwei Bildschirmen gerufen wird. Ein Flag, das eine
+ * Funktion setzt, gehoert zu der Funktion.
+ */
+import { useState } from 'react'
+import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-detector'
+import { BUILTIN_BACKEND_ID } from '../../lib/onboarding-backend'
+import { backendCall } from '../../api/backend'
+import { isTauri } from './onboarding-host'
+import type { LmStudioServerStatus } from '../models/ModelSelector'
+
+export interface BackendScan {
+ detectedBackends: DetectedBackend[]
+ detecting: boolean
+ selectedBackend: string
+ setSelectedBackend: (id: string) => void
+ /** LM Studio liegt auf der Platte, sein Server hoert aber nicht zu. */
+ lmstudioOfflineDetected: boolean
+ /** GGUFs in `~/.lmstudio/models/`, als Vertrauenshinweis in der Karte. */
+ lmstudioModelCount: number
+ runDetection: () => Promise<void>
+}
+
+export function useBackendScan(): BackendScan {
+ const [detectedBackends, setDetectedBackends] = useState<DetectedBackend[]>([])
+ const [detecting, setDetecting] = useState(false)
+ // 2.5.7: the built-in engine is the pre-selected default — a fresh install
+ // needs nothing installed. Detected Ollama/LM Studio are offered as Advanced.
+ const [selectedBackend, setSelectedBackend] = useState<string>(BUILTIN_BACKEND_ID)
+ // 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
+ // re-install. The install_lmstudio Tauri command is idempotent — it
+ // detects the existing install and skips straight to bootstrap+server
+ // start — so we route through the same code path either way; only the
+ // UI labelling differs.
+ const [lmstudioOfflineDetected, setLmstudioOfflineDetected] = useState(false)
+ // Soft-detect: GGUFs in ~/.lmstudio/models/ even when we can't locate
+ // lms.exe. Set when techx69-style users have LM Studio installed
+ // system-wide (C:\Program Files\LM Studio) and the Rust path scan misses
+ // it, but the canonical models dir is populated anyway. We surface a
+ // "Start LM Studio server" CTA either way — the model count gives a
+ // confidence cue in the offline-detected card.
+ const [lmstudioModelCount, setLmstudioModelCount] = useState(0)
+
+ /* ── Scan for backends ──────────────────────────────────── */
+ const runDetection = async () => {
+ setDetecting(true)
+ setLmstudioOfflineDetected(false)
+ setLmstudioModelCount(0)
+ const backends = await detectLocalBackends()
+ setDetectedBackends(backends)
+ if (backends.length > 0 && !selectedBackend) {
+ setSelectedBackend(backends[0].id)
+ } else if (backends.length === 0 && isTauri) {
+ // No live backend on any well-known port. Before we push the user
+ // through a 570 MB LM-Studio re-install, ask the Rust side whether
+ // LM Studio is actually present on disk — its embedded server may
+ // just be turned off. lmstudio_server_status is cheap (a single
+ // reqwest probe + a path check) and was added in the same sweep
+ // that introduced this branch.
+ //
+ // v2.4.4 (Bug #2): the status payload now also includes
+ // `models_detected` / `model_count` — set by scanning
+ // ~/.lmstudio/models/ for GGUF files. We treat that as a strong
+ // soft-detect signal: if the user has models in the canonical dir,
+ // they obviously *have* LM Studio, regardless of whether our path
+ // scan turned up lms.exe (techx69's system-wide install reproed this).
+ try {
+ const status = await backendCall<LmStudioServerStatus>('lmstudio_server_status')
+ const offline = status?.lms_present && !status?.running
+ const softDetect = status?.models_detected && !status?.running
+ if (offline || softDetect) {
+ setLmstudioOfflineDetected(true)
+ setLmstudioModelCount(Number(status?.model_count) || 0)
+ }
+ } catch { /* command unavailable — ignore */ }
+ }
+ setDetecting(false)
+ }
+
+ return {
+ detectedBackends,
+ detecting,
+ selectedBackend,
+ setSelectedBackend,
+ lmstudioOfflineDetected,
+ lmstudioModelCount,
+ runDetection,
+ }
+}
diff --git a/src/components/onboarding/use-installer-fleet.ts b/src/components/onboarding/use-installer-fleet.ts
new file mode 100644
index 00000000..63e4fca7
--- /dev/null
+++ b/src/components/onboarding/use-installer-fleet.ts
@@ -0,0 +1,93 @@
+/**
+ * Die vier Installer des Assistenten — und der EINE Takt, der sie zaehlt.
+ *
+ * Warum es dieses Modul gibt (und nicht vier Module, eins je Schritt):
+ * Ollama, LM Studio, ComfyUI und Python sind vier Anzeigen DERSELBEN
+ * Zustandsmaschine (AS-09, `./installer-state.ts`), und sie teilen sich eine
+ * Uhr. Eine Zerlegung „pro Schritt" haette genau das wieder auseinandergerissen:
+ * Ollama und LM Studio wohnen im Backend-Schritt, ComfyUI und Python im
+ * ComfyUI-Schritt — vier `useReducer` auf zwei Dateien, und die eine Uhr
+ * waere zwangslaeufig wieder zu zweien geworden, weil kein Schritt die
+ * Startzeit des anderen sieht. Genau der Zustand, den AS-09 abgeraeumt hat
+ * (vier `setInterval`, vier `elapsed`-States).
+ *
+ * Deshalb liegt die Flotte HIER, oberhalb der Schritte, und die Schritte
+ * bekommen nur die Anzeige, die sie zeichnen. Der Schnitt folgt dem geteilten
+ * Zustand, nicht der Bildschirmfolge.
+ *
+ * Was das Modul NICHT tut: es startet nichts und es pollt nichts. Welcher
+ * Tauri-Befehl gerufen und wie sein Status gelesen wird, gehoert zu dem
+ * Schritt, der den Knopf zeichnet — das ist pro Installer verschieden und
+ * waere hier vier Sonderfaelle in einer Datei, die gerade dafuer da ist,
+ * dass es keine vier mehr gibt.
+ */
+import { useEffect, useReducer, useState, type Dispatch } from 'react'
+import {
+ installerReducer, IDLE_INSTALLER, elapsedSeconds,
+ type InstallerState, type InstallerAction,
+} from './installer-state'
+
+export interface InstallerFleet {
+ ollama: InstallerState
+ ollamaDo: Dispatch<InstallerAction>
+ lmstudio: InstallerState
+ lmstudioDo: Dispatch<InstallerAction>
+ comfyInstall: InstallerState
+ comfyDo: Dispatch<InstallerAction>
+ pythonInstall: InstallerState
+ pythonDo: Dispatch<InstallerAction>
+ /** Laufzeit einer Installation in Sekunden, aus dem gemeinsamen Takt. */
+ secondsOf: (startedAt: number | null) => number
+}
+
+export function useInstallerFleet(): InstallerFleet {
+ // 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)
+ // P14: Python install state. On a fresh Windows box `python` is the
+ // Microsoft Store stub which exit-1's `pip install`. The ComfyUI install
+ // 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`.
+ // 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)
+ // 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)
+
+ // 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.startedAt
+ useEffect(() => {
+ if (anyStartedAt === null) return
+ const timer = setInterval(() => setNow(Date.now()), 1000)
+ return () => clearInterval(timer)
+ }, [anyStartedAt])
+
+ return {
+ ollama, ollamaDo,
+ lmstudio, lmstudioDo,
+ comfyInstall, comfyDo,
+ pythonInstall, pythonDo,
+ secondsOf,
+ }
+}
diff --git a/src/components/onboarding/wait-for-download.ts b/src/components/onboarding/wait-for-download.ts
new file mode 100644
index 00000000..3c409ae0
--- /dev/null
+++ b/src/components/onboarding/wait-for-download.ts
@@ -0,0 +1,29 @@
+/**
+ * Warten, bis eine Datei WIRKLICH auf der Platte liegt.
+ *
+ * Warum es dieses Modul gibt: zwei Schritte des Assistenten starten nach dem
+ * Herunterladen einen Server auf der Datei — der Modellschritt `llama-server`
+ * auf der Chat-GGUF, der Einbettungsschritt den Embeddings-Server auf der
+ * nomic-GGUF. Beide duerfen das erst tun, wenn der Bytestrom zu Ende ist,
+ * sonst startet die Maschine auf einem halben File. Das ist der EINZIGE
+ * Zustand, den sich diese beiden Schritte teilen; alles andere an ihnen ist
+ * privat. Genau deshalb steht er hier und nicht in einem von beiden.
+ *
+ * Gepollt statt abonniert, und das ist Absicht: der Fortschrittsbalken
+ * darueber liest denselben Store im selben Takt. Ein zweiter Weg (Subscription
+ * hier, Poll dort) waere ein zweiter Zeitbegriff fuer dieselbe Datei.
+ */
+import { useDownloadStore } from '../../stores/downloadStore'
+
+/**
+ * Loest auf, sobald der Download-Store die Datei als fertig meldet — oder
+ * wirft, sobald er sie als fehlgeschlagen meldet.
+ */
+export const awaitDownloadComplete = (filename: string): Promise<void> =>
+ new Promise<void>((resolve, reject) => {
+ const poll = setInterval(() => {
+ const d = useDownloadStore.getState().downloads[filename]
+ if (d?.status === 'complete') { clearInterval(poll); resolve() }
+ else if (d?.status === 'error') { clearInterval(poll); reject(new Error(d.error || 'Download failed')) }
+ }, 500)
+ })
diff --git a/src/lib/__tests__/error-text.test.ts b/src/lib/__tests__/error-text.test.ts
index b126bbdf..720f527d 100644
--- a/src/lib/__tests__/error-text.test.ts
+++ b/src/lib/__tests__/error-text.test.ts
@@ -61,10 +61,22 @@ describe('the surfaces that used to set foreign text as the whole message', () =
// Onboarding is the highest visibility surface in the app and it had four
// of these, one per installer. A bare log tail there is the first thing a
// new user ever reads from us.
- const src = read('components/onboarding/Onboarding.tsx')
+ //
+ // PATH ONLY (W-T3, 2026-09-01): the four installers used to sit in one
+ // 1909-line Onboarding.tsx. Two of them (Ollama, LM Studio) now live in
+ // BackendsStep.tsx and two (ComfyUI, Python) in ComfyStep.tsx. Both files
+ // are read here, so the claim still covers all four — reading only the
+ // shell would have made this test green by looking at a file that no
+ // longer contains a single installer.
+ const src = [
+ read('components/onboarding/BackendsStep.tsx'),
+ read('components/onboarding/ComfyStep.tsx'),
+ ].join('\n')
expect(src).toContain('withInstallerOutput')
expect(src).not.toMatch(/set\w*Error\(lastLog\)/)
expect(src).not.toMatch(/setPythonInstallError\(lastLog\)/)
+ // And the shell really is out of the installer business now.
+ expect(read('components/onboarding/Onboarding.tsx')).not.toContain('lastLog')
})
it('Settings frames its installer log tails too', () => {