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): the built-in engine starts, and a dead one says why
purple31d96f8e6eec
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rsindex 110325f0..9c7fa780 100644--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@ -297,15 +297,67 @@ fn split_shard_stem(stem: &str) -> Option<(&str, u32, u32)> {/// installed model (same rule a9ea114 established for MLX downloads).pub(crate) fn scan_gguf_models(dir: &Path) -> Vec<BundledModel> {let mut out = Vec::new();- // (base, total) → (part-numbers seen, path of part 1, byte sum)- let mut sets: std::collections::HashMap<(String, u32), (Vec<u32>, Option<String>, u64)> =+ // (dir, base, total) → (part-numbers seen, path of part 1, byte sum).+ // The directory is part of the key: two unrelated split sets that share a+ // base name in different subfolders must never merge into one entry.+ let mut sets: std::collections::HashMap<(PathBuf, String, u32), (Vec<u32>, Option<String>, u64)> =std::collections::HashMap::new();+ scan_gguf_dir(dir, 0, &mut out, &mut sets);+ for ((_dir, base, total), (mut parts, first_path, size)) in sets {+ parts.sort_unstable();+ parts.dedup();+ let complete = parts.len() as u32 == total && parts.first() == Some(&1);+ if let (true, Some(path)) = (complete, first_path) {+ out.push(BundledModel {+ name: base,+ path,+ size,+ });+ }+ }+ // A name is the picker id, so it has to be unique. The shallowest copy+ // wins (the flat app dir is the canonical place); ties fall to the path.+ out.sort_by(|a, b| {+ let depth = |p: &str| p.matches(['/', '\\']).count();+ a.name+ .cmp(&b.name)+ .then(depth(&a.path).cmp(&depth(&b.path)))+ .then(a.path.cmp(&b.path))+ });+ out.dedup_by(|a, b| a.name == b.name);+ out+}++/// How far below the app models dir the scan walks. 0 alone was the shipped+/// behaviour and it is still where every model the app writes today lands.+///+/// GH #118 (nayffy, 2026-08-27): before the download-routing fix, a chat model+/// installed on a fresh box was written to `<models>/<user>/<repo>/x.gguf`,+/// the LM Studio layout. The routing is fixed, but the boxes that already ran+/// the broken build have multi-gigabyte files sitting in those folders. Two+/// levels reach them, so those installs heal on the next model refresh instead+/// of asking the user to download everything a second time. Deeper than that+/// buys nothing and only costs directory reads.+const MAX_SCAN_DEPTH: usize = 2;++fn scan_gguf_dir(+ dir: &Path,+ depth: usize,+ out: &mut Vec<BundledModel>,+ sets: &mut std::collections::HashMap<(PathBuf, String, u32), (Vec<u32>, Option<String>, u64)>,+) {let entries = match std::fs::read_dir(dir) {Ok(e) => e,- Err(_) => return out,+ Err(_) => return,};for entry in entries.flatten() {let path = entry.path();+ if path.is_dir() {+ if depth < MAX_SCAN_DEPTH {+ scan_gguf_dir(&path, depth + 1, out, sets);+ }+ continue;+ }if !path.is_file() {continue;}@@ -338,8 +390,9 @@ pub(crate) fn scan_gguf_models(dir: &Path) -> Vec<BundledModel> {}let size = entry.metadata().map(|m| m.len()).unwrap_or(0);if let Some((base, part, total)) = split_shard_stem(&name) {+ let parent = path.parent().map(Path::to_path_buf).unwrap_or_default();let slot = sets- .entry((base.to_string(), total))+ .entry((parent, base.to_string(), total)).or_insert((Vec::new(), None, 0));slot.0.push(part);if part == 1 {@@ -354,20 +407,6 @@ pub(crate) fn scan_gguf_models(dir: &Path) -> Vec<BundledModel> {size,});}- for ((base, total), (mut parts, first_path, size)) in sets {- parts.sort_unstable();- parts.dedup();- let complete = parts.len() as u32 == total && parts.first() == Some(&1);- if let (true, Some(path)) = (complete, first_path) {- out.push(BundledModel {- name: base,- path,- size,- });- }- }- out.sort_by(|a, b| a.name.cmp(&b.name));- out}/// App-owned models directory for the built-in engine:@@ -554,6 +593,117 @@ fn wait_for_health(port: u16, timeout: Duration) -> Result<(), String> {))}+/// How a health wait ended.+#[derive(Debug, PartialEq)]+enum HealthWait {+ Ready,+ /// The child we spawned is gone. Nothing more will happen on that port.+ ChildExited,+ TimedOut,+}++/// Block until `/health` returns 200, the child exits, or the budget runs out.+///+/// The child half is the GH #118 half: `wait_for_health` watched only the+/// port, so an engine that died on a missing runtime library or a GPU backend+/// it could not initialise still left the user staring at a spinner for the+/// full budget (60 s, and up to 10 minutes on a big GGUF) before any message+/// appeared. The process is ours, its exit is knowable in milliseconds, so it+/// is checked on the same 300 ms tick as the port.+fn wait_for_health_or_exit(state: &AppState, port: u16, timeout: Duration) -> HealthWait {+ let deadline = Instant::now() + timeout;+ while Instant::now() < deadline {+ if engine_healthy(port) {+ return HealthWait::Ready;+ }+ let gone = {+ let mut guard = state.bundled_engine.lock().unwrap();+ match guard.as_mut() {+ Some(e) => e.child.try_wait().ok().flatten().is_some(),+ None => true,+ }+ };+ if gone {+ // One last look: a server can bind, answer, and the process can+ // still be reaped between the two checks on a fast load.+ return if engine_healthy(port) { HealthWait::Ready } else { HealthWait::ChildExited };+ }+ std::thread::sleep(Duration::from_millis(300));+ }+ HealthWait::TimedOut+}++/// Markers in llama-server's stderr that point at the GPU rather than at the+/// model file or the app. Lower-cased input.+fn stderr_blames_the_gpu(stderr: &str) -> bool {+ const MARKERS: &[&str] = &[+ "cuda",+ "no kernel image",+ "hip",+ "rocm",+ "vulkan",+ "out of memory",+ "cublas",+ "device memory",+ "ggml_backend_alloc",+ "failed to allocate",+ "compute capability",+ ];+ let lower = stderr.to_ascii_lowercase();+ MARKERS.iter().any(|m| lower.contains(m))+}++/// Markers that point at the model file itself.+fn stderr_blames_the_model(stderr: &str) -> bool {+ const MARKERS: &[&str] = &[+ "unknown model architecture",+ "failed to load model",+ "invalid magic",+ "unsupported model",+ "wrong number of tensors",+ "tensor .* not found",+ "gguf_init_from_file",+ ];+ let lower = stderr.to_ascii_lowercase();+ MARKERS.iter().any(|m| lower.contains(m))+}++/// One English sentence a user can act on, plus llama-server's own last words+/// so a bug report still carries them.+///+/// GH #118: "did not become healthy" named no cause, and the fresh-install+/// case named nothing at all because no start was ever attempted. The GPU+/// hint matters most on new cards: a Blackwell RTX 50-series board with a+/// driver or engine build that does not know it fails at load time, and+/// setting GPU Layers to 0 is the one setting in this app that gets the user+/// chatting anyway.+pub(crate) fn start_failure_message(failure: &StartFailure, port: u16, budget: Duration) -> String {+ let head = if failure.port_taken {+ format!(+ "Port {port} answers health checks, but the engine this app just started exited immediately. Another llama-server (likely left over from a previous session or crash) is occupying the port. Quit that process or reboot, then try again."+ )+ } else if failure.died {+ let hint = if stderr_blames_the_gpu(&failure.stderr) {+ " This looks like a graphics-card problem. Open Settings, Built-in Engine and set GPU Layers to 0 to run on the CPU, then try again."+ } else if stderr_blames_the_model(&failure.stderr) {+ " The engine refused the model file. Open Models, Discover and install a different quant."+ } else {+ " Reinstall Locally Uncensored if this keeps happening, or pick a different backend in Settings, AI Backends."+ };+ format!("The built-in engine started and exited again before it could serve on port {port}. It was tried twice.{hint}")+ } else {+ format!(+ "The built-in engine did not become healthy on port {port} within {}s (the budget scales with model size, and huge GGUFs can take minutes on a cold first load).",+ budget.as_secs()+ )+ };+ if failure.stderr.is_empty() {+ head+ } else {+ format!("{head}\n\n{}", failure.stderr)+ }+}+// ── Commands ─────────────────────────────────────────────────────────────────/// Start (or reuse) the managed chat engine for `model_path`. Idempotent: if@@ -665,15 +815,93 @@ fn start_bundled_engine_blocking(}let binary = resolve_engine_binary(app).ok_or_else(|| {+ // This used to name a build script. On a user's machine that is not an+ // instruction, it is noise; the only real remedies are a reinstall or a+ // different backend (GH #118).format!(- "Bundled engine binary not found ({}). Run scripts/build-llama.sh to produce the sidecar.",+ "The built-in engine program ({}) is missing from this installation. Reinstall Locally Uncensored, or pick a different backend in Settings, AI Backends.",sidecar_binary_name())})?;+ // Attempt 1, then exactly one clean retry.+ //+ // GH #118 (nayffy, 2026-08-27): the only thing a user ever saw when this+ // chain failed was a refused connection on 127.0.0.1:8127. Two things were+ // wrong with the old shape. The health wait watched only the port, so a+ // child that died in the first second still burned the whole budget (60 s+ // and up, scaled by model size) before saying anything. And a start was+ // one shot: the VRAM this very function asks ComfyUI and Ollama to release+ // is released ASYNCHRONOUSLY, so an engine that lost the race to a driver+ // still holding those pages had no second chance. House rule is+ // self-healing before an error message, so a died-on-start attempt gets+ // one more try after a short settle, and only what survives that becomes a+ // message.+ 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 failure = match first {+ Ok(()) => {+ println!("[Engine] Built-in engine healthy on port {port}");+ return Ok(serde_json::json!({+ "status": "started",+ "port": port,+ "model_path": model_path,+ "ctx": ctx,+ }));+ }+ Err(f) => f,+ };++ if !failure.died {+ // The budget ran out with the child still alive: it is loading slowly,+ // not failing. Retrying would just spend the budget twice.+ return Err(start_failure_message(&failure, port, deadline));+ }++ println!("[Engine] first start attempt exited immediately, retrying once");+ std::thread::sleep(Duration::from_millis(1500));+ match spawn_engine_attempt(state, &binary, &desired_args, &model_path, port, ctx) {+ Ok(()) => {+ println!("[Engine] Built-in engine healthy on port {port} (second attempt)");+ Ok(serde_json::json!({+ "status": "started",+ "port": port,+ "model_path": model_path,+ "ctx": ctx,+ "retried": true,+ }))+ }+ Err(second) => Err(start_failure_message(&second, port, deadline)),+ }+}++/// What one spawn-and-wait produced when it did not come up.+pub(crate) struct StartFailure {+ /// The child was gone before the health budget ran out. Distinguishes a+ /// crash (retry is worth it) from a slow load (retry is not).+ pub died: bool,+ /// True when the port answered health checks but our own child was dead.+ /// Somebody else owns that port.+ pub port_taken: bool,+ /// llama-server's own last words. Empty when it said nothing.+ pub stderr: String,+}++/// Spawn the engine and wait for it, watching BOTH the health endpoint and the+/// child. Reaps the child on every failure path so no half-loaded server is+/// left behind.+fn spawn_engine_attempt(+ state: &State<'_, AppState>,+ binary: &Path,+ args: &[String],+ model_path: &str,+ port: u16,+ ctx: u32,+) -> Result<(), StartFailure> {println!("[Engine] Starting built-in llama-server on port {port} — {model_path}");- let mut cmd = Command::new(&binary);- cmd.args(&desired_args)+ let mut cmd = Command::new(binary);+ cmd.args(args).stdin(Stdio::null()).stdout(Stdio::null())// llama-server writes the REASON a start fails here: a GGUF it refuses,@@ -690,62 +918,62 @@ fn start_bundled_engine_blocking(#[cfg(target_os = "windows")]cmd.creation_flags(CREATE_NO_WINDOW);- let mut child = cmd- .spawn()- .map_err(|e| format!("Failed to spawn bundled engine: {}", os_error::english(&e)))?;+ let mut child = match cmd.spawn() {+ Ok(c) => c,+ Err(e) => {+ return Err(StartFailure {+ died: true,+ port_taken: false,+ stderr: format!("Failed to spawn bundled engine: {}", os_error::english(&e)),+ })+ }+ };let diagnostics = child.stderr.take().map(super::shell::drain);*state.bundled_engine.lock().unwrap() = Some(BundledEngine {child,- model_path: model_path.clone(),+ model_path: model_path.to_string(),port,- ctx: Some(effective_ctx(&tuning)),- args: desired_args,+ ctx: Some(ctx),+ args: args.to_vec(),});- // Wait for the model to load. On failure, reap the child so we don't leave- // a zombie half-loaded server behind.- if let Err(e) = wait_for_health(port, health_timeout_for(&model_path)) {- let why = diagnostics- .map(|(buf, _)| tail_lines(&super::shell::captured_text(&buf), 12))- .unwrap_or_default();- stop_engine_locked(state);- return Err(if why.is_empty() { e } else { format!("{e}\n\n{why}") });- }-- // Health said OK — but was it OUR child that answered? A spawn that loses- // the port to an orphaned llama-server (left behind by a crashed or- // hard-killed session) dies on "address already in use" within- // milliseconds, and the probe above then hits the STRANGER: unknown model,- // unknown ctx, tuning that silently never applies, and a process no- // shutdown of ours can ever reap. Fail honestly with the child's own- // stderr instead of adopting it. (Live repro 2026-07-28: an embed server- // orphaned by a previous dev session made every later start look green.)- let spawn_died = {- let mut guard = state.bundled_engine.lock().unwrap();- match guard.as_mut() {- Some(e) => e.child.try_wait().ok().flatten().is_some(),- None => true,+ let outcome = wait_for_health_or_exit(&**state, port, health_timeout_for(model_path));+ if matches!(outcome, HealthWait::Ready) {+ // Health said OK, but was it OUR child that answered? A spawn that+ // loses the port to an orphaned llama-server (left behind by a crashed+ // or hard-killed session) dies on "address already in use" within+ // milliseconds, and the probe then hits the STRANGER: unknown model,+ // unknown ctx, tuning that silently never applies, and a process no+ // shutdown of ours can ever reap. Fail honestly instead of adopting+ // it. (Live repro 2026-07-28: an embed server orphaned by a previous+ // dev session made every later start look green.)+ let ours_alive = {+ let mut guard = state.bundled_engine.lock().unwrap();+ match guard.as_mut() {+ Some(e) => e.child.try_wait().ok().flatten().is_none(),+ None => false,+ }+ };+ if ours_alive {+ return Ok(());}- };- if spawn_died {let why = diagnostics.map(|(buf, _)| tail_lines(&super::shell::captured_text(&buf), 12)).unwrap_or_default();stop_engine_locked(state);- return Err(format!(- "Port {port} answers health checks, but the engine this app just started exited immediately — another llama-server (likely left over from a previous session or crash) is occupying the port. Quit that process or reboot, then try again.{}",- if why.is_empty() { String::new() } else { format!("\n\n{why}") }- ));+ return Err(StartFailure { died: true, port_taken: true, stderr: why });}- println!("[Engine] Built-in engine healthy on port {port}");- Ok(serde_json::json!({- "status": "started",- "port": port,- "model_path": model_path,- "ctx": effective_ctx(&tuning),- }))+ let why = diagnostics+ .map(|(buf, _)| tail_lines(&super::shell::captured_text(&buf), 12))+ .unwrap_or_default();+ stop_engine_locked(state);+ Err(StartFailure {+ died: matches!(outcome, HealthWait::ChildExited),+ port_taken: false,+ stderr: why,+ })}/// Stop the managed engine, killing the child. Idempotent.@@ -1637,6 +1865,207 @@ mod tests {std::fs::remove_dir_all(&dir).ok();}+ // ── GH #118 ────────────────────────────────────────────────────────────++ #[test]+ fn scan_finds_a_model_the_broken_routing_nested_under_user_and_repo() {+ // The exact shape a v2.6.6 fresh install produced: no active chat+ // model, so the LM Studio branch wrote the GGUF two levels down and+ // the flat scan reported an empty models folder while a 8 GB file sat+ // right there (nayffy, 2026-08-27).+ let dir = std::env::temp_dir().join(format!("lu-engine-nested-{}", std::process::id()));+ let nested = dir.join("TheDrummer").join("Cydonia-24B-v4.1-GGUF");+ std::fs::create_dir_all(&nested).unwrap();+ std::fs::write(nested.join("Cydonia-24B-v4.1-Q4_K_M.gguf"), b"aaaa").unwrap();++ let models = scan_gguf_models(&dir);+ assert_eq!(models.len(), 1, "the nested model must be listed");+ assert_eq!(models[0].name, "Cydonia-24B-v4.1-Q4_K_M");+ assert!(models[0].path.ends_with("Cydonia-24B-v4.1-Q4_K_M.gguf"));+ assert_eq!(models[0].size, 4);++ std::fs::remove_dir_all(&dir).ok();+ }++ #[test]+ fn scan_stops_below_two_levels_and_prefers_the_flat_copy() {+ let dir = std::env::temp_dir().join(format!("lu-engine-depth-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ // Flat copy: the canonical location, and the one the picker must get.+ std::fs::write(dir.join("dup.gguf"), b"a").unwrap();+ let nested = dir.join("user").join("repo");+ std::fs::create_dir_all(&nested).unwrap();+ std::fs::write(nested.join("dup.gguf"), b"bb").unwrap();+ // Three levels down is out of reach on purpose.+ let deep = dir.join("a").join("b").join("c");+ std::fs::create_dir_all(&deep).unwrap();+ std::fs::write(deep.join("toodeep.gguf"), b"ccc").unwrap();++ let models = scan_gguf_models(&dir);+ let names: Vec<&str> = models.iter().map(|m| m.name.as_str()).collect();+ assert_eq!(names, vec!["dup"], "one id per name, nothing from level 3");+ assert!(+ !models[0].path.contains("user"),+ "the flat copy wins: {}",+ models[0].path+ );++ std::fs::remove_dir_all(&dir).ok();+ }++ #[test]+ fn shard_sets_in_different_folders_never_merge() {+ // Two halves of the same base name in two repos are two broken sets,+ // not one complete one. Merging them would offer a model that cannot+ // load, which is the rule a9ea114 established for MLX downloads.+ let dir = std::env::temp_dir().join(format!("lu-engine-shardsplit-{}", std::process::id()));+ let one = dir.join("userA").join("repo");+ let two = dir.join("userB").join("repo");+ std::fs::create_dir_all(&one).unwrap();+ std::fs::create_dir_all(&two).unwrap();+ std::fs::write(one.join("Big-00001-of-00002.gguf"), b"a").unwrap();+ std::fs::write(two.join("Big-00002-of-00002.gguf"), b"b").unwrap();++ assert!(scan_gguf_models(&dir).is_empty());++ std::fs::remove_dir_all(&dir).ok();+ }++ /// A port nothing on this machine serves, so `engine_healthy` answers+ /// "refused" immediately instead of talking to a real engine.+ const DEAD_PORT: u16 = 49871;++ fn park_child(state: &AppState, child: std::process::Child) {+ *state.bundled_engine.lock().unwrap() = Some(BundledEngine {+ child,+ model_path: "/tmp/does-not-matter.gguf".into(),+ port: DEAD_PORT,+ ctx: Some(8192),+ args: Vec::new(),+ });+ }++ #[test]+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]+ fn a_child_that_dies_on_start_is_reported_at_once_and_not_after_the_budget() {+ // GH #118: the health wait watched only the port, so an engine that+ // exited in the first second (a missing runtime library, a GPU backend+ // that will not initialise) still burned the whole budget before the+ // user was told anything. The budget here is 30s; the answer has to+ // arrive in a fraction of that.+ let state = AppState::new();+ let child = std::process::Command::new("sh")+ .args(["-c", "exit 3"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn a child that exits immediately");+ park_child(&state, child);++ let began = Instant::now();+ let out = wait_for_health_or_exit(&state, DEAD_PORT, Duration::from_secs(30));+ let took = began.elapsed();++ assert_eq!(out, HealthWait::ChildExited);+ assert!(took < Duration::from_secs(5), "waited {took:?}, which is the old dead wait");+ }++ #[test]+ fn an_empty_engine_slot_is_not_something_to_wait_for() {+ let state = AppState::new();+ let began = Instant::now();+ assert_eq!(+ wait_for_health_or_exit(&state, DEAD_PORT, Duration::from_secs(30)),+ HealthWait::ChildExited+ );+ assert!(began.elapsed() < Duration::from_secs(5));+ }++ #[test]+ #[cfg_attr(target_os = "windows", ignore = "uses sleep")]+ fn a_child_that_is_still_loading_is_left_alone_until_the_budget_ends() {+ // Negative control for the check above: a LIVE child must still get+ // its full budget, or a big GGUF on a cold disk would be declared dead+ // while it is only slow (ENG-4).+ let state = AppState::new();+ let child = std::process::Command::new("sleep")+ .arg("30")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn a live child");+ park_child(&state, child);++ assert_eq!(+ wait_for_health_or_exit(&state, DEAD_PORT, Duration::from_millis(900)),+ HealthWait::TimedOut+ );++ // Do not leave the sleeper behind.+ {+ let mut guard = state.bundled_engine.lock().unwrap();+ if let Some(e) = guard.as_mut() {+ let _ = e.child.kill();+ let _ = e.child.wait();+ }+ }+ }++ #[test]+ fn a_dead_start_names_the_graphics_card_when_the_engine_blamed_it() {+ let f = StartFailure {+ died: true,+ port_taken: false,+ stderr: "ggml_cuda_init: failed to initialize CUDA: no kernel image is available for execution on the device".into(),+ };+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60));+ assert!(msg.contains("exited again"), "{msg}");+ assert!(msg.contains("tried twice"), "{msg}");+ assert!(msg.contains("GPU Layers to 0"), "{msg}");+ // llama-server's own words survive so a bug report still carries them.+ assert!(msg.contains("no kernel image"), "{msg}");+ }++ #[test]+ fn a_dead_start_points_at_the_model_when_the_engine_blamed_the_file() {+ let f = StartFailure {+ died: true,+ port_taken: false,+ stderr: "llama_model_load: error loading model: unknown model architecture 'wanx'".into(),+ };+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60));+ assert!(msg.contains("refused the model file"), "{msg}");+ assert!(!msg.contains("GPU Layers"), "{msg}");+ }++ #[test]+ fn a_stranger_on_the_port_keeps_its_own_message() {+ let f = StartFailure { died: true, port_taken: true, stderr: String::new() };+ let msg = start_failure_message(&f, 8127, Duration::from_secs(60));+ assert!(msg.contains("occupying the port"), "{msg}");+ assert!(!msg.contains("tried twice"), "{msg}");+ }++ #[test]+ fn a_slow_load_still_reports_the_budget_and_never_claims_a_crash() {+ let f = StartFailure { died: false, port_taken: false, stderr: String::new() };+ let msg = start_failure_message(&f, 8127, Duration::from_secs(220));+ assert!(msg.contains("did not become healthy on port 8127 within 220s"), "{msg}");+ assert!(!msg.contains("exited"), "{msg}");+ }++ #[test]+ fn gpu_blame_needs_actual_gpu_words() {+ assert!(stderr_blames_the_gpu("CUDA error: out of memory"));+ assert!(stderr_blames_the_gpu("ggml_vulkan: no devices found"));+ // Negative control: a plain port collision is not a GPU problem, and+ // sending that user into the GPU Layers setting would waste their time.+ assert!(!stderr_blames_the_gpu("error: bind(): Address already in use"));+ assert!(!stderr_blames_the_model("error: bind(): Address already in use"));+ }+#[test]fn scan_missing_dir_is_empty_not_error() {let dir = std::env::temp_dir().join("lu-engine-nonexistent-xyz-123");diff --git a/src/api/__tests__/builtin-engine-diagnose.test.ts b/src/api/__tests__/builtin-engine-diagnose.test.tsnew file mode 100644index 00000000..8b833609--- /dev/null+++ b/src/api/__tests__/builtin-engine-diagnose.test.ts@@ -0,0 +1,170 @@+/**+ * GH #118 (nayffy, 2026-08-27, Windows 11, v2.6.6): "Built in engine test+ * fails and console shows as below", followed by+ * `GET http://127.0.0.1:8127/v1/models net::ERR_CONNECTION_REFUSED`.+ *+ * The Test button in Settings, AI Backends turned a refused connection into a+ * red dot and nothing else. The app owns that process, so a refusal is a+ * question it can answer: is the engine up, is there a model to run at all,+ * does starting it work. House rule is self-healing before an error message,+ * so with `repair` the start is attempted first and only what survives that+ * becomes a sentence.+ *+ * Run: npx vitest run src/api/__tests__/builtin-engine-diagnose.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++vi.mock('../backend', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../backend')>()+ return { ...actual, backendCall: vi.fn() }+})++import { diagnoseBuiltinEngine } from '../builtin-ensure'+import { backendCall } from '../backend'+import { useProviderStore } from '../../stores/providerStore'++const asManagedSlot = () => {+ useProviderStore.setState((s) => ({+ providers: {+ ...s.providers,+ openai: { ...s.providers.openai, enabled: true, managed: true, baseUrl: 'http://127.0.0.1:8127/v1' },+ },+ }))+}++const asForeignSlot = () => {+ useProviderStore.setState((s) => ({+ providers: {+ ...s.providers,+ openai: { ...s.providers.openai, enabled: true, managed: false, baseUrl: 'https://api.openai.com/v1' },+ },+ }))+}++/** Answer the two probe commands; everything else throws. */+const backend = (+ status: unknown,+ models: unknown,+ onStart?: (args: unknown) => unknown,+) => {+ vi.mocked(backendCall).mockImplementation((async (cmd: string, args: unknown) => {+ if (cmd === 'bundled_engine_status') {+ if (status instanceof Error) throw status+ return status+ }+ if (cmd === 'list_bundled_models') {+ if (models instanceof Error) throw models+ return models+ }+ if (cmd === 'start_bundled_engine') {+ if (!onStart) throw new Error('start not expected in this case')+ return onStart(args)+ }+ throw new Error(`unexpected command ${cmd}`)+ }) as never)+}++describe('diagnoseBuiltinEngine', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ asManagedSlot()+ })++ it('stays silent for a slot that is not ours', async () => {+ asForeignSlot()+ const d = await diagnoseBuiltinEngine({ repair: true })+ expect(d).toEqual({ ok: false, reason: '', repaired: false })+ expect(backendCall).not.toHaveBeenCalled()+ })++ it('reports ok without touching anything when the engine is healthy', async () => {+ backend({ running: true, healthy: true }, { models: [] })+ const d = await diagnoseBuiltinEngine({ repair: true })+ expect(d.ok).toBe(true)+ expect(d.repaired).toBe(false)+ })++ it('names the missing model instead of the refused connection', async () => {+ backend({ running: false, healthy: false }, { models: [] })+ const d = await diagnoseBuiltinEngine({ repair: true })+ expect(d.ok).toBe(false)+ expect(d.reason).toMatch(/no chat model to load yet/i)+ expect(d.reason).toMatch(/Models, Discover/i)+ })++ it('does not count an embedding GGUF as a chat model', async () => {+ backend({ running: false, healthy: false }, {+ models: [{ name: 'nomic-embed-text-v1.5.Q4_K_M', path: '/m/nomic.gguf' }],+ })+ const d = await diagnoseBuiltinEngine({ repair: true })+ expect(d.reason).toMatch(/no chat model to load yet/i)+ })++ it('starts the engine on an installed model, which is the whole point', async () => {+ const started: unknown[] = []+ backend(+ { running: false, healthy: false },+ { models: [{ name: 'Cydonia-24B-v4.1-Q4_K_M', path: '/m/cydonia.gguf' }] },+ (args) => { started.push(args); return { status: 'started' } },+ )+ const d = await diagnoseBuiltinEngine({ repair: true })+ expect(d.ok).toBe(true)+ expect(d.repaired).toBe(true)+ expect(started).toEqual([{ modelPath: '/m/cydonia.gguf', tuning: expect.anything() }])+ })++ it('prefers the model the user already picked', async () => {+ const started: Array<{ modelPath?: string }> = []+ backend(+ { running: false, healthy: false },+ {+ models: [+ { name: 'first', path: '/m/first.gguf' },+ { name: 'second', path: '/m/second.gguf' },+ ],+ },+ (args) => { started.push(args as { modelPath?: string }); return { status: 'started' } },+ )+ await diagnoseBuiltinEngine({ repair: true, preferModel: 'openai::second' })+ expect(started[0].modelPath).toBe('/m/second.gguf')+ })++ it('hands the engine s own reason through when the start fails', async () => {+ backend(+ { running: false, healthy: false },+ { models: [{ name: 'Cydonia', path: '/m/cydonia.gguf' }] },+ () => { throw new Error('CUDA error: no kernel image is available') },+ )+ const d = await diagnoseBuiltinEngine({ repair: true })+ expect(d.ok).toBe(false)+ expect(d.reason).toMatch(/could not start "Cydonia"/)+ expect(d.reason).toContain('CUDA error: no kernel image is available')+ })++ it('never starts anything without repair, and still says what is wrong', async () => {+ const calls: string[] = []+ vi.mocked(backendCall).mockImplementation((async (cmd: string) => {+ calls.push(cmd)+ if (cmd === 'bundled_engine_status') return { running: false, healthy: false }+ if (cmd === 'list_bundled_models') return { models: [{ name: 'Cydonia', path: '/m/c.gguf' }] }+ throw new Error(`unexpected command ${cmd}`)+ }) as never)+ const d = await diagnoseBuiltinEngine({ repair: false })+ expect(calls).not.toContain('start_bundled_engine')+ expect(d.reason).toMatch(/not running/i)+ expect(d.reason).toMatch(/1 model is installed/i)+ })++ it('says so when the model folder itself cannot be read', async () => {+ backend({ running: false, healthy: false }, new Error('Create built-in models dir: permission denied'))+ const d = await diagnoseBuiltinEngine({ repair: true })+ expect(d.reason).toMatch(/model folder could not be read/i)+ expect(d.reason).toContain('permission denied')+ })++ it('keeps out of the way when there is no Tauri backend at all', async () => {+ backend(new Error('not in tauri'), { models: [] })+ const d = await diagnoseBuiltinEngine({ repair: true })+ expect(d).toEqual({ ok: false, reason: '', repaired: false })+ })+})diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.tsindex 006753aa..92b3d6f4 100644--- a/src/api/builtin-ensure.ts+++ b/src/api/builtin-ensure.ts@@ -203,3 +203,105 @@ export async function ensureBuiltinAgentCtx(modelName: string): Promise<void> {} catch { /* the lazy self-heal on the next send takes over */ }}}++// ── "Why is the built-in engine not answering?" ──────────────────────────────++export interface BuiltinEngineDiagnosis {+ /** The engine answers /v1 on its port right now. */+ ok: boolean+ /** English, user-facing, empty when `ok` or when this slot is not ours. */+ reason: string+ /** True when this diagnosis actually started the engine. */+ repaired: boolean+}++const OK: BuiltinEngineDiagnosis = { ok: true, reason: '', repaired: false }+const NOT_OURS: BuiltinEngineDiagnosis = { ok: false, reason: '', repaired: false }++/**+ * GH #118 (nayffy, 2026-08-27): the Built-in Engine test in Settings, AI+ * Backends answered with nothing but a red dot while the console carried+ * `GET http://127.0.0.1:8127/v1/models net::ERR_CONNECTION_REFUSED`. A refused+ * connection to a server the app owns is not a verdict, it is a question the+ * app can answer itself, so this asks it: is the engine up, is there a model+ * to run at all, and does a start attempt succeed. House rule is self-healing+ * before an error message, so with `repair` the obvious repair (start the+ * engine on an installed GGUF) is attempted before anything is reported.+ *+ * Never throws. A missing Tauri backend (browser/dev) reports `NOT_OURS`, so+ * the caller keeps whatever it did before.+ */+export async function diagnoseBuiltinEngine(+ opts: { repair?: boolean; preferModel?: string | null } = {},+): Promise<BuiltinEngineDiagnosis> {+ if (!isManagedBuiltinSlot()) return NOT_OURS++ let status: EngineStatusLite | null+ try {+ status = await backendCall<EngineStatusLite>('bundled_engine_status')+ } catch {+ return NOT_OURS+ }+ if (status?.healthy) return OK++ let models: Array<{ name: string; path: string }>+ try {+ const res = await backendCall<BundledList>('list_bundled_models')+ models = res?.models ?? []+ } catch (e) {+ return {+ ok: false,+ repaired: false,+ reason: `The built-in engine is not running and its model folder could not be read: ${errText(e)}`,+ }+ }++ const runnable = models.filter((m) => !isEmbeddingGguf(m.name))+ if (runnable.length === 0) {+ return {+ ok: false,+ repaired: false,+ reason:+ 'The built-in engine is installed but has no chat model to load yet. Open Models, Discover and install one, then test again.',+ }+ }++ if (!opts.repair) {+ return {+ ok: false,+ repaired: false,+ reason: `The built-in engine is not running. ${runnable.length} model${runnable.length === 1 ? ' is' : 's are'} installed. Pick one in the chat model picker to start the engine.`,+ }+ }++ const bare = opts.preferModel+ ? opts.preferModel.includes('::')+ ? opts.preferModel.split('::')[1]+ : opts.preferModel+ : ''+ const pick = runnable.find((m) => m.name === bare) ?? runnable[0]+ try {+ const tuning = useSettingsStore.getState().settings.builtinEngine+ await backendCall('start_bundled_engine', { modelPath: pick.path, tuning })+ return { ok: true, reason: '', repaired: true }+ } catch (e) {+ return {+ ok: false,+ repaired: false,+ reason: `The built-in engine could not start "${pick.name}": ${errText(e)}`,+ }+ }+}++function errText(e: unknown): string {+ return e instanceof Error ? e.message : String(e ?? 'unknown error')+}++// Duplicated from api/engine.ts on purpose: importing it would pull the+// provider/model layer into this module and reintroduce the import cycle the+// header warns about. Two patterns, one meaning, both covered by tests.+const EMBED_NAME_PATTERNS = [/embed/, /nomic-embed/, /bge-/, /e5-/, /gte-/, /sentence-/]+function isEmbeddingGguf(name: string): boolean {+ const lower = name.toLowerCase()+ return EMBED_NAME_PATTERNS.some((p) => p.test(lower))+}diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsxindex f604820c..34b18a6b 100644--- a/src/components/models/DiscoverModels.tsx+++ b/src/components/models/DiscoverModels.tsx@@ -24,7 +24,8 @@ import { useWorkflowStore } from '../../stores/workflowStore'import { getProviderIdFromModel } from '../../api/providers'import { startBundledEngine } from '../../api/engine'import { BUILTIN_BACKEND_ID } from '../../lib/onboarding-backend'-import { matchesLmStudioInstalled, type InstalledModelLike } from '../../lib/lmstudio-match'+import { matchesLocalGgufInstalled, type InstalledModelLike } from '../../lib/lmstudio-match'+import { resolveTextDownloadTarget } from '../../lib/text-download-target'import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir, parseHfUrl, extractGgufQuant, isShardedOrIncompatibleGguf } from '../../lib/hf-to-provider'import { GlassCard } from '../ui/GlassCard'import { GlowButton } from '../ui/GlowButton'@@ -239,7 +240,7 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:// The matcher (lib/lmstudio-match.ts, unit-tested) handles both the older// full-basename id form AND LM Studio's modern quant-less publisher/short// key (e.g. "qwen/qwen2.5-vl-7b" vs "Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf").- if (model.filename && matchesLmStudioInstalled(model.filename, installedModels as unknown as InstalledModelLike[])) {+ if (model.filename && matchesLocalGgufInstalled(model.filename, installedModels as unknown as InstalledModelLike[])) {return true}@@ -446,9 +447,20 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:// Built-in engine lives in the managed `openai` slot. A second chat model// downloaded here goes flat into the app-owned models dir and boots// llama-server, mirroring onboarding — never nested like LM Studio.- const isActiveBuiltin = activeProviderId === 'openai' && !!providers.openai?.managed- const isActiveLmStudio = activeProviderId === 'openai' && !providers.openai?.managed && (providers.openai?.name || '').toLowerCase().includes('lm studio')- const isActiveOllama = activeProviderId === 'ollama'+ //+ // GH #118: the three flags below used to be read off `activeProviderId`+ // alone, so a fresh install (no chat model picked yet) matched none of+ // them and the file went down the LM Studio branch into a nested folder+ // the built-in engine never scans. resolveTextDownloadTarget keeps the+ // active-model rule and adds the missing fallback.+ const downloadTarget = resolveTextDownloadTarget({+ activeChatModel,+ openai: providers.openai,+ ollamaEnabled: !!providers.ollama?.enabled,+ })+ const isActiveBuiltin = downloadTarget === 'builtin'+ const isActiveLmStudio = downloadTarget === 'lmstudio'+ const isActiveOllama = downloadTarget === 'ollama'// Ollama-native models: only meaningful with Ollama present. If the user// is chatting on LM Studio and clicks one of these (e.g. Qwen3.6 35B@@ -516,7 +528,11 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:setInstallError('Could not determine model directory. Please check app permissions.')return}- const ollamaCantLoad = isActiveOllama || (!isActiveLmStudio && !lmStudioEnabled && ollamaEnabledNow)+ // The note is about Ollama's split-GGUF gap, so it must only appear when+ // Ollama really is where the user would look for the model. With the+ // built-in engine as the target the parts land in the app's own flat+ // models dir and the Rust scan collapses the set, so the note would lie.+ const ollamaCantLoad = isActiveOllama || (!isActiveBuiltin && !isActiveLmStudio && !lmStudioEnabled && ollamaEnabledNow)setConfirmDownload({name: model.name,files: resolution.files,@@ -539,10 +555,7 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:// Route by the active chat model. If neither side has an active model yet// (first launch), fall back to the old enabled-wins logic.- let useOllamaPath: boolean- if (isActiveOllama) useOllamaPath = true- else if (isActiveBuiltin || isActiveLmStudio) useOllamaPath = false- else useOllamaPath = !lmStudioEnabled && ollamaEnabledNow // legacy fallback+ const useOllamaPath = isActiveOllamaif (useOllamaPath) {const ref = hfUrlToOllamaRef(realUrl, realName)diff --git a/src/components/models/ModelSelector.tsx b/src/components/models/ModelSelector.tsxindex cca2a774..e83210c0 100644--- a/src/components/models/ModelSelector.tsx+++ b/src/components/models/ModelSelector.tsx@@ -9,6 +9,7 @@ import { useUIStore } from '../../stores/uiStore'import { unloadAllModels, loadModel, unloadModel, listRunningModels } from '../../api/ollama'import { displayModelName, getProviderIdFromModel } from '../../api/providers'import { activateBuiltinModel, isManagedBuiltinActive } from '../../api/engine'+import { diagnoseBuiltinEngine } from '../../api/builtin-ensure'import { canUseTools, resolveToolSupport, type ToolSupport } from '../../lib/tool-support'import { backendCall } from '../../api/backend'import { listLoadedLmStudioModels, loadLmStudioModel, unloadLmStudioModel } from '../../api/lmstudio'@@ -458,6 +459,9 @@ export function ModelSelector({ openUpward = false, surface = 'chat' }: ModelSel// local models are gone" (it cost a whole repro round on 2026-08-07).const appMode = useSettingsStore((s) => s.settings.appMode)const [open, setOpen] = useState(false)+ // Read by the empty-state probe below, which runs before the render that+ // computes textModels. A ref keeps it out of the effect's dependency list.+ const textModelsEmptyRef = useRef(true)const [unloading, setUnloading] = useState(false)const [unloadDone, setUnloadDone] = useState(false)// B3 — per-model LM Studio load/unload state. `lmsLoaded` is the set@@ -655,6 +659,20 @@ export function ModelSelector({ openUpward = false, surface = 'chat' }: ModelSeluseEffect(() => { fetchModels() }, [fetchModels])+ // GH #118: an empty picker used to say "No models available" no matter what+ // was wrong, so a built-in engine that never started read like a machine+ // with nothing installed. Asked only while the dropdown is open and the list+ // is empty, and never repairs, because opening a dropdown must not boot a server.+ const [emptyReason, setEmptyReason] = useState('')+ useEffect(() => {+ if (!open || textModelsEmptyRef.current === false) return+ let cancelled = false+ diagnoseBuiltinEngine({ repair: false })+ .then((d) => { if (!cancelled && !d.ok && d.reason) setEmptyReason(d.reason) })+ .catch(() => { /* nothing to add, the generic line stands */ })+ return () => { cancelled = true }+ }, [open])+// Refetch when any provider's enabled state or baseUrl changes (e.g. user// enables LM Studio / adds Anthropic key in Settings, or the backend// picker activates an OpenAI-compatible provider). Without this the@@ -699,6 +717,7 @@ export function ModelSelector({ openUpward = false, surface = 'chat' }: ModelSelconst hiddenForCode = allTextModels.length - textModels.lengthconst groups = groupByFamily(textModels)const hasOllamaModels = textModels.some(m => ('provider' in m && m.provider === 'ollama') || !('provider' in m))+ textModelsEmptyRef.current = textModels.length === 0return (<div ref={ref} className="relative">@@ -780,7 +799,12 @@ export function ModelSelector({ openUpward = false, surface = 'chat' }: ModelSel{/* Scrollable model list */}<div className="py-1 max-h-[280px] overflow-y-auto scrollbar-thin">{textModels.length === 0 && (- <p className="text-[0.65rem] text-gray-600 text-center py-3">No models available</p>+ <div className="px-2.5 py-3 text-center">+ <p className="text-[0.65rem] text-gray-600">No models available</p>+ {emptyReason && (+ <p className="mt-1 text-[0.6rem] text-amber-300/90 leading-snug text-left">{emptyReason}</p>+ )}+ </div>)}{groups.map(({ family, models: groupModels }) => (diff --git a/src/components/settings/ProviderConfig.tsx b/src/components/settings/ProviderConfig.tsxindex 753220ce..d5fb1b1e 100644--- a/src/components/settings/ProviderConfig.tsx+++ b/src/components/settings/ProviderConfig.tsx@@ -6,6 +6,7 @@ import { getProvider } from '../../api/providers'import { PROVIDER_PRESETS } from '../../api/providers/types'import { Modal } from '../ui/Modal'import { backendCall } from '../../api/backend'+import { diagnoseBuiltinEngine } from '../../api/builtin-ensure'import type { ProviderId, ProviderConfig } from '../../api/providers/types'const isTauri = typeof window !== 'undefined' && !!(window as any).__TAURI_INTERNALS__@@ -87,6 +88,8 @@ export function ProviderSettings() {const [dropdownOpen, setDropdownOpen] = useState(false)const [testing, setTesting] = useState<ProviderId | null>(null)const [statuses, setStatuses] = useState<Record<string, 'idle' | 'connected' | 'failed'>>({})+ // Per-slot English explanation for a failed Test (GH #118).+ const [testDetail, setTestDetail] = useState<Record<string, string>>({})const [showKey, setShowKey] = useState<Record<string, boolean>>({})const [showCloudWarning, setShowCloudWarning] = useState(false)const [pendingPreset, setPendingPreset] = useState<typeof PROVIDER_PRESETS[0] | null>(null)@@ -165,13 +168,34 @@ export function ProviderSettings() {const handleTest = async (providerId: ProviderId) => {setTesting(providerId)setStatuses(prev => ({ ...prev, [providerId]: 'idle' }))+ setTestDetail(prev => ({ ...prev, [providerId]: '' }))+ let ok = falsetry {const client = getProvider(providerId)- const ok = await client.checkConnection()- setStatuses(prev => ({ ...prev, [providerId]: ok ? 'connected' : 'failed' }))+ ok = await client.checkConnection()} catch {- setStatuses(prev => ({ ...prev, [providerId]: 'failed' }))+ ok = false}+ // GH #118: a red dot was the whole answer the built-in engine gave, while+ // the console carried ERR_CONNECTION_REFUSED on 127.0.0.1:8127. The app+ // owns that process, so a failed test asks the app: start it if a model is+ // there, and otherwise say in one English sentence what is missing.+ // Only the openai slot can BE the built-in engine, and testing Anthropic+ // must never boot a local server as a side effect.+ if (!ok && providerId === 'openai') {+ const diag = await diagnoseBuiltinEngine({ repair: true })+ if (diag.ok) {+ try {+ ok = await getProvider(providerId).checkConnection()+ } catch {+ ok = false+ }+ }+ if (!ok && diag.reason) {+ setTestDetail(prev => ({ ...prev, [providerId]: diag.reason }))+ }+ }+ setStatuses(prev => ({ ...prev, [providerId]: ok ? 'connected' : 'failed' }))setTesting(null)// Bug (g): refresh after a Test click so the Start-Server button// appears the moment a user discovers their LM Studio server is down.@@ -346,6 +370,11 @@ export function ProviderSettings() {)}</div>+ {/* Why it failed, when the app can tell (GH #118). */}+ {status === 'failed' && testDetail[id] && (+ <p className="text-[0.6rem] text-red-300/90 leading-snug">{testDetail[id]}</p>+ )}+{/* API key storage disclaimer */}{needsKey && currentKey && (<p className="text-[0.5rem] text-gray-600 mt-0.5 leading-tight">diff --git a/src/lib/__tests__/lmstudio-match.test.ts b/src/lib/__tests__/lmstudio-match.test.tsindex fffd475c..be3b10ee 100644--- a/src/lib/__tests__/lmstudio-match.test.ts+++ b/src/lib/__tests__/lmstudio-match.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest'-import { matchesLmStudioInstalled, modelIdentity, extractQuant, type InstalledModelLike } from '../lmstudio-match'+import { matchesLmStudioInstalled, matchesLocalGgufInstalled, modelIdentity, extractQuant, type InstalledModelLike } from '../lmstudio-match'const lms = (id: string, field: 'model' | 'name' | 'lmsKey' = 'model'): InstalledModelLike => ({provider: 'openai',@@ -93,3 +93,36 @@ describe('split GGUF (-NNNNN-of-NNNNN) shard tails', () => {expect(extractQuant('phi-4-Q4_K_M.gguf')).toBe('q4km')})})++// GH #118 (nayffy, 2026-08-27): "If i close and reopen LU, it changed from+// 'Installed' to 'Get', but the 'Get' button doesn't do anything as the files+// are still downloaded." The badge only ever asked the LM Studio half of the+// installed list, and a built-in-engine model is stamped+// providerName: 'Built-in Engine'. The in-session download store was the only+// other evidence and it does not survive a restart.+const builtin = (id: string): InstalledModelLike => ({+ provider: 'openai',+ providerName: 'Built-in Engine',+ model: id,+})++describe('matchesLocalGgufInstalled: the built-in engine counts as installed too', () => {+ it('lights the badge for a GGUF the built-in engine reports from disk', () => {+ // list_bundled_models returns the file STEM, no .gguf.+ expect(matchesLocalGgufInstalled('Cydonia-24B-v4.1-Q4_K_M.gguf', [builtin('Cydonia-24B-v4.1-Q4_K_M')])).toBe(true)+ })+ it('still lights for LM Studio, so the old path is untouched', () => {+ expect(matchesLocalGgufInstalled('Hermes-3-Llama-3.1-8B.Q4_K_M.gguf', [lms('hermes-3-llama-3.1-8b.q4_k_m.gguf')])).toBe(true)+ })+ it('keeps the quant rule: a sibling quant on the built-in engine does NOT light the row', () => {+ expect(matchesLocalGgufInstalled('Cydonia-24B-v4.1-Q4_K_M.gguf', [builtin('Cydonia-24B-v4.1-Q6_K')])).toBe(false)+ })+ it('ignores a cloud slot that happens to sit on provider openai', () => {+ expect(matchesLocalGgufInstalled('Cydonia-24B-v4.1-Q4_K_M.gguf', [+ { provider: 'openai', providerName: 'OpenAI', model: 'Cydonia-24B-v4.1-Q4_K_M' },+ ])).toBe(false)+ })+ it('the LM-Studio-only function stays LM-Studio-only', () => {+ expect(matchesLmStudioInstalled('Cydonia-24B-v4.1-Q4_K_M.gguf', [builtin('Cydonia-24B-v4.1-Q4_K_M')])).toBe(false)+ })+})diff --git a/src/lib/__tests__/text-download-target.test.ts b/src/lib/__tests__/text-download-target.test.tsnew file mode 100644index 00000000..9985bf1f--- /dev/null+++ b/src/lib/__tests__/text-download-target.test.ts@@ -0,0 +1,117 @@+/**+ * GH #118 (nayffy, 2026-08-27, Windows 11, v2.6.6): "Unable to load built in+ * engine or models". A fresh install downloaded a chat model, the tile said+ * Installed, the Chat tab never saw it, a restart flipped the tile back to+ * Get, and the Built-in Engine test in Settings answered+ * `GET http://127.0.0.1:8127/v1/models net::ERR_CONNECTION_REFUSED`.+ *+ * All three came from this one decision. The download target was derived from+ * the ACTIVE chat model, and a fresh install has none, so the code fell+ * through to the legacy "whichever backend is enabled" rule: it wrote the GGUF+ * into the LM Studio layout (`<models>/<user>/<repo>/`), which the flat+ * `list_bundled_models` scan does not read, and it skipped+ * `start_bundled_engine` because that call sits behind the same flag.+ *+ * Run: npx vitest run src/lib/__tests__/text-download-target.test.ts+ */+import { describe, it, expect } from 'vitest'+import { resolveTextDownloadTarget } from '../text-download-target'++const SHIPPED_DEFAULTS = {+ openai: { enabled: true, managed: true, name: 'Built-in Engine' },+ ollamaEnabled: false,+}++describe('resolveTextDownloadTarget: the fresh install from #118', () => {+ it('sends the download to the built-in engine when no chat model was ever picked', () => {+ expect(resolveTextDownloadTarget({ activeChatModel: null, ...SHIPPED_DEFAULTS })).toBe('builtin')+ })++ it('treats an empty string the same as no model', () => {+ expect(resolveTextDownloadTarget({ activeChatModel: '', ...SHIPPED_DEFAULTS })).toBe('builtin')+ })++ it('does not hand a GGUF to a cloud slot the user happens to be chatting on', () => {+ // A GGUF cannot run at Anthropic, so the local destination decides alone.+ expect(+ resolveTextDownloadTarget({ activeChatModel: 'anthropic::claude-sonnet-4', ...SHIPPED_DEFAULTS }),+ ).toBe('builtin')+ expect(+ resolveTextDownloadTarget({ activeChatModel: 'lu-cloud::glm-5.3', ...SHIPPED_DEFAULTS }),+ ).toBe('builtin')+ })+})++describe('resolveTextDownloadTarget: the active model still decides (Bug Y/a, v2.5.0)', () => {+ it('an Ollama tag keeps the ollama pull path', () => {+ expect(+ resolveTextDownloadTarget({+ activeChatModel: 'qwen2.5:7b',+ openai: { enabled: false },+ ollamaEnabled: true,+ }),+ ).toBe('ollama')+ })++ it('an active built-in model stays on the built-in engine even with Ollama running', () => {+ expect(+ resolveTextDownloadTarget({+ activeChatModel: 'openai::Cydonia-24B-v4.1-Q4_K_M',+ openai: { enabled: true, managed: true, name: 'Built-in Engine' },+ ollamaEnabled: true,+ }),+ ).toBe('builtin')+ })++ it('an active LM Studio model keeps the nested LM Studio layout', () => {+ expect(+ resolveTextDownloadTarget({+ activeChatModel: 'openai::qwen2.5-7b-instruct',+ openai: { enabled: true, managed: false, name: 'LM Studio' },+ ollamaEnabled: false,+ }),+ ).toBe('lmstudio')+ })++ it('an active custom OpenAI-compatible server is neither of those', () => {+ expect(+ resolveTextDownloadTarget({+ activeChatModel: 'openai::my-model',+ openai: { enabled: true, managed: false, name: 'vLLM' },+ ollamaEnabled: false,+ }),+ ).toBe('openai-compat')+ })+})++describe('resolveTextDownloadTarget: no active model, other setups', () => {+ it('an Ollama user is untouched: choosing Ollama in onboarding disables the managed slot', () => {+ expect(+ resolveTextDownloadTarget({+ activeChatModel: null,+ openai: { enabled: false, managed: false },+ ollamaEnabled: true,+ }),+ ).toBe('ollama')+ })++ it('an LM Studio slot wins over Ollama, as before', () => {+ expect(+ resolveTextDownloadTarget({+ activeChatModel: null,+ openai: { enabled: true, managed: false, name: 'LM Studio' },+ ollamaEnabled: true,+ }),+ ).toBe('lmstudio')+ })++ it('with nothing local enabled the file still lands where this app can load it', () => {+ expect(+ resolveTextDownloadTarget({+ activeChatModel: null,+ openai: { enabled: false },+ ollamaEnabled: false,+ }),+ ).toBe('builtin')+ })+})diff --git a/src/lib/lmstudio-match.ts b/src/lib/lmstudio-match.tsindex 62a80575..53d3a94b 100644--- a/src/lib/lmstudio-match.ts+++ b/src/lib/lmstudio-match.ts@@ -63,6 +63,23 @@ export function modelIdentity(s: string): string {.replace(/[^a-z0-9]/g, '')}+/** An LM Studio entry in the installed-model list. */+function isLmStudioEntry(m: InstalledModelLike): boolean {+ if (m.provider !== 'openai') return false+ const pname = (m.providerName || '').toLowerCase()+ return pname.includes('lm studio') || pname.includes('lmstudio')+}++/**+ * A built-in-engine entry. `bundledToAIModels` stamps every downloaded GGUF+ * with `provider: 'openai'` and `providerName: 'Built-in Engine'`, and its+ * `model` is the file stem, so the same filename matcher fits it exactly.+ */+function isBuiltinEntry(m: InstalledModelLike): boolean {+ if (m.provider !== 'openai') return false+ return (m.providerName || '').toLowerCase().includes('built-in engine')+}+/*** True when any LM-Studio-installed model corresponds to the given GGUF* filename. Order: exact basename / `publisher/`-suffix (already quant-precise),@@ -73,15 +90,33 @@ export function matchesLmStudioInstalled(filename: string,installed: InstalledModelLike[],): boolean {+ return matchesInstalled(filename, installed.filter(isLmStudioEntry))+}++/**+ * Same question for every local GGUF store the app can write into: LM Studio+ * AND the built-in engine.+ *+ * GH #118 (nayffy, 2026-08-27): the Discover badge only ever consulted the LM+ * Studio half, so a chat model downloaded for the BUILT-IN engine lost its+ * INSTALLED badge on the next app start (the in-session download store is the+ * only other evidence and it does not survive a restart). The tile then+ * offered "Get" for a file that was already on disk. `list_bundled_models`+ * reads that disk on every model refresh, so the evidence was there the whole+ * time, just never asked.+ */+export function matchesLocalGgufInstalled(+ filename: string,+ installed: InstalledModelLike[],+): boolean {+ return matchesInstalled(filename, installed.filter((m) => isLmStudioEntry(m) || isBuiltinEntry(m)))+}++function matchesInstalled(filename: string, lms: InstalledModelLike[]): boolean {if (!filename) return falseconst wantBase = normalBase(filename)const wantId = modelIdentity(filename)const wantQuant = extractQuant(filename)- const lms = installed.filter((m) => {- if (m.provider !== 'openai') return false- const pname = (m.providerName || '').toLowerCase()- return pname.includes('lm studio') || pname.includes('lmstudio')- })for (const m of lms) {const candidates = [m.model, m.name, m.lmsKey].filter(Boolean)diff --git a/src/lib/text-download-target.ts b/src/lib/text-download-target.tsnew file mode 100644index 00000000..8e927945--- /dev/null+++ b/src/lib/text-download-target.ts@@ -0,0 +1,82 @@+/**+ * Where a chat-model (GGUF) download from Models, Discover has to land, and+ * which backend has to load it afterwards.+ *+ * GH #118 (nayffy, 2026-08-27, fresh Windows 11 install, v2.6.6): the answer+ * used to be derived from the ACTIVE chat model alone. On a fresh install+ * there is no active chat model yet, so every branch missed and the code fell+ * through to the legacy "whichever backend is enabled" rule. With the shipped+ * defaults (built-in engine on, Ollama off, LM Studio absent) that rule picked+ * the LM Studio flow: the GGUF was written into+ * `<app models dir>/<user>/<repo>/`, and `list_bundled_models` scans the app+ * models dir NON-recursively, so the finished download was invisible to chat.+ * Nothing called `start_bundled_engine` either, so 127.0.0.1:8127 stayed dead+ * and the Built-in Engine test in Settings answered ERR_CONNECTION_REFUSED.+ * Three symptoms, one missing branch.+ *+ * Pure on purpose: the routing decision is the part that was wrong, so it is+ * the part that gets unit tests.+ */++export type TextDownloadTarget =+ /** `ollama pull` into Ollama's own blob store. */+ | 'ollama'+ /** Flat write into the app-owned models dir, then boot llama-server on it. */+ | 'builtin'+ /** Nested `<user>/<repo>` write into LM Studio's scan dir. */+ | 'lmstudio'+ /** Some other OpenAI-compatible server the user configured themselves. */+ | 'openai-compat'++export interface TextDownloadTargetInput {+ /** `useModelStore.activeModel`: `<providerId>::<id>`, a bare Ollama tag, or null. */+ activeChatModel?: string | null+ openai?: { enabled?: boolean; managed?: boolean; name?: string } | null+ ollamaEnabled?: boolean+}++function isLmStudioName(name?: string): boolean {+ return (name || '').toLowerCase().includes('lm studio')+}++/** Provider id encoded in an active model name, or null for a bare Ollama tag. */+function providerIdOf(activeChatModel?: string | null): string | null {+ if (!activeChatModel) return null+ return activeChatModel.includes('::') ? activeChatModel.split('::')[0] : 'ollama'+}++/**+ * Resolve the download target.+ *+ * Rule 1, unchanged: an active chat model on a LOCAL backend decides, because+ * the file has to land where the picker the user is already looking at can see+ * it (Bug Y/a, Aldrich Ironhart, v2.5.0).+ *+ * Rule 2, the #118 fix: with no active local chat model, the app's OWN engine+ * wins whenever its slot is enabled and managed. A GGUF only runs locally, and+ * the built-in engine is the one local backend that is guaranteed to be there.+ * Choosing Ollama in onboarding disables the managed slot, so an Ollama user+ * never reaches this branch.+ */+export function resolveTextDownloadTarget(input: TextDownloadTargetInput): TextDownloadTarget {+ const { openai, ollamaEnabled } = input+ const active = providerIdOf(input.activeChatModel)+ const managedBuiltin = !!openai?.enabled && openai?.managed === true++ if (active === 'ollama') return 'ollama'+ if (active === 'openai') {+ if (openai?.managed) return 'builtin'+ return isLmStudioName(openai?.name) ? 'lmstudio' : 'openai-compat'+ }++ // No active model, or an active CLOUD model (anthropic / lu-cloud): a GGUF+ // cannot run there, so the local destination is decided on its own.+ if (managedBuiltin) return 'builtin'+ if (openai?.enabled && isLmStudioName(openai?.name)) return 'lmstudio'+ if (ollamaEnabled) return 'ollama'+ if (openai?.enabled) return 'openai-compat'+ // Nothing local is enabled at all. The bundled engine is the only backend+ // this app can promise, so send the file to its folder rather than to a+ // directory no installed program reads.+ return 'builtin'+}