The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(engine): ein misslungener Modellwechsel nimmt niemandem sein laufendes Modell weg
purple26623d2bfe4d
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rsindex ba9456cd..42dfc04e 100644--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@ -1237,9 +1237,91 @@ fn start_bundled_engine_blocking(}}+ // Was gerade bedient wird, damit ein misslungener Wechsel es+ // zurueckbringen kann. Ein Wechsel ist ein Halt UND ein Start, und bis+ // 2.6.8 war nur der Halt sicher: ein Klick auf eine kaputte GGUF beendete+ // die gesunde Engine 0,4 s spaeter, also bevor der erste Versuch mit der+ // neuen Datei ueberhaupt begann, und niemand holte sie zurueck. Wer ein+ // kaputtes Modell antippte, stand ohne Chat da (gemessen am 03.09.2026,+ // 21:11:48.611, Gegenprobe zu 29f22a1a).+ let vorher = {+ let guard = state.bundled_engine.lock().unwrap();+ guard.as_ref().map(|e| PreviousEngine {+ model_path: e.model_path.clone(),+ args: e.args.clone(),+ port: e.port,+ ctx: e.ctx,+ })+ };+// Different model (or dead) → stop the old process before spawning.stop_engine_locked(state);+ match start_after_stop(app, state, &model_path, &tuning, port, slot_dir.as_deref(), mmproj.as_deref())+ {+ Ok(v) => Ok(v),+ Err(msg) => Err(match (vorher, resolve_engine_binary(app)) {+ (Some(p), Some(bin)) if restore_engine(&bin, state, &p) => {+ format!("{msg}\n\n{RESTORED_NOTE}")+ }+ _ => msg,+ }),+ }+}++/// Die Engine, die vor einem Wechsel bediente.+struct PreviousEngine {+ model_path: String,+ args: Vec<String>,+ port: u16,+ ctx: Option<u32>,+}++/// Der Satz, der an die Fehlermeldung geht, wenn das alte Modell wieder laeuft.+/// Ohne ihn liest sich ein geglueckter Rueckfall wie ein Totalausfall, und der+/// Nutzer sucht nach etwas, das schon in Ordnung ist.+const RESTORED_NOTE: &str = "The model that was serving before is running again.";++/// Die vorherige Engine wieder starten, nachdem ein Wechsel gescheitert ist.+///+/// Der alte Prozess ist tot und laesst sich nicht zurueckholen, also wird er+/// aus genau dem argv neu gestartet, mit dem er lief. EIN Versuch, keine+/// Wiederholung: er bediente vor Sekunden noch, und ein zweiter Fehlschlag+/// hier waere nichts, woran ein Nutzer etwas aendern koennte. Er wuerde nur+/// die Fehlermeldung des eigentlichen Problems um Minuten verzoegern.+fn restore_engine(binary: &Path, state: &AppState, vorher: &PreviousEngine) -> bool {+ println!("[Engine] the switch failed, bringing back {}", vorher.model_path);+ let ok = spawn_engine_attempt(+ state,+ binary,+ &vorher.args,+ &vorher.model_path,+ vorher.port,+ vorher.ctx,+ )+ .is_ok();+ if !ok {+ println!("[Engine] could not bring back {}", vorher.model_path);+ }+ ok+}++/// Der Startweg ab dem Punkt, an dem die alte Engine bereits gestoppt ist.+///+/// Eigene Funktion, damit JEDER Fehlerausgang darin durch den Rueckfall oben+/// laeuft. Vorher standen hier vier `return Err(...)` im selben Rumpf wie der+/// Stopp, und ein Rueckfall haette an vier Stellen wiederholt werden muessen.+#[allow(clippy::too_many_arguments)]+fn start_after_stop(+ app: &AppHandle,+ state: &State<'_, AppState>,+ model_path: &str,+ tuning: &EngineTuning,+ port: u16,+ slot_dir: Option<&str>,+ mmproj: Option<&str>,+) -> Result<serde_json::Value, String> {+// The port must actually be FREE now: our own previous child (if any) was// killed AND reaped above, so anything still holding it is an orphaned or// foreign server, left over from a crashed or hard-killed session, or@@ -1334,11 +1416,11 @@ fn start_bundled_engine_blocking(println!("[Engine] port {preferred_port} is taken, the LU Engine moves to {port}");}let desired_args =- build_server_args(&model_path, &tuning, port, slot_dir.as_deref(), mmproj.as_deref());+ build_server_args(model_path, tuning, port, slot_dir, mmproj);- let deadline = health_timeout_for(&model_path);- let ctx = effective_ctx(&tuning);- let first = spawn_engine_attempt(state, &binary, &desired_args, &model_path, port, ctx);+ let deadline = health_timeout_for(model_path);+ let ctx = Some(effective_ctx(tuning));+ let first = spawn_engine_attempt(state, &binary, &desired_args, model_path, port, ctx);let failure = match first {Ok(()) => {println!("[Engine] LU Engine healthy on port {port}");@@ -1379,14 +1461,14 @@ fn start_bundled_engine_blocking(} else {println!("[Engine] the first attempt could not open port {port}, retrying on {retry_port}");build_server_args(- &model_path,- &tuning,+ model_path,+ tuning,retry_port,- slot_dir.as_deref(),- mmproj.as_deref(),+ slot_dir,+ mmproj,)};- match spawn_engine_attempt(state, &binary, &retry_args, &model_path, retry_port, ctx) {+ match spawn_engine_attempt(state, &binary, &retry_args, model_path, retry_port, ctx) {Ok(()) => {println!("[Engine] LU Engine healthy on port {retry_port} (second attempt)");Ok(serde_json::json!({@@ -1417,12 +1499,12 @@ pub(crate) struct StartFailure {/// child. Reaps the child on every failure path so no half-loaded server is/// left behind.fn spawn_engine_attempt(- state: &State<'_, AppState>,+ state: &AppState,binary: &Path,args: &[String],model_path: &str,port: u16,- ctx: u32,+ ctx: Option<u32>,) -> Result<(), StartFailure> {println!("[Engine] Starting LU Engine llama-server on port {port}, model {model_path}");let mut cmd = Command::new(binary);@@ -1468,7 +1550,7 @@ fn spawn_engine_attempt(child,model_path: model_path.to_string(),port,- ctx: Some(ctx),+ ctx,args: args.to_vec(),});@@ -2293,6 +2375,8 @@ pub(crate) fn stop_embed_locked(state: &AppState) -> bool {#[cfg(test)]mod tests {use super::*;+ use std::sync::atomic::{AtomicBool, Ordering};+ use std::sync::Arc;#[test]fn health_timeout_scales_with_model_size_and_caps() {@@ -3069,6 +3153,137 @@ mod tests {assert!(took < Duration::from_secs(5), "waited {took:?}, which is the old dead wait");}+ // ── Der Rueckfall nach einem misslungenen Wechsel ─────────────────────+ //+ // Gegenprobe zu 29f22a1a am 03.09.2026: ein Klick auf eine kaputte GGUF+ // beendete die laufende, gesunde Engine 0,4 s spaeter und liess den+ // Nutzer ohne Chat zurueck. Der Wechsel ist ein Halt und ein Start; nur+ // der Halt war sicher.++ /// Ein winziger Server, der auf `/health` mit 200 antwortet, bis der+ /// Schalter faellt. Damit ist der GESUNDE Ausgang von+ /// `spawn_engine_attempt` pruefbar, ohne eine echte llama-server-Binaerdatei:+ /// die Funktion fragt nur diesen einen Port.+ fn gesunder_port() -> (u16, Arc<AtomicBool>, std::thread::JoinHandle<()>) {+ use std::io::{Read, Write};+ let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");+ let port = listener.local_addr().unwrap().port();+ listener.set_nonblocking(true).unwrap();+ let stop = Arc::new(AtomicBool::new(false));+ let mein_stop = Arc::clone(&stop);+ let handle = std::thread::spawn(move || {+ while !mein_stop.load(Ordering::Relaxed) {+ match listener.accept() {+ Ok((mut sock, _)) => {+ let mut puffer = [0u8; 1024];+ let _ = sock.set_read_timeout(Some(Duration::from_millis(200)));+ let _ = sock.read(&mut puffer);+ let _ = sock.write_all(+ b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",+ );+ }+ Err(_) => std::thread::sleep(Duration::from_millis(20)),+ }+ }+ });+ (port, stop, handle)+ }++ #[test]+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]+ fn a_failed_switch_puts_the_previous_model_back_on_its_own_port() {+ let (port, stop, handle) = gesunder_port();+ let state = AppState::new();+ let vorher = PreviousEngine {+ model_path: "/tmp/hermes.gguf".into(),+ args: vec!["-c".into(), "sleep 30".into()],+ port,+ ctx: Some(8192),+ };++ let zurueck = restore_engine(+ Path::new(&crate::test_support::posix_shell()),+ &state,+ &vorher,+ );++ assert!(zurueck, "the previous engine did not come back");+ {+ let guard = state.bundled_engine.lock().unwrap();+ let e = guard.as_ref().expect("the slot is empty after a restore");+ // Genau das alte Modell, auf genau seinem Port, mit genau seinem+ // Kontext. Ein Rueckfall, der irgendetwas anderes startet, waere+ // schlimmer als keiner: der Nutzer chattet dann mit einem Modell,+ // das er nie gewaehlt hat.+ assert_eq!(e.model_path, "/tmp/hermes.gguf");+ assert_eq!(e.port, port);+ assert_eq!(e.ctx, Some(8192));+ assert_eq!(e.args, vorher.args);+ }++ stop.store(true, Ordering::Relaxed);+ let mut engine = state.bundled_engine.lock().unwrap().take().unwrap();+ let _ = engine.child.kill();+ let _ = engine.child.wait();+ let _ = handle.join();+ }++ #[test]+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]+ fn a_restore_that_fails_says_so_instead_of_claiming_success() {+ // Negativkontrolle. Ohne sie ginge der Fall oben auch auf einer+ // Funktion durch, die einfach immer `true` zurueckgibt, und die+ // Fehlermeldung verspraeche dem Nutzer ein Modell, das nicht laeuft.+ let state = AppState::new();+ let vorher = PreviousEngine {+ model_path: "/tmp/hermes.gguf".into(),+ args: vec!["-c".into(), "exit 1".into()],+ port: DEAD_PORT,+ ctx: Some(8192),+ };++ assert!(!restore_engine(+ Path::new(&crate::test_support::posix_shell()),+ &state,+ &vorher+ ));+ assert!(+ state.bundled_engine.lock().unwrap().is_none(),+ "a dead child was left in the slot, so the app would report it as running"+ );+ }++ #[test]+ fn every_failed_switch_runs_through_the_fallback() {+ // Quellanker: der Wechsel merkt sich die laufende Engine VOR dem Stopp+ // und hat genau EINEN Fehlerausgang, der den Rueckfall versucht. Vier+ // einzelne `return Err` im selben Rumpf waren der Grund, warum der+ // Rueckfall ueberhaupt fehlen konnte.+ let src = include_str!("engine.rs");+ let wechsel = src+ .split("fn start_bundled_engine_blocking(")+ .nth(1)+ .expect("the switch is gone")+ .split("\nfn ")+ .next()+ .unwrap();+ assert!(+ wechsel.contains("let vorher = {"),+ "the switch no longer remembers what was serving"+ );+ assert!(+ wechsel.contains("restore_engine("),+ "the switch no longer brings the previous engine back"+ );+ // Der Stopp steht VOR dem Start, sonst gaebe es nichts zu merken.+ let stopp = wechsel.find("stop_engine_locked(state);").expect("no stop");+ let merken = wechsel.find("let vorher = {").expect("no memory");+ assert!(merken < stopp, "the engine is stopped before it is remembered");+ // Und der Startweg danach ist EINE Funktion, nicht wieder ein Rumpf+ // mit eigenen Ausgaengen.+ assert!(wechsel.contains("start_after_stop("));+ }+#[test]fn an_empty_engine_slot_is_not_something_to_wait_for() {let state = AppState::new();diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rsindex 62bc0d35..e636fc9d 100644--- a/src-tauri/src/commands/shell.rs+++ b/src-tauri/src/commands/shell.rs@@ -68,6 +68,67 @@ pub(crate) fn drain(mut pipe: impl Read + Send + 'static) -> (Arc<Mutex<Captured(buf, done)}+/// Terminal-Steuerzeichen aus eingefangener Ausgabe entfernen.+///+/// Kindprozesse faerben ihre Ausgabe, wenn sie ein Terminal vermuten, und eine+/// Pipe reicht vielen dafuer aus: llama-server, pip und ComfyUI tun es alle.+/// Die Sequenzen kommen bis 2.6.8 ungefiltert im Fenster an und stehen dort+/// als Kaestchen mitten im Satz (gemessen am 03.09.2026 im Fehlerfeld der+/// Engine).+///+/// Entfernt wird, was ein Terminal steuert, nicht was es zeigt: CSI+/// (`ESC [ … Endbuchstabe`, also auch Farben und Cursorbewegungen), OSC+/// (`ESC ] … BEL` oder `ESC \`, wo Programme Fenstertitel setzen) und die+/// kurzen Zwei-Zeichen-Escapes. Text ohne ESC laeuft unveraendert durch, und+/// ein einzelnes ESC am Ende eines abgeschnittenen Puffers faellt weg statt+/// den Rest zu verschlucken.+///+/// Hier und nicht in der Fehlermeldung: JEDE eingefangene Ausgabe geht durch+/// diese Stelle, also auch die Installerprotokolle und die Agentenausgabe. Und+/// die Mustererkennung darueber (`stderr_blames_the_model` und ihre+/// Geschwister) liest denselben Text; ein Farbcode mitten im Wort hat dort+/// schon Treffer gekostet.+pub(crate) fn strip_ansi(roh: &str) -> String {+ if !roh.contains('\u{1b}') {+ return roh.to_string();+ }+ let mut aus = String::with_capacity(roh.len());+ let mut zeichen = roh.chars().peekable();+ while let Some(c) = zeichen.next() {+ if c != '\u{1b}' {+ aus.push(c);+ continue;+ }+ match zeichen.next() {+ // CSI: Parameter- und Zwischenbytes, dann ein Endbuchstabe 0x40..0x7E.+ Some('[') => {+ for z in zeichen.by_ref() {+ if ('\u{40}'..='\u{7e}').contains(&z) {+ break;+ }+ }+ }+ // OSC: laeuft bis BEL oder bis ESC \.+ Some(']') => {+ while let Some(z) = zeichen.next() {+ if z == '\u{7}' {+ break;+ }+ if z == '\u{1b}' {+ if zeichen.peek() == Some(&'\\') {+ zeichen.next();+ }+ break;+ }+ }+ }+ // Alles andere ist ein Zwei-Zeichen-Escape und ist damit erledigt.+ Some(_) | None => {}+ }+ }+ aus+}+/// Decode captured bytes leniently. Build tools on a non-UTF-8 Windows codepage/// emit bytes `read_to_string` rejects outright — that used to throw the whole/// output away and hand the model an empty string next to a successful exit code.@@ -76,7 +137,7 @@ pub(crate) fn captured_text(buf: &Arc<Mutex<Captured>>) -> String {Ok(c) => c,Err(poisoned) => poisoned.into_inner(),};- let mut text = String::from_utf8_lossy(&c.kept).into_owned();+ let mut text = strip_ansi(&String::from_utf8_lossy(&c.kept));if c.total > c.kept.len() {text.push_str(&format!("\n[output truncated: {} of {} bytes shown]",@@ -630,6 +691,17 @@ mod tests {assert!(text.ends_with('e'), "lost the tail: {:?}", text);}+ #[test]+ fn eingefangene_ausgabe_kommt_ohne_farbcodes_heraus() {+ // Die Verdrahtung, nicht der Filter: `strip_ansi` allein gruen zu+ // haben hiess bis hierher gar nichts, denn die Ausgabe lief an ihm+ // vorbei ins Fenster (gemessen am 03.09.2026 im Fehlerfeld der+ // Engine). Geprueft wird deshalb der Weg, den die echte Ausgabe nimmt.+ let text = capture(b"\x1b[0;33mwarn: \x1b[0mno kernel for this quant".to_vec());+ assert_eq!(text, "warn: no kernel for this quant");+ assert!(!text.contains('\u{1b}'), "an escape sequence reached the window: {text:?}");+ }+#[test]fn oversized_output_is_capped_and_says_so() {let text = capture(vec![b'x'; MAX_CAPTURE + 5_000]);@@ -747,3 +819,56 @@ mod tests {}}}++#[cfg(test)]+mod farbcode_tests {+ use super::strip_ansi;++ /// Genau die Zeile, die am 03.09.2026 im Fehlerfeld stand: llama-server+ /// faerbt seine Warnungen, und die Escape-Sequenzen kamen als Kaestchen+ /// mitten im Satz an.+ const ECHT: &str = "\u{1b}[0;33mwarn: \u{1b}[0mfailed to load model\u{1b}[0m";++ #[test]+ fn eine_gefaerbte_zeile_kommt_als_reiner_text_an() {+ assert_eq!(strip_ansi(ECHT), "warn: failed to load model");+ }++ #[test]+ fn text_ohne_steuerzeichen_bleibt_zeichen_fuer_zeichen_gleich() {+ // Negativkontrolle gegen einen Filter, der zu gierig ist. Umlaute,+ // Klammern und eckige Klammern stehen in Pfaden und in pip-Ausgaben.+ let roh = "C:\\Users\\Jörg\\models\\qwen[q4].gguf (3,2 GiB) 100%";+ assert_eq!(strip_ansi(roh), roh);+ }++ #[test]+ fn zeilenumbrueche_und_wagenruecklaeufe_ueberleben() {+ // Fortschrittsbalken schreiben \r. Wer den mitentfernt, klebt zwei+ // Zeilen zusammen und macht das Protokoll unlesbar.+ assert_eq!(strip_ansi("a\r\nb\n"), "a\r\nb\n");+ }++ #[test]+ fn ein_fenstertitel_verschluckt_nicht_den_rest_der_zeile() {+ // OSC endet mit BEL oder mit ESC-Backslash. Wer nur CSI kennt, laesst+ // den Titel als Text stehen; wer das Ende nicht kennt, frisst alles+ // danach.+ assert_eq!(strip_ansi("\u{1b}]0;Titel\u{7}fertig"), "fertig");+ assert_eq!(strip_ansi("\u{1b}]0;Titel\u{1b}\\fertig"), "fertig");+ }++ #[test]+ fn ein_abgeschnittener_puffer_verliert_nur_das_bruchstueck() {+ // Der Einfangpuffer hat eine Obergrenze und kann mitten in einer+ // Sequenz enden. Dann faellt das Bruchstueck weg, nicht der Text davor.+ assert_eq!(strip_ansi("fertig\u{1b}[0;3"), "fertig");+ assert_eq!(strip_ansi("fertig\u{1b}"), "fertig");+ }++ #[test]+ fn cursorbewegungen_gehen_mit_und_nicht_nur_farben() {+ // ComfyUI setzt den Cursor zurueck, um seinen Balken zu ueberschreiben.+ assert_eq!(strip_ansi("\u{1b}[2K\u{1b}[1Gnode 3/7"), "node 3/7");+ }+}diff --git a/src/api/lu-engine-switch.ts b/src/api/lu-engine-switch.tsindex cee9ebde..8a30527c 100644--- a/src/api/lu-engine-switch.ts+++ b/src/api/lu-engine-switch.ts@@ -23,7 +23,7 @@ import {slotHandbackUpdate, standbyOccupant,type HandoverSlot, type SlotOccupant,} from '../lib/openai-slot-handover'-import { isBuiltinEngineEntry, type InstalledModelLike } from '../lib/lmstudio-match'+import { isRowOfBackend, type InstalledModelLike } from '../lib/lmstudio-match'import { OpenAIProvider } from './providers/openai-provider'import type { ProviderModel } from './providers/types'import { PROVIDER_PRESETS } from './providers/types'@@ -164,7 +164,18 @@ export function chatProviderSwitchNote(name: string): string {* to list from a machine that may be offline, and "managed" is us.*/export function standbyChatBackend(): SlotOccupant | null {- const slot = useProviderStore.getState().providers.openai as HandoverSlot+ return standbyBackendOf(useProviderStore.getState().providers.openai as HandoverSlot)+}++/**+ * Dieselbe Frage an einen Steckplatz, den der Aufrufer schon hat.+ *+ * Der Waehler braucht die Antwort REAKTIV: die Gruppierung muss neu zeichnen,+ * sobald ein Klick den Steckplatz weiterreicht, und ein Blick in+ * `getState()` benachrichtigt niemanden. Deshalb steht die Regel hier, wo+ * beide Wege sie holen, statt ein zweites Mal im Bauteil.+ */+export function standbyBackendOf(slot: HandoverSlot): SlotOccupant | null {if (!(slot.enabled && slot.managed === true)) return nullconst waiting = standbyOccupant(slot)if (!waiting || !waiting.isLocal || waiting.managed) return null@@ -179,11 +190,7 @@ export function standbyChatBackend(): SlotOccupant | null {* and it is the same name the standby card carries.*/export function isStandbyBackendRow(row: InstalledModelLike | null | undefined): boolean {- if (!row || row.provider !== 'openai') return false- if (isBuiltinEngineEntry(row)) return false- const waiting = standbyChatBackend()- if (!waiting) return false- return (row.providerName || '').toLowerCase() === waiting.name.toLowerCase()+ return isRowOfBackend(row, standbyChatBackend()?.name)}/**diff --git a/src/components/models/ModelManager.tsx b/src/components/models/ModelManager.tsxindex f6ec5643..20c0df82 100644--- a/src/components/models/ModelManager.tsx+++ b/src/components/models/ModelManager.tsx@@ -21,7 +21,7 @@ import { MlxMediaSettings } from '../settings/MlxMediaSettings'import { backendCall } from '../../api/backend'import { customModelDirs } from '../../api/engine'import { counterView } from '../../lib/inventory-counter'-import { groupInstalledByProvider, needsLuEngineHeading } from '../../lib/lu-engine-rows'+import { groupInstalledByProvider, needsBackendSwitchHeading, LU_ENGINE_GROUP } from '../../lib/lu-engine-rows'import { isBuiltinEngineEntry } from '../../lib/lmstudio-match'import { LuEngineSwitchBar } from '../chat/LuEngineSwitchBar'import type { InstalledModelLike } from '../../lib/lmstudio-match'@@ -436,7 +436,7 @@ export function ModelManager() {// is an LU Engine group while another backend holds// the chat: then the heading is not decoration, it is// the warning that a click here moves the backend.- const showHeadings = needsLuEngineHeading(providerGroups.map((g) => g.label), luEngineHoldsChat)+ const showHeadings = needsBackendSwitchHeading(providerGroups.map((g) => g.label), luEngineHoldsChat ? null : LU_ENGINE_GROUP)let drawn = 0return providerGroups.map(({ label, models: rows }) => (<div key={label} className="space-y-1.5">diff --git a/src/components/models/ModelSelector.tsx b/src/components/models/ModelSelector.tsxindex 0ca2b89c..bc3626ff 100644--- a/src/components/models/ModelSelector.tsx+++ b/src/components/models/ModelSelector.tsx@@ -20,13 +20,14 @@ import { lmStudioSlotUpdate, adoptionReplacesBuiltinEngine } from '../../lib/lmsimport { nextProbeDelayMs } from '../../lib/probe-backoff'import { noChatBackendEnabled } from '../../lib/provider-visibility'import { cloudTeaserModels } from '../../lib/cloud-teaser-models'-import { splitLuEngineRows, needsLuEngineHeading, LU_ENGINE_GROUP } from '../../lib/lu-engine-rows'+import { splitBackendSwitchRows, needsBackendSwitchHeading } from '../../lib/lu-engine-rows'import { isBuiltinEngineEntry, type InstalledModelLike } from '../../lib/lmstudio-match'+import type { HandoverSlot } from '../../lib/openai-slot-handover'import {ensureLuEngineIsChatProvider, LU_ENGINE_SWITCH_NOTE, LU_ENGINE_SWAP_BUSY_NOTE,announceLuEngineSwapBusy, luEngineStartFailureNote,LM_STUDIO_LOAD_BUSY_NOTE, announceLmStudioLoadBusy,- handBackChatProviderForRow, chatProviderSwitchNote,+ handBackChatProviderForRow, chatProviderSwitchNote, standbyBackendOf,} from '../../api/lu-engine-switch'import { tryAcquireLuEngineSwap, releaseLuEngineSwap, luEngineSwapInFlight } from '../../api/lu-engine-swap-lock'import { useLuEngineSwitchStore } from '../../stores/luEngineSwitchStore'@@ -949,6 +950,9 @@ export function ModelSelector({ openUpward = false, surface = 'chat', answeredBy// Read reactively, not through isManagedBuiltinActive(): the grouping below// has to redraw the moment a pick hands the slot to the engine.const luEngineHoldsChat = useProviderStore((s) => s.providers.openai.enabled && s.providers.openai.managed === true)+ // Ebenfalls reaktiv, und aus demselben Grund: gibt ein Klick den Steckplatz+ // zurueck, verschwindet die Ueberschrift im selben Zug.+ const standbyName = useProviderStore((s) => standbyBackendOf(s.providers.openai as HandoverSlot)?.name ?? null)const activeModelObj = models.find((m) => m.name === activeModel)const activeDisplayName = activeModel? (activeModelObj && 'displayName' in activeModelObj && activeModelObj.displayName) ||@@ -969,24 +973,25 @@ export function ModelSelector({ openUpward = false, surface = 'chat', answeredBy? allTextModels.filter((m) => m.name === activeModel || canUseTools({ name: m.name, supportsTools: m.supportsTools })): allTextModelsconst hiddenForCode = allTextModels.length - textModels.length- // A14: while another backend holds the chat, the LU Engine rows are set- // apart under their own heading instead of blending into the family groups,- // because picking one of them moves the chat backend and a heading is the- // cheapest place to say that before the click. While the LU Engine IS the- // chat backend nothing is set apart and the picker groups by family exactly- // as it always has: there is no consequence to warn about then, and lineage- // is what people pick by.- const luEngineSplit = luEngineHoldsChat ? { luEngine: [], rest: textModels } : splitLuEngineRows(textModels)+ // A14: die Zeilen, deren Wahl das lokale Backend wechselt, stehen unter+ // ihrer eigenen Ueberschrift statt zwischen den Modellfamilien, denn ein+ // Klick darauf hat eine Folge und die Ueberschrift ist die billigste Stelle,+ // sie VOR dem Klick zu nennen. Welche Zeilen das sind, haengt daran, wer den+ // Steckplatz haelt: unsere GGUFs unter einem fremden Backend, die Zeilen des+ // wartenden Backends unter unserer eigenen Engine. Gibt es nichts zu+ // wechseln, gruppiert der Waehler nach Familie wie eh und je, denn dann gibt+ // es keine Folge zu melden und Abstammung ist, wonach Menschen waehlen.+ const wechsel = splitBackendSwitchRows(textModels, luEngineHoldsChat, standbyName)const groups: { family: string; models: AIModel[] }[] = [- ...(luEngineSplit.luEngine.length > 0- ? [{ family: LU_ENGINE_GROUP, models: luEngineSplit.luEngine }]+ ...(wechsel.switching.length > 0 && wechsel.label+ ? [{ family: wechsel.label, models: wechsel.switching }]: []),- ...groupByFamily(luEngineSplit.rest),+ ...groupByFamily(wechsel.rest),]// The one rule, asked rather than copied (second review): one group normally- // draws no heading, except an LU Engine group under a foreign chat backend,- // where the heading is the warning that picking from it moves the backend.- const showHeadings = needsLuEngineHeading(groups.map((g) => g.family), luEngineHoldsChat)+ // draws no heading, except the switch group, where the heading is the+ // warning that picking from it moves the backend.+ const showHeadings = needsBackendSwitchHeading(groups.map((g) => g.family), wechsel.label)const hasOllamaModels = textModels.some(m => ('provider' in m && m.provider === 'ollama') || !('provider' in m))textModelsEmptyRef.current = textModels.length === 0diff --git a/src/hooks/__tests__/installed-card-click-switches-the-backend.test.ts b/src/hooks/__tests__/installed-card-click-switches-the-backend.test.tsindex 9cc29fa2..9100bf19 100644--- a/src/hooks/__tests__/installed-card-click-switches-the-backend.test.ts+++ b/src/hooks/__tests__/installed-card-click-switches-the-backend.test.ts@@ -197,6 +197,32 @@ describe('when the engine does not come up for the card that was clicked', () =>expect(useProviderStore.getState().providers.openai.managed).toBe(true)})+ // Gegenprobe zu 29f22a1a, 03.09.2026, Befund 2: nach dem Fehlschlag stand+ // die Kachel des kaputten Modells auf ACTIVE und verlor ihren Use-Knopf,+ // waehrend auf dem Port kein Prozess lag. Die Auswahl wird vor dem Start+ // gesetzt, damit die Kachel sofort reagiert, also muss sie bei einem+ // Fehlschlag auch wieder zurueck.+ it('laesst die Kachel des Modells nicht auf ACTIVE stehen', async () => {+ activateBuiltinModel.mockRejectedValue(new Error('llama-server exited'))+ await clickCard(GGUF)+ expect(useModelStore.getState().activeModel).toBe(OLLAMA)+ })++ it('und auch nicht, wenn die Datei gar nicht mehr da ist', async () => {+ activateBuiltinModel.mockResolvedValue(false)+ await clickCard(GGUF)+ expect(useModelStore.getState().activeModel).toBe(OLLAMA)+ })++ // NEGATIVKONTROLLE: ein geglueckter Start laesst die Auswahl stehen. Ohne+ // diesen Fall ginge der obige auch auf einer Fassung durch, die die Auswahl+ // grundsaetzlich zurueckdreht.+ it('ein geglueckter Start behaelt das gewaehlte Modell', async () => {+ activateBuiltinModel.mockResolvedValue(true)+ await clickCard(GGUF)+ expect(useModelStore.getState().activeModel).toBe(GGUF)+ })+it('treats a false answer as a failure too, and says which file is gone', async () => {// activateBuiltinModel answers false when it cannot resolve the GGUF path,// even after refreshing the list once. Nothing was started.diff --git a/src/hooks/useModels.ts b/src/hooks/useModels.tsindex 4b381d58..a37891ee 100644--- a/src/hooks/useModels.ts+++ b/src/hooks/useModels.ts@@ -593,6 +593,14 @@ export function useModels() {switched = ensureLuEngineIsChatProvider()if (switched) useLuEngineSwitchStore.getState().announce(LU_ENGINE_SWITCH_NOTE)}+ // Was vorher bediente. Die Auswahl wird gesetzt, BEVOR die Engine laeuft,+ // damit die Kachel sofort reagiert; scheitert der Start, muss sie wieder+ // zurueck. Ohne das stand die Kachel eines kaputten Modells auf ACTIVE,+ // verlor ihren Use-Knopf und auf dem Port lag nichts (Gegenprobe zu+ // 29f22a1a am 03.09.2026, Befund 2). Die Rust-Seite holt im selben Fall+ // die vorherige Engine zurueck, also ist genau dieses Modell auch das,+ // was danach wirklich wieder bedient.+ const vorherAktiv = useModelStore.getState().activeModelsetActiveModel(name)const cfg = useProviderStore.getState().providers.openaiif (cfg.enabled && cfg.managed && getProviderIdFromModel(name) === 'openai') {@@ -603,6 +611,7 @@ export function useModels() {// tail Rust appends; the card says the same sentence now, from the same// helper, in the status row that is drawn right above the list.const sayItFailed = (reason: unknown) => {+ if (vorherAktiv !== name) setActiveModel(vorherAktiv)const line = luEngineStartFailureNote(name, reason)useLuEngineSwitchStore.getState().announce(switched ? `${LU_ENGINE_SWITCH_NOTE} ${line}` : line, 'error')diff --git a/src/lib/__tests__/lu-engine-groups.test.ts b/src/lib/__tests__/lu-engine-groups.test.tsindex 4a032ce9..f8464040 100644--- a/src/lib/__tests__/lu-engine-groups.test.ts+++ b/src/lib/__tests__/lu-engine-groups.test.ts@@ -11,22 +11,26 @@* Run: npx vitest run src/lib/__tests__/lu-engine-groups.test.ts*/import { describe, it, expect } from 'vitest'-import { splitLuEngineRows, groupInstalledByProvider, dropDuplicateLuEngineRows, needsLuEngineHeading, LU_ENGINE_GROUP } from '../lu-engine-rows'+import { splitBackendSwitchRows, groupInstalledByProvider, dropDuplicateLuEngineRows, needsBackendSwitchHeading, LU_ENGINE_GROUP } from '../lu-engine-rows'const lu = (n: string) => ({ name: `openai::${n}`, model: n, provider: 'openai', providerName: 'LU Engine' })const luOld = (n: string) => ({ name: `openai::${n}`, model: n, provider: 'openai', providerName: 'Built-in Engine' })const lms = (n: string) => ({ name: `openai::${n}`, model: n, provider: 'openai', providerName: 'LM Studio' })const ollama = (n: string) => ({ name: n, model: n, provider: 'ollama', providerName: 'Ollama' })-describe('splitLuEngineRows', () => {+describe('splitBackendSwitchRows, ein fremdes Backend bedient den Chat', () => {+ const teilen = <T extends { model: string; provider: string; providerName: string }>(rows: T[]) =>+ splitBackendSwitchRows(rows, false, 'LM Studio')+it('separates the engine rows from everything else, order untouched', () => {- const { luEngine, rest } = splitLuEngineRows([ollama('a'), lu('b'), lms('c'), lu('d')])- expect(luEngine.map((m) => m.model)).toEqual(['b', 'd'])+ const { label, switching, rest } = teilen([ollama('a'), lu('b'), lms('c'), lu('d')])+ expect(label).toBe(LU_ENGINE_GROUP)+ expect(switching.map((m) => m.model)).toEqual(['b', 'd'])expect(rest.map((m) => m.model)).toEqual(['a', 'c'])})it('a row recorded under the old name belongs to the same group', () => {- expect(splitLuEngineRows([luOld('b')]).luEngine.length).toBe(1)+ expect(teilen([luOld('b')]).switching.length).toBe(1)})// NEGATIVE CONTROL: LM Studio shares provider id 'openai' with the engine.@@ -34,7 +38,48 @@ describe('splitLuEngineRows', () => {// LU Engine group and offer to switch the backend for models that are// already running on the one in front.it('never takes an LM Studio row along', () => {- expect(splitLuEngineRows([lms('c')]).luEngine).toEqual([])+ expect(teilen([lms('c')]).switching).toEqual([])+ })+})++// ── Persona 2, Punkt 9 (03.09.2026): der Weg zurueck hatte keine Ueberschrift ──+//+// Versprochen war „a running LM Studio stays in the model picker after the+// chat has moved to the LU Engine. Its models keep their own heading in the+// list". Im Waehler standen sie zwischen Qwen und Hermes, ohne ein Wort+// darueber, dass ein Klick den Steckplatz zurueckgibt.+describe('splitBackendSwitchRows, die LU Engine bedient den Chat', () => {+ const teilen = <T extends { model: string; provider: string; providerName: string }>(rows: T[]) =>+ splitBackendSwitchRows(rows, true, 'LM Studio')++ it('setzt die Zeilen des wartenden Backends unter dessen eigenen Namen ab', () => {+ const { label, switching, rest } = teilen([ollama('a'), lu('b'), lms('c'), lms('e')])+ expect(label).toBe('LM Studio')+ expect(switching.map((m) => m.model)).toEqual(['c', 'e'])+ expect(rest.map((m) => m.model)).toEqual(['a', 'b'])+ })++ // NEGATIVKONTROLLE: unsere eigenen Zeilen sind jetzt die laufenden. Sie+ // abzusetzen hiesse, vor einem Wechsel zu warnen, den es nicht gibt.+ it('nimmt die eigene Engine nie mit', () => {+ expect(teilen([lu('b'), luOld('x')]).switching).toEqual([])+ })++ // NEGATIVKONTROLLE: wartet niemand, gibt es nichts abzusetzen und der+ // Waehler gruppiert nach Familie wie eh und je.+ it('ohne wartendes Backend bleibt alles beim Rest', () => {+ const { label, switching, rest } = splitBackendSwitchRows([lms('c'), lu('b')], true, null)+ expect(label).toBeNull()+ expect(switching).toEqual([])+ expect(rest.length).toBe(2)+ })++ // Ein drittes lokales Backend, das gerade NICHT wartet, wird nicht+ // mitgenommen: der Name entscheidet, nicht die Protokoll-Familie.+ it('trennt zwei OpenAI-Backends an ihrem Namen', () => {+ const jan = { name: 'openai::x', model: 'x', provider: 'openai', providerName: 'Jan' }+ const { switching } = splitBackendSwitchRows([lms('c'), jan], true, 'LM Studio')+ expect(switching.map((m) => m.model)).toEqual(['c'])})})@@ -194,7 +239,7 @@ describe('de-duplication asks about the FILE, never about the model', () => {// ── A14 review 7: the heading is the warning, so it cannot be optional ──────-describe('when the LU Engine heading has to be drawn', () => {+describe('when the switch heading has to be drawn', () => {const labels = <T extends { label: string }>(g: T[]) => g.map((x) => x.label)const luGroup = labels(groupInstalledByProvider([lu('a')]))const ollamaGroup = labels(groupInstalledByProvider([ollama('a')]))@@ -204,29 +249,36 @@ describe('when the LU Engine heading has to be drawn', () => {// Engine folder, with Ollama or LM Studio in front, got one unlabelled list// and a click that moved his chat backend without a word of warning.it('one LU Engine group under a foreign backend still gets its heading', () => {- expect(needsLuEngineHeading(luGroup, false)).toBe(true)+ expect(needsBackendSwitchHeading(luGroup, LU_ENGINE_GROUP)).toBe(true)})it('and so does a list with more than one backend in it, either way round', () => {- expect(needsLuEngineHeading(both, false)).toBe(true)- expect(needsLuEngineHeading(both, true)).toBe(true)+ expect(needsBackendSwitchHeading(both, LU_ENGINE_GROUP)).toBe(true)+ expect(needsBackendSwitchHeading(both, null)).toBe(true)+ })++ // Und dieselbe Regel andersherum: eine einzige LM-Studio-Gruppe unter+ // unserer eigenen Engine traegt ihre Ueberschrift, weil der Klick darauf+ // den Steckplatz zurueckgibt.+ it('eine einzelne Gruppe des wartenden Backends bekommt sie ebenso', () => {+ expect(needsBackendSwitchHeading(['LM Studio'], 'LM Studio')).toBe(true)})// NEGATIVE CONTROL: a plain Ollama box looks exactly as it did before. A// heading over the only list there names nothing the user did not know.it('a single foreign group draws none', () => {- expect(needsLuEngineHeading(ollamaGroup, false)).toBe(false)- expect(needsLuEngineHeading(ollamaGroup, true)).toBe(false)+ expect(needsBackendSwitchHeading(ollamaGroup, LU_ENGINE_GROUP)).toBe(false)+ expect(needsBackendSwitchHeading(ollamaGroup, null)).toBe(false)})// NEGATIVE CONTROL: with the LU Engine itself in front there is no switch to// warn about, so its own single group needs no heading either.it('and neither does the LU Engine when it is already the chat backend', () => {- expect(needsLuEngineHeading(luGroup, true)).toBe(false)+ expect(needsBackendSwitchHeading(luGroup, null)).toBe(false)})it('an empty list needs nothing', () => {- expect(needsLuEngineHeading([], false)).toBe(false)+ expect(needsBackendSwitchHeading([], LU_ENGINE_GROUP)).toBe(false)})})@@ -247,12 +299,12 @@ describe('the Installed list and the picker ask the same rule', () => {it('the composer picker calls it instead of counting groups itself', async () => {const src = await read('../../components/models/ModelSelector.tsx')- expect(src).toContain('needsLuEngineHeading(groups.map((g) => g.family), luEngineHoldsChat)')+ expect(src).toContain('needsBackendSwitchHeading(groups.map((g) => g.family), wechsel.label)')expect(src).not.toMatch(/family === LU_ENGINE_GROUP\)\) &&/)})it('and so does the Installed list', async () => {const src = await read('../../components/models/ModelManager.tsx')- expect(src).toContain('needsLuEngineHeading(providerGroups.map((g) => g.label), luEngineHoldsChat)')+ expect(src).toContain('needsBackendSwitchHeading(providerGroups.map((g) => g.label), luEngineHoldsChat ? null : LU_ENGINE_GROUP)')})})diff --git a/src/lib/lmstudio-match.ts b/src/lib/lmstudio-match.tsindex 0bb13919..73b41f4b 100644--- a/src/lib/lmstudio-match.ts+++ b/src/lib/lmstudio-match.ts@@ -72,6 +72,25 @@ export function isLmStudioEntry(m: InstalledModelLike): boolean {return pname.includes('lm studio') || pname.includes('lmstudio')}+/**+ * Gehoert diese Zeile dem lokalen Backend namens `name`.+ *+ * Jedes Backend, das das OpenAI-Protokoll spricht, traegt `provider: 'openai'`+ * — das ist der eine Steckplatz, den sie sich teilen. Auseinander halten kann+ * sie nur der Anzeigename, und der ist derselbe, den die Karte in den+ * Einstellungen zeigt. Unsere eigene Engine ist nie gemeint: sie hat ihre+ * eigene Erkennung eine Zeile weiter unten, und wer sie hier mitzaehlt, haelt+ * das Laufende fuer das Wartende.+ */+export function isRowOfBackend(+ m: InstalledModelLike | null | undefined,+ name: string | null | undefined,+): boolean {+ if (!m || !name || m.provider !== 'openai') return false+ if (isBuiltinEngineEntry(m)) return false+ return (m.providerName || '').toLowerCase() === name.toLowerCase()+}+/*** An LU Engine entry. `bundledToAIModels` stamps every downloaded GGUF with* `provider: 'openai'` and `providerName: 'LU Engine'` ('Built-in Engine'diff --git a/src/lib/lu-engine-rows.ts b/src/lib/lu-engine-rows.tsindex e6852ec4..87f27229 100644--- a/src/lib/lu-engine-rows.ts+++ b/src/lib/lu-engine-rows.ts@@ -21,8 +21,8 @@*/import {- isSameGgufFile, isLmStudioEntry, isBuiltinEngineEntry, modelIdentity, extractQuant,- type InstalledModelLike,+ isSameGgufFile, isLmStudioEntry, isBuiltinEngineEntry, isRowOfBackend, modelIdentity,+ extractQuant, type InstalledModelLike,} from './lmstudio-match'/** The heading LU Engine rows sit under, in Installed and in the picker. */@@ -263,16 +263,42 @@ function sameFile(}/**- * The LU Engine rows and everything else, kept apart.+ * Die Zeilen, deren Wahl das lokale Chat-Backend WECHSELT, und der Rest.*- * Order within each half is left exactly as it came in: the list is built in a- * deliberate order upstream and this is a split, not a sort.+ * Es ist immer genau eine Sorte, und welche, haengt daran, wer den Steckplatz+ * gerade haelt:+ *+ * - Ein fremdes Backend bedient den Chat: dann sind es unsere eigenen+ * GGUF-Zeilen. Ein Klick darauf holt den Chat zur LU Engine.+ * - Die LU Engine bedient den Chat: dann sind es die Zeilen des Backends, das+ * daneben wartet. Ein Klick darauf gibt ihm den Steckplatz zurueck.+ *+ * Bis 2.6.8 stand hier nur die erste Haelfte, und die zweite fehlte still: die+ * Release-Notiz versprach „a running LM Studio ... its models keep their own+ * heading in the list", die Kommentare in api/lu-engine-switch.ts beschrieben+ * denselben Weg zurueck, und im Waehler standen die LM-Studio-Zeilen ohne+ * Ueberschrift zwischen den Modellfamilien (Persona 2 am 03.09.2026, Punkt 9).+ * Die Ueberschrift ist keine Zierde, sie ist die Warnung vor der Folge, und+ * die Folge gibt es in beide Richtungen.+ *+ * `standbyName` ist der Anzeigename des wartenden Backends oder null. Die+ * Reihenfolge innerhalb beider Haelften bleibt, wie sie ankam: das ist eine+ * Teilung, keine Sortierung.*/-export function splitLuEngineRows<T extends InstalledModelLike>(models: T[]): { luEngine: T[]; rest: T[] } {- const luEngine: T[] = []+export function splitBackendSwitchRows<T extends InstalledModelLike>(+ models: T[],+ luEngineHoldsChat: boolean,+ standbyName: string | null,+): { label: string | null; switching: T[]; rest: T[] } {+ const label = luEngineHoldsChat ? standbyName : LU_ENGINE_GROUP+ const gehoertDazu = luEngineHoldsChat+ ? (m: T) => isRowOfBackend(m, standbyName)+ : (m: T) => isBuiltinEngineEntry(m)+ if (!label) return { label: null, switching: [], rest: models }+ const switching: T[] = []const rest: T[] = []- for (const m of models) (isBuiltinEngineEntry(m) ? luEngine : rest).push(m)- return { luEngine, rest }+ for (const m of models) (gehoertDazu(m) ? switching : rest).push(m)+ return { label, switching, rest }}/** One heading and the rows under it. */@@ -282,7 +308,9 @@ export interface ProviderGroup<T> {}/**- * Must the LU Engine heading be drawn even though there is only one group.+ * Muss die Wechsel-Ueberschrift gezeichnet werden, obwohl es nur eine Gruppe+ * gibt. `switchLabel` ist die Ueberschrift der Zeilen, deren Wahl das Backend+ * wechselt, oder null, wenn es solche Zeilen gerade nicht gibt.** A14 review 7: the render dropped every heading at one group, which is right* for a plain Ollama box and wrong for the exact machine this whole change is@@ -294,9 +322,9 @@ export interface ProviderGroup<T> {* of warning. The heading is the warning, so it is drawn whenever a foreign* backend holds the chat, group count be damned.*/-export function needsLuEngineHeading(labels: string[], luEngineHoldsChat: boolean): boolean {+export function needsBackendSwitchHeading(labels: string[], switchLabel: string | null): boolean {if (labels.length > 1) return true- return !luEngineHoldsChat && labels.includes(LU_ENGINE_GROUP)+ return switchLabel !== null && labels.includes(switchLabel)}/**