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(models): der eigene Modellordner wird gelesen, nicht nur beschrieben
purple4b4b5bc7d78f
diff --git a/src-tauri/src/commands/custom_models.rs b/src-tauri/src/commands/custom_models.rsnew file mode 100644index 00000000..0201ac7a--- /dev/null+++ b/src-tauri/src/commands/custom_models.rs@@ -0,0 +1,225 @@+//! The user's own model folder, handed to ComfyUI.+//!+//! GH #122 (zrmdsxa) plus the Discord thread "Read me first" (ever.noob):+//! the folder under Settings → Model Storage was a download target and nothing+//! more. Chat GGUFs in it are read by `engine::scan_gguf_roots` now, but a+//! `.safetensors` is a different problem: LU never scans image or video models+//! off the disk at all. That inventory comes out of ComfyUI's own `/object_info`+//! enums, and ComfyUI only lists what sits under its own `models/` tree.+//!+//! So the honest way in is ComfyUI's own mechanism: an extra-model-paths config.+//! We write our own file and pass it with `--extra-model-paths-config`, so a+//! hand written `extra_model_paths.yaml` in the ComfyUI folder is never touched+//! and nothing changes for a user who set none. Two limits are real and the+//! Settings text says both: it reaches a ComfyUI that LU starts, and it takes+//! effect the next time ComfyUI starts.+//!+//! Only subfolders NAMED like ComfyUI's model folders are mapped. A flat dump+//! of mixed files is left alone on purpose: mapping it into every key would+//! offer one checkpoint as a LoRA, a VAE and a ControlNet at the same time.++use std::path::{Path, PathBuf};++/// The `folder_paths` keys ComfyUI accepts in an extra-model-paths file, which+/// are also the folder names it uses on disk. Kept in step with+/// `subfolderForSource` in `src/api/comfyui.ts` (a test holds the two lists+/// against each other).+pub(crate) const COMFY_MODEL_FOLDERS: &[&str] = &[+ "checkpoints",+ "clip_vision",+ "controlnet",+ "diffusion_models",+ "embeddings",+ "loras",+ "style_models",+ "text_encoders",+ "upscale_models",+ "vae",+];++/// Which ComfyUI-shaped folders exist below `root`.+///+/// Both layouts count: the folder the user picked may itself be a ComfyUI-style+/// tree (`G:\AI\Models\loras`) or may hold one (`G:\AI\Models\models\loras`).+/// Returned in the order of `COMFY_MODEL_FOLDERS` so the written file is stable+/// and a rewrite with nothing changed produces the same bytes.+pub(crate) fn comfy_shaped_subdirs(root: &Path) -> Vec<(&'static str, PathBuf)> {+ let mut out = Vec::new();+ for key in COMFY_MODEL_FOLDERS {+ for candidate in [root.join(key), root.join("models").join(key)] {+ if candidate.is_dir() {+ out.push((*key, candidate));+ break;+ }+ }+ }+ out+}++/// The YAML ComfyUI reads, or `None` when the folder holds nothing ComfyUI+/// could place. Absolute paths per key rather than one `base_path`, because the+/// two layouts above can be mixed inside one folder.+///+/// Windows paths are quoted, so a drive letter's colon and the backslashes+/// cannot be read as YAML syntax. A path with a `"` in it is dropped rather+/// than escaped: no model folder needs one, and a half-escaped path would make+/// ComfyUI fail to parse the whole file and lose the other folders with it.+pub(crate) fn build_extra_model_paths_yaml(root: &Path) -> Option<String> {+ let found: Vec<(&str, PathBuf)> = comfy_shaped_subdirs(root)+ .into_iter()+ .filter(|(_, p)| !p.to_string_lossy().contains('"'))+ .collect();+ if found.is_empty() {+ return None;+ }+ let mut s = String::from(+ "# Written by Locally Uncensored from Settings -> Model Storage.\n\+ # Edit the folder in the app, not this file: it is rewritten on every change.\n\+ lu_custom_models:\n",+ );+ for (key, path) in found {+ s.push_str(&format!(" {}: \"{}\"\n", key, path.to_string_lossy()));+ }+ Some(s)+}++/// Where the generated file lives: beside the app's own models dir, never+/// inside the user's ComfyUI folder.+pub(crate) fn extra_model_paths_file() -> Result<PathBuf, String> {+ let base = dirs::data_dir().ok_or("Cannot resolve app data directory")?;+ let dir = base.join("Locally Uncensored");+ std::fs::create_dir_all(&dir)+ .map_err(|e| format!("Create app data dir: {}", crate::os_error::english(&e)))?;+ Ok(dir.join("lu_extra_model_paths.yaml"))+}++/// The file to pass to ComfyUI, or `None` when there is nothing to pass.+/// Called from the ComfyUI start path, so it never creates anything.+pub fn extra_model_paths_arg() -> Option<PathBuf> {+ let base = dirs::data_dir()?;+ let file = base+ .join("Locally Uncensored")+ .join("lu_extra_model_paths.yaml");+ if file.is_file() {+ Some(file)+ } else {+ None+ }+}++/// Write (or remove) the extra-model-paths file for the folder under Model+/// Storage. Idempotent, and safe to call on every settings change.+///+/// Reports what it did, so the Settings panel can name the folders it found+/// instead of claiming a success the user cannot check.+#[tauri::command]+pub fn sync_custom_model_paths(dir: Option<String>) -> Result<serde_json::Value, String> {+ let file = extra_model_paths_file()?;+ let trimmed = dir.unwrap_or_default().trim().to_string();+ let yaml = if trimmed.is_empty() {+ None+ } else {+ build_extra_model_paths_yaml(Path::new(&trimmed))+ };+ let folders: Vec<String> = if trimmed.is_empty() {+ Vec::new()+ } else {+ comfy_shaped_subdirs(Path::new(&trimmed))+ .into_iter()+ .map(|(k, _)| k.to_string())+ .collect()+ };+ match yaml {+ Some(text) => {+ std::fs::write(&file, text)+ .map_err(|e| format!("Write model paths file: {}", crate::os_error::english(&e)))?;+ }+ None => {+ // A folder that stopped being ComfyUI-shaped must not keep feeding+ // ComfyUI the old paths, so the file goes away with it.+ if file.exists() {+ std::fs::remove_file(&file).map_err(|e| {+ format!("Remove model paths file: {}", crate::os_error::english(&e))+ })?;+ }+ }+ }+ Ok(serde_json::json!({+ "written": !folders.is_empty(),+ "file": file.to_string_lossy(),+ "folders": folders,+ }))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn tmp(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join("lu-custom-models-tests").join(name);+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ #[test]+ fn finds_comfy_shaped_folders_in_both_layouts() {+ let root = tmp("both-layouts");+ std::fs::create_dir_all(root.join("loras")).unwrap();+ std::fs::create_dir_all(root.join("models").join("checkpoints")).unwrap();+ let found = comfy_shaped_subdirs(&root);+ let keys: Vec<&str> = found.iter().map(|(k, _)| *k).collect();+ assert_eq!(keys, vec!["checkpoints", "loras"]);+ assert_eq!(found[0].1, root.join("models").join("checkpoints"));+ assert_eq!(found[1].1, root.join("loras"));+ }++ #[test]+ fn the_direct_layout_wins_over_the_nested_one() {+ // Both exist: the folder the user pointed at is the one he meant.+ let root = tmp("direct-wins");+ std::fs::create_dir_all(root.join("vae")).unwrap();+ std::fs::create_dir_all(root.join("models").join("vae")).unwrap();+ let found = comfy_shaped_subdirs(&root);+ assert_eq!(found.len(), 1);+ assert_eq!(found[0].1, root.join("vae"));+ }++ /// Negative control: a folder full of models but with no ComfyUI folder+ /// name in it produces NO file. Mapping a flat dump into every key would+ /// offer one checkpoint as a LoRA and a ControlNet at the same time.+ #[test]+ fn a_flat_folder_produces_no_config() {+ let root = tmp("flat");+ std::fs::write(root.join("juggernautXL_v9.safetensors"), b"x").unwrap();+ std::fs::create_dir_all(root.join("Text Generation")).unwrap();+ assert!(comfy_shaped_subdirs(&root).is_empty());+ assert!(build_extra_model_paths_yaml(&root).is_none());+ }++ #[test]+ fn yaml_quotes_the_path_and_names_every_folder() {+ let root = tmp("yaml");+ std::fs::create_dir_all(root.join("loras")).unwrap();+ std::fs::create_dir_all(root.join("vae")).unwrap();+ let text = build_extra_model_paths_yaml(&root).unwrap();+ assert!(text.starts_with("# Written by Locally Uncensored"));+ assert!(text.contains("lu_custom_models:\n"));+ assert!(text.contains(&format!(" loras: \"{}\"\n", root.join("loras").display())));+ assert!(text.contains(&format!(" vae: \"{}\"\n", root.join("vae").display())));+ // Every value is quoted, so a Windows `G:\...` cannot be read as YAML.+ for line in text.lines().filter(|l| l.starts_with(" ")) {+ let value = line.split_once(": ").unwrap().1;+ assert!(value.starts_with('"') && value.ends_with('"'), "unquoted: {line}");+ }+ }++ /// Negative control: a missing folder is not an error and not a config.+ #[test]+ fn a_folder_that_is_not_there_yields_nothing() {+ let root = std::env::temp_dir().join("lu-custom-models-tests").join("nope-not-here");+ let _ = std::fs::remove_dir_all(&root);+ assert!(comfy_shaped_subdirs(&root).is_empty());+ assert!(build_extra_model_paths_yaml(&root).is_none());+ }+}diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rsindex 0d649cac..28ec6113 100644--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@ -322,34 +322,62 @@ pub(crate) fn split_shard_stem(stem: &str) -> Option<(&str, u32, u32)> {/// all, so a paused or aborted multi-part download never impersonates an/// installed model (same rule a9ea114 established for MLX downloads).pub(crate) fn scan_gguf_models(dir: &Path) -> Vec<BundledModel> {- let mut out = Vec::new();- // (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,- });+ scan_gguf_roots(&[ScanRoot { dir, max_depth: MAX_SCAN_DEPTH }])+}++/// One folder the GGUF scan walks, and how deep it may go there.+pub(crate) struct ScanRoot<'a> {+ pub dir: &'a Path,+ pub max_depth: usize,+}++/// The same scan over SEVERAL folders, in priority order.+///+/// GH #122 (zrmdsxa, 2026-08-28): the folder the user names under Model+/// Storage was a download target and nothing else. A GGUF that was already+/// sitting in `G:\AI\Models`, or one an earlier LU download had put there,+/// was never looked at, so the Models tab stayed empty and the file could not+/// be loaded at all. The app models dir is root 0 and still wins every name+/// collision, so adding a custom folder can never displace what the app+/// installed itself.+pub(crate) fn scan_gguf_roots(roots: &[ScanRoot]) -> Vec<BundledModel> {+ // (root index, model). The index is the first tie-break below, so an+ // earlier root always wins a duplicate name.+ let mut ranked: Vec<(usize, BundledModel)> = Vec::new();+ for (rank, root) in roots.iter().enumerate() {+ let mut out = Vec::new();+ // (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(root.dir, 0, root.max_depth, &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,+ });+ }}+ ranked.extend(out.into_iter().map(|m| (rank, m)));}- // 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| {+ // A name is the picker id, so it has to be unique. The earlier root wins,+ // then the shallowest copy (the flat app dir is the canonical place);+ // ties fall to the path.+ ranked.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))+ a.1.name+ .cmp(&b.1.name)+ .then(a.0.cmp(&b.0))+ .then(depth(&a.1.path).cmp(&depth(&b.1.path)))+ .then(a.1.path.cmp(&b.1.path))});+ let mut out: Vec<BundledModel> = ranked.into_iter().map(|(_, m)| m).collect();out.dedup_by(|a, b| a.name == b.name);out}@@ -364,11 +392,18 @@ pub(crate) fn scan_gguf_models(dir: &Path) -> Vec<BundledModel> {/// 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;+pub(crate) const MAX_SCAN_DEPTH: usize = 2;++/// How far the scan walks below a folder the USER named under Model Storage.+/// Deeper than the app dir on purpose: a grown model library is filed by hand+/// (`G:\AI\Models\Text Generation\<author>\<repo>\file.gguf` in GH #122's+/// screenshots), and two levels stop one folder short of exactly that.+pub(crate) const MAX_CUSTOM_SCAN_DEPTH: usize = 4;fn scan_gguf_dir(dir: &Path,depth: usize,+ max_depth: usize,out: &mut Vec<BundledModel>,sets: &mut std::collections::HashMap<(PathBuf, String, u32), (Vec<u32>, Option<String>, u64)>,) {@@ -379,8 +414,8 @@ fn scan_gguf_dir(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);+ if depth < max_depth {+ scan_gguf_dir(&path, depth + 1, max_depth, out, sets);}continue;}@@ -1088,23 +1123,61 @@ pub async fn swap_bundled_model(.map_err(|e| format!("Engine swap task failed to run: {e}"))?}-/// List `*.gguf` files in the built-in models dir, marking the one currently-/// loaded. Used by the frontend instead of `/v1/models` (which would only-/// report the single loaded model).+/// Which folders `list_bundled_models` walks, in priority order: the app+/// models dir first, then whatever the user named under Model Storage.+///+/// A blank entry, a duplicate, and the app dir named a second time are all+/// dropped here, so the caller can hand the setting over raw.+pub(crate) fn bundled_scan_dirs(app_dir: &Path, extra: &[String]) -> Vec<PathBuf> {+ let mut out = vec![app_dir.to_path_buf()];+ // Windows paths arrive with a drive letter and backslashes and are+ // compared case-insensitively; `G:\AI\Models` and `g:/ai/models\` are one+ // folder. PathBuf does not know that, so the key is normalised by hand.+ let key = |p: &Path| {+ p.to_string_lossy()+ .replace('\\', "/")+ .trim_end_matches('/')+ .to_lowercase()+ };+ let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();+ seen.insert(key(app_dir));+ for raw in extra {+ let trimmed = raw.trim();+ if trimmed.is_empty() {+ continue;+ }+ let path = PathBuf::from(trimmed);+ if seen.insert(key(&path)) {+ out.push(path);+ }+ }+ out+}++/// List `*.gguf` files in the built-in models dir AND in every folder the user+/// named under Model Storage, marking the one currently loaded. Used by the+/// frontend instead of `/v1/models` (which would only report the single loaded+/// model).// ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread.// The State borrow cannot cross into the blocking pool, so the handle is// re-resolved there from the AppHandle (same pattern as engine.rs/whisper.rs).#[tauri::command]-pub async fn list_bundled_models(app: tauri::AppHandle) -> Result<serde_json::Value, String> {+pub async fn list_bundled_models(+ app: tauri::AppHandle,+ extra_dirs: Option<Vec<String>>,+) -> Result<serde_json::Value, String> {tokio::task::spawn_blocking(move || {let state = app.state::<AppState>();- list_bundled_models_blocking(&state)+ list_bundled_models_blocking(&state, &extra_dirs.unwrap_or_default())}).await.map_err(|e| format!("list_bundled_models task: {e}"))?}-fn list_bundled_models_blocking(state: &AppState) -> Result<serde_json::Value, String> {+fn list_bundled_models_blocking(+ state: &AppState,+ extra_dirs: &[String],+) -> Result<serde_json::Value, String> {let dir = builtin_models_dir()?;let loaded = state.bundled_engine@@ -1112,7 +1185,16 @@ fn list_bundled_models_blocking(state: &AppState) -> Result<serde_json::Value, S.unwrap().as_ref().map(|e| e.model_path.clone());- let models: Vec<serde_json::Value> = scan_gguf_models(&dir)+ let dirs = bundled_scan_dirs(&dir, extra_dirs);+ let roots: Vec<ScanRoot> = dirs+ .iter()+ .enumerate()+ .map(|(i, d)| ScanRoot {+ dir: d.as_path(),+ max_depth: if i == 0 { MAX_SCAN_DEPTH } else { MAX_CUSTOM_SCAN_DEPTH },+ })+ .collect();+ let models: Vec<serde_json::Value> = scan_gguf_roots(&roots).into_iter().map(|m| {let is_loaded = loaded.as_deref() == Some(m.path.as_str());@@ -1132,6 +1214,10 @@ fn list_bundled_models_blocking(state: &AppState) -> Result<serde_json::Value, S.collect();Ok(serde_json::json!({"dir": dir.to_string_lossy(),+ // Every folder that was actually walked, app dir first. The Model+ // Storage panel says which ones those were instead of leaving the+ // user to guess whether his folder was read.+ "dirs": dirs.iter().map(|d| d.to_string_lossy().to_string()).collect::<Vec<_>>(),"models": models,}))}@@ -2027,6 +2113,144 @@ mod tests {std::fs::remove_dir_all(&dir).ok();}+ // ── GH #122: the user's own model folder ───────────────────────────────++ fn scratch(name: &str) -> PathBuf {+ let dir = std::env::temp_dir()+ .join("lu-engine-custom")+ .join(format!("{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ fn roots<'a>(app: &'a Path, custom: &'a Path) -> Vec<ScanRoot<'a>> {+ vec![+ ScanRoot { dir: app, max_depth: MAX_SCAN_DEPTH },+ ScanRoot { dir: custom, max_depth: MAX_CUSTOM_SCAN_DEPTH },+ ]+ }++ #[test]+ fn the_custom_folder_is_read_at_the_depth_a_hand_filed_library_needs() {+ // The two shapes from the issue: the folder itself (`G:\AI\Models`)+ // with the model one level down under `Text Generation`, and a library+ // filed by author and repo below that.+ let app = scratch("app-empty");+ let custom = scratch("custom-deep");+ let one = custom.join("Text Generation");+ std::fs::create_dir_all(&one).unwrap();+ std::fs::write(one.join("Cydonia-24B-v4.1-Q4_K_M.gguf"), b"aaaa").unwrap();+ let four = custom+ .join("Text Generation")+ .join("TheDrummer")+ .join("Cydonia-GGUF");+ std::fs::create_dir_all(&four).unwrap();+ std::fs::write(four.join("Rocinante-12B-Q6_K.gguf"), b"bb").unwrap();++ let models = scan_gguf_roots(&roots(&app, &custom));+ let names: Vec<&str> = models.iter().map(|m| m.name.as_str()).collect();+ assert_eq!(names, vec!["Cydonia-24B-v4.1-Q4_K_M", "Rocinante-12B-Q6_K"]);+ // The path is absolute and points into the user's folder, which is+ // what makes the model loadable: llama-server is started with it.+ assert!(models[0].path.contains("Text Generation"));++ std::fs::remove_dir_all(&app).ok();+ std::fs::remove_dir_all(&custom).ok();+ }++ /// Negative control: without the custom root the same folder produces+ /// nothing at all. This is the shipped behaviour GH #122 reported.+ #[test]+ fn without_the_custom_root_the_same_folder_stays_invisible() {+ let app = scratch("app-empty-neg");+ let custom = scratch("custom-neg");+ let one = custom.join("Text Generation");+ std::fs::create_dir_all(&one).unwrap();+ std::fs::write(one.join("Cydonia-24B-v4.1-Q4_K_M.gguf"), b"aaaa").unwrap();++ assert!(scan_gguf_models(&app).is_empty());++ std::fs::remove_dir_all(&app).ok();+ std::fs::remove_dir_all(&custom).ok();+ }++ #[test]+ fn the_app_folder_wins_a_duplicate_name_even_when_it_lies_deeper() {+ let app = scratch("app-dup");+ let custom = scratch("custom-dup");+ let nested = app.join("user").join("repo");+ std::fs::create_dir_all(&nested).unwrap();+ std::fs::write(nested.join("dup.gguf"), b"a").unwrap();+ std::fs::write(custom.join("dup.gguf"), b"bb").unwrap();++ let models = scan_gguf_roots(&roots(&app, &custom));+ assert_eq!(models.len(), 1, "one id per name");+ assert!(+ models[0].path.contains("app-dup"),+ "the app copy must win: {}",+ models[0].path+ );++ std::fs::remove_dir_all(&app).ok();+ std::fs::remove_dir_all(&custom).ok();+ }++ #[test]+ fn a_split_set_in_the_custom_folder_is_one_entry_and_an_incomplete_one_is_none() {+ let app = scratch("app-shards");+ let custom = scratch("custom-shards");+ std::fs::write(custom.join("Big-00001-of-00002.gguf"), b"a").unwrap();+ std::fs::write(custom.join("Big-00002-of-00002.gguf"), b"bb").unwrap();+ // Negative control in the same folder: a set missing part 2 is not a+ // model and must not be offered.+ std::fs::write(custom.join("Half-00001-of-00003.gguf"), b"c").unwrap();++ let models = scan_gguf_roots(&roots(&app, &custom));+ let names: Vec<&str> = models.iter().map(|m| m.name.as_str()).collect();+ assert_eq!(names, vec!["Big"]);+ assert_eq!(models[0].size, 3, "the set weighs both parts");++ std::fs::remove_dir_all(&app).ok();+ std::fs::remove_dir_all(&custom).ok();+ }++ #[test]+ fn the_scan_list_drops_blanks_duplicates_and_the_app_dir_named_again() {+ let app = Path::new("/data/Locally Uncensored/models");+ let dirs = bundled_scan_dirs(+ app,+ &[+ " ".to_string(),+ "G:\\AI\\Models".to_string(),+ // The same folder written the other way round: one entry.+ "g:/ai/models/".to_string(),+ "/data/Locally Uncensored/models".to_string(),+ "/mnt/second".to_string(),+ ],+ );+ assert_eq!(+ dirs,+ vec![+ PathBuf::from("/data/Locally Uncensored/models"),+ PathBuf::from("G:\\AI\\Models"),+ PathBuf::from("/mnt/second"),+ ],+ );+ }++ /// Negative control: no custom folder set leaves the list exactly as it+ /// shipped, one root.+ #[test]+ fn no_custom_folder_leaves_one_root() {+ let app = Path::new("/data/Locally Uncensored/models");+ assert_eq!(bundled_scan_dirs(app, &[]), vec![PathBuf::from(app)]);+ assert_eq!(+ bundled_scan_dirs(app, &["".to_string(), " ".to_string()]),+ vec![PathBuf::from(app)],+ );+ }+/// 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;diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 5f7bf3b5..47b0d154 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -2,6 +2,7 @@ pub mod agent;pub mod bg_tasks;pub mod repo_map;pub mod comfy_ws;+pub mod custom_models;pub mod download;pub mod engine;pub mod filesystem;diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rsindex ffb2c065..8e378b87 100644--- a/src-tauri/src/commands/process.rs+++ b/src-tauri/src/commands/process.rs@@ -1468,6 +1468,19 @@ fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String>comfy_args.push("--use-flash-attention");println!("[ComfyUI] flash-attn detected in {} — enabling Flash Attention", python);}+ // The folder under Settings -> Model Storage, when it holds ComfyUI-shaped+ // subfolders (GH #122). ComfyUI lists only what sits under its own models+ // tree, so its own extra-model-paths mechanism is the way a LoRA on+ // another drive becomes visible and loadable. Our own file, passed by+ // flag: a hand written extra_model_paths.yaml in the ComfyUI folder is+ // never read, written or overwritten by us.+ let extra_paths_file = crate::commands::custom_models::extra_model_paths_arg()+ .map(|p| p.to_string_lossy().to_string());+ if let Some(file) = &extra_paths_file {+ comfy_args.push("--extra-model-paths-config");+ comfy_args.push(file);+ println!("[ComfyUI] Extra model paths: {}", file);+ }let mut cmd = Command::new(&python);cmd.args(&comfy_args).current_dir(&comfy_path)diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 62116802..a91aaa4a 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -280,6 +280,8 @@ fn main() {commands::engine::swap_bundled_model,commands::engine::list_bundled_models,commands::engine::list_importable_models,+ // The user's own model folder, handed to ComfyUI (GH #122)+ commands::custom_models::sync_custom_model_paths,commands::engine::import_local_model,// Built-in embeddings server (bundled llama-server --embeddings, P5)commands::engine::start_bundled_embed,diff --git a/src/api/__tests__/custom-model-folder.test.ts b/src/api/__tests__/custom-model-folder.test.tsnew file mode 100644index 00000000..bf58c967--- /dev/null+++ b/src/api/__tests__/custom-model-folder.test.ts@@ -0,0 +1,111 @@+/**+ * GH #122 (zrmdsxa, 2026-08-28): "Custom location not detecting my models".+ *+ * The folder under Settings → Model Storage was a download TARGET and nothing+ * else. `hfDownloadPathOverride` was read by the downloader and by onboarding,+ * and by no scan anywhere, so a GGUF already sitting in `G:\AI\Models` was+ * never looked at: Models tab empty, model not loadable, no way to tell why.+ *+ * What is proven here is the frontend half: the setting reaches the scan, in+ * the shape Windows writes it, and a model that comes back from the folder+ * becomes an Installed row the picker can load. The scan itself, its depth and+ * its precedence rules are proven in Rust+ * (`src-tauri/src/commands/engine.rs`, tests `the_custom_folder_is_read_…`).+ *+ * Run: npx vitest run src/api/__tests__/custom-model-folder.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'++const backendCall = vi.fn()+vi.mock('../backend', () => ({+ backendCall: (...args: unknown[]) => backendCall(...args),+ isTauri: () => true,+ isMacOS: () => false,+}))++import { customModelDirs, listBundledModels, bundledToAIModels } from '../engine'+import { useSettingsStore } from '../../stores/settingsStore'+import { DEFAULT_SETTINGS } from '../../lib/constants'++/** The path exactly as Windows hands it over: drive letter, backslashes,+ * a space in a folder name. All three were in the issue's screenshots. */+const WINDOWS_FOLDER = 'G:\\AI\\Models'++function setFolder(dir: string) {+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, hfDownloadPathOverride: dir } })+}++beforeEach(() => {+ backendCall.mockReset()+ setFolder('')+})++describe('the folder under Model Storage reaches the scan', () => {+ it('hands the Windows path to the backend, verbatim', async () => {+ setFolder(WINDOWS_FOLDER)+ expect(customModelDirs()).toEqual([WINDOWS_FOLDER])++ backendCall.mockResolvedValue({ dir: '/app/models', dirs: ['/app/models', WINDOWS_FOLDER], models: [] })+ await listBundledModels()++ expect(backendCall).toHaveBeenCalledWith('list_bundled_models', {+ extraDirs: [WINDOWS_FOLDER],+ })+ })++ it('trims what the user typed, because a trailing space is not a folder', () => {+ setFolder(' G:\\AI\\Models ')+ expect(customModelDirs()).toEqual([WINDOWS_FOLDER])+ })++ // Negative control: with no folder set, nothing extra is scanned. This is+ // the shipped single-folder behaviour and it must not change for the users+ // who never touched the setting.+ it('asks for no extra folder when the setting is empty', async () => {+ expect(customModelDirs()).toEqual([])+ setFolder(' ')+ expect(customModelDirs()).toEqual([])++ backendCall.mockResolvedValue({ dir: '/app/models', models: [] })+ await listBundledModels()+ expect(backendCall).toHaveBeenCalledWith('list_bundled_models', { extraDirs: [] })+ })+})++describe('a model found in that folder is an Installed row', () => {+ it('carries the folder path through to a loadable picker entry', async () => {+ setFolder(WINDOWS_FOLDER)+ backendCall.mockResolvedValue({+ dir: '/app/models',+ dirs: ['/app/models', WINDOWS_FOLDER],+ models: [+ {+ name: 'Cydonia-24B-v4.1-Q4_K_M',+ path: 'G:\\AI\\Models\\Text Generation\\Cydonia-24B-v4.1-Q4_K_M.gguf',+ size: 14_000_000_000,+ loaded: false,+ ctx_train: 32768,+ },+ ],+ })++ const bundled = await listBundledModels()+ expect(bundled).toHaveLength(1)+ // The absolute path is what makes it loadable: the engine is started with+ // it, so a model on another drive works exactly like one in the app dir.+ expect(bundled[0].path).toContain('G:\\AI\\Models')++ const rows = bundledToAIModels(bundled)+ expect(rows).toHaveLength(1)+ expect(rows[0].name).toBe('openai::Cydonia-24B-v4.1-Q4_K_M')+ expect(rows[0].providerName).toBe('Built-in Engine')+ expect(rows[0].size).toBe(14_000_000_000)+ })++ // Negative control: an empty folder is an empty list, not an invented row.+ it('invents nothing when the folder holds no GGUF', async () => {+ setFolder(WINDOWS_FOLDER)+ backendCall.mockResolvedValue({ dir: '/app/models', dirs: ['/app/models', WINDOWS_FOLDER], models: [] })+ expect(bundledToAIModels(await listBundledModels())).toEqual([])+ })+})diff --git a/src/api/__tests__/engine.test.ts b/src/api/__tests__/engine.test.tsindex bd787c1e..2367ed03 100644--- a/src/api/__tests__/engine.test.ts+++ b/src/api/__tests__/engine.test.ts@@ -85,7 +85,7 @@ describe('engine command wrappers', () => {models: [{ name: 'qwen', path: '/data/models/qwen.gguf', size: 400, loaded: true }],} as never)const models = await listBundledModels()- expect(backendCall).toHaveBeenCalledWith('list_bundled_models')+ expect(backendCall).toHaveBeenCalledWith('list_bundled_models', { extraDirs: [] })expect(models).toHaveLength(1)expect(models[0].name).toBe('qwen')})@@ -176,7 +176,7 @@ describe('activateBuiltinModel', () => {// store chokepoint), so ONE refresh is expected — but never a swap for a// name that stays unknown.expect(backendCall).toHaveBeenCalledTimes(1)- expect(backendCall).toHaveBeenCalledWith('list_bundled_models')+ expect(backendCall).toHaveBeenCalledWith('list_bundled_models', { extraDirs: [] })expect(backendCall).not.toHaveBeenCalledWith('swap_bundled_model', expect.anything())})})diff --git a/src/api/engine.ts b/src/api/engine.tsindex 1a108157..8504bb3b 100644--- a/src/api/engine.ts+++ b/src/api/engine.ts@@ -203,9 +203,27 @@ export async function bundledEmbedLaneReady(): Promise<boolean> {}}-/** List downloaded GGUFs in the app models dir. Refreshes the name→path map. */+/**+ * Every folder the GGUF scan walks: the app models dir (Rust adds that one)+ * plus the folder the user named under Settings → Model Storage.+ *+ * GH #122 (zrmdsxa, 2026-08-28): that setting was a download TARGET and+ * nothing else. A GGUF already sitting in it was never looked at, so the+ * Models tab stayed empty next to a folder full of models. Empty setting →+ * empty list, which is exactly the shipped single-folder scan.+ */+export function customModelDirs(): string[] {+ const dir = useSettingsStore.getState().settings.hfDownloadPathOverride?.trim() || ''+ return dir ? [dir] : []+}++/** List downloaded GGUFs in the app models dir and in the user's own model+ * folder. Refreshes the name→path map. */export async function listBundledModels(): Promise<BundledModel[]> {- const res = await backendCall<{ dir: string; models: BundledModel[] }>('list_bundled_models')+ const res = await backendCall<{ dir: string; dirs?: string[]; models: BundledModel[] }>(+ 'list_bundled_models',+ { extraDirs: customModelDirs() },+ )const models = res?.models ?? []pathByName.clear()ctxTrainByName.clear()diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 3f483917..0ba86715 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -63,6 +63,7 @@ import { isMlxImageHost } from '../../api/mlx-image'import { ArrowUpCircle, KeyRound, RefreshCw } from 'lucide-react'import { CLOUD_BASE } from '../../api/cloud/config'import { formatBytes } from '../../lib/formatters'+import { syncCustomModelDir } from '../../lib/custom-model-dir'// ── User profile picture (Appearance) ───────────────────────────// Self-contained like HfDownloadPathSetting. Stores the picture as a@@ -252,33 +253,59 @@ function WorkflowSection() {)}-// ── Model Storage (HF GGUF download path override) ─────────────+// ── Model Storage (the user's own model folder) ─────────────────+//+// GH #122 (zrmdsxa) + Discord "Read me first" (ever.noob): this folder was a+// download TARGET and nothing else. Models already sitting in it were never+// looked at, and the copy above the field said nothing about that, so the+// Models tab stayed empty beside a folder full of models. It is read now+// (lib/custom-model-dir.ts), and the copy says what it does.function HfDownloadPathSetting() {const override = useSettingsStore(s => s.settings.hfDownloadPathOverride)const updateSettings = useSettingsStore(s => s.updateSettings)const [draft, setDraft] = useState(override)+ const [comfyFolders, setComfyFolders] = useState<string[] | null>(null)useEffect(() => { setDraft(override) }, [override])+ // Both directions of the folder: our own GGUF scan reads it on the next+ // model refresh, and the ComfyUI-shaped subfolders in it are handed to+ // ComfyUI. Runs on mount too, so a folder set by an older build reaches+ // ComfyUI without the user having to touch the field again.+ useEffect(() => {+ let alive = true+ void syncCustomModelDir(override).then((folders) => { if (alive) setComfyFolders(folders) })+ return () => { alive = false }+ }, [override])++ function apply(next: string) {+ setDraft(next)+ updateSettings({ hfDownloadPathOverride: next })+ // The Models tab is the surface this setting is about: refresh it now+ // instead of after the next navigation.+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))+ }+async function pickFolder() {try {const chosen = await backendCall<string | null>('pick_folder')- if (chosen) { setDraft(chosen); updateSettings({ hfDownloadPathOverride: chosen }) }+ if (chosen) apply(chosen)} catch {}}return (<div className="space-y-2 py-1"><div className="text-[0.6rem] text-gray-500 leading-relaxed">- Custom location for downloaded GGUFs. Leave empty to auto-detect from your active provider's models folder (e.g. <code className="font-mono">~/.lmstudio/models</code> for LM Studio). Ollama is unaffected, it manages its own blob store; LU pulls Ollama models via <code className="font-mono">ollama pull</code> regardless of this setting.+ Your own model folder. LU downloads GGUFs here, and it also reads this folder: every <code className="font-mono">.gguf</code> in it, up to four levels down, is listed under Installed and can be loaded straight from there. Leave empty to auto-detect from your active provider's models folder (e.g. <code className="font-mono">~/.lmstudio/models</code> for LM Studio). Ollama is unaffected, it manages its own blob store; LU pulls Ollama models via <code className="font-mono">ollama pull</code> regardless of this setting.</div><div className="flex items-center gap-2"><inputtype="text"value={draft}onChange={(e) => setDraft(e.target.value)}- onBlur={() => updateSettings({ hfDownloadPathOverride: draft.trim() })}+ onBlur={() => apply(draft.trim())}placeholder="(auto-detect)"+ aria-label="Your own model folder"className="flex-1 px-2 py-1 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-700 dark:text-gray-300 font-mono focus:outline-none focus:border-white/20"/><button@@ -289,13 +316,23 @@ function HfDownloadPathSetting() {</button>{override && (<button- onClick={() => { setDraft(''); updateSettings({ hfDownloadPathOverride: '' }) }}+ onClick={() => apply('')}className="px-2.5 py-1 rounded-md text-[0.6rem] text-gray-500 hover:text-red-400 transition-colors">Reset</button>)}</div>+ {/* Image and video models are a different question and the text says so+ rather than implying the folder covers them: that inventory comes out+ of ComfyUI's own lists, so LU can only hand ComfyUI the folder. */}+ {override && comfyFolders !== null && (+ <div className="text-[0.6rem] text-gray-500 leading-relaxed">+ {comfyFolders.length > 0+ ? <>Image and video: LU passes <code className="font-mono">{comfyFolders.join(', ')}</code> from this folder to ComfyUI. Takes effect the next time LU starts ComfyUI, and only for a ComfyUI that LU starts.</>+ : <>Image and video models in this folder stay invisible: ComfyUI lists only its own folders. Name the subfolders like ComfyUI does (<code className="font-mono">checkpoints</code>, <code className="font-mono">loras</code>, <code className="font-mono">vae</code>, …) and LU hands them over.</>}+ </div>+ )}</div>)}diff --git a/src/lib/__tests__/custom-model-dir-comfy.test.ts b/src/lib/__tests__/custom-model-dir-comfy.test.tsnew file mode 100644index 00000000..13ad8efb--- /dev/null+++ b/src/lib/__tests__/custom-model-dir-comfy.test.ts@@ -0,0 +1,113 @@+/**+ * The second half of GH #122, and the Discord thread "Read me first"+ * (ever.noob, 2026-08-28): LoRAs the user dropped into a folder of his own+ * stayed invisible.+ *+ * LU never scans image or video models off the disk, that inventory comes out+ * of ComfyUI's own `/object_info` enums, and ComfyUI lists only what sits under+ * its own models tree. So there is nothing for LU to scan here and no honest+ * way to call such a file Installed; the fix is to hand the folder to ComfyUI+ * through ComfyUI's own extra-model-paths mechanism. Which subfolders qualify,+ * and the fact that a flat folder qualifies for none, is proven in Rust+ * (`src-tauri/src/commands/custom_models.rs`). This file proves the handover+ * is wired and that the Settings copy no longer claims more than it does.+ *+ * Run: npx vitest run src/lib/__tests__/custom-model-dir-comfy.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { readFileSync } from 'fs'+import { join } from 'path'++const backendCall = vi.fn()+vi.mock('../../api/backend', () => ({+ backendCall: (...args: unknown[]) => backendCall(...args),+ isTauri: () => true,+ isMacOS: () => false,+}))++import { syncCustomModelDir } from '../custom-model-dir'++beforeEach(() => { backendCall.mockReset() })++describe('handing the folder to ComfyUI', () => {+ it('names the folder and reports back what ComfyUI will get', async () => {+ backendCall.mockResolvedValue({ written: true, file: '/data/lu_extra_model_paths.yaml', folders: ['loras', 'vae'] })+ const folders = await syncCustomModelDir(' G:\\AI\\Models ')+ expect(backendCall).toHaveBeenCalledWith('sync_custom_model_paths', { dir: 'G:\\AI\\Models' })+ expect(folders).toEqual(['loras', 'vae'])+ })++ it('clears the registration when the folder is unset', async () => {+ backendCall.mockResolvedValue({ written: false, file: '/data/lu_extra_model_paths.yaml', folders: [] })+ expect(await syncCustomModelDir('')).toEqual([])+ expect(backendCall).toHaveBeenCalledWith('sync_custom_model_paths', { dir: '' })+ expect(await syncCustomModelDir(null)).toEqual([])+ })++ // Negative control: an older backend that does not know the command, or a+ // drive that went away, costs the handover and NOTHING else. The GGUF scan+ // is a separate path and must keep working.+ it('stays quiet when the backend cannot do it', async () => {+ backendCall.mockRejectedValue(new Error('Unknown backend command: sync_custom_model_paths'))+ await expect(syncCustomModelDir('G:\\AI\\Models')).resolves.toEqual([])+ })+})++describe('the Model Storage copy tells the truth', () => {+ const src = readFileSync(+ join(process.cwd(), 'src/components/settings/SettingsPage.tsx'),+ 'utf8',+ )++ it('says the folder is read, not only written to', () => {+ // The shipped sentence started "Custom location for downloaded GGUFs" and+ // stopped there, which is why two users concluded the setting was broken+ // rather than one-directional.+ expect(src).toMatch(/it also reads this folder/)+ expect(src).toMatch(/listed under Installed/)+ })++ it('is honest that image and video go through ComfyUI', () => {+ expect(src).toMatch(/passes <code className="font-mono">\{comfyFolders\.join/)+ expect(src).toMatch(/only for a ComfyUI that LU starts/)+ // And says plainly what happens when the folder is not ComfyUI-shaped,+ // instead of leaving a silent no-op behind.+ expect(src).toMatch(/stay invisible/)+ })++ it('hands the folder over whenever the setting changes', () => {+ expect(src).toMatch(/syncCustomModelDir\(override\)/)+ })++ // Negative control: the old text must be gone, or the honest sentence would+ // just sit next to the misleading one.+ it('no longer calls the folder a download target and nothing else', () => {+ expect(src).not.toMatch(/Custom location for downloaded GGUFs\./)+ })+})++describe('the folder names Rust looks for are the folders ComfyUI uses', () => {+ it('matches subfolderForSource, so the two lists cannot drift apart', () => {+ const rust = readFileSync(+ join(process.cwd(), 'src-tauri/src/commands/custom_models.rs'),+ 'utf8',+ )+ const block = rust.split('COMFY_MODEL_FOLDERS: &[&str] = &[')[1].split('];')[0]+ const rustFolders = new Set([...block.matchAll(/"([a-z_]+)"/g)].map((m) => m[1]))++ const ts = readFileSync(join(process.cwd(), 'src/api/comfyui.ts'), 'utf8')+ const fn = ts.split('export function subfolderForSource')[1].split('\n}')[0]+ const tsFolders = [...fn.matchAll(/return '([^']+)'/g)]+ .map((m) => m[1])+ // The AnimateDiff motion modules live under custom_nodes, which is not a+ // folder_paths key and cannot be mapped this way.+ .filter((f) => !f.includes('/'))++ for (const folder of tsFolders) {+ expect(rustFolders.has(folder), `${folder} is a ComfyUI models folder Rust does not map`).toBe(true)+ }+ // Negative control: a folder name that ComfyUI has no key for must not be+ // in the Rust list either.+ expect(rustFolders.has('custom_nodes')).toBe(false)+ })+})diff --git a/src/lib/custom-model-dir.ts b/src/lib/custom-model-dir.tsnew file mode 100644index 00000000..6dfd4f90--- /dev/null+++ b/src/lib/custom-model-dir.ts@@ -0,0 +1,46 @@+/**+ * The folder under Settings → Model Storage, handed to ComfyUI.+ *+ * GH #122 (zrmdsxa) and the Discord thread "Read me first" (ever.noob) are one+ * folder apart: a chat GGUF in a folder of your own, and a LoRA in one. The+ * GGUF side is ours: `list_bundled_models` scans the folder now. The LoRA+ * side is not: LU never reads image or video models off the disk, that+ * inventory comes out of ComfyUI's `/object_info` enums, and ComfyUI lists+ * only what sits under its own models tree.+ *+ * So this is the handover. Rust writes ComfyUI's own extra-model-paths file+ * for the ComfyUI-shaped subfolders it finds and passes it at start; a+ * hand written `extra_model_paths.yaml` in the user's ComfyUI folder is never+ * touched. Two limits are real and the Settings copy names both: a ComfyUI+ * that LU starts, and the next start of it.+ */++import { backendCall } from '../api/backend'+import { log } from './logger'++export interface CustomModelPathSync {+ written: boolean+ file: string+ /** ComfyUI folder names found in the folder, e.g. `['loras', 'vae']`. */+ folders: string[]+}++/**+ * Register (or clear) the folder with ComfyUI. Returns the folder names that+ * were handed over, `[]` when there were none.+ *+ * Never throws: an older backend without the command, or a folder that has+ * gone away with the drive it lived on, costs the handover and nothing else.+ * The GGUF scan is a separate path and keeps working either way.+ */+export async function syncCustomModelDir(dir: string | undefined | null): Promise<string[]> {+ try {+ const res = await backendCall<CustomModelPathSync>('sync_custom_model_paths', {+ dir: (dir ?? '').trim(),+ })+ return res?.folders ?? []+ } catch (err) {+ log.warn('[models] custom model folder not handed to ComfyUI', { err })+ return []+ }+}