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.

feat(Fenster): das Onboarding laeuft in einem eigenen kleinen Fenster, mittig vom Betriebssystem gesetzt — die App bleibt das grosse

Davidbe2e3849cb02
diff --git a/src-tauri/capabilities/onboarding.json b/src-tauri/capabilities/onboarding.json
new file mode 100644
index 00000000..ee5556de
--- /dev/null
+++ b/src-tauri/capabilities/onboarding.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "../gen/schemas/desktop-schema.json",
+ "identifier": "onboarding",
+ "description": "Capability of the first-launch window (label `onboarding`, built in src/onboarding_window.rs). Deliberately NOT the main-window capability: the wizard needs to move itself, minimise, close, listen for events and open a vendor's download page in the browser — nothing that spawns a process. The `shell:allow-spawn` entries of default.json exist for external MCP servers, which the wizard never starts; a window that runs before the user has set anything up gets the smallest surface that carries it.",
+ "windows": ["onboarding"],
+ "permissions": [
+ "core:default",
+ "core:window:allow-minimize",
+ "core:window:allow-close",
+ "core:window:allow-start-dragging",
+ "core:webview:default",
+ "shell:allow-open"
+ ]
+}
diff --git a/src-tauri/gen/schemas/capabilities.json b/src-tauri/gen/schemas/capabilities.json
index 511e60d3..0f99368c 100644
--- a/src-tauri/gen/schemas/capabilities.json
+++ b/src-tauri/gen/schemas/capabilities.json
@@ -1 +1 @@
-{"default":{"identifier":"default","description":"Main-window capability. shell:allow-spawn is the only permission here that can start a process, and it is scoped to the two package runners external MCP servers are actually launched with (npx, uvx). Every general-purpose interpreter and container runtime was removed: node, deno, bun, python and py all take a one-shot eval flag (node -e, python -c), npm/pnpm/yarn run whatever a package.json in the cwd defines, and docker run -v /:/host hands out the whole disk. With those in the allow-list, any script-execution bug in the WebView (a PDF viewer, a markdown renderer, a dependency) was code execution on the user's machine rather than defacement inside the app.","local":true,"windows":["main"],"permissions":["core:default","core:window:default","core:window:allow-minimize","core:window:allow-maximize","core:window:allow-unmaximize","core:window:allow-close","core:window:allow-is-maximized","core:window:allow-toggle-maximize","core:window:allow-start-dragging","core:webview:default",{"identifier":"shell:allow-spawn","allow":[{"args":true,"cmd":"npx","name":"npx"},{"args":true,"cmd":"npx.cmd","name":"npx.cmd"},{"args":true,"cmd":"uvx","name":"uvx"}]},"shell:allow-stdin-write","shell:allow-kill","shell:allow-open","updater:default"]}}
\ No newline at end of file
+{"default":{"identifier":"default","description":"Main-window capability. shell:allow-spawn is the only permission here that can start a process, and it is scoped to the two package runners external MCP servers are actually launched with (npx, uvx). Every general-purpose interpreter and container runtime was removed: node, deno, bun, python and py all take a one-shot eval flag (node -e, python -c), npm/pnpm/yarn run whatever a package.json in the cwd defines, and docker run -v /:/host hands out the whole disk. With those in the allow-list, any script-execution bug in the WebView (a PDF viewer, a markdown renderer, a dependency) was code execution on the user's machine rather than defacement inside the app.","local":true,"windows":["main"],"permissions":["core:default","core:window:default","core:window:allow-minimize","core:window:allow-maximize","core:window:allow-unmaximize","core:window:allow-close","core:window:allow-is-maximized","core:window:allow-toggle-maximize","core:window:allow-start-dragging","core:webview:default",{"identifier":"shell:allow-spawn","allow":[{"args":true,"cmd":"npx","name":"npx"},{"args":true,"cmd":"npx.cmd","name":"npx.cmd"},{"args":true,"cmd":"uvx","name":"uvx"}]},"shell:allow-stdin-write","shell:allow-kill","shell:allow-open","updater:default"]},"onboarding":{"identifier":"onboarding","description":"Capability of the first-launch window (label `onboarding`, built in src/onboarding_window.rs). Deliberately NOT the main-window capability: the wizard needs to move itself, minimise, close, listen for events and open a vendor's download page in the browser — nothing that spawns a process. The `shell:allow-spawn` entries of default.json exist for external MCP servers, which the wizard never starts; a window that runs before the user has set anything up gets the smallest surface that carries it.","local":true,"windows":["onboarding"],"permissions":["core:default","core:window:allow-minimize","core:window:allow-close","core:window:allow-start-dragging","core:webview:default","shell:allow-open"]}}
\ No newline at end of file
diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rs
index 037a695f..869cef69 100644
--- a/src-tauri/src/commands/process.rs
+++ b/src-tauri/src/commands/process.rs
@@ -134,12 +134,16 @@ pub(crate) fn tie_child_to_app_lifetime(pid: u32) {
let _ = pid;
}
-/// Show the main window (called from frontend after React renders)
+/// Show the CALLING window (called from a frontend once React has rendered).
+///
+/// Every window starts hidden, so this is the one place a window becomes
+/// visible — and whether it may is a question of who else is on screen: the
+/// main window stays hidden while the onboarding runs in its own window, and
+/// once the onboarding is done, showing the main window is what closes the
+/// small one. The rule lives in `onboarding_window::reveal`.
#[tauri::command]
-pub fn show_window(app: tauri::AppHandle) {
- if let Some(window) = app.get_webview_window("main") {
- let _ = window.show();
- }
+pub fn show_window(window: tauri::WebviewWindow) {
+ crate::onboarding_window::reveal(&window);
}
/// Bug J: does this system need ComfyUI's --cpu fallback flag?
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index 079cb266..1c288479 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -575,14 +575,14 @@ pub fn is_onboarding_done() -> bool {
.unwrap_or(false)
}
-/// Persist onboarding completion to %APPDATA% (outside NSIS install dir).
-/// Pass `done: false` to clear the marker so the first-launch wizard runs again.
-#[tauri::command]
-pub fn set_onboarding_done(done: Option<bool>) -> Result<(), String> {
+/// Write (or clear) the marker file `is_onboarding_done` reads. Plain IO, no
+/// window logic — `set_onboarding_done` and the startup migration in
+/// `onboarding_window::decide_first_window` both come through here.
+pub(crate) fn write_onboarding_marker(done: bool) -> Result<(), String> {
let dir = persistent_dir()?;
std::fs::create_dir_all(&dir).map_err(|e| os_error::english(&e))?;
let path = dir.join("onboarding_done");
- if done.unwrap_or(true) {
+ if done {
std::fs::write(&path, "1").map_err(|e| os_error::english(&e))?;
} else if path.exists() {
std::fs::remove_file(&path).map_err(|e| os_error::english(&e))?;
@@ -590,6 +590,23 @@ pub fn set_onboarding_done(done: Option<bool>) -> Result<(), String> {
Ok(())
}
+/// Persist onboarding completion to %APPDATA% (outside NSIS install dir).
+/// Pass `done: false` to clear the marker so the first-launch wizard runs again.
+///
+/// The windows follow the marker (`onboarding_window::follow_marker`): `true`
+/// from the onboarding window hands over to the main window, `false` from
+/// Settings → "Re-run onboarding" brings the small window back. Only after a
+/// successful write — the marker is the one truth the windows are decided
+/// from, and moving them on a marker that is not there would leave the main
+/// window hidden behind a rule it can never satisfy.
+#[tauri::command]
+pub fn set_onboarding_done(app: tauri::AppHandle, done: Option<bool>) -> Result<(), String> {
+ let done = done.unwrap_or(true);
+ write_onboarding_marker(done)?;
+ crate::onboarding_window::follow_marker(&app, done);
+ Ok(())
+}
+
/// Return the current local date/time/timezone. Agents should call this
/// instead of googling "what day is it" — the info is free and exact.
///
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index ff08aa81..e138315d 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -11,6 +11,7 @@ mod install_state;
// remote.rs embeds the finished page with include_str!.
#[cfg(test)]
mod mobile_page;
+mod onboarding_window;
mod os_error;
mod os_paths;
mod private_tmp;
@@ -251,12 +252,10 @@ fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
- // 2nd launch → focus existing window instead of spawning another process.
- if let Some(window) = app.get_webview_window("main") {
- let _ = window.show();
- let _ = window.unminimize();
- let _ = window.set_focus();
- }
+ // 2nd launch → focus the existing window instead of spawning
+ // another process. "The" window is the onboarding window while
+ // setup runs, the main window afterwards (onboarding_window.rs).
+ onboarding_window::bring_to_front(app);
}))
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_updater::Builder::new().build())
@@ -470,12 +469,17 @@ fn main() {
commands::bg_tasks::shell_task_list,
// Window management
commands::process::show_window,
+ onboarding_window::onboarding_window_open,
])
.setup(|app| {
- #[cfg(debug_assertions)]
- if let Some(window) = app.get_webview_window("main") {
- window.open_devtools();
- }
+ // DevTools for debug builds used to open HERE, on the still
+ // hidden main window. Measured on macOS (2026-09-01, debug
+ // bundle): WebKit docks the inspector into the window and
+ // orders that window front — a hidden main window became
+ // visible at launch, next to the onboarding window. The
+ // inspector now opens in `onboarding_window::reveal`, on
+ // whichever window is actually shown, so a debug build behaves
+ // like the shipped one.
// Remove Windows DWM shadow/border (the 1mm border around the window)
#[cfg(target_os = "windows")]
@@ -483,33 +487,35 @@ fn main() {
let _ = window.set_shadow(false);
}
- // ─── Bug D (surfingbird1010): force-show fallback ───
- // The window starts hidden (visible:false in tauri.conf.json) and is
- // normally revealed by the frontend's invoke('show_window') once React
- // mounts (App.tsx). If the WebView never loads, or a render/hydration
- // throw happens before that effect runs (corrupt persisted state,
- // GPU/WebView2 fault), the window would stay hidden forever and the app
- // looks like it "runs with no window". Reveal it unconditionally after a
- // timeout so the user always gets a window. The frontend's earlier
- // show_window is idempotent, so a healthy launch sees no double-show /
- // flicker. 10 s is comfortably longer than a normal cold React mount
- // (~1-2 s) yet short enough not to feel broken on a slow i7/8 GB box.
- {
- let handle = app.handle().clone();
- std::thread::spawn(move || {
- std::thread::sleep(std::time::Duration::from_secs(10));
- if let Some(window) = handle.get_webview_window("main") {
- // Treat "unknown" as hidden → show (a redundant show on an
- // already-visible window is a harmless no-op).
- if !window.is_visible().unwrap_or(false) {
- println!("[Window] Force-show fallback fired (frontend never called show_window)");
- let _ = window.show();
- let _ = window.set_focus();
- }
- }
- });
+ // ─── Erststart: Onboarding im eigenen Fenster ───
+ // Decided HERE, before any window is visible, from the marker file
+ // (and the store backup, for installs older than the marker). With
+ // the onboarding pending, a small centred window carries the wizard
+ // and the main window stays hidden until the marker is written —
+ // see onboarding_window.rs for the whole hand-over. A failure to
+ // build that window fails setup: a hidden main window plus no
+ // onboarding window would be an app without a window.
+ if onboarding_window::decide_first_window() == onboarding_window::FirstWindow::Onboarding {
+ onboarding_window::open(app.handle())?;
}
+ // ─── Bug D (surfingbird1010): force-show fallback ───
+ // Every window starts hidden (visible:false in tauri.conf.json, and
+ // the onboarding window is built the same way) and is normally
+ // revealed by the frontend's invoke('show_window') once React
+ // mounts. If the WebView never loads, or a render/hydration throw
+ // happens before that effect runs (corrupt persisted state,
+ // GPU/WebView2 fault), the window would stay hidden forever and the
+ // app looks like it "runs with no window". Reveal the FRONT window
+ // after a timeout so the user always gets one — through the same
+ // rule as show_window, so the fallback can never pop the main
+ // window up over a running onboarding. The frontend's earlier
+ // show_window is idempotent, so a healthy launch sees no
+ // double-show / flicker. 10 s is comfortably longer than a normal
+ // cold React mount (~1-2 s) yet short enough not to feel broken on
+ // a slow i7/8 GB box.
+ onboarding_window::force_show_after(app.handle().clone(), onboarding_window::FORCE_SHOW_DELAY);
+
// ─── System Tray ───
let show = MenuItem::with_id(app, "show", "Show", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
@@ -525,12 +531,7 @@ fn main() {
.menu(&menu)
.on_menu_event(|app, event| {
match event.id().as_ref() {
- "show" => {
- if let Some(window) = app.get_webview_window("main") {
- let _ = window.show();
- let _ = window.set_focus();
- }
- }
+ "show" => onboarding_window::bring_to_front(app),
"quit" => {
// Tauri's AppState Drop doesn't fire reliably on
// Windows after `app.exit(0)` — run the explicit
@@ -545,11 +546,7 @@ fn main() {
})
.on_tray_icon_event(|tray, event| {
if let tauri::tray::TrayIconEvent::DoubleClick { .. } = event {
- let app = tray.app_handle();
- if let Some(window) = app.get_webview_window("main") {
- let _ = window.show();
- let _ = window.set_focus();
- }
+ onboarding_window::bring_to_front(tray.app_handle());
}
})
.build(app)?;
diff --git a/src-tauri/src/onboarding_window.rs b/src-tauri/src/onboarding_window.rs
new file mode 100644
index 00000000..4f8bdcf0
--- /dev/null
+++ b/src-tauri/src/onboarding_window.rs
@@ -0,0 +1,616 @@
+//! Das Onboarding bekommt ein eigenes, kleines, mittiges Fenster.
+//!
+//! Der Wunsch des Eigentümers: „das onboarding ein separates kleines fenster,
+//! immer mittig vom betriebssystem gespawnt, und die eigentliche LU app soll
+//! dann das normale große fenster sein. mac und windows."
+//!
+//! ── Wer entscheidet ────────────────────────────────────────────────────────
+//!
+//! RUST, und zwar bevor das erste Pixel erscheint. Das Hauptfenster startet
+//! seit jeher unsichtbar (`visible: false` in `tauri.conf.json`) und wird erst
+//! gezeigt, wenn das Frontend `show_window` ruft. Genau an dieser Stelle
+//! greift dieses Modul: `reveal()` zeigt ein Fenster nur, wenn es dran ist.
+//!
+//! Die eine Wahrheit ist die Markerdatei `onboarding_done` (siehe
+//! `commands::system::is_onboarding_done`). Die Fenster FOLGEN dem Marker:
+//!
+//! Start, Marker fehlt → `open()` erzeugt das Fenster `onboarding`, klein,
+//! mittig, nicht größenveränderbar. Das Hauptfenster
+//! bleibt unsichtbar; sein Frontend wartet
+//! (`src/main.tsx`) und lädt KEINEN Store, damit es
+//! später frisch liest, was der Assistent geschrieben
+//! hat.
+//! Start, Marker da → wie bisher. Kein zweites Fenster, auch nicht kurz.
+//! Marker wird gesetzt → `follow_marker(true)`: das Hauptfenster erfährt es
+//! per Ereignis, bootet, ruft `show_window`, und
+//! `reveal()` zeigt es ZUERST und schließt das
+//! Onboarding-Fenster DANACH. Andersherum sähe der
+//! Nutzer einen Moment lang kein Fenster.
+//! Marker wird gelöscht → `follow_marker(false)`: „Onboarding zurücksetzen"
+//! in den Einstellungen. Das kleine Fenster kommt
+//! wieder; das große verschwindet, sobald das kleine
+//! sichtbar ist (dieselbe Reihenfolge, andere
+//! Richtung).
+//! Onboarding-Fenster zu, Marker fehlt → die App beendet sich. Das
+//! Onboarding ist nicht fertig; ein unsichtbares
+//! Hauptfenster wäre eine App ohne Fenster.
+//!
+//! ── Warum das Hauptfenster trotzdem existiert ─────────────────────────────
+//!
+//! Es steht in `tauri.conf.json`, und daran hängen Tray, Einzelinstanz und
+//! die Zur-Leiste-statt-Schließen-Logik in `main.rs`. Es unsichtbar zu lassen
+//! ist billiger und sicherer, als es nachträglich zu erzeugen: alles, was
+//! `get_webview_window("main")` ruft, findet es weiterhin.
+//!
+//! ── Plattformabhängig ─────────────────────────────────────────────────────
+//!
+//! Die Dekoration folgt dem Rezept des Hauptfensters DER JEWEILIGEN PLATTFORM
+//! (`tauri.macos.conf.json` bzw. `tauri.windows.conf.json`), damit das erste
+//! Fenster der App nicht wie eine andere App aussieht:
+//!
+//! macOS `decorations: true`, `titleBarStyle: Overlay`, `hiddenTitle`:
+//! die nativen Ampeln links, kein Titel, der Inhalt läuft bis oben
+//! durch. Die Ziehfläche ist der Systembalken selbst.
+//! Windows `decorations: false`, `transparent: true`, kein DWM-Schatten:
+//! die App ersetzt den Systembalken; das Onboarding zeichnet
+//! Minimieren und Schließen selbst (kein Maximieren — das Fenster
+//! ist nicht größenveränderbar). Die Ziehfläche ist der
+//! `data-tauri-drag-region`-Streifen in `Onboarding.tsx`.
+//!
+//! Die `#[cfg]`-Zeilen in `open()` sind die einzigen plattformabhängigen
+//! Zeilen dieses Moduls.
+
+use std::time::Duration;
+
+use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindow, WebviewWindowBuilder};
+
+use crate::commands::system::{is_onboarding_done, restore_stores, write_onboarding_marker};
+use crate::state::AppState;
+
+/// Das Label des Hauptfensters (`tauri.conf.json`).
+pub const MAIN: &str = "main";
+/// Das Label des Onboarding-Fensters. Das Frontend liest es über
+/// `getCurrentWebviewWindow().label` (`src/lib/host-window.ts`) — es steht dort
+/// noch einmal als Literal, und ein Test hält beide Literale gleich.
+pub const ONBOARDING: &str = "onboarding";
+/// Das Ereignis, mit dem das wartende Hauptfenster erfährt, dass es dran ist.
+pub const DONE_EVENT: &str = "onboarding:done";
+
+/// Gemessen, nicht geraten (Playwright, 640 px breit, `--ui-scale 1.15`):
+/// der längste erreichbare Bildschirm ist der Maschinen-Schritt mit
+/// aufgeklapptem „Use another engine" — 531 px Inhalt. Dazu die Ziehfläche
+/// (37 px) und der Rand (18 px): 586 px. 640 lässt 54 px Luft, damit die
+/// Fortschrittspunkte nicht unter den Streifen rutschen. Die Breite trägt den
+/// Modell-Schritt (`max-w-xl`, 603 px gerendert) ohne Umbruch, und 640 ist
+/// zugleich Tailwinds `sm`-Schwelle, ab der die Modellkarten zweispaltig
+/// laufen. Was darüber hinausgeht (aufgeklappte Alternativlisten,
+/// Installations-Protokolle), scrollt in der Karte — `Onboarding.tsx`.
+pub const ONBOARDING_WIDTH: f64 = 640.0;
+pub const ONBOARDING_HEIGHT: f64 = 640.0;
+
+/// Wie lange das Frontend Zeit hat, `show_window` zu rufen, bevor Rust das
+/// vorderste Fenster von sich aus zeigt (Bug D, siehe `main.rs`).
+pub const FORCE_SHOW_DELAY: Duration = Duration::from_secs(10);
+/// Wie lange nach dem Setzen des Markers das Hauptfenster Zeit hat, sich zu
+/// melden, bevor Rust die Übergabe selbst erzwingt. Länger als der Kaltstart
+/// des Frontends (Keychain bis 3 s + React-Mount), kürzer als ein Nutzer auf
+/// einen Knopf starrt, der „Opening LU…" sagt.
+pub const HANDOVER_GRACE: Duration = Duration::from_secs(15);
+
+/// Welches Fenster beim Start als erstes sichtbar wird.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FirstWindow {
+ Main,
+ Onboarding,
+}
+
+/// Die reine Entscheidung. `marker` ist die Markerdatei, `backup_says_done`
+/// die Aussage des Store-Backups (siehe `onboarding_done_in_backup`).
+///
+/// Das Backup zählt, weil die Markerdatei jünger ist als das Onboarding:
+/// eine Installation von vor dem Marker hat `onboardingDone: true` im Store
+/// und im Backup, aber keine Datei. `AppShell.tsx` schrieb den Marker in dem
+/// Fall beim Boot nach — zu spät für eine Entscheidung, die VOR dem ersten
+/// Fenster fällt. Also zieht Rust dieselbe Migration hier vor.
+pub fn first_window(marker: bool, backup_says_done: bool) -> FirstWindow {
+ if marker || backup_says_done {
+ FirstWindow::Main
+ } else {
+ FirstWindow::Onboarding
+ }
+}
+
+/// Sagt das Store-Backup (`store_backup.json`, Form `{ "<key>": "<raw
+/// localStorage-String>" }`), dass das Onboarding schon durch war?
+///
+/// Der Eintrag `chat-settings` ist der zustand-persist-Umschlag
+/// `{"state":{"settings":{"onboardingDone":true,…}},"version":n}` — als
+/// String im String, deshalb zweimal parsen. Alles, was nicht genau so
+/// aussieht, heißt „nein": im Zweifel lieber ein Onboarding zu viel als eine
+/// App, die ohne Einrichtung startet.
+pub fn onboarding_done_in_backup(backup_json: &str) -> bool {
+ let outer: serde_json::Value = match serde_json::from_str(backup_json) {
+ Ok(v) => v,
+ Err(_) => return false,
+ };
+ let raw = match outer.get("chat-settings").and_then(|v| v.as_str()) {
+ Some(s) => s,
+ None => return false,
+ };
+ let inner: serde_json::Value = match serde_json::from_str(raw) {
+ Ok(v) => v,
+ Err(_) => return false,
+ };
+ inner
+ .pointer("/state/settings/onboardingDone")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false)
+}
+
+/// Die Entscheidung mit ihren Eingaben von der Platte — einmal, im `setup`.
+/// Schreibt den Marker nach, wenn nur das Backup ihn kannte, damit jeder
+/// spätere Start die kurze Frage stellt.
+pub fn decide_first_window() -> FirstWindow {
+ let marker = is_onboarding_done();
+ let backup_says_done = !marker
+ && matches!(restore_stores(), Ok(Some(json)) if onboarding_done_in_backup(&json));
+ if backup_says_done {
+ if let Err(e) = write_onboarding_marker(true) {
+ tracing::warn!("onboarding marker could not be migrated from the backup: {e}");
+ }
+ }
+ first_window(marker, backup_says_done)
+}
+
+/// Was `reveal()` mit einem Fenster tut, das sich zeigen will.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Reveal {
+ /// Zeigen. Für das Onboarding-Fenster heißt das zusätzlich: das
+ /// Hauptfenster verstecken, falls es sichtbar war (Zurücksetzen aus den
+ /// Einstellungen) — erst zeigen, dann verstecken, nie andersherum.
+ Show,
+ /// Das Hauptfenster zeigen und DANACH das Onboarding-Fenster schließen.
+ ShowAndCloseOnboarding,
+ /// Das Hauptfenster bleibt unsichtbar: das Onboarding läuft noch, in
+ /// seinem eigenen Fenster.
+ KeepHidden,
+}
+
+/// Die reine Regel hinter `reveal()`. Ein Fenster ohne Stellvertreter wird
+/// immer gezeigt — ein Nutzer ohne Fenster ist der schlimmste Zustand, und
+/// das Hauptfenster kann das Onboarding zur Not selbst zeichnen
+/// (`AppShell.tsx`, der bisherige Weg).
+pub fn reveal_decision(label: &str, onboarding_done: bool, onboarding_window_exists: bool) -> Reveal {
+ if label == ONBOARDING {
+ return Reveal::Show;
+ }
+ match (onboarding_done, onboarding_window_exists) {
+ (_, false) => Reveal::Show,
+ (true, true) => Reveal::ShowAndCloseOnboarding,
+ (false, true) => Reveal::KeepHidden,
+ }
+}
+
+/// `show_window` aus dem Frontend landet hier, für JEDES Fenster.
+pub fn reveal(window: &WebviewWindow) {
+ let app = window.app_handle();
+ let onboarding = app.get_webview_window(ONBOARDING);
+ match reveal_decision(window.label(), is_onboarding_done(), onboarding.is_some()) {
+ Reveal::KeepHidden => {
+ tracing::info!("main window stays hidden: the onboarding runs in its own window");
+ }
+ Reveal::Show => {
+ let _ = window.show();
+ let _ = window.set_focus();
+ open_devtools_in_debug(window);
+ if window.label() == ONBOARDING {
+ if let Some(main) = app.get_webview_window(MAIN) {
+ if main.is_visible().unwrap_or(false) {
+ let _ = main.hide();
+ }
+ }
+ }
+ }
+ Reveal::ShowAndCloseOnboarding => {
+ // Reihenfolge ist Absicht: erst das große Fenster, dann das kleine
+ // weg. Beide Aufrufe gehen als Nachrichten an die Ereignisschleife
+ // und werden in dieser Reihenfolge abgearbeitet.
+ let _ = window.show();
+ let _ = window.set_focus();
+ open_devtools_in_debug(window);
+ if let Some(o) = onboarding {
+ // `destroy`, nicht `close`: `close` löst CloseRequested aus,
+ // und der Handler darunter würde „Onboarding nicht fertig"
+ // prüfen — es IST fertig, aber der Weg soll gar nicht erst
+ // durch die Frage führen.
+ let _ = o.destroy();
+ }
+ }
+ }
+}
+
+/// DevTools in Debug-Builds — auf dem Hauptfenster, sobald es gezeigt wird,
+/// und erst dann. Gemessen (macOS, Debug-Bundle, 01.09.2026): auf einem noch
+/// unsichtbaren Fenster geöffnet, dockt WebKit den Inspector ins Fenster
+/// und holt es damit nach vorn — das versteckte Hauptfenster stand neben dem
+/// Onboarding-Fenster auf dem Bildschirm. Deshalb nicht mehr im `setup`.
+///
+/// Nur das Hauptfenster: im 640×640-Fenster nähme der gedockte Inspector
+/// die halbe Fläche (ebenfalls gemessen). Wer ihn dort braucht, öffnet ihn
+/// mit Cmd/Ctrl+Shift+I — Debug-Builds erlauben das.
+fn open_devtools_in_debug(window: &WebviewWindow) {
+ #[cfg(debug_assertions)]
+ if window.label() == MAIN {
+ window.open_devtools();
+ }
+ #[cfg(not(debug_assertions))]
+ let _ = window;
+}
+
+/// Erzeugt das Onboarding-Fenster — unsichtbar, bis sein Frontend
+/// `show_window` ruft (derselbe Weg wie beim Hauptfenster, aus demselben
+/// Grund: kein weißer Blitz vor dem ersten Frame). Gibt ein schon
+/// vorhandenes zurück statt ein zweites zu bauen.
+pub fn open(app: &AppHandle) -> tauri::Result<WebviewWindow> {
+ if let Some(existing) = app.get_webview_window(ONBOARDING) {
+ return Ok(existing);
+ }
+
+ let builder = WebviewWindowBuilder::new(app, ONBOARDING, WebviewUrl::default())
+ .title("LU")
+ .inner_size(ONBOARDING_WIDTH, ONBOARDING_HEIGHT)
+ .resizable(false)
+ .maximizable(false)
+ .center()
+ .visible(false)
+ // Anders als das Hauptfenster (`dragDropEnabled: false`) lässt dieses
+ // Fenster Tauris Drop-Handler auf dem Standard: der Assistent hat
+ // keine Ablagefläche (die drei der App — Composer, Trainings-Board,
+ // RAG-Panel — liegen alle hinter dem Onboarding), also gibt es hier
+ // nichts, was der Handler stören könnte. Kommt je eine dazu, greift
+ // `html5-drop-enabled.test.ts` und macht den Tausch ausdrücklich.
+ .focused(true);
+
+ // ── plattformabhängig: das Dekorationsrezept des jeweiligen Hauptfensters ──
+ #[cfg(target_os = "macos")]
+ let builder = builder
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .hidden_title(true);
+ #[cfg(not(target_os = "macos"))]
+ let builder = builder.decorations(false).transparent(true);
+
+ let window = builder.build()?;
+
+ // Wie beim Hauptfenster in `main.rs`: ohne das zeichnet DWM einen
+ // 1-mm-Rand um ein rahmenloses Fenster.
+ #[cfg(target_os = "windows")]
+ let _ = window.set_shadow(false);
+
+ let handle = app.clone();
+ window.on_window_event(move |event| {
+ if let tauri::WindowEvent::CloseRequested { .. } = event {
+ if !is_onboarding_done() {
+ quit(&handle);
+ }
+ }
+ });
+
+ Ok(window)
+}
+
+/// Das Onboarding-Fenster wurde geschlossen, bevor das Onboarding fertig war:
+/// derselbe Weg wie „Quit" im Tray, damit kein Kindprozess zurückbleibt.
+fn quit(app: &AppHandle) {
+ tracing::info!("onboarding window closed before setup finished — quitting");
+ if let Some(state) = app.try_state::<AppState>() {
+ state.shutdown_subprocesses();
+ }
+ app.exit(0);
+}
+
+/// Läuft das Onboarding gerade in seinem eigenen Fenster? Das Hauptfenster
+/// fragt das beim Boot (`src/main.tsx`) und wartet dann, statt die App zu
+/// laden.
+#[tauri::command]
+pub fn onboarding_window_open(app: AppHandle) -> bool {
+ app.get_webview_window(ONBOARDING).is_some()
+}
+
+/// Die Fenster folgen dem Marker — aufgerufen von `set_onboarding_done`,
+/// NACH dem erfolgreichen Schreiben.
+pub fn follow_marker(app: &AppHandle, done: bool) {
+ let onboarding = app.get_webview_window(ONBOARDING);
+ if done {
+ if onboarding.is_none() {
+ // Die Migration aus `AppShell.tsx` (Marker nachschreiben) oder ein
+ // Onboarding, das noch im Hauptfenster lief. Nichts zu wechseln.
+ return;
+ }
+ // Rundruf, kein `emit_to`: das Hauptfenster hört mit dem Standardziel
+ // (`Any`), und ein zweiter Hörer existiert für dieses Ereignis nicht.
+ if let Err(e) = app.emit(DONE_EVENT, ()) {
+ tracing::warn!("could not tell the main window the onboarding is done: {e}");
+ }
+ handover_fallback(app.clone(), HANDOVER_GRACE);
+ } else if onboarding.is_none() {
+ // „Onboarding zurücksetzen": das kleine Fenster kommt wieder. Das
+ // Hauptfenster bleibt sichtbar, bis das kleine sich gezeigt hat —
+ // `reveal()` versteckt es dann.
+ if let Err(e) = open(app) {
+ tracing::error!("could not open the onboarding window: {e}");
+ }
+ }
+}
+
+/// Das vorderste Fenster: das Onboarding, solange es existiert, sonst das
+/// Hauptfenster. Tray-„Show", Doppelklick aufs Tray-Symbol und ein zweiter
+/// Start der App holen dieses Fenster nach vorn.
+pub fn front_window(app: &AppHandle) -> Option<WebviewWindow> {
+ app.get_webview_window(ONBOARDING)
+ .or_else(|| app.get_webview_window(MAIN))
+}
+
+pub fn bring_to_front(app: &AppHandle) {
+ if let Some(window) = front_window(app) {
+ let _ = window.show();
+ let _ = window.unminimize();
+ let _ = window.set_focus();
+ }
+}
+
+/// Bug D (`main.rs`): ruft das Frontend nie `show_window`, zeigt Rust das
+/// vorderste Fenster nach `delay` von sich aus. Geht durch `reveal()`, damit
+/// auch der Notweg die Regel kennt — ein Hauptfenster, das während des
+/// Onboardings aufpoppt, wäre genau der Blitz, den das Ganze verhindern soll.
+pub fn force_show_after(app: AppHandle, delay: Duration) {
+ std::thread::spawn(move || {
+ std::thread::sleep(delay);
+ if let Some(window) = front_window(&app) {
+ if !window.is_visible().unwrap_or(false) {
+ println!(
+ "[Window] Force-show fallback fired for '{}' (frontend never called show_window)",
+ window.label()
+ );
+ reveal(&window);
+ }
+ }
+ });
+}
+
+/// Meldet sich das Hauptfenster nach dem Marker nicht (Boot hängt, Keychain
+/// klemmt), erzwingt Rust die Übergabe: Hauptfenster zeigen, Onboarding zu.
+fn handover_fallback(app: AppHandle, delay: Duration) {
+ std::thread::spawn(move || {
+ std::thread::sleep(delay);
+ if let Some(main) = app.get_webview_window(MAIN) {
+ if !main.is_visible().unwrap_or(false) && is_onboarding_done() {
+ println!("[Window] Handover fallback fired (main never called show_window after onboarding)");
+ reveal(&main);
+ }
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const MAIN_RS: &str = include_str!("main.rs");
+ const PROCESS_RS: &str = include_str!("commands/process.rs");
+ const SYSTEM_RS: &str = include_str!("commands/system.rs");
+
+ // ── Die Entscheidung vor dem ersten Pixel ─────────────────────────────
+
+ #[test]
+ fn ohne_marker_und_ohne_backup_kommt_das_onboarding_fenster() {
+ assert_eq!(first_window(false, false), FirstWindow::Onboarding);
+ }
+
+ #[test]
+ fn mit_marker_kommt_das_hauptfenster_und_sonst_nichts() {
+ assert_eq!(first_window(true, false), FirstWindow::Main);
+ assert_eq!(first_window(true, true), FirstWindow::Main);
+ }
+
+ #[test]
+ fn ein_backup_von_vor_dem_marker_zaehlt_wie_der_marker() {
+ // Die Migration aus AppShell.tsx, vorgezogen: sonst sähe jeder
+ // Aufsteiger von einer Version ohne Markerdatei den Assistenten
+ // noch einmal.
+ assert_eq!(first_window(false, true), FirstWindow::Main);
+ }
+
+ #[test]
+ fn das_backup_wird_zweimal_geparst_weil_der_store_ein_string_im_string_ist() {
+ let inner = r#"{"state":{"settings":{"theme":"dark","onboardingDone":true}},"version":7}"#;
+ let backup = serde_json::json!({ "chat-settings": inner, "lu-providers": "{}" }).to_string();
+ assert!(onboarding_done_in_backup(&backup));
+ }
+
+ #[test]
+ fn im_zweifel_sagt_das_backup_nein() {
+ let cases = [
+ "",
+ "not json",
+ "{}",
+ r#"{"chat-settings": 42}"#,
+ r#"{"chat-settings": "not json"}"#,
+ r#"{"chat-settings": "{\"state\":{\"settings\":{}}}"}"#,
+ r#"{"chat-settings": "{\"state\":{\"settings\":{\"onboardingDone\":false}}}"}"#,
+ r#"{"chat-settings": "{\"state\":{\"settings\":{\"onboardingDone\":\"true\"}}}"}"#,
+ ];
+ for c in cases {
+ assert!(!onboarding_done_in_backup(c), "must be false for {c:?}");
+ }
+ }
+
+ // ── Die Regel hinter show_window ──────────────────────────────────────
+
+ #[test]
+ fn das_onboarding_fenster_darf_sich_immer_zeigen() {
+ assert_eq!(reveal_decision(ONBOARDING, false, true), Reveal::Show);
+ assert_eq!(reveal_decision(ONBOARDING, true, true), Reveal::Show);
+ }
+
+ #[test]
+ fn das_hauptfenster_bleibt_unsichtbar_solange_das_onboarding_in_seinem_fenster_laeuft() {
+ assert_eq!(reveal_decision(MAIN, false, true), Reveal::KeepHidden);
+ }
+
+ #[test]
+ fn nach_dem_marker_zeigt_sich_das_hauptfenster_und_schliesst_das_kleine() {
+ assert_eq!(reveal_decision(MAIN, true, true), Reveal::ShowAndCloseOnboarding);
+ }
+
+ #[test]
+ fn ohne_stellvertreter_wird_das_hauptfenster_immer_gezeigt() {
+ // Marker fehlt, aber es gibt kein Onboarding-Fenster: das
+ // Hauptfenster zeichnet den Assistenten selbst (AppShell), so wie
+ // vor diesem Modul. Ein Nutzer ohne Fenster ist keine Option.
+ assert_eq!(reveal_decision(MAIN, false, false), Reveal::Show);
+ assert_eq!(reveal_decision(MAIN, true, false), Reveal::Show);
+ }
+
+ #[test]
+ fn ein_fremdes_label_wird_wie_das_hauptfenster_behandelt() {
+ // Ein Fenster, das dieses Modul nicht kennt (DevTools-Fenster
+ // haben kein Webview-Label; ein künftiges Fenster hätte eines),
+ // darf das Onboarding nicht überdecken.
+ assert_eq!(reveal_decision("something-else", false, true), Reveal::KeepHidden);
+ }
+
+ // ── Maße und Fristen ──────────────────────────────────────────────────
+
+ #[test]
+ fn das_fenster_traegt_den_laengsten_gemessenen_schritt() {
+ // 531 px Inhalt + 37 px Ziehfläche + 18 px Rand, gemessen am
+ // 01.09.2026 (siehe Kommentar an den Konstanten). Kleiner als das
+ // Hauptfenster in beiden Richtungen, sonst wäre es kein „kleines".
+ let longest_step_px: f64 = 531.0 + 37.0 + 18.0;
+ let (w, h) = (ONBOARDING_WIDTH, ONBOARDING_HEIGHT);
+ assert!(h >= longest_step_px, "{h} does not hold the longest step ({longest_step_px})");
+ assert!(w < 1280.0 && h < 800.0, "{w}x{h} is not smaller than the main window");
+ // Die `sm`-Schwelle von Tailwind: darunter würde der Modell-Schritt
+ // einspaltig und damit höher als gemessen.
+ assert!(w >= 640.0, "{w} is below Tailwind's sm breakpoint");
+ }
+
+ #[test]
+ fn die_uebergabefrist_ist_laenger_als_ein_kaltstart_und_kuerzer_als_geduld() {
+ // Keychain-Hydration ist auf 3 s gedeckelt (main.tsx), der
+ // React-Mount braucht 1-2 s: unter 5 s würde der Notweg gesunde
+ // Starts überholen. Über 60 s starrt der Nutzer auf „Opening LU…".
+ let secs = HANDOVER_GRACE.as_secs();
+ assert!((5..=60).contains(&secs), "handover grace out of range: {secs}s");
+ assert!(FORCE_SHOW_DELAY.as_secs() >= 5);
+ }
+
+ // ── Verdrahtung: die Regel wird auch benutzt ──────────────────────────
+
+ #[test]
+ fn show_window_geht_fuer_jedes_fenster_durch_reveal() {
+ let f = &PROCESS_RS[PROCESS_RS.find("pub fn show_window(").expect("show_window exists")..];
+ let f = &f[..f.find("\n}\n").expect("show_window ends")];
+ assert!(
+ f.contains("window: tauri::WebviewWindow") && f.contains("onboarding_window::reveal(&window)"),
+ "show_window must reveal the CALLING window through the rule:\n{f}"
+ );
+ assert!(
+ !f.contains("get_webview_window(\"main\")"),
+ "show_window must not hard-wire the main window any more:\n{f}"
+ );
+ }
+
+ #[test]
+ fn das_setup_entscheidet_vor_dem_ersten_fenster() {
+ let setup = &MAIN_RS[MAIN_RS.find(".setup(|app| {").expect("setup exists")..];
+ let setup = &setup[..setup.find(".build(tauri::generate_context!())").expect("build follows setup")];
+ assert!(
+ setup.contains("onboarding_window::decide_first_window()"),
+ "setup must ask the marker before any window is shown"
+ );
+ assert!(
+ setup.contains("onboarding_window::open(app.handle())?"),
+ "a failed onboarding window must fail setup loudly, not leave a hidden main window"
+ );
+ assert!(
+ setup.contains("onboarding_window::force_show_after("),
+ "the force-show fallback must go through the rule"
+ );
+ assert!(
+ !setup.contains("std::thread::sleep(std::time::Duration::from_secs(10))"),
+ "the old main-only force-show thread must be gone"
+ );
+ assert!(
+ !setup.contains("open_devtools()"),
+ "devtools on a hidden window make it visible (measured on macOS) — they open in reveal()"
+ );
+ }
+
+ #[test]
+ fn devtools_oeffnen_nur_auf_dem_fenster_das_gezeigt_wird() {
+ let src = include_str!("onboarding_window.rs");
+ let reveal_fn = &src[src.find("pub fn reveal(").expect("reveal exists")..];
+ let reveal_fn = &reveal_fn[..reveal_fn.find("\n}\n").expect("reveal ends")];
+ assert_eq!(reveal_fn.matches("open_devtools_in_debug(window)").count(), 2);
+ let hidden = &reveal_fn[reveal_fn.find("Reveal::KeepHidden =>").unwrap()..reveal_fn.find("Reveal::Show =>").unwrap()];
+ assert!(!hidden.contains("open_devtools"), "never on the window that stays hidden");
+ }
+
+ #[test]
+ fn tray_und_zweiter_start_holen_das_vorderste_fenster_nach_vorn() {
+ let main_fn = &MAIN_RS[MAIN_RS.find("\nfn main() {").expect("main exists")..];
+ let main_fn = &main_fn[..main_fn.find("\n}\n").expect("main ends")];
+ assert_eq!(
+ main_fn.matches("onboarding_window::bring_to_front(").count(),
+ 3,
+ "single-instance, tray Show and tray double-click must all use bring_to_front"
+ );
+ }
+
+ #[test]
+ fn das_kommando_ist_registriert() {
+ assert!(
+ MAIN_RS.contains("onboarding_window::onboarding_window_open,"),
+ "onboarding_window_open is not in generate_handler!"
+ );
+ }
+
+ #[test]
+ fn set_onboarding_done_laesst_die_fenster_dem_marker_folgen() {
+ let f = &SYSTEM_RS[SYSTEM_RS.find("pub fn set_onboarding_done(").expect("exists")..];
+ let f = &f[..f.find("\n}\n").expect("ends")];
+ let write = f.find("write_onboarding_marker(").expect("the command writes the marker");
+ let follow = f.find("onboarding_window::follow_marker(").expect("the command moves the windows");
+ assert!(write < follow, "the marker is written BEFORE the windows follow it");
+ assert!(f.contains("?;"), "a failed write must not move the windows — the marker is the truth");
+ }
+
+ #[test]
+ fn das_onboarding_fenster_schliesst_sich_nur_per_destroy() {
+ // `close()` würde CloseRequested auslösen; der Handler darunter
+ // beendet die App, wenn der Marker fehlt. Der Handover geht daran
+ // vorbei.
+ let src = include_str!("onboarding_window.rs");
+ let reveal_fn = &src[src.find("pub fn reveal(").expect("reveal exists")..];
+ let reveal_fn = &reveal_fn[..reveal_fn.find("\n}\n").expect("reveal ends")];
+ assert!(reveal_fn.contains("o.destroy()"));
+ assert!(!reveal_fn.contains("o.close()"));
+ }
+
+ #[test]
+ fn die_frontend_seite_kennt_dasselbe_label() {
+ let host = include_str!("../../src/lib/host-window.ts");
+ assert!(
+ host.contains(&format!("'{ONBOARDING}'")),
+ "src/lib/host-window.ts must read the label {ONBOARDING:?}"
+ );
+ assert!(
+ host.contains(&format!("'{DONE_EVENT}'")),
+ "src/lib/host-window.ts must listen for {DONE_EVENT:?}"
+ );
+ let cap = include_str!("../capabilities/onboarding.json");
+ let cap: serde_json::Value = serde_json::from_str(cap).expect("capability is JSON");
+ assert_eq!(cap["windows"], serde_json::json!([ONBOARDING]));
+ }
+}
diff --git a/src/App.tsx b/src/App.tsx
index 42175294..dbabc1eb 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,28 +1,22 @@
import { useEffect } from 'react'
import { MotionConfig } from 'framer-motion'
import { AppShell } from './components/layout/AppShell'
-import { useSettingsStore } from './stores/settingsStore'
import { useVoiceStore } from './stores/voiceStore'
+import { pushPersistedChoicesToRust } from './lib/rust-boot-sync'
function App() {
useEffect(() => {
- // In Tauri: show the window once React has rendered (window starts hidden)
+ // In Tauri: show the window once React has rendered (window starts hidden).
+ // Rust decides whether it may — while the onboarding runs in its own
+ // window, the main window stays hidden (onboarding_window.rs).
if (window.__TAURI_INTERNALS__) {
import('@tauri-apps/api/core').then(({ invoke }) => {
invoke('show_window').catch(() => {})
})
- // The keychain is the store of record for the HuggingFace token; Rust
- // holds it in memory only, so every boot pushes it down again. Without
- // this, only opening Settings would arm the token, and a model download
- // started from Create or the Model Manager would still go out anonymous
- // and throttled.
- import('./api/mlx-image').then(async ({ isMlxImageHost, applyHfToken, HF_TOKEN_ACCOUNT }) => {
- if (!isMlxImageHost()) return
- const { secretGet } = await import('./api/backend')
- const stored = await secretGet(HF_TOKEN_ACCOUNT).catch(() => null)
- if (stored) await applyHfToken(stored).catch(() => {})
- })
+ // HuggingFace token + persisted GPU selection → Rust. Shared with the
+ // onboarding window, which boots without App (lib/rust-boot-sync.ts).
+ void pushPersistedChoicesToRust().catch(() => {})
}
// Probe local Whisper (STT) once at boot and push the result into the voice
@@ -40,22 +34,6 @@ function App() {
.then((ok) => useVoiceStore.getState().setTtsAvailable(ok))
.catch(() => {})
})
-
- // Bug BB v2.5.0 — push persisted GPU selection from localStorage into
- // AppState at app boot so the next Ollama / ComfyUI spawn picks it up
- // without the user having to open Settings first. Read the setting
- // synchronously off the store (already hydrated from localStorage by
- // zustand persist middleware).
- if (window.__TAURI_INTERNALS__) {
- const s = useSettingsStore.getState().settings
- const selection = {
- vendor: s.gpuVendor || 'auto',
- indices: s.gpuIndices || [],
- }
- import('@tauri-apps/api/core').then(({ invoke }) => {
- invoke('set_gpu_selection', { selection }).catch(() => {})
- })
- }
}, [])
// „Bewegung reduzieren" respektieren (Audit Welle 2). Die CSS-Regel in
diff --git a/src/components/__tests__/icon-leiter.test.ts b/src/components/__tests__/icon-leiter.test.ts
index 08021448..f43abdcb 100644
--- a/src/components/__tests__/icon-leiter.test.ts
+++ b/src/components/__tests__/icon-leiter.test.ts
@@ -106,29 +106,36 @@ describe('die optische Korrektur ist Arithmetik, gegen die echte lucide-Formel',
})
describe('die Korrektur haengt an der Wurzel, nicht an 668 Call-Sites', () => {
+ // Die Wurzel ist seit dem eigenen Onboarding-Fenster `main.tsx`: dort
+ // verzweigt der Boot nach dem Fensterlabel in ZWEI Baeume (App im
+ // Hauptfenster, OnboardingWindow im kleinen), und der Provider liegt
+ // ueber der Verzweigung. Vorher stand er in AppShell um dessen fruehe
+ // Rueckgaben — das reichte, solange es nur einen Baum gab.
+ const root = read('main.tsx')
const shell = read('components', 'layout', 'AppShell.tsx')
- it('AppShell haengt den Provider um den Baum und nimmt die Konstante', () => {
- expect(shell).toMatch(/<LucideProvider absoluteStrokeWidth strokeWidth=\{ICON_STROKE_PX\}>/)
- expect(shell).toMatch(/import \{ ICON_STROKE_PX \} from '\.\.\/ui\/icon-size'/)
+ it('main.tsx haengt den Provider um den Baum und nimmt die Konstante', () => {
+ expect(root).toMatch(/<LucideProvider absoluteStrokeWidth strokeWidth=\{ICON_STROKE_PX\}>/)
+ expect(root).toMatch(/import \{ ICON_STROKE_PX \} from '\.\/components\/ui\/icon-size'/)
})
- it('der Provider steht UM die frueheren Rueckgaben, nicht darin', () => {
- // AppShell kehrt vor dem Rahmen zweimal frueh zurueck (restoring,
- // Onboarding). Laege der Provider erst im Hauptzweig, traege
- // ausgerechnet der erste Bildschirm der App die Korrektur nicht.
- const wrapper = shell.match(/export function AppShell\(\)\s*\{[\s\S]*?\n\}/)?.[0] ?? ''
- expect(wrapper).toContain('<LucideProvider')
- expect(wrapper).toContain('<AppShellTree />')
- // Und der Baum mit den fruehen Rueckgaben ist wirklich das Kind.
- expect(shell).toMatch(/function AppShellTree\(\)/)
- const tree = shell.slice(shell.indexOf('function AppShellTree()'))
- expect(tree).toContain('if (!onboardingDone)')
- expect(tree).not.toContain('<LucideProvider')
+ it('der Provider steht UEBER der Verzweigung, nicht in einem der Baeume', () => {
+ // Laege er in App oder AppShell, traege ausgerechnet der erste
+ // Bildschirm der App — der Assistent im kleinen Fenster — die Korrektur
+ // nicht; laege er in beiden, waeren es zwei Rezepte.
+ const render = root.slice(root.indexOf('createRoot(rootEl).render('))
+ expect(render).toContain('<LucideProvider')
+ expect(render).toContain('{tree}')
+ expect(root).toContain("hostWindow === 'onboarding'")
+ expect(shell).not.toContain('<LucideProvider')
+ expect(read('App.tsx')).not.toContain('<LucideProvider')
+ expect(read('components', 'onboarding', 'OnboardingWindow.tsx')).not.toContain('<LucideProvider')
+ // Und AppShells fruehe Rueckgaben liegen weiterhin darunter.
+ expect(shell).toContain('if (!onboardingDone)')
})
it('genau eine Stelle in der App setzt den Provider', () => {
- expect((ALL.match(/<LucideProvider/g) ?? []).length).toBe(1)
+ expect(((ALL + '\n' + root).match(/<LucideProvider/g) ?? []).length).toBe(1)
})
})
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index 7fc5a3c1..a4ab0ce9 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -1,5 +1,4 @@
import { useEffect, useLayoutEffect, useState } from 'react'
-import { LucideProvider } from 'lucide-react'
import { Header } from './Header'
import { StaleModelsBanner } from './StaleModelsBanner'
import { StorageQuotaToast } from './StorageQuotaToast'
@@ -15,7 +14,6 @@ import {
OnboardingSkeleton,
SettingsSkeleton,
} from './ViewSkeletons'
-import { ICON_STROKE_PX } from '../ui/icon-size'
import { useUIStore } from '../../stores/uiStore'
import { useSettingsStore } from '../../stores/settingsStore'
import { useCompareStore } from '../../stores/compareStore'
@@ -111,35 +109,14 @@ const loadCreateExperimental = () => import('../create/experimental/CreateExperi
const loadOnboarding = () => import('../onboarding/Onboarding').then((m) => ({ default: m.Onboarding }))
/**
- * Die optische Korrektur der Icon-Leiter, einmal fuer die ganze App.
- *
- * lucide skaliert seinen 24er-Strich mit der Groesse: `2 * size / 24`. Bei
- * den 19 Groessen, die diese App heute setzt (siehe `ui/icon-size.ts`),
- * heisst das 0,67px Strich bei size=8 und 1,67px bei size=20 — Faktor 2,5
- * zwischen zwei Icons in derselben Zeile, und keiner der beiden Werte liegt
- * auf einem Geraetepixel. `absoluteStrokeWidth` dreht die Rechnung um
- * (`strokeWidth * 24 / size`) und haelt die GESEHENE Staerke konstant auf
- * ICON_STROKE_PX = 1 CSS-Pixel: ein Geraetepixel bei 1x, zwei bei 2x.
- *
- * Warum hier und nicht an 668 Call-Sites: es ist dieselbe Entscheidung wie
- * bei `.lu-control` und beim Fokusring — ein Rezept an der Wurzel, das die
- * Call-Sites nichts dazuschreiben laesst. Der Provider steht UM die beiden
- * frueheren Rueckgaben herum (Onboarding rendert vor dem App-Rahmen), sonst
- * traege ausgerechnet der erste Bildschirm der App die Korrektur nicht.
- *
- * Kosten: keine. `useLucideContext()` ruft jedes lucide-Icon ohnehin schon
- * auf, der Wert ist in `LucideProvider` memoisiert und haengt hier an zwei
- * Konstanten — es gibt keinen Render, den es vorher nicht auch gab.
+ * Die optische Korrektur der Icon-Leiter (`LucideProvider`) stand bis zum
+ * eigenen Onboarding-Fenster HIER, um die beiden fruehen Rueckgaben unten
+ * herum. Seit `index.html` in zwei Fenstern laedt, gibt es zwei Wurzeln —
+ * `App` im Hauptfenster, `OnboardingWindow` im kleinen — und der Provider
+ * liegt in `main.tsx` ueber beiden, einmal. Die Begruendung (ein Rezept an
+ * der Wurzel statt an 668 Call-Sites) steht dort.
*/
export function AppShell() {
- return (
- <LucideProvider absoluteStrokeWidth strokeWidth={ICON_STROKE_PX}>
- <AppShellTree />
- </LucideProvider>
- )
-}
-
-function AppShellTree() {
// Targeted, NOT `useUIStore()`. A whole-store subscription here put the
// entire app tree behind every uiStore write — and the explorer's resize
// handle writes `explorerWidth` on every pointermove, so dragging the
diff --git a/src/components/onboarding/ModelsStep.tsx b/src/components/onboarding/ModelsStep.tsx
index f9a99c49..25deb1e1 100644
--- a/src/components/onboarding/ModelsStep.tsx
+++ b/src/components/onboarding/ModelsStep.tsx
@@ -63,7 +63,6 @@ export function ModelsStep({ skin, scan, fleet, step, setStep, pulledModels, set
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.
@@ -133,12 +132,16 @@ export function ModelsStep({ skin, scan, fleet, step, setStep, pulledModels, set
}
} else if (!useOllamaPath) {
const settingsOverride = useSettingsStore.getState().settings.hfDownloadPathOverride?.trim() || ''
- destDir = settingsOverride || hfModelPath || (await detectProviderModelPath(providers.openai?.name || 'LM Studio'))
+ // `hfModelPath` stand hier als Zwischenspeicher fuer die Erkennung —
+ // ein `useState`, das nur ein zweiter Klick auf „Install" in derselben
+ // Sitzung je gelesen haette, um sich EINEN Rust-Aufruf zu sparen. Die
+ // Erkennung ist idempotent und billig; der Zustand ist weg (AS-09
+ // zaehlt die `useState` des Ordners).
+ destDir = settingsOverride || (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) {
diff --git a/src/components/onboarding/Onboarding.tsx b/src/components/onboarding/Onboarding.tsx
index 498d3d1b..34bb546e 100644
--- a/src/components/onboarding/Onboarding.tsx
+++ b/src/components/onboarding/Onboarding.tsx
@@ -62,6 +62,7 @@ import { onboardingSkin } from './onboarding-skin'
import { useBackendScan } from './use-backend-scan'
import { useInstallerFleet } from './use-installer-fleet'
import { isTauri } from './onboarding-host'
+import { hostWindow } from '../../lib/host-window'
import { BackendsStep } from './BackendsStep'
import { ComfyStep } from './ComfyStep'
import { ModelsStep } from './ModelsStep'
@@ -100,7 +101,19 @@ export function Onboarding() {
const fleet = useInstallerFleet()
const { selectedBackend, detectedBackends, runDetection } = scan
- const finish = () => {
+ // Läuft der Assistent in seinem eigenen kleinen Fenster (Erststart,
+ // `src-tauri/src/onboarding_window.rs`) oder im Hauptfenster (Browser-
+ // Vorschau, Notweg ohne eigenes Fenster)? Die Antwort kommt aus
+ // `lib/host-window.ts`, nirgends sonst.
+ const ownWindow = hostWindow === 'onboarding'
+ // Die Übergabe im eigenen Fenster: nach dem Marker bootet das Hauptfenster,
+ // und dessen `show_window` schließt dieses hier. Bis dahin sagt der Knopf,
+ // was gerade passiert.
+ // EIN Zustand, nicht zwei: Phase und Fehler gehören zusammen (AS-09 zählt
+ // die `useState` des Ordners und darf nicht steigen).
+ const [handover, setHandover] = useState<{ phase: 'idle' | 'running' } | { phase: 'failed'; error: string }>({ phase: 'idle' })
+
+ const finish = async () => {
updateSettings({ onboardingDone: true })
// B4: a brand new install must NOT be greeted by "what is new in 2.6.3"
// right after setting the app up for the first time. Stamping the current
@@ -108,15 +121,29 @@ export function Onboarding() {
// an upgrade never runs this wizard, so its flag stays null and it gets the
// notes. This is the ONLY place that stamps without showing anything.
useReleaseNotesStore.getState().markNotesSeen(currentVersion)
+ if (!isTauri) return
// Persist to filesystem so NSIS updates don't reset onboarding.
- //
- // Level (a): silent on purpose. updateSettings() above is what actually
- // ends the wizard, and it is persisted. This only writes the recovery
- // marker, which AppShell re-writes on any later boot where it is missing
- // (the migration next to `is_onboarding_done`). So a failure here heals
- // itself, and reporting it would put an error on the last screen of a
- // setup that succeeded.
- if (isTauri) backendCall('set_onboarding_done').catch(() => {})
+ if (!ownWindow) {
+ // Level (a): silent on purpose. updateSettings() above is what actually
+ // ends the wizard, and it is persisted. This only writes the recovery
+ // marker, which AppShell re-writes on any later boot where it is missing
+ // (the migration next to `is_onboarding_done`). So a failure here heals
+ // itself, and reporting it would put an error on the last screen of a
+ // setup that succeeded.
+ backendCall('set_onboarding_done').catch(() => {})
+ return
+ }
+ // Im eigenen Fenster ist der Marker KEIN stiller Fall mehr: Rust
+ // entscheidet die Fenster daraus, und ohne Marker gibt es kein
+ // Hauptfenster. Ein Fehler steht deshalb hier, mit Ursache, und der Knopf
+ // bleibt drückbar — der Store ist schon geschrieben, ein zweiter Versuch
+ // schreibt nur die Datei noch einmal.
+ setHandover({ phase: 'running' })
+ try {
+ await backendCall('set_onboarding_done')
+ } catch (e) {
+ setHandover({ phase: 'failed', error: `LU could not save that setup is complete: ${e instanceof Error ? e.message : String(e)}` })
+ }
}
// Hard rule: on macOS, local image/video generation is Apple MLX only —
@@ -175,16 +202,34 @@ export function Onboarding() {
// Teil des Assistenten. Jetzt steht der Anzeiger IM Fluss, direkt ueber
// der Karte, und der Abstand ist der `gap` einer Spalte statt der Rest
// einer Zentrierung.
- <div className={`h-screen w-screen flex flex-col items-center justify-center gap-5 p-4 ${bgClass}`}>
- {/* Drag region + window controls */}
+ // `overflow-y-auto` plus die Spalte mit `my-auto` darunter: im eigenen
+ // Fenster (640x640, nicht groessenveraenderbar) tragen die gemessenen
+ // Bildschirme ohne Scrollen; was darueber hinausgeht — aufgeklappte
+ // Alternativlisten, Installations-Protokolle — scrollt. Auto-Raender
+ // statt nur `justify-center`, weil ein zentrierter Flex-Inhalt, der
+ // hoeher ist als sein Kasten, oben ABGESCHNITTEN wuerde: die Raender
+ // werden bei Ueberlauf null und der Inhalt beginnt oben, sonst bleiben
+ // sie die Zentrierung, die vorher `justify-center` allein war.
+ <div className={`h-screen w-screen flex flex-col items-center justify-center gap-5 p-4 overflow-y-auto ${bgClass}`}>
+ {/* Drag region + window controls. Im eigenen Fenster folgt der Streifen
+ dem Rezept der Titelleiste (`layout/Titlebar.tsx`): auf dem Mac
+ zeichnet das System die Ampeln links (Overlay-Balken), also keine
+ eigenen Knoepfe; auf Windows/Linux ersetzt die App den Systembalken
+ — Minimieren und Schliessen, KEIN Maximieren, das Fenster ist nicht
+ groessenveraenderbar. Im Hauptfenster bleibt der alte Satz. */}
{isTauri && (
<div data-tauri-drag-region className="fixed top-0 left-0 right-0 h-8 z-50 flex items-center justify-end select-none">
- <button onClick={handleMinimize} className={winBtn} aria-label="Minimize"><Minus size={ICON_SM} /></button>
- <button onClick={handleMaximize} className={winBtn} aria-label="Maximize"><Square size={ICON_SM} /></button>
- <button onClick={handleClose} className={`${winBtn} hover:bg-red-500 hover:text-white`} aria-label="Close"><XIcon size={ICON_SM} /></button>
+ {!(ownWindow && isMacOS()) && (<>
+ <button onClick={handleMinimize} className={winBtn} aria-label="Minimize"><Minus size={ICON_SM} /></button>
+ {!ownWindow && (
+ <button onClick={handleMaximize} className={winBtn} aria-label="Maximize"><Square size={ICON_SM} /></button>
+ )}
+ <button onClick={handleClose} className={`${winBtn} hover:bg-red-500 hover:text-white`} aria-label="Close"><XIcon size={ICON_SM} /></button>
+ </>)}
</div>
)}
+ <div className="w-full flex flex-col items-center gap-5 my-auto">
{/* Step indicator — Punkte UND Text. Sechs anonyme Punkte konnten die
Frage „wie viele noch?" nicht beantworten; „Step 2 of 4 · Model"
kann es. Die Hoehe ist fest, damit ein Schrittwechsel die Karte
@@ -332,12 +377,16 @@ export function Onboarding() {
? `Connected to ${detectedBackends.find(b => b.id === selectedBackend)?.name || detectedBackends[0].name}. You're ready to go.`
: 'You can configure backends and install models anytime from Settings and the Models tab.'}
</p>
- <button onClick={finish} className={primaryBtn}>
- Get Started <ArrowRight size={14} />
+ <button onClick={finish} className={primaryBtn} disabled={handover.phase === 'running'}>
+ {handover.phase === 'running' ? 'Opening LU…' : <>Get Started <ArrowRight size={14} /></>}
</button>
+ {handover.phase === 'failed' && (
+ <p className="t-micro text-red-400">{handover.error}</p>
+ )}
</motion.div>
)}
</AnimatePresence>
+ </div>
</div>
)
}
diff --git a/src/components/onboarding/OnboardingWindow.tsx b/src/components/onboarding/OnboardingWindow.tsx
new file mode 100644
index 00000000..0fd8c333
--- /dev/null
+++ b/src/components/onboarding/OnboardingWindow.tsx
@@ -0,0 +1,45 @@
+/**
+ * Der kleinste Baum, der den Assistenten trägt — für das eigene Fenster.
+ *
+ * NICHT `App` und nicht `AppShell`: die würden im kleinen Fenster die ganze
+ * Anwendung hochfahren — Backup-Triade, Backend-Erkennung, Remote-Hörer,
+ * Whisper-Probe, Modell-Gesundheitsscan — und beim Schließen des Fensters
+ * stürbe das alles mittendrin. Hier steht nur, was der Assistent wirklich
+ * braucht, und alles davon steht aus demselben Grund auch um ihn herum, wenn
+ * er im Hauptfenster läuft (`AppShell.tsx`, `App.tsx`):
+ *
+ * MotionConfig „Bewegung reduzieren" für framer-motion, das die
+ * CSS-Regel in index.css nicht erreicht.
+ * show_window das Fenster ist unsichtbar gebaut (kein weißer Blitz)
+ * und zeigt sich, sobald React steht — derselbe Weg wie
+ * beim Hauptfenster.
+ * pushPersisted… HF-Token und GPU-Wahl nach Rust, bevor der Assistent
+ * lädt oder spawnt (siehe `lib/rust-boot-sync.ts`).
+ *
+ * Der LucideProvider (Strichstärke der Icon-Leiter) fehlt hier NICHT aus
+ * Versehen: er liegt in `main.tsx` über beiden Bäumen, einmal.
+ *
+ * Was hier fehlt, fehlt mit Absicht: der Assistent selbst hydriert seine
+ * Stores (Settings, Provider, Downloads, Release-Notes) aus localStorage,
+ * das beide Webviews teilen. Das Hauptfenster wartet derweil, ohne einen
+ * davon geladen zu haben (`main.tsx`), und liest nach dem Abschluss frisch.
+ */
+import { useEffect } from 'react'
+import { MotionConfig } from 'framer-motion'
+import { pushPersistedChoicesToRust } from '../../lib/rust-boot-sync'
+import { Onboarding } from './Onboarding'
+
+export function OnboardingWindow() {
+ useEffect(() => {
+ import('@tauri-apps/api/core').then(({ invoke }) => {
+ invoke('show_window').catch(() => {})
+ })
+ void pushPersistedChoicesToRust().catch(() => {})
+ }, [])
+
+ return (
+ <MotionConfig reducedMotion="user">
+ <Onboarding />
+ </MotionConfig>
+ )
+}
diff --git a/src/components/onboarding/__tests__/installer-state.test.ts b/src/components/onboarding/__tests__/installer-state.test.ts
index 4cec3bcb..5719e85d 100644
--- a/src/components/onboarding/__tests__/installer-state.test.ts
+++ b/src/components/onboarding/__tests__/installer-state.test.ts
@@ -59,6 +59,10 @@ const lies = (name: string) => codeOnly(readFileSync(resolve(DIR, name), 'utf8')
/** Die Dateien, aus denen der Assistent nach der Zerlegung besteht. */
const ASSISTENT = [
'Onboarding.tsx',
+ // Der Rahmen fuer das eigene Fenster (Erststart): kein Schritt, aber der
+ // Baum, der die Schale traegt — und damit ein Ort, an dem `useState`
+ // auftauchen koennte. Deshalb zaehlt er mit.
+ 'OnboardingWindow.tsx',
'BackendsStep.tsx',
'ComfyStep.tsx',
'ModelsStep.tsx',
diff --git a/src/components/onboarding/__tests__/onboarding-fenster.test.ts b/src/components/onboarding/__tests__/onboarding-fenster.test.ts
new file mode 100644
index 00000000..e41e4a17
--- /dev/null
+++ b/src/components/onboarding/__tests__/onboarding-fenster.test.ts
@@ -0,0 +1,260 @@
+/**
+ * Das Onboarding im eigenen Fenster — was der Quelltext darüber zusichert.
+ *
+ * Was hier NICHT steht: ob das Fenster erscheint, wie groß es ist, wo es
+ * liegt. Das sieht nur eine laufende App (`npx tauri build --debug`, dann
+ * messen). Was ein Quelltext-Test sagen kann: dass die Bausteine so
+ * zusammengesteckt sind, wie der Entwurf es verlangt, und dass keiner von
+ * ihnen leise wieder auseinanderläuft.
+ *
+ * Lauf: npx vitest run src/components/onboarding/__tests__/onboarding-fenster.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+const ROOT = resolve(__dirname, '..', '..', '..', '..')
+const read = (...p: string[]) => readFileSync(resolve(ROOT, ...p), 'utf8')
+const codeOnly = (src: string) =>
+ src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1')
+
+const MAIN_TSX = codeOnly(read('src', 'main.tsx'))
+const APP_TSX = codeOnly(read('src', 'App.tsx'))
+const WINDOW_TSX = codeOnly(read('src', 'components', 'onboarding', 'OnboardingWindow.tsx'))
+const ONBOARDING_TSX = codeOnly(read('src', 'components', 'onboarding', 'Onboarding.tsx'))
+const HOST = codeOnly(read('src', 'lib', 'host-window.ts'))
+const BOOT_SYNC = codeOnly(read('src', 'lib', 'rust-boot-sync.ts'))
+const RUST = read('src-tauri', 'src', 'onboarding_window.rs')
+const CONF = JSON.parse(read('src-tauri', 'tauri.conf.json'))
+const CAP_MAIN = JSON.parse(read('src-tauri', 'capabilities', 'default.json'))
+const CAP_ONB = JSON.parse(read('src-tauri', 'capabilities', 'onboarding.json'))
+
+// ── Frage 1: woher weiß das Frontend, in welchem Fenster es läuft? ─────────
+
+describe('main.tsx verzweigt am Fensterlabel — und nur dort', () => {
+ it('holt die Antwort aus lib/host-window und nicht aus einem eigenen Prädikat', () => {
+ expect(MAIN_TSX).toContain("import('./lib/host-window')")
+ expect(MAIN_TSX).toContain("hostWindow === 'onboarding'")
+ expect(MAIN_TSX).not.toContain('__TAURI_INTERNALS__')
+ })
+
+ it('wartet im Hauptfenster auf die Übergabe, BEVOR es App oder einen Store importiert', () => {
+ const wait = MAIN_TSX.indexOf('await awaitOnboardingHandover()')
+ const app = MAIN_TSX.indexOf("import('./App.tsx')")
+ const providers = MAIN_TSX.indexOf("import('./stores/providerStore')")
+ expect(wait).toBeGreaterThan(-1)
+ expect(app).toBeGreaterThan(wait)
+ expect(providers).toBeGreaterThan(wait)
+ })
+
+ it('das Warten hört auf das Ereignis UND sieht nach dem Marker — das Ereignis kann vor dem Hörer gefeuert sein', () => {
+ const fn = HOST.slice(HOST.indexOf('export async function awaitOnboardingHandover'))
+ expect(fn).toContain("invoke<boolean>('onboarding_window_open')")
+ expect(fn).toContain('listen(ONBOARDING_DONE_EVENT, settle)')
+ expect(fn).toContain("invoke<boolean>('is_onboarding_done')")
+ // Reihenfolge: erst hören, dann nachsehen. Andersherum bliebe die Lücke.
+ expect(fn.indexOf('listen(ONBOARDING_DONE_EVENT')).toBeLessThan(fn.indexOf("invoke<boolean>('is_onboarding_done')"))
+ })
+})
+
+// ── Frage 2: was rendert das Onboarding-Fenster? ───────────────────────────
+
+describe('das kleine Fenster trägt den kleinsten Baum', () => {
+ it('OnboardingWindow rendert den Assistenten — nicht App, nicht AppShell', () => {
+ expect(WINDOW_TSX).toContain("from './Onboarding'")
+ expect(WINDOW_TSX).not.toContain('AppShell')
+ expect(WINDOW_TSX).not.toMatch(/from '\.\.\/\.\.\/App'/)
+ })
+
+ it('und um ihn herum genau das, was AppShell und App auch um ihn legen', () => {
+ // MotionConfig (Bewegung reduzieren) wie in App, show_window wie in App.
+ // Der LucideProvider (Strichstärke) liegt seit den zwei Wurzeln in
+ // main.tsx über BEIDEN Bäumen — siehe icon-leiter.test.ts.
+ expect(WINDOW_TSX).toContain('<MotionConfig reducedMotion="user">')
+ expect(WINDOW_TSX).not.toContain('<LucideProvider')
+ expect(WINDOW_TSX).toContain("invoke('show_window')")
+ expect(APP_TSX).toContain('<MotionConfig reducedMotion="user">')
+ })
+
+ it('HF-Token und GPU-Wahl gehen aus BEIDEN Fenstern nach Rust, aus einer Funktion', () => {
+ expect(BOOT_SYNC).toContain("invoke('set_gpu_selection', { selection })")
+ expect(BOOT_SYNC).toContain('applyHfToken(stored)')
+ expect(APP_TSX).toContain('pushPersistedChoicesToRust()')
+ expect(WINDOW_TSX).toContain('pushPersistedChoicesToRust()')
+ // Die alten Kopien in App.tsx sind weg.
+ expect(APP_TSX).not.toContain('set_gpu_selection')
+ expect(APP_TSX).not.toContain('applyHfToken')
+ })
+
+ it('das Hauptfenster zeichnet den Assistenten weiterhin selbst, wenn kein kleines Fenster da ist', () => {
+ // Browser-Vorschau, die Playwright-Suite (Label `main`, Mock ohne
+ // Fenster) und der Notweg in Rust (`reveal_decision`: ohne
+ // Stellvertreter wird gezeigt) laufen alle über diesen Zweig.
+ const shell = codeOnly(read('src', 'components', 'layout', 'AppShell.tsx'))
+ expect(shell).toContain('if (!onboardingDone) {')
+ expect(shell).toContain('<LazyView load={loadOnboarding} fallback={<OnboardingSkeleton />} />')
+ })
+})
+
+// ── Frage 3: rahmenlos oder dekoriert? ────────────────────────────────────
+
+describe('die Dekoration folgt dem Hauptfenster der jeweiligen Plattform', () => {
+ const mac = JSON.parse(read('src-tauri', 'tauri.macos.conf.json')).app.windows[0]
+ const win = JSON.parse(read('src-tauri', 'tauri.windows.conf.json')).app.windows[0]
+
+ it('macOS: Overlay-Balken mit verstecktem Titel, wie das Hauptfenster', () => {
+ expect(mac.titleBarStyle).toBe('Overlay')
+ expect(mac.hiddenTitle).toBe(true)
+ expect(RUST).toContain('#[cfg(target_os = "macos")]')
+ expect(RUST).toContain('.title_bar_style(tauri::TitleBarStyle::Overlay)')
+ expect(RUST).toContain('.hidden_title(true)')
+ })
+
+ it('Windows: rahmenlos und transparent ohne DWM-Schatten, wie das Hauptfenster', () => {
+ expect(win.decorations).toBe(false)
+ expect(win.transparent).toBe(true)
+ expect(RUST).toContain('#[cfg(not(target_os = "macos"))]')
+ expect(RUST).toContain('.decorations(false).transparent(true)')
+ expect(RUST).toContain('#[cfg(target_os = "windows")]')
+ expect(RUST).toContain('window.set_shadow(false)')
+ })
+
+ it('rahmenlos braucht eine Ziehfläche — der Streifen bleibt, festgenagelt', () => {
+ expect(ONBOARDING_TSX).toContain('data-tauri-drag-region className="fixed top-0 left-0 right-0 h-8')
+ expect(CAP_ONB.permissions).toContain('core:window:allow-start-dragging')
+ })
+
+ it('im eigenen Fenster gibt es kein Maximieren, auf dem Mac keine eigenen Knöpfe', () => {
+ expect(ONBOARDING_TSX).toContain("const ownWindow = hostWindow === 'onboarding'")
+ expect(ONBOARDING_TSX).toContain('{!(ownWindow && isMacOS()) && (<>')
+ expect(ONBOARDING_TSX).toContain('{!ownWindow && (')
+ expect(RUST).toContain('.resizable(false)')
+ expect(RUST).toContain('.maximizable(false)')
+ expect(CAP_ONB.permissions).not.toContain('core:window:allow-maximize')
+ expect(CAP_ONB.permissions).not.toContain('core:window:allow-toggle-maximize')
+ })
+})
+
+// ── Frage 4: der Download überlebt den Fensterwechsel ─────────────────────
+
+describe('der Starter-Download läuft in Rust, und das Fenster geht nicht mittendrin zu', () => {
+ it('download_model_to_path spawnt eine tokio-Task und hält den Stand im AppState', () => {
+ const dl = read('src-tauri', 'src', 'commands', 'download.rs')
+ const fn = dl.slice(dl.indexOf('pub async fn download_model_to_path('))
+ expect(fn.slice(0, 4000)).toContain('tokio::spawn(async move {')
+ expect(fn.slice(0, 4000)).toContain('Arc::clone(&state.downloads)')
+ })
+
+ it('der Ollama-Pull ebenso: Rust pullt, das Fenster hört nur Ereignisse', () => {
+ const proxy = read('src-tauri', 'src', 'commands', 'proxy.rs')
+ expect(proxy).toContain('app.emit("pull-progress"')
+ const ollama = codeOnly(read('src', 'api', 'ollama.ts'))
+ expect(ollama).toContain('listen<string>("pull-progress"')
+ })
+
+ it('kein Schritt lässt den Nutzer weiter, solange er lädt — also endet das Onboarding nie mit laufendem Download', () => {
+ const models = codeOnly(read('src', 'components', 'onboarding', 'ModelsStep.tsx'))
+ const embeds = codeOnly(read('src', 'components', 'onboarding', 'EmbeddingsStep.tsx'))
+ // Modelle: „Skip for now" verschwindet, sobald ein Download läuft.
+ expect(models).toMatch(/: !isDownloading \? \(\s*<button\s+onClick=\{\(\) => setStep\('embeddings'\)\}/)
+ // Einbettungen: „Continue/Skip" ist deaktiviert, solange gepullt wird.
+ expect(embeds).toContain('disabled={embeddingsPulling}')
+ })
+
+ it('und geschlossen wird das kleine Fenster erst, nachdem das große sichtbar ist', () => {
+ const reveal = RUST.slice(RUST.indexOf('pub fn reveal('), RUST.indexOf('pub fn open('))
+ const show = reveal.lastIndexOf('window.show()')
+ const destroy = reveal.indexOf('o.destroy()')
+ expect(show).toBeGreaterThan(-1)
+ expect(destroy).toBeGreaterThan(show)
+ })
+})
+
+// ── Frage 5: Größe ─────────────────────────────────────────────────────────
+
+describe('die Größe ist gemessen, nicht geraten', () => {
+ const w = Number(/pub const ONBOARDING_WIDTH: f64 = ([\d.]+);/.exec(RUST)?.[1])
+ const h = Number(/pub const ONBOARDING_HEIGHT: f64 = ([\d.]+);/.exec(RUST)?.[1])
+
+ it('640 x 640: trägt den längsten gemessenen Schritt (531 + 37 + 18) und ist kleiner als das Hauptfenster', () => {
+ expect(w).toBe(640)
+ expect(h).toBe(640)
+ expect(h).toBeGreaterThanOrEqual(531 + 37 + 18)
+ expect(w).toBeLessThan(CONF.app.windows[0].width)
+ expect(h).toBeLessThan(CONF.app.windows[0].height)
+ })
+
+ it('was darüber hinausgeht, scrollt — ohne oben abgeschnitten zu werden', () => {
+ expect(ONBOARDING_TSX).toContain('h-screen w-screen flex flex-col items-center justify-center gap-5 p-4 overflow-y-auto')
+ expect(ONBOARDING_TSX).toContain('<div className="w-full flex flex-col items-center gap-5 my-auto">')
+ })
+
+ it('das Hauptfenster in tauri.conf.json ist unverändert das eine, große', () => {
+ expect(CONF.app.windows).toHaveLength(1)
+ expect(CONF.app.windows[0]).toMatchObject({ width: 1280, height: 800, visible: false })
+ // Das kleine Fenster steht NICHT in der Konfiguration: Rust baut es,
+ // und nur dann, wenn der Marker fehlt.
+ expect(JSON.stringify(CONF)).not.toContain('"onboarding"')
+ })
+})
+
+// ── Frage 6: Zurücksetzen in den Einstellungen ────────────────────────────
+
+describe('„Re-run onboarding" bringt das kleine Fenster zurück — über den Marker', () => {
+ it('die Einstellungen löschen den Marker, und die Fenster folgen ihm', () => {
+ const settings = codeOnly(read('src', 'components', 'settings', 'SettingsPage.tsx'))
+ expect(settings).toContain("await backendCall('set_onboarding_done', { done: false })")
+ const system = read('src-tauri', 'src', 'commands', 'system.rs')
+ expect(system).toContain('crate::onboarding_window::follow_marker(&app, done);')
+ const follow = RUST.slice(RUST.indexOf('pub fn follow_marker('), RUST.indexOf('pub fn front_window('))
+ expect(follow).toContain('else if onboarding.is_none()')
+ expect(follow).toContain('open(app)')
+ })
+
+ it('erst zeigt sich das kleine, dann verschwindet das große — nie ein Moment ohne Fenster', () => {
+ const reveal = RUST.slice(RUST.indexOf('pub fn reveal('), RUST.indexOf('pub fn open('))
+ const showBlock = reveal.slice(reveal.indexOf('Reveal::Show =>'), reveal.indexOf('Reveal::ShowAndCloseOnboarding =>'))
+ expect(showBlock.indexOf('window.show()')).toBeLessThan(showBlock.indexOf('main.hide()'))
+ })
+})
+
+// ── Das Onboarding-Fenster als Fenster ────────────────────────────────────
+
+describe('das Fenster selbst', () => {
+ it('wird vom System mittig gesetzt, unsichtbar gebaut und vom Frontend gezeigt', () => {
+ const open = RUST.slice(RUST.indexOf('pub fn open('), RUST.indexOf('fn quit('))
+ expect(open).toContain('.center()')
+ expect(open).toContain('.visible(false)')
+ expect(open).toContain('WebviewUrl::default()')
+ })
+
+ it('zu heißt Ende, solange das Onboarding nicht fertig ist', () => {
+ const open = RUST.slice(RUST.indexOf('pub fn open('), RUST.indexOf('fn quit('))
+ expect(open).toContain('tauri::WindowEvent::CloseRequested')
+ expect(open).toContain('if !is_onboarding_done()')
+ expect(open).toContain('quit(&handle)')
+ const quit = RUST.slice(RUST.indexOf('fn quit('), RUST.indexOf('#[tauri::command]'))
+ expect(quit).toContain('shutdown_subprocesses()')
+ expect(quit).toContain('app.exit(0)')
+ })
+
+ it('seine Capability ist die kleine, nicht die des Hauptfensters', () => {
+ expect(CAP_MAIN.windows).toEqual(['main'])
+ expect(CAP_ONB.windows).toEqual(['onboarding'])
+ const spawn = CAP_ONB.permissions.find((p: unknown) => typeof p === 'object' && p !== null && (p as { identifier?: string }).identifier === 'shell:allow-spawn')
+ expect(spawn).toBeUndefined()
+ expect(CAP_ONB.permissions).not.toContain('updater:default')
+ // Was der Assistent wirklich braucht: bewegen, minimieren, schließen,
+ // Ereignisse hören (core:default), Herstellerseiten im Browser öffnen.
+ for (const p of ['core:default', 'core:window:allow-minimize', 'core:window:allow-close', 'core:window:allow-start-dragging', 'shell:allow-open']) {
+ expect(CAP_ONB.permissions).toContain(p)
+ }
+ })
+
+ it('im eigenen Fenster ist der Marker kein stiller Fall: der Knopf sagt, was passiert, und ein Fehler steht da', () => {
+ expect(ONBOARDING_TSX).toContain("setHandover({ phase: 'running' })")
+ expect(ONBOARDING_TSX).toContain("await backendCall('set_onboarding_done')")
+ expect(ONBOARDING_TSX).toContain("handover.phase === 'running' ? 'Opening LU…'")
+ expect(ONBOARDING_TSX).toContain("{handover.phase === 'failed' && (")
+ })
+})
diff --git a/src/lib/__tests__/host-window.test.ts b/src/lib/__tests__/host-window.test.ts
new file mode 100644
index 00000000..2b6824d5
--- /dev/null
+++ b/src/lib/__tests__/host-window.test.ts
@@ -0,0 +1,94 @@
+/**
+ * In welchem Fenster läuft das Frontend? — die eine Stelle, die es weiß.
+ *
+ * Seit das Onboarding ein eigenes Fenster hat, lädt `index.html` zweimal:
+ * im Hauptfenster `main` und im kleinen Fenster `onboarding`. Beide werden
+ * aus dem Fensterlabel unterschieden, und zwar in `lib/host-window.ts` und
+ * nirgends sonst — das ist die Regel, die dieser Test hält.
+ *
+ * Lauf: npx vitest run src/lib/__tests__/host-window.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync, readdirSync, statSync } from 'node:fs'
+import { join, resolve } from 'node:path'
+import { hostWindowFrom, hostWindow, ONBOARDING_WINDOW_LABEL, ONBOARDING_DONE_EVENT } from '../host-window'
+
+const ROOT = resolve(__dirname, '..', '..', '..')
+const codeOnly = (src: string) =>
+ src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1')
+
+function walk(dir: string, out: string[] = []): string[] {
+ for (const name of readdirSync(dir)) {
+ const p = join(dir, name)
+ if (statSync(p).isDirectory()) walk(p, out)
+ else if (/\.(ts|tsx)$/.test(name) && !/\.test\.tsx?$/.test(name)) out.push(p)
+ }
+ return out
+}
+
+describe('hostWindowFrom: das Label sagt, welches Fenster', () => {
+ it('kein Label heißt Browser-Vorschau', () => {
+ expect(hostWindowFrom(null)).toBe('browser')
+ })
+
+ it('das Onboarding-Label heißt Onboarding-Fenster', () => {
+ expect(hostWindowFrom(ONBOARDING_WINDOW_LABEL)).toBe('onboarding')
+ expect(hostWindowFrom('onboarding')).toBe('onboarding')
+ })
+
+ it('jedes andere Label ist das Hauptfenster — auch ein unbekanntes', () => {
+ // Ein drittes Fenster müsste hier ausdrücklich dazukommen. Bis dahin ist
+ // „nicht das Onboarding" gleichbedeutend mit „die App".
+ expect(hostWindowFrom('main')).toBe('main')
+ expect(hostWindowFrom('something-new')).toBe('main')
+ expect(hostWindowFrom('')).toBe('main')
+ })
+
+ it('ohne Tauri-Laufzeit (hier: node) ist der Wirt der Browser, und nichts wirft', () => {
+ expect(hostWindow).toBe('browser')
+ })
+})
+
+describe('das Label wird an EINER Stelle gelesen', () => {
+ const files = walk(resolve(ROOT, 'src'))
+
+ it('getCurrentWebviewWindow kommt außerhalb von host-window.ts nicht vor', () => {
+ const offenders = files
+ .filter((f) => !f.endsWith(`${'/lib/host-window.ts'}`))
+ .filter((f) => codeOnly(readFileSync(f, 'utf8')).includes('getCurrentWebviewWindow'))
+ .map((f) => f.slice(ROOT.length + 1))
+ expect(offenders).toEqual([])
+ })
+
+ it('niemand liest metadata.currentWebview selbst', () => {
+ const offenders = files
+ .filter((f) => codeOnly(readFileSync(f, 'utf8')).includes('metadata.currentWebview'))
+ .map((f) => f.slice(ROOT.length + 1))
+ expect(offenders).toEqual([])
+ })
+
+ it('und wer die Antwort braucht, importiert sie von dort', () => {
+ // Die drei Stellen, die verzweigen: der Einstieg (welcher Baum), die
+ // Schale des Assistenten (welche Fensterknöpfe, welche Übergabe).
+ for (const f of ['src/main.tsx', 'src/components/onboarding/Onboarding.tsx']) {
+ expect(codeOnly(readFileSync(resolve(ROOT, f), 'utf8')), f).toMatch(/lib\/host-window'/)
+ }
+ })
+})
+
+describe('Rust und Frontend meinen dasselbe Label und dasselbe Ereignis', () => {
+ const rust = readFileSync(resolve(ROOT, 'src-tauri', 'src', 'onboarding_window.rs'), 'utf8')
+
+ it('das Label', () => {
+ expect(rust).toContain(`pub const ONBOARDING: &str = "${ONBOARDING_WINDOW_LABEL}";`)
+ })
+
+ it('das Ereignis', () => {
+ expect(rust).toContain(`pub const DONE_EVENT: &str = "${ONBOARDING_DONE_EVENT}";`)
+ })
+
+ it('die Capability des kleinen Fensters gilt genau diesem Label', () => {
+ const cap = JSON.parse(readFileSync(resolve(ROOT, 'src-tauri', 'capabilities', 'onboarding.json'), 'utf8'))
+ expect(cap.windows).toEqual([ONBOARDING_WINDOW_LABEL])
+ })
+})
diff --git a/src/lib/host-window.ts b/src/lib/host-window.ts
new file mode 100644
index 00000000..029e1e46
--- /dev/null
+++ b/src/lib/host-window.ts
@@ -0,0 +1,85 @@
+/**
+ * In welchem Fenster läuft dieses Frontend?
+ *
+ * Seit das Onboarding ein eigenes Fenster hat (`src-tauri/src/onboarding_window.rs`),
+ * lädt `index.html` in ZWEI Webviews: dem Hauptfenster `main` und dem kleinen
+ * Fenster `onboarding`. Die Antwort kommt aus dem Fensterlabel, das Tauri jedem
+ * Webview mitgibt (`getCurrentWebviewWindow().label`) — und sie steht genau
+ * hier, einmal. Dieses Projekt hat schon mehrfach daran gekrankt, dass eine
+ * Frage zwei Wege hatte, von denen einer gepflegt wurde; deshalb liest kein
+ * anderes Modul das Label selbst.
+ *
+ * Was hier NICHT steht: ob wir überhaupt in Tauri laufen. Das Prädikat dafür
+ * gibt es zweimal mit Absicht (`api/backend.ts` mit v1-Rückfall,
+ * `onboarding-host.ts` streng v2), und dieses Modul braucht keines von beiden:
+ * ohne Tauri wirft `getCurrentWebviewWindow()`, und der Fang darunter heißt
+ * `browser`.
+ */
+import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'
+
+export type HostWindow = 'main' | 'onboarding' | 'browser'
+
+/** Das Label des Onboarding-Fensters — dasselbe Literal wie `ONBOARDING` in
+ * `onboarding_window.rs`; ein Rust-Test hält beide gleich. */
+export const ONBOARDING_WINDOW_LABEL = 'onboarding'
+
+/** Das Ereignis, mit dem Rust dem wartenden Hauptfenster sagt, dass der
+ * Marker geschrieben ist — `DONE_EVENT` drüben. */
+export const ONBOARDING_DONE_EVENT = 'onboarding:done'
+
+/**
+ * Die reine Zuordnung, ohne Fenster: `null` heißt „kein Tauri-Webview". Jedes
+ * andere Label als das Onboarding-Label ist das Hauptfenster — ein künftiges
+ * drittes Fenster müsste hier ausdrücklich dazukommen, nicht stillschweigend
+ * als Onboarding durchgehen.
+ */
+export function hostWindowFrom(label: string | null): HostWindow {
+ if (label === null) return 'browser'
+ return label === ONBOARDING_WINDOW_LABEL ? 'onboarding' : 'main'
+}
+
+function currentLabel(): string | null {
+ try {
+ return getCurrentWebviewWindow().label
+ } catch {
+ return null
+ }
+}
+
+/** Einmal beim Laden ausgewertet: ein Webview wechselt sein Fenster nicht. */
+export const hostWindow: HostWindow = hostWindowFrom(currentLabel())
+
+/**
+ * Das Hauptfenster beim Boot: läuft das Onboarding gerade im eigenen
+ * Fenster, dann WARTEN — ohne einen Store zu laden. Die Stores hydrieren aus
+ * localStorage, und genau dort schreibt der Assistent drüben gerade den
+ * Provider, das Theme, den Abschluss. Ein Hauptfenster, das schon hydriert
+ * hätte, würde beim nächsten `set` mit seinem alten Stand darüberschreiben.
+ *
+ * Löst auf, sobald der Marker gesetzt ist — per Ereignis, oder sofort, wenn
+ * er beim Nachsehen schon da war (das Ereignis kann vor dem Hörer gefeuert
+ * sein, wenn der Nutzer den Assistenten schneller durchklickt, als dieses
+ * Fenster bootet). Ohne Stellvertreter-Fenster löst es sofort auf; das
+ * Hauptfenster zeichnet den Assistenten dann selbst (`AppShell.tsx`).
+ */
+export async function awaitOnboardingHandover(): Promise<void> {
+ if (hostWindow !== 'main') return
+ const { invoke } = await import('@tauri-apps/api/core')
+ const delegated = await invoke<boolean>('onboarding_window_open').catch(() => false)
+ if (!delegated) return
+ const { listen } = await import('@tauri-apps/api/event')
+ await new Promise<void>((resolve) => {
+ let settled = false
+ const settle = () => {
+ if (settled) return
+ settled = true
+ resolve()
+ }
+ listen(ONBOARDING_DONE_EVENT, settle)
+ .then(() => invoke<boolean>('is_onboarding_done'))
+ .then((done) => { if (done) settle() })
+ // Kein Hörer, keine Antwort: lieber die App booten als ewig warten —
+ // Rust zeigt das Hauptfenster nach HANDOVER_GRACE ohnehin von sich aus.
+ .catch(settle)
+ })
+}
diff --git a/src/lib/rust-boot-sync.ts b/src/lib/rust-boot-sync.ts
new file mode 100644
index 00000000..04b057e6
--- /dev/null
+++ b/src/lib/rust-boot-sync.ts
@@ -0,0 +1,47 @@
+/**
+ * Was ein Fenster beim Boot nach Rust drückt, damit der nächste Kindprozess
+ * und der nächste Download die gespeicherten Entscheidungen des Nutzers
+ * kennen.
+ *
+ * Bis zum eigenen Onboarding-Fenster stand das in `App.tsx`, und der
+ * Assistent lief unter `App` — also lief es auch für ihn. Jetzt bootet das
+ * Onboarding-Fenster OHNE `App` (`OnboardingWindow.tsx`, der kleinste Baum,
+ * der den Assistenten trägt), und beide Dinge braucht es trotzdem:
+ *
+ * - den HuggingFace-Token: der Starter-Download geht sonst anonym und
+ * gedrosselt hinaus (nach „Onboarding zurücksetzen" liegt einer im
+ * Schlüsselbund; auf einer frischen Installation ist der Weg ein No-op).
+ * - die GPU-Auswahl (Bug BB v2.5.0): der ComfyUI-Schritt spawnt einen
+ * Prozess, der sie lesen muss.
+ *
+ * Einmal geschrieben, zweimal gerufen — sonst hätte der Assistent im eigenen
+ * Fenster still weniger gekonnt als im Hauptfenster.
+ */
+import { useSettingsStore } from '../stores/settingsStore'
+
+export async function pushPersistedChoicesToRust(): Promise<void> {
+ const [{ invoke }, { isMlxImageHost, applyHfToken, HF_TOKEN_ACCOUNT }] = await Promise.all([
+ import('@tauri-apps/api/core'),
+ import('../api/mlx-image'),
+ ])
+
+ // Persisted GPU selection → AppState, so the next Ollama / ComfyUI spawn
+ // picks it up without the user having to open Settings first. Read
+ // synchronously off the store (already hydrated by zustand persist).
+ const s = useSettingsStore.getState().settings
+ const selection = {
+ vendor: s.gpuVendor || 'auto',
+ indices: s.gpuIndices || [],
+ }
+ invoke('set_gpu_selection', { selection }).catch(() => {})
+
+ // The keychain is the store of record for the HuggingFace token; Rust
+ // holds it in memory only, so every boot pushes it down again. Without
+ // this, only opening Settings would arm the token, and a model download
+ // started from Create, the Model Manager or the wizard would still go out
+ // anonymous and throttled.
+ if (!isMlxImageHost()) return
+ const { secretGet } = await import('../api/backend')
+ const stored = await secretGet(HF_TOKEN_ACCOUNT).catch(() => null)
+ if (stored) await applyHfToken(stored).catch(() => {})
+}
diff --git a/src/main.tsx b/src/main.tsx
index 7a48d594..1ee9dffc 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -1,6 +1,8 @@
import './index.css'
-import { StrictMode } from 'react'
+import { StrictMode, type ReactNode } from 'react'
import { createRoot } from 'react-dom/client'
+import { LucideProvider } from 'lucide-react'
+import { ICON_STROKE_PX } from './components/ui/icon-size'
import { mountFatalError } from './lib/fatal-error'
import { installMcpShutdown } from './api/mcp/shutdown'
@@ -22,11 +24,29 @@ installMcpShutdown()
// via dynamic import inside a catch so any boot throw renders an actionable
// recovery screen (which also force-shows the window) instead of a blank page.
// The Rust force-show timeout (main.rs setup) is the ultimate net.
-async function boot() {
- const [{ default: App }, { ErrorBoundary }] = await Promise.all([
- import('./App.tsx'),
- import('./components/ui/ErrorBoundary'),
- ])
+/**
+ * Welcher Baum in diesem Fenster steht. `index.html` lädt seit dem eigenen
+ * Onboarding-Fenster in zwei Webviews; die Antwort kommt aus dem Fensterlabel
+ * und steht einmal, in lib/host-window.ts.
+ */
+async function treeForThisWindow(): Promise<ReactNode> {
+ const { hostWindow, awaitOnboardingHandover } = await import('./lib/host-window')
+
+ // Das kleine Fenster bekommt den kleinsten Baum, der den Assistenten trägt
+ // (OnboardingWindow.tsx) — nicht App, nicht AppShell, keine Keychain-
+ // Hydration: nichts, das beim Schließen des Fensters mittendrin stürbe.
+ if (hostWindow === 'onboarding') {
+ const { OnboardingWindow } = await import('./components/onboarding/OnboardingWindow')
+ return <OnboardingWindow />
+ }
+
+ // Das Hauptfenster wartet, solange das Onboarding drüben läuft — und zwar
+ // VOR dem ersten Store-Import, damit es nachher frisch aus localStorage
+ // liest, was der Assistent geschrieben hat. Ohne Onboarding-Fenster löst
+ // das sofort auf.
+ await awaitOnboardingHandover()
+
+ const { default: App } = await import('./App.tsx')
// H5: load provider API keys from the OS keychain (Win/macOS) before the UI
// can issue a provider call, migrating any old localStorage key into the
// vault. Time-boxed so a wedged keychain can never block launch; no-op /
@@ -38,10 +58,40 @@ async function boot() {
new Promise((resolve) => setTimeout(resolve, 3000)),
])
} catch { /* keychain hydration is best-effort */ }
+ return <App />
+}
+
+async function boot() {
+ const [tree, { ErrorBoundary }] = await Promise.all([
+ treeForThisWindow(),
+ import('./components/ui/ErrorBoundary'),
+ ])
+ // Die optische Korrektur der Icon-Leiter, einmal fuer die ganze App — und
+ // seit den zwei Fenstern hier, ueber BEIDEN Baeumen, statt in AppShell.
+ //
+ // lucide skaliert seinen 24er-Strich mit der Groesse: `2 * size / 24`. Bei
+ // den 19 Groessen, die diese App setzt (siehe `ui/icon-size.ts`), heisst
+ // das 0,67px Strich bei size=8 und 1,67px bei size=20 — Faktor 2,5
+ // zwischen zwei Icons in derselben Zeile, und keiner der beiden Werte liegt
+ // auf einem Geraetepixel. `absoluteStrokeWidth` dreht die Rechnung um
+ // (`strokeWidth * 24 / size`) und haelt die GESEHENE Staerke konstant auf
+ // ICON_STROKE_PX = 1 CSS-Pixel: ein Geraetepixel bei 1x, zwei bei 2x.
+ //
+ // Warum hier und nicht an 668 Call-Sites: es ist dieselbe Entscheidung wie
+ // bei `.lu-control` und beim Fokusring — ein Rezept an der Wurzel, das die
+ // Call-Sites nichts dazuschreiben laesst. Und warum ueber der Verzweigung:
+ // sonst truege ausgerechnet der erste Bildschirm der App (der Assistent im
+ // kleinen Fenster) die Korrektur nicht.
+ //
+ // Kosten: keine. `useLucideContext()` ruft jedes lucide-Icon ohnehin schon
+ // auf, der Wert ist in `LucideProvider` memoisiert und haengt hier an zwei
+ // Konstanten — es gibt keinen Render, den es vorher nicht auch gab.
createRoot(rootEl).render(
<StrictMode>
<ErrorBoundary root>
- <App />
+ <LucideProvider absoluteStrokeWidth strokeWidth={ICON_STROKE_PX}>
+ {tree}
+ </LucideProvider>
</ErrorBoundary>
</StrictMode>,
)