Skip to content

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

fix(models): der YAML-Pfad zerlegte ComfyUI, und der Sync hing am Hauptthread

purple4d6973c3caf7
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 1831334c..2ed31ad3 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2565,6 +2565,7 @@ dependencies = [
"rfd",
"serde",
"serde_json",
+ "serde_yaml",
"sha2",
"socket2 0.5.10",
"sysinfo",
@@ -4515,6 +4516,19 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "serde_yaml"
+version = "0.9.34+deprecated"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
+dependencies = [
+ "indexmap 2.13.0",
+ "itoa",
+ "ryu",
+ "serde",
+ "unsafe-libyaml",
+]
+
[[package]]
name = "serialize-to-javascript"
version = "0.1.2"
@@ -5875,6 +5889,12 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+[[package]]
+name = "unsafe-libyaml"
+version = "0.2.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
+
[[package]]
name = "untrusted"
version = "0.9.0"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index da73307d..ad9c1f84 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -89,3 +89,6 @@ codegen-units = 1
lto = true
opt-level = "s"
strip = true
+
+[dev-dependencies]
+serde_yaml = "0.9.34"
diff --git a/src-tauri/src/commands/custom_models.rs b/src-tauri/src/commands/custom_models.rs
index cfe0bae5..d7e660f0 100644
--- a/src-tauri/src/commands/custom_models.rs
+++ b/src-tauri/src/commands/custom_models.rs
@@ -60,14 +60,22 @@ pub(crate) fn comfy_shaped_subdirs(root: &Path) -> Vec<(&'static str, PathBuf)>
/// 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.
+/// SINGLE quotes, and every `'` inside the path doubled. A double-quoted YAML
+/// scalar treats the backslash as an escape character, so a Windows path is not
+/// a string there at all: PyYAML reads `"G:\AI\Models\loras"` as
+/// `unknown escape character 'A'` and `"D:\text_encoders"` as `D:<TAB>ext_...`.
+/// ComfyUI's `load_extra_path_config` runs without a try/except, so a file like
+/// that does not cost the folder mapping, it costs ComfyUI: the Windows user
+/// this whole fix exists for would have been left without one. A single-quoted
+/// scalar has no escapes at all, which is exactly what a path needs.
+///
+/// A path carrying a line break or another control character is dropped instead
+/// of quoted. No model folder has one, and a broken line would take the other
+/// folders in the file down 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('"'))
+ .filter(|(_, p)| !p.to_string_lossy().chars().any(|c| c.is_control()))
.collect();
if found.is_empty() {
return None;
@@ -78,11 +86,22 @@ pub(crate) fn build_extra_model_paths_yaml(root: &Path) -> Option<String> {
lu_custom_models:\n",
);
for (key, path) in found {
- s.push_str(&format!(" {}: \"{}\"\n", key, path.to_string_lossy()));
+ s.push_str(&yaml_path_line(key, &path));
}
Some(s)
}
+/// One `key: path` line. The single place the quoting rule above lives, so a
+/// test can hold a literal Windows path against the SHIPPED formatting instead
+/// of against a copy of it.
+pub(crate) fn yaml_path_line(key: &str, path: &Path) -> String {
+ format!(
+ " {}: '{}'\n",
+ key,
+ path.to_string_lossy().replace('\'', "''")
+ )
+}
+
/// 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> {
@@ -107,45 +126,114 @@ pub fn extra_model_paths_arg() -> Option<PathBuf> {
}
}
+/// Is this a path we can even ask the file system about?
+///
+/// A relative path would resolve against whatever the app's working directory
+/// happens to be, and `~/models` is a shell convention the OS does not expand.
+/// Both used to produce silence: no folders, no file, no word about it.
+pub(crate) fn is_usable_root(root: &Path) -> bool {
+ !root.as_os_str().is_empty() && root.is_absolute()
+}
+
+/// One syscall that answers "is the folder there and readable" before the
+/// per-key stats run. On a dead network drive every stat blocks for the SMB
+/// timeout, so asking twenty times what one call already answered is twenty
+/// times the wait.
+pub(crate) fn root_reachable(root: &Path) -> bool {
+ std::fs::read_dir(root).is_ok()
+}
+
+/// What the folder is currently worth to ComfyUI.
+pub(crate) fn folder_status(root: &Path) -> &'static str {
+ if !is_usable_root(root) {
+ "unusable"
+ } else if !root_reachable(root) {
+ "unreachable"
+ } else {
+ "ok"
+ }
+}
+
/// 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.
+/// ASYNC + spawn_blocking, like `list_bundled_models`: a synchronous Tauri
+/// command runs on the MAIN thread, and this one stats a path the user chose.
+/// Point it at a network drive that went away and the whole window freezes
+/// until the mount times out. Same pattern, same reason.
#[tauri::command]
-pub fn sync_custom_model_paths(dir: Option<String>) -> Result<serde_json::Value, String> {
+pub async fn sync_custom_model_paths(dir: Option<String>) -> Result<serde_json::Value, String> {
+ tokio::task::spawn_blocking(move || sync_custom_model_paths_blocking(dir.as_deref()))
+ .await
+ .map_err(|e| format!("sync_custom_model_paths task: {e}"))?
+}
+
+/// Reports what it did, so the Settings panel can name the folders it found,
+/// or say why there were none, instead of claiming a success the user cannot
+/// check.
+pub(crate) fn sync_custom_model_paths_blocking(
+ dir: Option<&str>,
+) -> 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()
+ // The Mac runs local media on MLX and never starts ComfyUI
+ // (process::comfy_supported_here), so there is nobody to hand the folder
+ // to. Say that instead of writing a file no process will ever open, and
+ // clear one an earlier build may have left behind.
+ if !crate::commands::process::comfy_supported_here() {
+ let mut res = sync_custom_model_paths_to(&file, None)?;
+ res["status"] = serde_json::json!("unsupported");
+ return Ok(res);
+ }
+ sync_custom_model_paths_to(&file, dir)
+}
+
+/// The same work against a named file. The target is a parameter so the tests
+/// write into a temp file of their own: the real one lives in the app data dir
+/// and belongs to the installed app, not to a test run.
+pub(crate) fn sync_custom_model_paths_to(
+ file: &Path,
+ dir: Option<&str>,
+) -> Result<serde_json::Value, String> {
+ let trimmed = dir.unwrap_or("").trim().to_string();
+ let (status, folders, yaml) = if trimmed.is_empty() {
+ ("off", Vec::new(), None)
} else {
- comfy_shaped_subdirs(Path::new(&trimmed))
- .into_iter()
- .map(|(k, _)| k.to_string())
- .collect()
+ let root = Path::new(&trimmed);
+ match folder_status(root) {
+ "ok" => {
+ let found = comfy_shaped_subdirs(root);
+ let names: Vec<String> = found.iter().map(|(k, _)| k.to_string()).collect();
+ let yaml = build_extra_model_paths_yaml(root);
+ // The names come from the same walk that produced the file, so
+ // a folder that was dropped for an unquotable path can never be
+ // reported as handed over.
+ let names = if yaml.is_some() { names } else { Vec::new() };
+ ("ok", names, yaml)
+ }
+ other => (other, Vec::new(), None),
+ }
};
- match yaml {
+ match &yaml {
Some(text) => {
- std::fs::write(&file, 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.
+ // A folder that stopped being ComfyUI-shaped, or that went away
+ // with its drive, must not keep feeding ComfyUI the old paths.
if file.exists() {
- std::fs::remove_file(&file).map_err(|e| {
+ 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(),
+ // True only when a file is on disk for ComfyUI to read. It used to be
+ // derived from the folder list, which said "written" for a folder whose
+ // only mappable path had been dropped.
+ "written": yaml.is_some(),
+ "status": status,
"file": file.to_string_lossy(),
"folders": folders,
}))
@@ -199,21 +287,168 @@ mod tests {
assert!(build_extra_model_paths_yaml(&root).is_none());
}
+ /// The bug this file exists to avoid, held against a real YAML parser
+ /// rather than against a count of quote characters.
+ ///
+ /// A double-quoted YAML scalar treats the backslash as an escape, so the
+ /// shipped writer produced a file PyYAML refuses: `unknown escape
+ /// character 'A'` for `G:\AI\...`, and a silent `D:<TAB>ext_encoders` for
+ /// `D:\text_encoders`. ComfyUI reads that file without a try/except, so the
+ /// Windows user this fix is for would have lost ComfyUI itself.
+ #[test]
+ fn a_literal_windows_path_survives_a_real_yaml_parser() {
+ for raw in [
+ r"G:\AI\Models",
+ r"C:\Users\bob\models",
+ r"D:",
+ // The apostrophe is the one character a single-quoted scalar has to
+ // handle, and a real folder can carry one.
+ r"E:\Bob's Models",
+ ] {
+ let root = PathBuf::from(raw);
+ // The folders are built by hand here: these paths do not exist on
+ // the machine running the test, and the question is the QUOTING.
+ let found = vec![
+ ("loras", root.join("loras")),
+ ("text_encoders", root.join("text_encoders")),
+ ("vae", root.join("vae")),
+ ];
+ let mut yaml = String::from("lu_custom_models:\n");
+ for (key, path) in &found {
+ yaml.push_str(&yaml_path_line(key, path));
+ }
+
+ let parsed: serde_yaml::Value =
+ serde_yaml::from_str(&yaml).unwrap_or_else(|e| panic!("{raw}: {e}\n{yaml}"));
+ let block = parsed.get("lu_custom_models").expect("block missing");
+ for (key, path) in &found {
+ let got = block.get(*key).and_then(|v| v.as_str()).unwrap_or("");
+ assert_eq!(
+ got,
+ path.to_string_lossy(),
+ "{raw}: {key} came back mangled",
+ );
+ }
+ }
+ }
+
+ /// Negative control for the same parser: the shipped double-quoted form is
+ /// genuinely broken, so the test above is not passing by accident.
#[test]
- fn yaml_quotes_the_path_and_names_every_folder() {
+ fn the_old_double_quoted_form_would_have_broken_comfyui() {
+ let broken = "lu_custom_models:\n loras: \"G:\\AI\\Models\\loras\"\n";
+ assert!(
+ serde_yaml::from_str::<serde_yaml::Value>(broken).is_err(),
+ "a double-quoted Windows path must not parse: {broken}",
+ );
+ // And the quieter half: this one parses, into the wrong string.
+ let silent = "lu_custom_models:\n text_encoders: \"D:\\text_encoders\"\n";
+ let parsed: serde_yaml::Value = serde_yaml::from_str(silent).expect("parses");
+ let got = parsed["lu_custom_models"]["text_encoders"].as_str().unwrap();
+ assert_ne!(got, r"D:\text_encoders");
+ assert!(got.contains('\t'), "the \\t escape ate the folder name: {got:?}");
+ }
+
+ #[test]
+ fn the_generated_file_parses_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}");
- }
+
+ let parsed: serde_yaml::Value = serde_yaml::from_str(&text).expect("must parse");
+ let block = &parsed["lu_custom_models"];
+ assert_eq!(block["loras"].as_str().unwrap(), root.join("loras").to_string_lossy());
+ assert_eq!(block["vae"].as_str().unwrap(), root.join("vae").to_string_lossy());
+ }
+
+ // ── The folder the user typed, before any stat ────────────────────────
+
+ #[test]
+ fn a_relative_path_or_a_tilde_is_refused_instead_of_silently_doing_nothing() {
+ assert!(!is_usable_root(Path::new("models")));
+ assert!(!is_usable_root(Path::new("../models")));
+ assert!(!is_usable_root(Path::new("~/models")));
+ assert!(!is_usable_root(Path::new("")));
+ assert_eq!(folder_status(Path::new("~/models")), "unusable");
+ }
+
+ /// Negative control: a real absolute folder is usable and reachable, so the
+ /// guard above cannot be refusing everything.
+ #[test]
+ fn a_real_absolute_folder_passes_both_guards() {
+ let root = tmp("guards");
+ assert!(is_usable_root(&root));
+ assert!(root_reachable(&root));
+ assert_eq!(folder_status(&root), "ok");
+ }
+
+ #[test]
+ fn a_folder_that_is_gone_reads_as_unreachable_not_as_empty() {
+ let root = tmp("vanished");
+ std::fs::remove_dir_all(&root).unwrap();
+ assert!(is_usable_root(&root));
+ assert!(!root_reachable(&root));
+ assert_eq!(folder_status(&root), "unreachable");
+ }
+
+ // ── What the Settings panel is told ───────────────────────────────────
+
+ #[test]
+ fn the_sync_reports_the_folders_it_wrote_and_says_written_only_then() {
+ let root = tmp("sync-ok");
+ std::fs::create_dir_all(root.join("loras")).unwrap();
+ let file = tmp("sync-ok-out").join("lu_extra_model_paths.yaml");
+ let res = sync_custom_model_paths_to(&file, Some(root.to_str().unwrap())).unwrap();
+ assert_eq!(res["status"], "ok");
+ assert_eq!(res["written"], true);
+ assert_eq!(res["folders"][0], "loras");
+ let on_disk = std::fs::read_to_string(&file).unwrap();
+ let parsed: serde_yaml::Value = serde_yaml::from_str(&on_disk).expect("must parse");
+ assert_eq!(
+ parsed["lu_custom_models"]["loras"].as_str().unwrap(),
+ root.join("loras").to_string_lossy(),
+ );
+ }
+
+ /// Negative control, and the bug in the first cut: a folder ComfyUI cannot
+ /// use wrote no file and still reported `written: true`, and the same call
+ /// has to take an older file away with it.
+ #[test]
+ fn a_flat_folder_writes_nothing_says_so_and_clears_an_older_file() {
+ let file = tmp("sync-clear-out").join("lu_extra_model_paths.yaml");
+ let good = tmp("sync-clear-good");
+ std::fs::create_dir_all(good.join("vae")).unwrap();
+ sync_custom_model_paths_to(&file, Some(good.to_str().unwrap())).unwrap();
+ assert!(file.exists(), "precondition: a file was written");
+
+ let flat = tmp("sync-clear-flat");
+ std::fs::write(flat.join("sdxl.safetensors"), b"x").unwrap();
+ let res = sync_custom_model_paths_to(&file, Some(flat.to_str().unwrap())).unwrap();
+ assert_eq!(res["status"], "ok", "the folder itself is readable");
+ assert_eq!(res["written"], false);
+ assert_eq!(res["folders"].as_array().unwrap().len(), 0);
+ assert!(!file.exists(), "the old file must not keep feeding ComfyUI");
+ }
+
+ #[test]
+ fn an_unreachable_or_relative_folder_is_named_as_such_and_writes_nothing() {
+ let gone = tmp("sync-gone");
+ std::fs::remove_dir_all(&gone).unwrap();
+ let file = tmp("sync-bad-out").join("lu_extra_model_paths.yaml");
+ let res = sync_custom_model_paths_to(&file, Some(gone.to_str().unwrap())).unwrap();
+ assert_eq!(res["status"], "unreachable");
+ assert_eq!(res["written"], false);
+
+ let res = sync_custom_model_paths_to(&file, Some("~/models")).unwrap();
+ assert_eq!(res["status"], "unusable");
+ assert_eq!(res["written"], false);
+
+ // Negative control: no folder at all is not a fault, it is "off".
+ let res = sync_custom_model_paths_to(&file, Some(" ")).unwrap();
+ assert_eq!(res["status"], "off");
+ assert_eq!(res["written"], false);
}
/// Negative control: a missing folder is not an error and not a config.
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index b3ea8a79..dc4c92a0 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -63,7 +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'
+import { syncCustomModelDir, type CustomModelDirResult } from '../../lib/custom-model-dir'
import { CivitaiApiKeySetting } from './CivitaiApiKeySetting'
// ── User profile picture (Appearance) ───────────────────────────
@@ -266,7 +266,7 @@ 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)
+ const [comfy, setComfy] = useState<CustomModelDirResult | null>(null)
useEffect(() => { setDraft(override) }, [override])
// Both directions of the folder: our own GGUF scan reads it on the next
@@ -275,7 +275,7 @@ function HfDownloadPathSetting() {
// ComfyUI without the user having to touch the field again.
useEffect(() => {
let alive = true
- void syncCustomModelDir(override).then((folders) => { if (alive) setComfyFolders(folders) })
+ void syncCustomModelDir(override).then((res) => { if (alive) setComfy(res) })
return () => { alive = false }
}, [override])
@@ -324,16 +324,50 @@ function HfDownloadPathSetting() {
</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>
- )}
+ {override && comfy !== null && <CustomModelDirNote result={comfy} />}
+ </div>
+ )
+}
+
+/**
+ * What became of the folder, in one line.
+ *
+ * A path the OS cannot use, or a drive that is not there, used to be silence:
+ * no models, no file, no word about it. And image and video are a different
+ * question from chat, because that inventory comes out of ComfyUI's own lists,
+ * so LU can only hand ComfyUI the folder. On the Mac it cannot even do that:
+ * local media there is MLX and LU never starts a ComfyUI, so promising one
+ * would be a lie (Rust answers `unsupported` for that host).
+ */
+function CustomModelDirNote({ result }: { result: CustomModelDirResult }) {
+ const cls = "text-[0.6rem] leading-relaxed"
+ if (result.status === 'unusable') {
+ return (
+ <div className={`${cls} text-amber-600 dark:text-amber-400`}>
+ That is not a full path, so nothing can be read from it. Use a complete path such as <code className="font-mono">C:\AI\Models</code> or <code className="font-mono">/mnt/models</code>. A leading <code className="font-mono">~</code> is a shell shorthand the app does not expand.
+ </div>
+ )
+ }
+ if (result.status === 'unreachable') {
+ return (
+ <div className={`${cls} text-amber-600 dark:text-amber-400`}>
+ LU cannot read that folder. Check that the drive is connected and the path is spelled the way the system spells it.
+ </div>
+ )
+ }
+ if (result.status === 'unsupported') {
+ return (
+ <div className={`${cls} text-gray-500`}>
+ Chat models in this folder are read. Image and video on the Mac run on Apple MLX, not ComfyUI, so image models in this folder are not picked up. Install those under Local Media (Apple MLX).
+ </div>
+ )
+ }
+ if (result.status === 'unknown') return null
+ return (
+ <div className={`${cls} text-gray-500`}>
+ {result.folders.length > 0
+ ? <>Image and video: LU passes <code className="font-mono">{result.folders.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>
)
}
diff --git a/src/lib/__tests__/custom-model-dir-comfy.test.ts b/src/lib/__tests__/custom-model-dir-comfy.test.ts
index 13ad8efb..be647c02 100644
--- a/src/lib/__tests__/custom-model-dir-comfy.test.ts
+++ b/src/lib/__tests__/custom-model-dir-comfy.test.ts
@@ -31,25 +31,33 @@ 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 ')
+ backendCall.mockResolvedValue({ written: true, status: 'ok', file: '/data/lu_extra_model_paths.yaml', folders: ['loras', 'vae'] })
+ const res = await syncCustomModelDir(' G:\\AI\\Models ')
expect(backendCall).toHaveBeenCalledWith('sync_custom_model_paths', { dir: 'G:\\AI\\Models' })
- expect(folders).toEqual(['loras', 'vae'])
+ expect(res).toEqual({ status: 'ok', folders: ['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([])
+ backendCall.mockResolvedValue({ written: false, status: 'off', file: '/data/lu_extra_model_paths.yaml', folders: [] })
+ expect(await syncCustomModelDir('')).toEqual({ status: 'off', folders: [] })
expect(backendCall).toHaveBeenCalledWith('sync_custom_model_paths', { dir: '' })
- expect(await syncCustomModelDir(null)).toEqual([])
+ expect(await syncCustomModelDir(null)).toEqual({ status: 'off', folders: [] })
+ })
+
+ it('carries a folder that cannot be read through as its own verdict', async () => {
+ backendCall.mockResolvedValue({ written: false, status: 'unreachable', file: '/x', folders: [] })
+ expect(await syncCustomModelDir('Z:\\gone')).toEqual({ status: 'unreachable', folders: [] })
+ backendCall.mockResolvedValue({ written: false, status: 'unusable', file: '/x', folders: [] })
+ expect(await syncCustomModelDir('~/models')).toEqual({ status: 'unusable', folders: [] })
})
// 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.
+ // drive that went away, costs the handover and NOTHING else. It must not
+ // invent a verdict either, so the panel stays quiet instead of accusing the
+ // folder. 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([])
+ await expect(syncCustomModelDir('G:\\AI\\Models')).resolves.toEqual({ status: 'unknown', folders: [] })
})
})
@@ -68,13 +76,26 @@ describe('the Model Storage copy tells the truth', () => {
})
it('is honest that image and video go through ComfyUI', () => {
- expect(src).toMatch(/passes <code className="font-mono">\{comfyFolders\.join/)
+ expect(src).toMatch(/passes <code className="font-mono">\{result\.folders\.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('does not promise ComfyUI on a host that never starts one', () => {
+ // The Mac runs local media on MLX. The promise used to render there too.
+ expect(src).toMatch(/result\.status === 'unsupported'/)
+ expect(src).toMatch(/run on Apple MLX, not ComfyUI/)
+ })
+
+ it('says why a folder produced nothing instead of going quiet', () => {
+ expect(src).toMatch(/result\.status === 'unusable'/)
+ expect(src).toMatch(/result\.status === 'unreachable'/)
+ expect(src).toMatch(/That is not a full path/)
+ expect(src).toMatch(/Check that the drive is connected/)
+ })
+
it('hands the folder over whenever the setting changes', () => {
expect(src).toMatch(/syncCustomModelDir\(override\)/)
})
diff --git a/src/lib/custom-model-dir.ts b/src/lib/custom-model-dir.ts
index 6dfd4f90..9aa473bd 100644
--- a/src/lib/custom-model-dir.ts
+++ b/src/lib/custom-model-dir.ts
@@ -18,29 +18,56 @@
import { backendCall } from '../api/backend'
import { log } from './logger'
+/**
+ * What the folder is worth right now.
+ *
+ * `unusable` is a relative path or a `~` the OS never expands, `unreachable` is
+ * a folder LU cannot read (an unplugged drive, a dead network mount). Both used
+ * to be silence: no folders, no file, no word about it.
+ */
+export type CustomModelDirStatus =
+ | 'off'
+ | 'ok'
+ | 'unusable'
+ | 'unreachable'
+ /** This host never starts a ComfyUI, so there is nobody to hand the folder
+ * to. The Mac, where local media is MLX. */
+ | 'unsupported'
+ | 'unknown'
+
export interface CustomModelPathSync {
+ /** Whether a config file is on disk for ComfyUI to read. */
written: boolean
+ status: CustomModelDirStatus
file: string
- /** ComfyUI folder names found in the folder, e.g. `['loras', 'vae']`. */
+ /** ComfyUI folder names handed over, e.g. `['loras', 'vae']`. */
+ folders: string[]
+}
+
+export interface CustomModelDirResult {
+ status: CustomModelDirStatus
folders: string[]
}
/**
- * Register (or clear) the folder with ComfyUI. Returns the folder names that
- * were handed over, `[]` when there were none.
+ * Register (or clear) the folder with ComfyUI, and report back what it is
+ * worth.
*
- * 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.
+ * Never throws: an older backend without the command costs the handover and
+ * nothing else, and says `unknown` rather than inventing a verdict. The GGUF
+ * scan is a separate path and keeps working either way.
*/
-export async function syncCustomModelDir(dir: string | undefined | null): Promise<string[]> {
+export async function syncCustomModelDir(
+ dir: string | undefined | null,
+): Promise<CustomModelDirResult> {
+ const trimmed = (dir ?? '').trim()
try {
const res = await backendCall<CustomModelPathSync>('sync_custom_model_paths', {
- dir: (dir ?? '').trim(),
+ dir: trimmed,
})
- return res?.folders ?? []
+ return { status: res?.status ?? 'unknown', folders: res?.folders ?? [] }
} catch (err) {
log.warn('[models] custom model folder not handed to ComfyUI', { err })
- return []
+ return { status: 'unknown', folders: [] }
}
}