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: Create aus Discord und GitHub 139 bis 143

purplebe09d07c9fbc
diff --git a/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts b/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts
index 686be8d9..e6466879 100644
--- a/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts
+++ b/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts
@@ -146,6 +146,18 @@ describe('endpointMap covers every backendCall/invokeMedia site the frontend can
// and exports through a blob download, so there is no dev route to add.
'export_chats_dialog', 'import_chats_dialog', 'read_chat_attachment',
'save_binary_file_dialog', 'save_chat_attachment_dialog', 'write_chat_attachment',
+ // Model header sniff (Discord 2026-09-28): reads safetensors headers in
+ // the local ComfyUI model folders. The only call site (applyHeaderSniff in
+ // api/comfyui.ts) sits behind isTauri() and keeps the name-based answer
+ // everywhere else, so there is no dev route to add.
+ 'sniff_model_files',
+ // Gallery delete to the Recycle Bin (lib/gallery-trash.ts), behind
+ // isTauri(): the browser build has no filesystem to clean.
+ 'trash_comfy_output',
+ // Where ComfyUI models land when ComfyUI runs on another machine (GH
+ // #143, api/discover.ts comfyModelTarget). A missing route answers
+ // "local", which is what the dev server always is.
+ 'comfy_model_target',
'exit_app', 'file_read', 'find_orphan_downloads', 'fix_comfyui_cors', 'funnel_ping',
'get_comfy_gpu_status', 'get_current_time', 'import_local_model', 'install_character_trainer',
'install_lmstudio', 'install_lmstudio_status', 'install_method', 'install_python',
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 0b82c9fe..2e42f690 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2583,6 +2583,7 @@ dependencies = [
"tracing",
"tracing-appender",
"tracing-subscriber",
+ "trash",
"url",
"urlencoding",
"uuid",
@@ -5760,6 +5761,24 @@ dependencies = [
"tracing-serde",
]
+[[package]]
+name = "trash"
+version = "5.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be89b3fe156965d29ac4f8522f3a640c655affdd9f21cb4f36857f0c92c00317"
+dependencies = [
+ "chrono",
+ "libc",
+ "log",
+ "objc2",
+ "objc2-foundation",
+ "once_cell",
+ "percent-encoding",
+ "scopeguard",
+ "urlencoding",
+ "windows 0.62.2",
+]
+
[[package]]
name = "tray-icon"
version = "0.21.3"
@@ -6447,11 +6466,23 @@ version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
- "windows-collections",
+ "windows-collections 0.2.0",
"windows-core 0.61.2",
- "windows-future",
+ "windows-future 0.2.1",
"windows-link 0.1.3",
- "windows-numerics",
+ "windows-numerics 0.2.0",
+]
+
+[[package]]
+name = "windows"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
+dependencies = [
+ "windows-collections 0.3.2",
+ "windows-core 0.62.2",
+ "windows-future 0.3.2",
+ "windows-numerics 0.3.1",
]
[[package]]
@@ -6463,6 +6494,15 @@ dependencies = [
"windows-core 0.61.2",
]
+[[package]]
+name = "windows-collections"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
+dependencies = [
+ "windows-core 0.62.2",
+]
+
[[package]]
name = "windows-core"
version = "0.57.0"
@@ -6488,6 +6528,19 @@ dependencies = [
"windows-strings 0.4.2",
]
+[[package]]
+name = "windows-core"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
+dependencies = [
+ "windows-implement 0.60.2",
+ "windows-interface 0.59.3",
+ "windows-link 0.2.1",
+ "windows-result 0.4.1",
+ "windows-strings 0.5.1",
+]
+
[[package]]
name = "windows-future"
version = "0.2.1"
@@ -6496,7 +6549,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core 0.61.2",
"windows-link 0.1.3",
- "windows-threading",
+ "windows-threading 0.1.0",
+]
+
+[[package]]
+name = "windows-future"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
+dependencies = [
+ "windows-core 0.62.2",
+ "windows-link 0.2.1",
+ "windows-threading 0.2.1",
]
[[package]]
@@ -6565,6 +6629,16 @@ dependencies = [
"windows-link 0.1.3",
]
+[[package]]
+name = "windows-numerics"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
+dependencies = [
+ "windows-core 0.62.2",
+ "windows-link 0.2.1",
+]
+
[[package]]
name = "windows-registry"
version = "0.6.1"
@@ -6723,6 +6797,15 @@ dependencies = [
"windows-link 0.1.3",
]
+[[package]]
+name = "windows-threading"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
+dependencies = [
+ "windows-link 0.2.1",
+]
+
[[package]]
name = "windows-version"
version = "0.1.7"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index ba5b71a6..ef3eb499 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -38,6 +38,9 @@ which = "6"
regex = "1"
glob = "0.3"
sysinfo = "0.33"
+# Gallery delete moves the render to the Recycle Bin / Trash instead of
+# erasing it (Discord 2026-09-25: deleted renders stayed in ComfyUI/output).
+trash = "5"
walkdir = "2"
hostname = "0.4"
whoami = "1"
diff --git a/src-tauri/src/commands/chat_attachments.rs b/src-tauri/src/commands/chat_attachments.rs
index 55bd7358..834a96e8 100644
--- a/src-tauri/src/commands/chat_attachments.rs
+++ b/src-tauri/src/commands/chat_attachments.rs
@@ -176,13 +176,13 @@ pub(crate) fn write_export<W: Write>(content: &str, out: &mut W, dir: &Path) ->
&& content[..start].ends_with('"')
&& content[id_end..].starts_with('"')
&& content[..start - 1].trim_end().strip_suffix(':').map(|k| k.trim_end().ends_with("\"data\"")).unwrap_or(false);
- out.write_all(content[at..start].as_bytes())?;
+ out.write_all(&content.as_bytes()[at..start])?;
if is_image_data {
match read_attachment(dir, id) {
Ok(data) => out.write_all(data.as_bytes())?,
Err(_) => {
missing += 1;
- out.write_all(content[start..id_end].as_bytes())?;
+ out.write_all(&content.as_bytes()[start..id_end])?;
}
}
at = id_end;
@@ -191,7 +191,7 @@ pub(crate) fn write_export<W: Write>(content: &str, out: &mut W, dir: &Path) ->
at = start + PREFIX.len();
}
}
- out.write_all(content[at..].as_bytes())?;
+ out.write_all(&content.as_bytes()[at..])?;
Ok(missing)
}
@@ -324,7 +324,8 @@ fn referenced_ids(files: &[PathBuf]) -> Result<HashSet<String>, String> {
}
type ScanStamp = (std::time::SystemTime, u64);
-static SCAN_CACHE: std::sync::LazyLock<Mutex<std::collections::HashMap<PathBuf, (ScanStamp, HashSet<String>)>>> =
+type ScanCache = std::collections::HashMap<PathBuf, (ScanStamp, HashSet<String>)>;
+static SCAN_CACHE: std::sync::LazyLock<Mutex<ScanCache>> =
std::sync::LazyLock::new(|| Mutex::new(std::collections::HashMap::new()));
fn scan_file(path: &Path) -> Result<HashSet<String>, String> {
diff --git a/src-tauri/src/commands/comfy_folders.rs b/src-tauri/src/commands/comfy_folders.rs
index 8cc5b086..fddd2022 100644
--- a/src-tauri/src/commands/comfy_folders.rs
+++ b/src-tauri/src/commands/comfy_folders.rs
@@ -176,6 +176,12 @@ impl ComfyFolders {
/// file the catalog calls a `diffusion_models` file belongs in the folder of
/// that name. Both are scanned, so this is about keeping the tree the way
/// the user (and our own delete) expects it, not about visibility.
+ /// Every directory the engine scans for one key (`diffusion_models` is
+ /// `[models/unet, models/diffusion_models]` plus extra_model_paths).
+ pub fn dirs_for(&self, key: &str) -> Vec<PathBuf> {
+ self.dirs.get(&key.trim().to_ascii_lowercase()).cloned().unwrap_or_default()
+ }
+
pub fn dir_for(&self, subfolder: &str) -> Option<PathBuf> {
let key = subfolder.trim().to_ascii_lowercase();
if key.is_empty() || key.contains('/') || key.contains('\\') {
diff --git a/src-tauri/src/commands/custom_models.rs b/src-tauri/src/commands/custom_models.rs
index 52b48a72..7b7d9598 100644
--- a/src-tauri/src/commands/custom_models.rs
+++ b/src-tauri/src/commands/custom_models.rs
@@ -193,7 +193,7 @@ fn remember_root(dir: &str) {
remember_root_in(&crate::os_paths::app_config_json(), dir);
}
-fn remembered_root() -> RememberedRoot {
+pub(crate) fn remembered_root() -> RememberedRoot {
remembered_root_in(&crate::os_paths::app_config_json())
}
diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rs
index d239aa82..b0abe7a3 100644
--- a/src-tauri/src/commands/download.rs
+++ b/src-tauri/src/commands/download.rs
@@ -17,7 +17,7 @@ use crate::state::{AppState, DownloadProgress};
/// drive letter, no `..` — so a crafted `filename` (e.g. "..\\..\\Start
/// Menu\\Programs\\Startup\\x.bat") can't escape the target directory and drop
/// an autostart payload. Falls back to "download" if nothing usable remains.
-fn sanitize_filename(name: &str) -> String {
+pub(crate) fn sanitize_filename(name: &str) -> String {
let base = name.rsplit(['/', '\\']).next().unwrap_or("");
let cleaned: String = base.chars().filter(|c| !matches!(c, '/' | '\\' | ':' | '\0')).collect();
let cleaned = cleaned.trim();
@@ -30,7 +30,7 @@ fn sanitize_filename(name: &str) -> String {
/// Reject a subfolder that tries to escape the base (absolute path, drive
/// letter, or any `..` segment). Returns the subfolder unchanged when safe.
-fn safe_subfolder(subfolder: &str) -> Result<(), String> {
+pub(crate) fn safe_subfolder(subfolder: &str) -> Result<(), String> {
let norm = subfolder.replace('\\', "/");
let p = std::path::Path::new(&norm);
// `starts_with('/')` also catches Windows drive-relative roots like `/x`,
@@ -195,6 +195,29 @@ mod model_folder_tests {
std::fs::remove_dir_all(&root).ok();
}
+ /// GH #143: a ComfyUI on another machine. Which hosts are this machine,
+ /// and where its files go instead: the storage folder, ComfyUI's layout.
+ #[test]
+ fn a_remote_comfyui_gets_its_files_in_comfyui_layout_here() {
+ for local in ["", "localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0", "127.0.0.2", " LOCALHOST "] {
+ assert!(super::host_is_this_machine(local), "{local}");
+ }
+ for remote in ["192.168.1.20", "comfy.lan", "10.0.0.5", "ai-box"] {
+ assert!(!super::host_is_this_machine(remote), "{remote}");
+ }
+
+ let root = scratch("remote-root");
+ let dest = super::remote_models_dir(&root, "loras").unwrap();
+ assert_eq!(dest, root.join("loras"));
+ assert!(dest.is_dir());
+ let pack = super::remote_models_dir(&root, "custom_nodes/ComfyUI-AnimateDiff-Evolved/models").unwrap();
+ assert_eq!(pack, root.join("custom_nodes/ComfyUI-AnimateDiff-Evolved/models"));
+ for bad in ["../../etc", "a/../../b", "/abs/path", "C:/x"] {
+ assert!(super::remote_models_dir(&root, bad).is_err(), "{bad}");
+ }
+ std::fs::remove_dir_all(&root).ok();
+ }
+
/// The jail is unchanged, and it runs BEFORE anything the engine said.
#[test]
fn an_escaping_subfolder_is_still_refused() {
@@ -513,7 +536,7 @@ mod download_security_tests {
/// Split a ComfyUI enum name ("wan/x.safetensors" or plain "x.safetensors")
/// into its relative dir + basename so both halves can go through the same
/// jail checks the downloader uses.
-fn split_model_ref(name: &str) -> (String, String) {
+pub(crate) fn split_model_ref(name: &str) -> (String, String) {
let norm = name.replace('\\', "/");
match norm.rsplit_once('/') {
Some((dir, base)) => (dir.to_string(), base.to_string()),
@@ -576,6 +599,12 @@ pub async fn delete_comfy_model(
extraDirs: Option<Vec<String>>,
state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
+ if let Some(remote) = remote_comfy(&state) {
+ return Err(format!(
+ "{} is on the ComfyUI machine ({}), and LU cannot delete files there. Remove it from the models folder of ComfyUI on that machine.",
+ filename, remote.host
+ ));
+ }
let comfy_path = state
.comfy_path
.lock()
@@ -676,8 +705,86 @@ fn models_dir_in(
Ok(dir)
}
+/// A ComfyUI on another machine (GH #143, duindain: Ollama and ComfyUI as
+/// services on a LAN box, LU on a Windows PC). Its model folders are on THAT
+/// machine and nothing here can write into them: the folder names it reports
+/// are paths over there, and a ComfyUI install found on this PC is not the one
+/// rendering. Downloads went to one or the other and ended in "Create models
+/// dir: permission denied (os error 5)" or "ComfyUI path not set". They land
+/// in the Model Storage folder now, in ComfyUI's own layout (`loras/...`,
+/// `checkpoints/...`), so copying its folders into the `models` folder over
+/// there, or sharing the folder with that machine, is all it takes.
+pub(crate) struct RemoteComfy {
+ pub host: String,
+ pub root: PathBuf,
+}
+
+pub(crate) fn remote_comfy(state: &State<'_, AppState>) -> Option<RemoteComfy> {
+ let host = state.comfy_host.lock().map(|h| h.clone()).unwrap_or_default();
+ if host_is_this_machine(&host) {
+ return None;
+ }
+ Some(RemoteComfy { host, root: remote_models_root() })
+}
+
+fn host_is_this_machine(host: &str) -> bool {
+ let h = host.trim().trim_matches(|c| c == '[' || c == ']');
+ crate::commands::process::is_local_host(h)
+ || h.parse::<std::net::IpAddr>()
+ .map(|ip| ip.is_loopback() || ip.is_unspecified())
+ .unwrap_or(false)
+}
+
+/// The Model Storage folder when one is set, else a folder in Downloads.
+fn remote_models_root() -> PathBuf {
+ use crate::commands::custom_models::{remembered_root, RememberedRoot};
+ match remembered_root() {
+ RememberedRoot::Folder(dir) => PathBuf::from(dir),
+ _ => dirs::download_dir()
+ .or_else(dirs::home_dir)
+ .unwrap_or_else(std::env::temp_dir)
+ .join("LU ComfyUI models"),
+ }
+}
+
+fn remote_models_dir(root: &Path, subfolder: &str) -> Result<PathBuf, String> {
+ safe_subfolder(subfolder)?;
+ let dir = root.join(subfolder);
+ fs::create_dir_all(&dir)
+ .map_err(|e| format!("Create models dir {}: {}", dir.display(), os_error::english(&e)))?;
+ Ok(dir)
+}
+
+/// Where a ComfyUI model of `subfolder` goes: `models_dir_in`, plus the one
+/// case its arguments cannot show, a ComfyUI on another machine.
+async fn comfy_models_dir(
+ state: &State<'_, AppState>,
+ comfy_path: &Option<String>,
+ subfolder: &str,
+) -> Result<PathBuf, String> {
+ if let Some(remote) = remote_comfy(state) {
+ return remote_models_dir(&remote.root, subfolder);
+ }
+ models_dir_in(engine_folders(state).await.as_ref(), comfy_path, subfolder)
+}
+
+/// For the frontend: whether ComfyUI models land on this machine only, and
+/// where. The Model Manager and Create say so instead of waiting for a
+/// ComfyUI that can never see the file.
+#[tauri::command]
+pub fn comfy_model_target(state: State<'_, AppState>) -> serde_json::Value {
+ match remote_comfy(&state) {
+ Some(r) => serde_json::json!({
+ "remote": true,
+ "host": r.host,
+ "root": r.root.to_string_lossy(),
+ }),
+ None => serde_json::json!({ "remote": false }),
+ }
+}
+
/// The engine's answer, asked fresh, for the paths that can await it.
-async fn engine_folders(state: &State<'_, AppState>) -> Option<comfy_folders::ComfyFolders> {
+pub(crate) async fn engine_folders(state: &State<'_, AppState>) -> Option<comfy_folders::ComfyFolders> {
let host = state.comfy_host.lock().map(|h| h.clone()).unwrap_or_default();
let port = state.comfy_port.lock().map(|p| *p).unwrap_or(0);
if port == 0 {
@@ -716,7 +823,7 @@ pub async fn download_model(
p.clone()
};
- let dest_dir = models_dir_in(engine_folders(&state).await.as_ref(), &comfy_path, &subfolder)?;
+ let dest_dir = comfy_models_dir(&state, &comfy_path, &subfolder).await?;
let dest_file = dest_dir.join(sanitize_filename(&filename));
let expected_sha256 = match expectedSha256.as_deref() {
@@ -1700,7 +1807,7 @@ pub async fn check_download_space(
// reading a cache that can predate it, a cold cache pointed the
// very first space check of a session at the wrong drive (K5's
// customer-visible half of the same bug).
- models_dir_in(engine_folders(&state).await.as_ref(), &comfy_path, &sub)?
+ comfy_models_dir(&state, &comfy_path, &sub).await?
}
_ => return Err("check_download_space needs a subfolder or a destDir".to_string()),
};
@@ -1927,7 +2034,7 @@ pub async fn resume_download(
p.clone()
};
- let dest_dir = models_dir_in(engine_folders(&state).await.as_ref(), &comfy_path, &subfolder)?;
+ let dest_dir = comfy_models_dir(&state, &comfy_path, &subfolder).await?;
let dest_file = dest_dir.join(&id);
let tmp_path = dest_file.with_extension("download");
@@ -2360,11 +2467,18 @@ pub async fn check_model_sizes(
// The same folders the download wrote into. Asking the old way here would
// measure a tree nothing was written to and report every file as missing.
let folders = engine_folders(&state).await;
+ // A ComfyUI on another machine: the files are measured where they were
+ // written, in the Model Storage folder (GH #143).
+ let remote = remote_comfy(&state);
let mut results = Vec::with_capacity(files.len());
for file in &files {
- let dest_dir = match models_dir_in(folders.as_ref(), &comfy_path, &file.subfolder) {
+ let dest = match &remote {
+ Some(r) => remote_models_dir(&r.root, &file.subfolder),
+ None => models_dir_in(folders.as_ref(), &comfy_path, &file.subfolder),
+ };
+ let dest_dir = match dest {
Ok(d) => d,
Err(_) => {
results.push(CheckFileResult {
@@ -2480,7 +2594,13 @@ mod tests {
"check_download_space still reads the stale cache instead of asking the engine"
);
assert!(delete_body.contains("engine_folders(&state).await"), "{delete_body}");
- assert!(space_body.contains("engine_folders(&state).await"), "{space_body}");
+ // The space check goes through comfy_models_dir since GH #143 (a
+ // remote ComfyUI measures the Model Storage folder), and that one asks
+ // the engine fresh for everything else.
+ assert!(space_body.contains("comfy_models_dir(&state"), "{space_body}");
+ let dir_body = fn_body(src, "async fn comfy_models_dir(");
+ assert!(dir_body.contains("engine_folders(state).await"), "{dir_body}");
+ assert!(!dir_body.contains("comfy_folders::cached()"), "{dir_body}");
}
#[test]
diff --git a/src-tauri/src/commands/gallery_files.rs b/src-tauri/src/commands/gallery_files.rs
new file mode 100644
index 00000000..0486d307
--- /dev/null
+++ b/src-tauri/src/commands/gallery_files.rs
@@ -0,0 +1,89 @@
+//! Gallery delete reaches the file too (Discord 2026-09-25, boromirofgeo:
+//! "when deleting files in app from gallery, they are still in output
+//! folder, which is getting bigger and bigger").
+//!
+//! The render goes to the Recycle Bin / Trash, not into oblivion: a misclick
+//! in the gallery must stay recoverable. Only files inside ComfyUI's output
+//! folder are touched, by the same path rules as the model probes (no
+//! absolute paths, no `..`, media extensions only).
+
+use std::path::{Path, PathBuf};
+
+use serde::Serialize;
+use tauri::State;
+
+use crate::commands::download::{safe_subfolder, sanitize_filename};
+use crate::state::AppState;
+
+const MEDIA_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "webp", "gif", "mp4", "webm", "mov", "mkv", "wav", "mp3", "flac", "ogg"];
+
+#[derive(Debug, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct TrashResult {
+ /// The file was found and moved to the Recycle Bin / Trash.
+ pub trashed: bool,
+ /// Nothing to do: the file was not there (already gone, or ComfyUI writes
+ /// to an output folder this app does not know).
+ pub missing: bool,
+}
+
+/// The file a gallery entry names, inside `output_dir`, or None when the name
+/// tries to leave it or is not a media file.
+pub fn output_file(output_dir: &Path, filename: &str, subfolder: &str) -> Option<PathBuf> {
+ if filename.is_empty() || sanitize_filename(filename) != filename {
+ return None;
+ }
+ if !subfolder.is_empty() && safe_subfolder(subfolder).is_err() {
+ return None;
+ }
+ let ext = Path::new(filename).extension()?.to_str()?.to_ascii_lowercase();
+ if !MEDIA_EXTENSIONS.contains(&ext.as_str()) {
+ return None;
+ }
+ let dir = if subfolder.is_empty() { output_dir.to_path_buf() } else { output_dir.join(subfolder.replace('\\', "/")) };
+ Some(dir.join(filename))
+}
+
+#[tauri::command]
+pub async fn trash_comfy_output(filename: String, subfolder: String, state: State<'_, AppState>) -> Result<TrashResult, String> {
+ let comfy_path = {
+ let mut p = state.comfy_path.lock().map_err(|e| e.to_string())?;
+ if p.is_none() {
+ if let Some(found) = crate::commands::process::find_comfyui_path() {
+ *p = Some(found);
+ }
+ }
+ p.clone()
+ };
+ let Some(base) = comfy_path else {
+ return Ok(TrashResult { trashed: false, missing: true });
+ };
+ let path = output_file(&PathBuf::from(base).join("output"), &filename, &subfolder)
+ .ok_or_else(|| "That gallery entry does not name a file in the ComfyUI output folder.".to_string())?;
+ if !path.is_file() {
+ return Ok(TrashResult { trashed: false, missing: true });
+ }
+ tauri::async_runtime::spawn_blocking(move || trash::delete(&path))
+ .await
+ .map_err(|e| e.to_string())?
+ .map_err(|e| format!("Could not move the file to the trash: {e}"))?;
+ Ok(TrashResult { trashed: true, missing: false })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_media_files_inside_the_output_folder() {
+ let out = PathBuf::from("/comfy/output");
+ assert_eq!(output_file(&out, "locally_uncensored_00001_.png", ""), Some(out.join("locally_uncensored_00001_.png")));
+ assert_eq!(output_file(&out, "clip.mp4", "video"), Some(out.join("video").join("clip.mp4")));
+ assert_eq!(output_file(&out, "../../secret.png", ""), None);
+ assert_eq!(output_file(&out, "x.png", "../.."), None);
+ assert_eq!(output_file(&out, "x.png", "/etc"), None);
+ assert_eq!(output_file(&out, "model.safetensors", ""), None);
+ assert_eq!(output_file(&out, "noext", ""), None);
+ assert_eq!(output_file(&out, "", ""), None);
+ }
+}
diff --git a/src-tauri/src/commands/install/custom_nodes.rs b/src-tauri/src/commands/install/custom_nodes.rs
index b60bd875..8c70d866 100644
--- a/src-tauri/src/commands/install/custom_nodes.rs
+++ b/src-tauri/src/commands/install/custom_nodes.rs
@@ -55,6 +55,15 @@ pub async fn install_custom_node(
// Snapshot the state the blocking worker needs before spawning it: a Tauri
// `State` (and the MutexGuard behind it) is not Send, so clone the values
// out and move owned copies into the worker.
+ // A ComfyUI on another machine loads its node packs from THAT machine's
+ // custom_nodes folder, which nothing here can reach (GH #143). Cloning into
+ // a ComfyUI found on this PC helped nobody; say what to do instead.
+ if let Some(remote) = crate::commands::download::remote_comfy(&state) {
+ return Err(format!(
+ "Your ComfyUI runs on {} and LU cannot install node packs on another machine. Install {} there (ComfyUI-Manager, or git clone {} into its custom_nodes folder), then restart that ComfyUI.",
+ remote.host, nodeName, repoUrl
+ ));
+ }
let comfy_path = { state.comfy_path.lock().unwrap().clone() };
let fallback_python = { state.python_bin.lock().unwrap().clone() };
// Freeze fix (David 2026-07-04): the git clone + pip below are blocking. As
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index fbcfab31..ba237bc4 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -22,6 +22,7 @@ pub mod logging;
pub mod media_cmds;
pub mod mlx;
pub mod mlx_snapshot;
+pub mod model_sniff;
pub mod oauth;
pub mod process;
pub mod proxy;
@@ -36,6 +37,7 @@ pub mod tts;
pub mod video;
pub mod waitlist;
pub mod funnel;
+pub mod gallery_files;
pub mod whisper;
// ── uselu-compat error helpers ────────────────────────────────────────
diff --git a/src-tauri/src/commands/model_sniff.rs b/src-tauri/src/commands/model_sniff.rs
new file mode 100644
index 00000000..d81aaa45
--- /dev/null
+++ b/src-tauri/src/commands/model_sniff.rs
@@ -0,0 +1,333 @@
+//! Which model family a main model file belongs to, read from the file itself.
+//!
+//! Discord 2026-09-26..28 (boromirofgeo, haschbar): Edit failed with "Node 1
+//! (CheckpointLoaderSimple): Value not in list" for every model but the one
+//! SDXL checkpoint. The frontend names a model's family from its FILE NAME,
+//! and a name it cannot place fell to the checkpoint pipeline, which only
+//! reads models/checkpoints. CivitAI names say nothing reliable about the
+//! architecture, but the safetensors header does: it lists every tensor, and
+//! each family has its own layout. Only the header is read (8 bytes plus a
+//! JSON block of a few hundred KB), never the weights.
+//!
+//! The key layouts below were read off real headers on 2026-09-28 (HTTP range
+//! requests against the Comfy-Org and vendor repos): FLUX 1 (dev unet and the
+//! schnell all-in-one), FLUX 2 Klein, Krea 2, Z-Image Turbo, Qwen-Image 2.1,
+//! Qwen-Image 1, ERNIE-Image, SDXL (ldm checkpoint and diffusers unet), SD 3.5,
+//! HiDream, Chroma, Lumina 2 and Wan 2.2.
+
+use std::collections::{HashMap, HashSet};
+use std::fs::File;
+use std::io::Read;
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+use std::time::SystemTime;
+
+use serde::{Deserialize, Serialize};
+use tauri::State;
+
+use crate::commands::download::{engine_folders, safe_subfolder, sanitize_filename, split_model_ref};
+use crate::state::AppState;
+
+/// A header larger than this is not a model header we want to parse.
+const MAX_HEADER_BYTES: u64 = 64 * 1024 * 1024;
+
+#[derive(Debug, Clone, Default, PartialEq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Sniff {
+ /// LU's name for the family ("flux", "zimage", ...), or a family LU has no
+ /// pipeline for ("chroma", "hidream", ...). None when the layout is unknown.
+ pub arch: Option<String>,
+ /// The file carries its own text encoder (an all-in-one checkpoint).
+ pub has_text_encoder: bool,
+ /// The file carries its own VAE.
+ pub has_vae: bool,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct SniffRequest {
+ /// "checkpoints" or "diffusion_models": the ComfyUI list the name came from.
+ pub folder: String,
+ /// The name exactly as ComfyUI lists it, subfolders included.
+ pub name: String,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SniffResult {
+ pub folder: String,
+ pub name: String,
+ #[serde(flatten)]
+ pub sniff: Sniff,
+}
+
+/// The family, from tensor names and the one shape that separates Z-Image
+/// from Lumina 2 (same layout, different caption width). Pure, so the tests
+/// can feed it the real key sets.
+pub fn classify<'a>(tensors: impl IntoIterator<Item = (&'a str, Option<&'a [u64]>)>) -> Sniff {
+ let mut stems: HashSet<String> = HashSet::new();
+ let mut has_text_encoder = false;
+ let mut has_vae = false;
+ let mut cap_width: Option<u64> = None;
+ for (key, shape) in tensors {
+ if key == "__metadata__" {
+ continue;
+ }
+ if key.starts_with("text_encoders.") || key.starts_with("conditioner.") || key.starts_with("cond_stage_model.") {
+ has_text_encoder = true;
+ continue;
+ }
+ if key.starts_with("vae.") || key.starts_with("first_stage_model.") {
+ has_vae = true;
+ continue;
+ }
+ let bare = key
+ .strip_prefix("model.diffusion_model.")
+ .or_else(|| key.strip_prefix("diffusion_model."))
+ .or_else(|| key.strip_prefix("model."))
+ .unwrap_or(key);
+ if bare == "cap_embedder.0.weight" {
+ cap_width = shape.and_then(|s| s.first().copied());
+ }
+ if let Some(stem) = bare.split('.').next() {
+ stems.insert(stem.to_string());
+ }
+ }
+ let has = |s: &str| stems.contains(s);
+ let arch = if has("double_stream_modulation_img") {
+ Some("flux2")
+ } else if has("distilled_guidance_layer") {
+ Some("chroma")
+ } else if has("double_blocks") && has("single_blocks") {
+ Some("flux")
+ } else if has("txtfusion") && has("blocks") {
+ Some("krea2")
+ } else if has("noise_refiner") && has("context_refiner") && has("cap_embedder") {
+ // Z-Image feeds Qwen3-4B (2560 wide); Lumina 2 feeds Gemma 2 (2304).
+ Some(if cap_width == Some(2560) { "zimage" } else { "lumina2" })
+ } else if has("text_proj") && has("x_embedder") && has("layers") {
+ Some("ernie_image")
+ } else if has("transformer_blocks") && has("img_in") && has("txt_in") {
+ // 2.1 carries a shared top-level modulation; Qwen-Image 1 and its Edit
+ // models carry txt_norm instead and need a different encoder.
+ Some(if has("modulation") { "qwenimage" } else { "qwenimage1" })
+ } else if has("double_stream_blocks") {
+ Some("hidream")
+ } else if has("joint_blocks") {
+ Some("sd3")
+ } else if has("input_blocks") && has("output_blocks") {
+ Some(if has("label_emb") { "sdxl" } else { "sd15" })
+ } else if has("down_blocks") && has("up_blocks") {
+ Some(if has("add_embedding") { "sdxl" } else { "sd15" })
+ } else if has("blocks") && has("patch_embedding") {
+ Some("wan")
+ } else if has("decoder") && (has("encoder") || has("post_quant_conv")) && !has_text_encoder {
+ // A bare autoencoder that landed in a model folder (Discord
+ // 2026-09-26: minimax_h3_video_vae_fp16 listed as an image model).
+ Some("vae")
+ } else if has("text_model") || has("embed_tokens") || (has("encoder") && has("shared")) {
+ // CLIP, LLM or T5 text encoder, same story.
+ Some("text_encoder")
+ } else {
+ None
+ };
+ Sniff { arch: arch.map(str::to_string), has_text_encoder, has_vae }
+}
+
+/// Read and classify one file's header. None when it is not a readable
+/// safetensors file.
+pub fn sniff_file(path: &Path) -> Option<Sniff> {
+ let mut f = File::open(path).ok()?;
+ let total = f.metadata().ok()?.len();
+ let mut len = [0u8; 8];
+ f.read_exact(&mut len).ok()?;
+ let n = u64::from_le_bytes(len);
+ if n == 0 || n > MAX_HEADER_BYTES || n + 8 > total {
+ return None;
+ }
+ let mut buf = vec![0u8; n as usize];
+ f.read_exact(&mut buf).ok()?;
+ let header: serde_json::Map<String, serde_json::Value> = serde_json::from_slice(&buf).ok()?;
+ let shapes: Vec<(String, Option<Vec<u64>>)> = header
+ .iter()
+ .map(|(k, v)| {
+ let shape = v.get("shape").and_then(|s| s.as_array()).map(|a| a.iter().filter_map(|x| x.as_u64()).collect());
+ (k.clone(), shape)
+ })
+ .collect();
+ Some(classify(shapes.iter().map(|(k, s)| (k.as_str(), s.as_deref()))))
+}
+
+type CacheKey = (PathBuf, u64, Option<SystemTime>);
+static CACHE: Mutex<Option<HashMap<CacheKey, Option<Sniff>>>> = Mutex::new(None);
+
+fn sniff_cached(path: &Path) -> Option<Sniff> {
+ let meta = path.metadata().ok()?;
+ let key = (path.to_path_buf(), meta.len(), meta.modified().ok());
+ if let Some(hit) = CACHE.lock().ok().and_then(|c| c.as_ref().and_then(|m| m.get(&key).cloned())) {
+ return hit;
+ }
+ let sniff = sniff_file(path);
+ if let Ok(mut c) = CACHE.lock() {
+ c.get_or_insert_with(HashMap::new).insert(key, sniff.clone());
+ }
+ sniff
+}
+
+/// Where a listed name lives, looking only inside the given folders. The name
+/// comes from a ComfyUI answer, so it is held to the same rule as the size
+/// probe: no absolute paths, no `..`, nothing outside the model folders.
+fn locate(dirs: &[PathBuf], name: &str) -> Option<PathBuf> {
+ let (sub, base) = split_model_ref(name);
+ if !sub.is_empty() && safe_subfolder(&sub).is_err() {
+ return None;
+ }
+ if sanitize_filename(&base) != base {
+ return None;
+ }
+ let lower = base.to_ascii_lowercase();
+ if !(lower.ends_with(".safetensors") || lower.ends_with(".sft")) {
+ return None;
+ }
+ dirs.iter()
+ .map(|d| if sub.is_empty() { d.join(&base) } else { d.join(&sub).join(&base) })
+ .find(|p| p.is_file())
+}
+
+fn candidate_dirs(folders: Option<&crate::commands::comfy_folders::ComfyFolders>, comfy_path: &Option<String>, folder: &str) -> Vec<PathBuf> {
+ let keys: &[&str] = match folder {
+ "checkpoints" => &["checkpoints"],
+ "diffusion_models" => &["diffusion_models", "unet"],
+ _ => &[],
+ };
+ let mut dirs: Vec<PathBuf> = Vec::new();
+ for key in keys {
+ if let Some(f) = folders {
+ for d in f.dirs_for(key) {
+ if !dirs.contains(&d) {
+ dirs.push(d);
+ }
+ }
+ }
+ if let Some(base) = comfy_path {
+ let d = PathBuf::from(base).join("models").join(key);
+ if !dirs.contains(&d) {
+ dirs.push(d);
+ }
+ }
+ }
+ dirs
+}
+
+/// The family of each listed main model, read from its header. A file this
+/// machine cannot see (remote ComfyUI, GGUF, moved) comes back with no arch,
+/// and the frontend keeps its name-based answer.
+#[tauri::command]
+pub async fn sniff_model_files(files: Vec<SniffRequest>, state: State<'_, AppState>) -> Result<Vec<SniffResult>, String> {
+ let comfy_path = state.comfy_path.lock().map(|p| p.clone()).unwrap_or(None);
+ let folders = engine_folders(&state).await;
+ tauri::async_runtime::spawn_blocking(move || {
+ files
+ .into_iter()
+ .map(|req| {
+ let dirs = candidate_dirs(folders.as_ref(), &comfy_path, &req.folder);
+ let sniff = locate(&dirs, &req.name).and_then(|p| sniff_cached(&p)).unwrap_or_default();
+ SniffResult { folder: req.folder, name: req.name, sniff }
+ })
+ .collect()
+ })
+ .await
+ .map_err(|e| e.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn arch(keys: &[&str]) -> Option<String> {
+ classify(keys.iter().map(|k| (*k, None))).arch
+ }
+
+ #[test]
+ fn families_from_real_key_layouts() {
+ assert_eq!(arch(&["double_blocks.0.img_attn.qkv.weight", "single_blocks.0.linear1.weight", "guidance_in.in_layer.weight"]).as_deref(), Some("flux"));
+ assert_eq!(arch(&["double_blocks.0.x", "single_blocks.0.x", "double_stream_modulation_img.lin.weight"]).as_deref(), Some("flux2"));
+ assert_eq!(arch(&["double_blocks.0.x", "single_blocks.0.x", "distilled_guidance_layer.in_proj.weight"]).as_deref(), Some("chroma"));
+ assert_eq!(arch(&["blocks.0.attn.qkv.weight", "txtfusion.0.x", "tmlp.0.weight", "first.weight"]).as_deref(), Some("krea2"));
+ assert_eq!(arch(&["layers.0.x", "text_proj.weight", "x_embedder.weight", "adaLN_modulation.1.weight"]).as_deref(), Some("ernie_image"));
+ assert_eq!(arch(&["transformer_blocks.0.x", "img_in.weight", "txt_in.weight", "modulation.weight"]).as_deref(), Some("qwenimage"));
+ assert_eq!(arch(&["transformer_blocks.0.x", "img_in.weight", "txt_in.weight", "txt_norm.weight"]).as_deref(), Some("qwenimage1"));
+ assert_eq!(arch(&["double_stream_blocks.0.x", "caption_projection.0.x"]).as_deref(), Some("hidream"));
+ assert_eq!(arch(&["model.diffusion_model.joint_blocks.0.x", "text_encoders.clip_l.x"]).as_deref(), Some("sd3"));
+ assert_eq!(arch(&["blocks.0.x", "patch_embedding.weight", "text_embedding.0.weight"]).as_deref(), Some("wan"));
+ assert_eq!(arch(&["foo.weight"]), None);
+ assert_eq!(arch(&["encoder.conv_in.weight", "decoder.conv_out.weight"]).as_deref(), Some("vae"));
+ assert_eq!(arch(&["model.layers.0.mlp.weight", "model.embed_tokens.weight"]).as_deref(), Some("text_encoder"));
+ assert_eq!(arch(&["encoder.block.0.x", "shared.weight"]).as_deref(), Some("text_encoder"));
+ assert_eq!(arch(&["text_model.encoder.layers.0.x"]).as_deref(), Some("text_encoder"));
+ }
+
+ #[test]
+ fn sdxl_and_sd15_in_both_layouts() {
+ assert_eq!(arch(&["model.diffusion_model.input_blocks.0.0.weight", "model.diffusion_model.output_blocks.0.x", "model.diffusion_model.label_emb.0.0.weight"]).as_deref(), Some("sdxl"));
+ assert_eq!(arch(&["model.diffusion_model.input_blocks.0.0.weight", "model.diffusion_model.output_blocks.0.x"]).as_deref(), Some("sd15"));
+ assert_eq!(arch(&["down_blocks.0.x", "up_blocks.0.x", "add_embedding.linear_1.weight"]).as_deref(), Some("sdxl"));
+ assert_eq!(arch(&["down_blocks.0.x", "up_blocks.0.x"]).as_deref(), Some("sd15"));
+ }
+
+ #[test]
+ fn zimage_and_lumina2_differ_by_caption_width() {
+ let keys = ["noise_refiner.0.x", "context_refiner.0.x", "cap_embedder.0.weight", "layers.0.x"];
+ let z: Vec<(&str, Option<&[u64]>)> = keys.iter().map(|k| (*k, if *k == "cap_embedder.0.weight" { Some(&[2560u64][..]) } else { None })).collect();
+ let l: Vec<(&str, Option<&[u64]>)> = keys.iter().map(|k| (*k, if *k == "cap_embedder.0.weight" { Some(&[2304u64][..]) } else { None })).collect();
+ assert_eq!(classify(z).arch.as_deref(), Some("zimage"));
+ assert_eq!(classify(l).arch.as_deref(), Some("lumina2"));
+ }
+
+ #[test]
+ fn all_in_one_checkpoint_reports_its_parts() {
+ let s = classify(["model.diffusion_model.double_blocks.0.x", "model.diffusion_model.single_blocks.0.x", "text_encoders.t5xxl.x", "vae.decoder.x"].iter().map(|k| (*k, None)));
+ assert_eq!(s, Sniff { arch: Some("flux".into()), has_text_encoder: true, has_vae: true });
+ }
+
+ /// Against real headers (keys + shapes as JSON, fetched by range request).
+ /// Skipped unless LU_SNIFF_FIXTURES points at such a folder; each file is
+ /// named <expected arch>.json.
+ #[test]
+ fn real_headers_when_available() {
+ let Ok(dir) = std::env::var("LU_SNIFF_FIXTURES") else { return };
+ for entry in std::fs::read_dir(dir).unwrap() {
+ let path = entry.unwrap().path();
+ let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ let shapes: Vec<(String, Option<Vec<u64>>)> = v["keys"].as_array().unwrap().iter().map(|k| {
+ let k = k.as_str().unwrap().to_string();
+ let s = v["shapes"].get(&k).and_then(|s| s.as_array()).map(|a| a.iter().filter_map(|x| x.as_u64()).collect());
+ (k, s)
+ }).collect();
+ let got = classify(shapes.iter().map(|(k, s)| (k.as_str(), s.as_deref()))).arch.unwrap_or_default();
+ let want = path.file_stem().unwrap().to_string_lossy().to_string();
+ println!("{want}: {got}");
+ assert_eq!(got, want);
+ }
+ }
+
+ #[test]
+ fn reads_a_real_header_and_refuses_garbage() {
+ let dir = std::env::temp_dir().join(format!("lu-sniff-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let header = br#"{"__metadata__":{"x":"y"},"cap_embedder.0.weight":{"dtype":"BF16","shape":[2560],"data_offsets":[0,2]},"noise_refiner.0.w":{"dtype":"BF16","shape":[1],"data_offsets":[2,4]},"context_refiner.0.w":{"dtype":"BF16","shape":[1],"data_offsets":[4,6]}}"#;
+ let mut bytes = (header.len() as u64).to_le_bytes().to_vec();
+ bytes.extend_from_slice(header);
+ bytes.extend_from_slice(&[0u8; 6]);
+ let good = dir.join("renamed_by_civitai.safetensors");
+ std::fs::write(&good, &bytes).unwrap();
+ assert_eq!(sniff_file(&good).unwrap().arch.as_deref(), Some("zimage"));
+ let bad = dir.join("broken.safetensors");
+ std::fs::write(&bad, u64::MAX.to_le_bytes()).unwrap();
+ assert_eq!(sniff_file(&bad), None);
+ // Found by name inside the folder, never outside it.
+ assert_eq!(locate(std::slice::from_ref(&dir), "renamed_by_civitai.safetensors"), Some(good));
+ assert_eq!(locate(std::slice::from_ref(&dir), "../renamed_by_civitai.safetensors"), None);
+ assert_eq!(locate(std::slice::from_ref(&dir), "model.gguf"), None);
+ std::fs::remove_dir_all(&dir).ok();
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 33950a40..70ff90c1 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -540,6 +540,8 @@ fn main() {
commands::chat_attachments::save_chat_attachment_dialog,
commands::chat_attachments::export_chats_dialog,
commands::chat_attachments::import_chats_dialog,
+ commands::model_sniff::sniff_model_files,
+ commands::gallery_files::trash_comfy_output,
commands::system::restore_stores,
commands::system::backup_rag_chunks,
commands::system::restore_rag_chunks,
@@ -550,6 +552,7 @@ fn main() {
commands::self_migrate_cmd::self_migrate_finish,
// Downloads
commands::download::download_model,
+ commands::download::comfy_model_target,
commands::download::download_model_to_path,
commands::download::download_progress,
commands::download::pause_download,
diff --git a/src/api/__tests__/comfyui-models.test.ts b/src/api/__tests__/comfyui-models.test.ts
index 440b14a4..0a7b8c14 100644
--- a/src/api/__tests__/comfyui-models.test.ts
+++ b/src/api/__tests__/comfyui-models.test.ts
@@ -107,8 +107,10 @@ describe('classifyModel', () => {
expect(classifyModel('qwenimage_2_1.safetensors')).toBe('qwenimage')
// Older Qwen-Image generations stay unknown rather than being routed onto
// the 2.1 pipeline, which would build a node graph they cannot run.
- expect(classifyModel('qwen_image_fp8_e4m3fn.safetensors')).toBe('unknown')
- expect(classifyModel('qwen_image_edit_2509_fp8.safetensors')).toBe('unknown')
+ // Since 2026-09-28 they have their own pipeline (qwenimage1), see
+ // qwen-image-21-workflow.test.ts and sniffed-families-workflow.test.ts.
+ expect(classifyModel('qwen_image_fp8_e4m3fn.safetensors')).toBe('qwenimage1')
+ expect(classifyModel('qwen_image_edit_2509_fp8.safetensors')).toBe('qwenimage1')
// Companion files, which this same function also sees.
expect(classifyModel('qwen3vl_8b_int8_convrot.safetensors')).toBe('unknown')
expect(classifyModel('qwen_image_vae.safetensors')).toBe('unknown')
diff --git a/src/api/__tests__/edit-loader-guards.test.ts b/src/api/__tests__/edit-loader-guards.test.ts
new file mode 100644
index 00000000..c9403d82
--- /dev/null
+++ b/src/api/__tests__/edit-loader-guards.test.ts
@@ -0,0 +1,84 @@
+/**
+ * Discord 2026-09-26..28 (boromirofgeo, haschbar, tbjdrw): Edit came back with
+ * "ComfyUI rejected workflow: ... Node 1 (CheckpointLoaderSimple): Value not
+ * in list" or "Node 2 (CLIPLoader): Value not in list". The builder picked the
+ * loader from the file NAME, so a file LU cannot place that sits in
+ * diffusion_models went to CheckpointLoaderSimple, and a family whose text
+ * encoder type the local ComfyUI does not have went to CLIPLoader anyway.
+ * Both now stop before submit, and Create fixes what it can (see
+ * sniffed-families-workflow.test.ts and render-fixups.test.ts).
+ *
+ * Run: npx vitest run src/api/__tests__/edit-loader-guards.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('../comfyui-nodes', async (o) => ({ ...(await o<typeof import('../comfyui-nodes')>()), getAllNodeInfo: vi.fn() }))
+vi.mock('../comfyui', async (o) => ({
+ ...(await o<typeof import('../comfyui')>()),
+ findMatchingCLIP: vi.fn(async () => 'qwen_3_4b.safetensors'),
+ findMatchingVAE: vi.fn(async () => 'ae.safetensors'),
+}))
+
+import { buildDynamicWorkflow, WorkflowUnavailableError } from '../dynamic-workflow'
+import { getAllNodeInfo } from '../comfyui-nodes'
+import { classifyModel, isStrayAddonFile } from '../comfyui'
+import { classTypes } from './graph-test-support'
+
+const nodes = (clipTypes: string[]): Record<string, unknown> => {
+ const n: Record<string, unknown> = {}
+ for (const k of ['CLIPTextEncode', 'KSampler', 'EmptyLatentImage', 'EmptySD3LatentImage', 'LoadImage', 'VAEEncode', 'VAEDecode', 'SaveImage', 'VAELoader', 'ConditioningZeroOut'])
+ n[k] = { input: { required: {} } }
+ n.CheckpointLoaderSimple = { input: { required: { ckpt_name: [['juggernautXL_v9.safetensors']] } } }
+ n.UNETLoader = { input: { required: { unet_name: [['mystery_merge_v3.safetensors', 'z_image_turbo_bf16.safetensors', 'krea2_fp8.safetensors']] } } }
+ n.CLIPLoader = { input: { required: { clip_name: [['qwen_3_4b.safetensors']], type: [clipTypes] } } }
+ return n
+}
+const edit = (model: string) => ({
+ model, prompt: 'make the door red', negativePrompt: '', sampler: 'euler', scheduler: 'normal',
+ width: 1024, height: 1024, steps: 8, cfgScale: 1, seed: 1, batchSize: 1, inputImage: 'src.png', denoise: 0.7,
+}) as never
+
+describe('Edit never submits a loader value ComfyUI does not list', () => {
+ beforeEach(() => vi.mocked(getAllNodeInfo).mockResolvedValue(nodes(['stable_diffusion', 'qwen_image', 'krea2']) as never))
+
+ it('a real checkpoint still builds the checkpoint img2img graph', async () => {
+ const wf = await buildDynamicWorkflow(edit('juggernautXL_v9.safetensors'), classifyModel('juggernautXL_v9.safetensors'))
+ expect(classTypes(wf)).toEqual(expect.arrayContaining(['CheckpointLoaderSimple', 'LoadImage', 'VAEEncode']))
+ })
+
+ it('a file neither name nor header can place is refused with a reason, not sent to CheckpointLoaderSimple', async () => {
+ const model = 'mystery_merge_v3.safetensors'
+ const run = buildDynamicWorkflow(edit(model), classifyModel(model))
+ await expect(run).rejects.toBeInstanceOf(WorkflowUnavailableError)
+ await expect(run).rejects.toThrow(/does not recognize which model family/)
+ })
+
+ it('a file ComfyUI no longer lists is refused with a reason', async () => {
+ await expect(buildDynamicWorkflow(edit('gone.safetensors'), 'sdxl')).rejects.toThrow(/no longer in ComfyUI's model list/)
+ })
+
+ it('a text encoder type the local ComfyUI lacks asks for a ComfyUI update', async () => {
+ vi.mocked(getAllNodeInfo).mockResolvedValue(nodes(['stable_diffusion', 'qwen_image']) as never)
+ const run = buildDynamicWorkflow(edit('krea2_fp8.safetensors'), 'krea2')
+ await expect(run).rejects.toBeInstanceOf(WorkflowUnavailableError)
+ await expect(run).rejects.toThrow(/Update ComfyUI/)
+ // ...and says so in a way Create can act on (it offers the update).
+ await expect(run).rejects.toMatchObject({ needsComfyUpdate: true })
+ // Z-Image's type is there, so it still builds.
+ const wf = await buildDynamicWorkflow(edit('z_image_turbo_bf16.safetensors'), 'zimage')
+ expect(classTypes(wf)).toEqual(expect.arrayContaining(['UNETLoader', 'CLIPLoader', 'VAEEncode']))
+ })
+})
+
+describe('stray VAE files stay out of the model picker', () => {
+ it.each([
+ ['minimax_h3_video_vae_fp16.safetensors', true],
+ ['qwen_image_vae.safetensors', true],
+ ['sdxl_vae.safetensors', true],
+ ['sub\\\\wan_2.1_vae.safetensors', true],
+ ['juggernautXL_v9.safetensors', false],
+ ['sdxl_bakedvae_model.safetensors', false],
+ ['realvisxl_v40_vae.safetensors', false],
+ ['ae.safetensors', false],
+ ])('%s -> %s', (name, stray) => expect(isStrayAddonFile(name)).toBe(stray))
+})
diff --git a/src/api/__tests__/header-sniff.test.ts b/src/api/__tests__/header-sniff.test.ts
new file mode 100644
index 00000000..40e68377
--- /dev/null
+++ b/src/api/__tests__/header-sniff.test.ts
@@ -0,0 +1,65 @@
+/**
+ * The model lists take the family from the file header when the name cannot
+ * say it (Discord 2026-09-28), drop stray VAE / text encoder files, and keep
+ * the name-based answer whenever the header is not readable.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const backend = vi.hoisted(() => ({ call: vi.fn(), tauri: vi.fn(() => true) }))
+vi.mock('../backend', async (o) => ({ ...(await o<typeof import('../backend')>()), backendCall: backend.call, isTauri: backend.tauri }))
+
+import { applyHeaderSniff, classifyModel, type ClassifiedModel } from '../comfyui'
+
+const list = (): ClassifiedModel[] => [
+ { name: 'kr2_realism.safetensors', type: classifyModel('kr2_realism.safetensors'), source: 'diffusion_model' },
+ { name: 'myMix_v3.safetensors', type: 'unknown', source: 'checkpoint' },
+ { name: 'minimax_h3_video_vae_fp16.safetensors', type: 'unknown', source: 'checkpoint' },
+ { name: 'wan2.2_ti2v_5B_fp16.safetensors', type: 'wan22', source: 'diffusion_model' },
+ { name: 'pony.gguf', type: 'unknown', source: 'diffusion_model' },
+]
+
+beforeEach(() => {
+ backend.tauri.mockReturnValue(true)
+ backend.call.mockReset().mockImplementation(async (_cmd: string, args: { files: Array<{ folder: string; name: string }> }) =>
+ args.files.map((f) => ({
+ ...f,
+ arch: f.name.startsWith('kr2') ? 'krea2' : f.name.startsWith('myMix') ? 'flux' : f.name.includes('vae') ? 'vae' : null,
+ hasTextEncoder: f.name.startsWith('myMix'), hasVae: f.name.startsWith('myMix'),
+ })))
+})
+
+describe('applyHeaderSniff', () => {
+ it('retypes from the header, records the parts, drops a bare VAE', async () => {
+ const models = list()
+ await applyHeaderSniff(models)
+ expect(models.map((m) => [m.name, m.type])).toEqual([
+ ['kr2_realism.safetensors', 'krea2'],
+ ['myMix_v3.safetensors', 'flux'],
+ ['wan2.2_ti2v_5B_fp16.safetensors', 'wan22'],
+ ['pony.gguf', 'unknown'],
+ ])
+ expect(models[1].parts).toEqual({ textEncoder: true, vae: true })
+ })
+
+ it('asks only about image-lane names, never a video name or a GGUF, with the right folder', async () => {
+ await applyHeaderSniff(list())
+ const asked = backend.call.mock.calls[0][1].files
+ expect(asked).toEqual([
+ { folder: 'diffusion_models', name: 'kr2_realism.safetensors' },
+ { folder: 'checkpoints', name: 'myMix_v3.safetensors' },
+ { folder: 'checkpoints', name: 'minimax_h3_video_vae_fp16.safetensors' },
+ ])
+ })
+
+ it('outside the desktop app or on a failing backend the names stand', async () => {
+ backend.tauri.mockReturnValue(false)
+ const a = list()
+ await applyHeaderSniff(a)
+ expect(a).toEqual(list())
+ backend.tauri.mockReturnValue(true)
+ backend.call.mockRejectedValue(new Error('no such command'))
+ const b = list()
+ await applyHeaderSniff(b)
+ expect(b).toEqual(list())
+ })
+})
diff --git a/src/api/__tests__/qwen-image-21-workflow.test.ts b/src/api/__tests__/qwen-image-21-workflow.test.ts
index 0297c700..01bbe830 100644
--- a/src/api/__tests__/qwen-image-21-workflow.test.ts
+++ b/src/api/__tests__/qwen-image-21-workflow.test.ts
@@ -107,10 +107,11 @@ describe('Qwen-Image 2.1 classification', () => {
expect(classifyModel('qwen_image_vae.safetensors')).not.toBe('qwenimage')
})
- it('leaves the older Qwen-Image generations alone', () => {
- expect(classifyModel('qwen_image_fp8_e4m3fn.safetensors')).toBe('unknown')
- expect(classifyModel('qwen_image_edit_2509_fp8.safetensors')).toBe('unknown')
- expect(classifyModel('qwen_image_2512_bf16.safetensors')).toBe('unknown')
+ it('keeps the older Qwen-Image generations off the 2.1 pipeline (they have their own)', () => {
+ expect(classifyModel('qwen_image_fp8_e4m3fn.safetensors')).toBe('qwenimage1')
+ expect(classifyModel('qwen_image_edit_2509_fp8.safetensors')).toBe('qwenimage1')
+ expect(classifyModel('qwen_image_2512_bf16.safetensors')).toBe('qwenimage1')
+ expect(classifyModel('qwen_image_vae.safetensors')).toBe('unknown')
})
it('is an image model type, so it shows in Generate AND in Edit', () => {
diff --git a/src/api/__tests__/remote-comfy-bundle.test.ts b/src/api/__tests__/remote-comfy-bundle.test.ts
new file mode 100644
index 00000000..e26988a1
--- /dev/null
+++ b/src/api/__tests__/remote-comfy-bundle.test.ts
@@ -0,0 +1,94 @@
+/**
+ * GH #143 (duindain): Ollama and ComfyUI as services on a LAN box, LU on a
+ * Windows PC. Every model download for ComfyUI failed, with "Create models dir:
+ * permission denied (os error 5)" or "ComfyUI path not set", and the node pack
+ * install with "ComfyUI not found".
+ *
+ * The files land on this machine now, in the Model Storage folder and in
+ * ComfyUI's layout (download.rs remote_comfy, tested there), and the Model
+ * Manager says where they went and what is left to do on the other machine,
+ * instead of trying to install a node pack into a ComfyUI that is not here.
+ */
+import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
+import type { ModelBundle } from '../discover'
+
+const backendCall = vi.fn<(cmd: string, args?: unknown) => Promise<unknown>>()
+
+vi.mock('../backend', () => ({
+ backendCall: (...a: unknown[]) => backendCall(...(a as [string, unknown])),
+ localFetch: vi.fn(async () => new Response('{}', { status: 200 })),
+ comfyuiUrl: (p: string) => `http://192.168.1.20:8188${p}`,
+ fetchExternal: vi.fn(),
+ fetchLocalhostBytes: vi.fn(),
+ isTauri: () => true,
+}))
+
+import { comfyModelTarget, installBundleComplete, remoteBundleNotice } from '../discover'
+
+const REMOTE = { remote: true, host: '192.168.1.20', root: 'D:\\LU models' }
+
+const bundle = (): ModelBundle => ({
+ name: 'Wan 2.1 Unfiltered',
+ description: '',
+ tags: [],
+ totalSizeGB: 1,
+ vramRequired: '12 GB',
+ customNodes: ['gguf'],
+ files: [{
+ name: '', description: '', pulls: '', tags: [], updated: '',
+ downloadUrl: 'https://example.test/wan.gguf',
+ filename: 'wan.gguf',
+ subfolder: 'unet',
+ sizeGB: 1,
+ }],
+} as unknown as ModelBundle)
+
+beforeAll(() => {
+ ;(globalThis as unknown as { window: EventTarget }).window = new EventTarget()
+})
+
+beforeEach(() => {
+ backendCall.mockReset().mockImplementation(async (cmd: string) => {
+ if (cmd === 'comfy_model_target') return REMOTE
+ if (cmd === 'check_model_sizes') return []
+ if (cmd === 'check_download_space') return { fits: true }
+ if (cmd === 'download_model') return { status: 'started', id: '1' }
+ return { status: 'installed' }
+ })
+})
+
+describe('a bundle for a ComfyUI on another machine', () => {
+ it('downloads, installs no node pack here, and reports what is left over there', async () => {
+ const report = await installBundleComplete(bundle())
+ const calls = backendCall.mock.calls.map((c) => c[0])
+ expect(calls).toContain('download_model')
+ expect(calls).not.toContain('install_custom_node')
+ expect(report.remote).toEqual({ host: '192.168.1.20', root: 'D:\\LU models', customNodes: ['ComfyUI-GGUF'] })
+ })
+
+ it('the notice names the machine, the folder, the layout and the node pack', () => {
+ const text = remoteBundleNotice('Wan 2.1 Unfiltered', { host: '192.168.1.20', root: 'D:\\LU models', customNodes: ['ComfyUI-GGUF'] })
+ expect(text).toContain('your ComfyUI runs on 192.168.1.20')
+ expect(text).toContain('D:\\LU models')
+ expect(text).toContain("ComfyUI's own folder layout")
+ expect(text).toContain('this node pack on that machine: ComfyUI-GGUF')
+ })
+
+ it('COUNTER-CHECK: a ComfyUI on this machine installs its node pack as before', async () => {
+ backendCall.mockImplementation(async (cmd: string) => {
+ if (cmd === 'comfy_model_target') return { remote: false }
+ if (cmd === 'check_model_sizes') return []
+ if (cmd === 'check_download_space') return { fits: true }
+ if (cmd === 'download_model') return { status: 'started', id: '1' }
+ return { status: 'installed' }
+ })
+ const report = await installBundleComplete(bundle())
+ expect(report.remote).toBeUndefined()
+ await vi.waitFor(() => expect(backendCall.mock.calls.map((c) => c[0])).toContain('install_custom_node'))
+ })
+
+ it('an older backend without the command counts as local', async () => {
+ backendCall.mockImplementation(async () => { throw new Error('unknown command') })
+ await expect(comfyModelTarget()).resolves.toEqual({ remote: false })
+ })
+})
diff --git a/src/api/__tests__/sniffed-families-workflow.test.ts b/src/api/__tests__/sniffed-families-workflow.test.ts
new file mode 100644
index 00000000..66c91202
--- /dev/null
+++ b/src/api/__tests__/sniffed-families-workflow.test.ts
@@ -0,0 +1,169 @@
+/**
+ * Discord 2026-09-26..28: every model LU could not place by NAME went to
+ * CheckpointLoaderSimple and came back "Value not in list". The header sniff
+ * (commands/model_sniff.rs) now names the family, and each family gets the
+ * graph of its official Comfy-Org template. The loader follows the folder
+ * the file sits in, and missing companion files come back as downloadable
+ * specs instead of a dead end.
+ *
+ * Run: npx vitest run src/api/__tests__/sniffed-families-workflow.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('../comfyui-nodes', async (o) => ({ ...(await o<typeof import('../comfyui-nodes')>()), getAllNodeInfo: vi.fn() }))
+vi.mock('../comfyui', async (o) => ({
+ ...(await o<typeof import('../comfyui')>()),
+ findMatchingCLIP: vi.fn(async () => 'qwen_3_4b.safetensors'),
+ findMatchingVAE: vi.fn(async () => 'ae.safetensors'),
+ findFluxCLIPPair: vi.fn(async () => ({ t5: 't5xxl_fp8_e4m3fn_scaled.safetensors', clipL: 'clip_l.safetensors' })),
+}))
+
+import { buildDynamicWorkflow, WorkflowUnavailableError } from '../dynamic-workflow'
+import { getAllNodeInfo } from '../comfyui-nodes'
+import { findMatchingCLIP } from '../comfyui'
+import { classTypes, nodeOf } from './graph-test-support'
+
+const ENCODERS = [
+ 't5xxl_fp8_e4m3fn_scaled.safetensors', 'clip_l.safetensors', 'clip_g.safetensors', 'clip_l_hidream.safetensors',
+ 'clip_g_hidream.safetensors', 'llama_3.1_8b_instruct_fp8_scaled.safetensors', 'gemma_2_2b_fp16.safetensors',
+ 'qwen_2.5_vl_7b_fp8_scaled.safetensors', 'qwen_3_4b.safetensors',
+]
+const VAES = ['ae.safetensors', 'qwen_image_vae.safetensors', 'sdxl_vae.safetensors']
+const CHECKPOINTS = ['juggernautXL_v9.safetensors', 'sd3.5_large_fp8_scaled.safetensors', 'flux1-dev-fp8.safetensors']
+const UNETS = [
+ 'Chroma1-HD-fp8mixed.safetensors', 'hidream_i1_fast_fp8.safetensors', 'hidream_i1_dev_fp8.safetensors',
+ 'lumina_2_model_bf16.safetensors', 'qwen_image_fp8_e4m3fn.safetensors', 'qwen_image_edit_2509_fp8_e4m3fn.safetensors',
+ 'realvisxl_unet_only.safetensors', 'z_image_turbo_bf16.safetensors',
+]
+
+function nodes(opts: { encoders?: string[]; vaes?: string[]; clipTypes?: string[] } = {}): Record<string, unknown> {
+ const n: Record<string, unknown> = {}
+ for (const k of ['CLIPTextEncode', 'KSampler', 'EmptyLatentImage', 'EmptySD3LatentImage', 'LoadImage', 'VAEEncode', 'VAEDecode',
+ 'SaveImage', 'ModelSamplingAuraFlow', 'ModelSamplingSD3', 'TextEncodeQwenImageEditPlus', 'CFGNorm', 'FluxKontextImageScale',
+ 'QuadrupleCLIPLoader', 'TripleCLIPLoader', 'DualCLIPLoader', 'ConditioningZeroOut'])
+ n[k] = { input: { required: {} } }
+ n.CheckpointLoaderSimple = { input: { required: { ckpt_name: [CHECKPOINTS] } } }
+ n.UNETLoader = { input: { required: { unet_name: [UNETS] } } }
+ n.CLIPLoader = { input: { required: { clip_name: [opts.encoders ?? ENCODERS], type: [opts.clipTypes ?? ['stable_diffusion', 'chroma', 'lumina2', 'qwen_image', 'flux2', 'krea2']] } } }
+ n.VAELoader = { input: { required: { vae_name: [opts.vaes ?? VAES] } } }
+ return n
+}
+const run = (model: string, extra: Record<string, unknown> = {}) => ({
+ model, prompt: 'a red door', negativePrompt: 'blurry', sampler: 'euler', scheduler: 'simple',
+ width: 1024, height: 1024, steps: 20, cfgScale: 4, seed: 1, batchSize: 1, ...extra,
+}) as never
+
+beforeEach(() => {
+ vi.mocked(getAllNodeInfo).mockResolvedValue(nodes() as never)
+})
+
+describe('each sniffed family builds its official template graph', () => {
+ it('Chroma: UNET + CLIPLoader(chroma, T5) + ae + AuraFlow shift 1 + SD3 latent', async () => {
+ const wf = await buildDynamicWorkflow(run('Chroma1-HD-fp8mixed.safetensors'), 'chroma')
+ expect(nodeOf(wf, 'UNETLoader')![1].inputs.unet_name).toBe('Chroma1-HD-fp8mixed.safetensors')
+ expect(nodeOf(wf, 'CLIPLoader')![1].inputs).toMatchObject({ clip_name: 't5xxl_fp8_e4m3fn_scaled.safetensors', type: 'chroma' })
+ expect(nodeOf(wf, 'VAELoader')![1].inputs.vae_name).toBe('ae.safetensors')
+ expect(nodeOf(wf, 'ModelSamplingAuraFlow')![1].inputs.shift).toBe(1)
+ expect(classTypes(wf)).toContain('EmptySD3LatentImage')
+ expect(classTypes(wf)).not.toContain('CheckpointLoaderSimple')
+ })
+
+ it('HiDream: QuadrupleCLIPLoader in template order, ModelSamplingSD3 3 (fast) or 6 (dev)', async () => {
+ const fast = await buildDynamicWorkflow(run('hidream_i1_fast_fp8.safetensors'), 'hidream')
+ expect(nodeOf(fast, 'QuadrupleCLIPLoader')![1].inputs).toEqual({
+ clip_name1: 'clip_l_hidream.safetensors', clip_name2: 'clip_g_hidream.safetensors',
+ clip_name3: 't5xxl_fp8_e4m3fn_scaled.safetensors', clip_name4: 'llama_3.1_8b_instruct_fp8_scaled.safetensors',
+ })
+ expect(nodeOf(fast, 'ModelSamplingSD3')![1].inputs.shift).toBe(3)
+ const dev = await buildDynamicWorkflow(run('hidream_i1_dev_fp8.safetensors'), 'hidream')
+ expect(nodeOf(dev, 'ModelSamplingSD3')![1].inputs.shift).toBe(6)
+ })
+
+ it('Lumina 2: Gemma 2 2B, AuraFlow 6, and the system prompt ahead of the user prompt', async () => {
+ const wf = await buildDynamicWorkflow(run('lumina_2_model_bf16.safetensors'), 'lumina2')
+ expect(nodeOf(wf, 'CLIPLoader')![1].inputs).toMatchObject({ clip_name: 'gemma_2_2b_fp16.safetensors', type: 'lumina2' })
+ expect(nodeOf(wf, 'ModelSamplingAuraFlow')![1].inputs.shift).toBe(6)
+ const texts = Object.values(wf).filter((n) => n.class_type === 'CLIPTextEncode').map((n) => String(n.inputs!.text))
+ expect(texts[0]).toMatch(/^You are an assistant designed to generate superior images.* <Prompt Start> a red door$/)
+ expect(texts[1]).toMatch(/low-quality images based on textual prompts <Prompt Start> blurry$/)
+ })
+
+ it('Qwen-Image 1: Qwen2.5-VL, qwen_image_vae, AuraFlow 3.1; a source image is plain img2img', async () => {
+ const wf = await buildDynamicWorkflow(run('qwen_image_fp8_e4m3fn.safetensors', { inputImage: 'src.png', denoise: 0.6 }), 'qwenimage1')
+ expect(nodeOf(wf, 'CLIPLoader')![1].inputs).toMatchObject({ clip_name: 'qwen_2.5_vl_7b_fp8_scaled.safetensors', type: 'qwen_image' })
+ expect(nodeOf(wf, 'VAELoader')![1].inputs.vae_name).toBe('qwen_image_vae.safetensors')
+ expect(nodeOf(wf, 'ModelSamplingAuraFlow')![1].inputs.shift).toBe(3.1)
+ expect(nodeOf(wf, 'KSampler')![1].inputs.denoise).toBe(0.6)
+ expect(classTypes(wf)).not.toContain('TextEncodeQwenImageEditPlus')
+ })
+
+ it('Qwen-Image-Edit: the source goes through TextEncodeQwenImageEditPlus on both sides, denoise 1, CFGNorm, shift 3', async () => {
+ const wf = await buildDynamicWorkflow(run('qwen_image_edit_2509_fp8_e4m3fn.safetensors', { inputImage: 'house.png', denoise: 0.7 }), 'qwenimage1')
+ const edits = Object.values(wf).filter((n) => n.class_type === 'TextEncodeQwenImageEditPlus')
+ expect(edits.map((n) => n.inputs!.prompt)).toEqual(['a red door', 'blurry'])
+ const [scaleId] = nodeOf(wf, 'FluxKontextImageScale')!
+ for (const e of edits) expect(e.inputs!.image1).toEqual([scaleId, 0])
+ const [encId, enc] = nodeOf(wf, 'VAEEncode')!
+ expect(enc.inputs.pixels).toEqual([scaleId, 0])
+ const [, sampler] = nodeOf(wf, 'KSampler')!
+ expect(sampler.inputs.latent_image).toEqual([encId, 0])
+ expect(sampler.inputs.denoise).toBe(1)
+ expect(nodeOf(wf, 'ModelSamplingAuraFlow')![1].inputs.shift).toBe(3)
+ expect(classTypes(wf)).toContain('CFGNorm')
+ expect(nodeOf(wf, 'LoadImage')![1].inputs.image).toBe('house.png')
+ })
+
+ it('SD 3.5 all-in-one checkpoint: MODEL, CLIP and VAE from the checkpoint itself', async () => {
+ const wf = await buildDynamicWorkflow(run('sd3.5_large_fp8_scaled.safetensors', { modelParts: { textEncoder: true, vae: true } }), 'sd3')
+ const [ckptId] = nodeOf(wf, 'CheckpointLoaderSimple')!
+ expect(classTypes(wf)).not.toContain('TripleCLIPLoader')
+ expect(classTypes(wf)).not.toContain('VAELoader')
+ expect(nodeOf(wf, 'CLIPTextEncode')![1].inputs.clip).toEqual([ckptId, 1])
+ expect(nodeOf(wf, 'VAEDecode')![1].inputs.vae).toEqual([ckptId, 2])
+ })
+
+ it('an SDXL unet in diffusion_models: UNETLoader + DualCLIPLoader(sdxl) + sdxl_vae, Edit works on it', async () => {
+ const wf = await buildDynamicWorkflow(run('realvisxl_unet_only.safetensors', { inputImage: 'src.png', denoise: 0.7 }), 'sdxl')
+ expect(nodeOf(wf, 'UNETLoader')![1].inputs.unet_name).toBe('realvisxl_unet_only.safetensors')
+ expect(nodeOf(wf, 'DualCLIPLoader')![1].inputs).toEqual({ clip_name1: 'clip_l.safetensors', clip_name2: 'clip_g.safetensors', type: 'sdxl' })
+ expect(nodeOf(wf, 'VAELoader')![1].inputs.vae_name).toBe('sdxl_vae.safetensors')
+ expect(classTypes(wf)).not.toContain('CheckpointLoaderSimple')
+ expect(classTypes(wf)).toContain('VAEEncode')
+ })
+})
+
+describe('the loader follows the folder', () => {
+ it('a FLUX all-in-one file in models/checkpoints loads through CheckpointLoaderSimple and uses its own parts', async () => {
+ const wf = await buildDynamicWorkflow(run('flux1-dev-fp8.safetensors', { modelParts: { textEncoder: true, vae: true } }), 'flux')
+ const [ckptId] = nodeOf(wf, 'CheckpointLoaderSimple')!
+ expect(classTypes(wf)).not.toContain('UNETLoader')
+ expect(nodeOf(wf, 'KSampler')![1].inputs.model).toEqual([ckptId, 0])
+ expect(nodeOf(wf, 'VAEDecode')![1].inputs.vae).toEqual([ckptId, 2])
+ })
+})
+
+describe('missing pieces come back as something Create can fix', () => {
+ it('a missing encoder / VAE names downloadable files with their sizes', async () => {
+ vi.mocked(getAllNodeInfo).mockResolvedValue(nodes({ encoders: ['clip_l.safetensors'], vaes: [] }) as never)
+ const err = await buildDynamicWorkflow(run('hidream_i1_fast_fp8.safetensors'), 'hidream').catch((e) => e)
+ expect(err).toBeInstanceOf(WorkflowUnavailableError)
+ const names = (err as WorkflowUnavailableError).missing!.map((m) => m.downloadFilename)
+ expect(names).toEqual(['clip_g_hidream.safetensors', 't5xxl_fp8_e4m3fn_scaled.safetensors', 'llama_3.1_8b_instruct_fp8_scaled.safetensors', 'ae.safetensors'])
+ for (const m of (err as WorkflowUnavailableError).missing!) {
+ expect(m.downloadUrl).toMatch(/^https:\/\/huggingface\.co\//)
+ expect(m.sizeGB).toBeGreaterThan(0)
+ }
+ })
+
+ it('an existing family whose resolver names a registry file gets that file as a download', async () => {
+ vi.mocked(findMatchingCLIP).mockRejectedValueOnce(new Error('No Z-Image text encoder found. Download "qwen_3_4b.safetensors" from the Model Manager.'))
+ const err = await buildDynamicWorkflow(run('z_image_turbo_bf16.safetensors'), 'zimage').catch((e) => e)
+ expect((err as WorkflowUnavailableError).missing?.map((m) => m.downloadFilename)).toEqual(['qwen_3_4b.safetensors'])
+ })
+
+ it('a loader type the local ComfyUI lacks asks for the update', async () => {
+ vi.mocked(getAllNodeInfo).mockResolvedValue(nodes({ clipTypes: ['stable_diffusion'] }) as never)
+ const err = await buildDynamicWorkflow(run('Chroma1-HD-fp8mixed.safetensors'), 'chroma').catch((e) => e)
+ expect(err).toMatchObject({ name: 'WorkflowUnavailableError', needsComfyUpdate: true })
+ })
+})
diff --git a/src/api/__tests__/vram-handoff.test.ts b/src/api/__tests__/vram-handoff.test.ts
index f456ae0a..feb3a7f7 100644
--- a/src/api/__tests__/vram-handoff.test.ts
+++ b/src/api/__tests__/vram-handoff.test.ts
@@ -992,3 +992,52 @@ describe('chat-gen image path — per-architecture defaults (not one hardcoded c
expect(buildDynamicWorkflow.mock.calls[0][0].width).toBe(512)
})
})
+
+// ── The chat image tool: framing (GH #142) and the model family (Discord) ──
+
+describe('vramHandoffGenerate — what the image tool builds', () => {
+ beforeEach(() => {
+ getActiveAgentModel.mockReturnValue({ name: 'gpt-4o', providerId: 'openai', remote: false })
+ buildDynamicWorkflow.mockResolvedValue({ '9': { class_type: 'SaveImage' } })
+ submitWorkflow.mockResolvedValue('pid-1')
+ getHistory.mockResolvedValue(completedHistory())
+ })
+ const built = () => buildDynamicWorkflow.mock.calls[0] as [Record<string, unknown>, string]
+
+ it('GH #142: a full-body prompt with no size gets the portrait frame, not the square', async () => {
+ getImageModels.mockResolvedValue([{ name: 'sdxl.safetensors', type: 'sdxl', source: 'checkpoint' }])
+ await vramHandoffGenerate('image', { prompt: 'full body shot of a woman kneeling on a bed, whole bed in frame' })
+ expect([built()[0].width, built()[0].height]).toEqual([832, 1216])
+ })
+
+ it('SD 1.5 gets its own trained portrait size', async () => {
+ getImageModels.mockResolvedValue([{ name: 'sd15.safetensors', type: 'sd15', source: 'checkpoint' }])
+ await vramHandoffGenerate('image', { prompt: 'a knight, head to toe, standing' })
+ expect([built()[0].width, built()[0].height]).toEqual([512, 768])
+ })
+
+ it('a size the caller named wins', async () => {
+ getImageModels.mockResolvedValue([{ name: 'sdxl.safetensors', type: 'sdxl', source: 'checkpoint' }])
+ await vramHandoffGenerate('image', { prompt: 'full body shot of a woman', width: 1216, height: 832 })
+ expect([built()[0].width, built()[0].height]).toEqual([1216, 832])
+ })
+
+ it('COUNTER-CHECK: anything else keeps the model default', async () => {
+ getImageModels.mockResolvedValue([{ name: 'sdxl.safetensors', type: 'sdxl', source: 'checkpoint' }])
+ await vramHandoffGenerate('image', { prompt: 'close-up portrait of a woman' })
+ expect([built()[0].width, built()[0].height]).toEqual([1024, 1024])
+ })
+
+ it('the family comes from the header list, with the parts the file carries', async () => {
+ // A Z-Image under a CivitAI name the name rules cannot place: by name
+ // alone it went to the checkpoint loader and ComfyUI refused it.
+ getImageModels.mockResolvedValue([{
+ name: 'mystery_merge_v3.safetensors', type: 'zimage', source: 'diffusion_model',
+ parts: { textEncoder: false, vae: false },
+ }])
+ await vramHandoffGenerate('image', { prompt: 'a lighthouse at dusk' })
+ const [params, type] = built()
+ expect(type).toBe('zimage')
+ expect(params.modelParts).toEqual({ textEncoder: false, vae: false })
+ })
+})
diff --git a/src/api/__tests__/wrapper-node-names.test.ts b/src/api/__tests__/wrapper-node-names.test.ts
index 417ebab9..434ba5ae 100644
--- a/src/api/__tests__/wrapper-node-names.test.ts
+++ b/src/api/__tests__/wrapper-node-names.test.ts
@@ -49,6 +49,11 @@ const CORE_NODES = new Set([
// Comfy-Org templates for Qwen-Image 2.1. It arrived in 0.37.0, which is
// younger than most of this list, so determineStrategy gates the lane on
// its presence and says which version adds it.
+ // Checked against ComfyUI master on 2026-09-28 for the header-sniffed
+ // families: QuadrupleCLIPLoader (nodes_hidream), TripleCLIPLoader
+ // (nodes_sd3), TextEncodeQwenImageEditPlus (nodes_qwen), CFGNorm
+ // (nodes_cfg), FluxKontextImageScale (nodes_flux).
+ 'QuadrupleCLIPLoader', 'TripleCLIPLoader', 'TextEncodeQwenImageEditPlus', 'CFGNorm', 'FluxKontextImageScale',
'CLIPTextEncode', 'TextEncodeQwenImage21', 'CLIPSetLastLayer', 'CLIPVisionEncode', 'ConditioningZeroOut',
'InpaintModelConditioning', 'AudioEncoderEncode', 'ModelSamplingSD3', 'ModelSamplingAuraFlow',
'SVD_img2vid_Conditioning', 'VideoLinearCFGGuidance',
diff --git a/src/api/comfyui.ts b/src/api/comfyui.ts
index f7b66606..bbb91fdd 100644
--- a/src/api/comfyui.ts
+++ b/src/api/comfyui.ts
@@ -52,6 +52,9 @@ export interface GenerateParams {
seed: number
batchSize: number
inputImage?: string // I2I source image filename (uploaded to ComfyUI)
+ /** What the model file carries besides the diffusion model (header sniff).
+ * Lets an all-in-one file in models/checkpoints use its own encoder/VAE. */
+ modelParts?: { textEncoder: boolean; vae: boolean }
denoise?: number // I2I denoise strength (0.0–1.0, default 1.0 = full txt2img)
removebg?: boolean // Background removal: LoadImage → RMBG → SaveImage cutout (no diffusion)
// Local Edit (mask inpaint): ComfyUI /upload/image filename of the painted
@@ -153,7 +156,7 @@ export function galleryTypeForFile(
// 2.5.8: ace / wans2v / wananimate / wanvace are the specialized local-lane
// architectures (music, talking character, motion control). They are neither
// image nor video picker material — each lane has its own model list.
-export type ModelType = 'flux' | 'flux2' | 'krea2' | 'zimage' | 'ernie_image' | 'qwenimage' | 'sdxl' | 'sd15' | 'wan' | 'wan22' | 'hunyuan' | 'ltx' | 'mochi' | 'cosmos' | 'cogvideo' | 'svd' | 'framepack' | 'pyramidflow' | 'allegro' | 'ace' | 'wans2v' | 'wananimate' | 'wanvace' | 'animatediff' | 'unknown'
+export type ModelType = 'flux' | 'flux2' | 'krea2' | 'zimage' | 'ernie_image' | 'qwenimage' | 'qwenimage1' | 'chroma' | 'hidream' | 'sd3' | 'lumina2' | 'sdxl' | 'sd15' | 'wan' | 'wan22' | 'hunyuan' | 'ltx' | 'mochi' | 'cosmos' | 'cogvideo' | 'svd' | 'framepack' | 'pyramidflow' | 'allegro' | 'ace' | 'wans2v' | 'wananimate' | 'wanvace' | 'animatediff' | 'unknown'
export type VideoBackend = 'wan' | 'animatediff' | 'none'
export interface ClassifiedModel {
@@ -166,6 +169,9 @@ export interface ClassifiedModel {
* (counter-check 2026-08-29, and five more folders in the R5 re-measure
* the day after). */
source: ComfyModelSource
+ /** What the file carries besides the diffusion model, read from its header
+ * (commands/model_sniff.rs). Absent when the header was not readable. */
+ parts?: { textEncoder: boolean; vae: boolean }
}
/** The ComfyUI\models folders that hold files a user installs, none of which
@@ -284,6 +290,21 @@ export function classifyModel(name: string | null | undefined): ModelType {
// Before the 'krea' check and the 'xl' suffix scan below, so no later tag
// can take a 2.1 file first.
if (/qwen[._-]?image/.test(lower) && /2[._-]?1/.test(lower)) return 'qwenimage'
+ // Qwen-Image 1 (2508, 2512) and Qwen-Image-Edit (2509, 2511, FireRed):
+ // Qwen2.5-VL 7B encoder, qwen_image_vae, and for the edit files
+ // TextEncodeQwenImageEditPlus (Discord 2026-09-28: "every model except
+ // Juggernaut" — these used to fall through to 'unknown' and the checkpoint
+ // loader). Never the VAE that carries the same stem.
+ if ((/qwen[._-]?image/.test(lower) || lower.includes('firered_image_edit')) && !/[._-]vae/.test(lower)) return 'qwenimage1'
+
+ // Families that used to fall through to 'unknown' and the checkpoint loader.
+ // The header sniff (commands/model_sniff.rs) finds them under any name; the
+ // names here cover a ComfyUI on another machine, where no header is readable.
+ // Word start only: zavychromaXL is an SDXL checkpoint.
+ if (/(^|[^a-z])chroma/.test(lower)) return 'chroma'
+ if (lower.includes('hidream')) return 'hidream'
+ if (/(^|[^a-z0-9])sd[._-]?3|stable[._-]?diffusion[._-]?3/.test(lower)) return 'sd3'
+ if (lower.includes('lumina') || lower.includes('netayume')) return 'lumina2'
// Z-Image (uses qwen_image CLIP type, NOT flux2 — different embedding dimensions)
if (lower.includes('z_image') || lower.includes('z-image') || lower.includes('zimage')) return 'zimage'
@@ -320,8 +341,20 @@ export function classifyModel(name: string | null | undefined): ModelType {
return 'unknown'
}
+/** HiDream I1 ships as fast, dev and full, three different samplers
+ * (hidream_i1_fast / _dev / _full templates). Fast is the type default. */
+export function hidreamSampling(model: string): { steps: number; cfg: number; sampler: string; scheduler: string } {
+ const lower = model.toLowerCase()
+ if (lower.includes('full')) return { steps: 50, cfg: 5.0, sampler: 'uni_pc', scheduler: 'simple' }
+ if (lower.includes('dev')) return { steps: 28, cfg: 1.0, sampler: 'lcm', scheduler: 'normal' }
+ const d = MODEL_TYPE_DEFAULTS.hidream
+ return { steps: d.steps, cfg: d.cfg, sampler: d.sampler, scheduler: d.scheduler }
+}
+
export function isImageModelType(type: ModelType): boolean {
- return type === 'flux' || type === 'flux2' || type === 'krea2' || type === 'zimage' || type === 'ernie_image' || type === 'qwenimage' || type === 'sdxl' || type === 'sd15' || type === 'unknown'
+ return type === 'flux' || type === 'flux2' || type === 'krea2' || type === 'zimage' || type === 'ernie_image' || type === 'qwenimage'
+ || type === 'qwenimage1' || type === 'chroma' || type === 'hidream' || type === 'sd3' || type === 'lumina2'
+ || type === 'sdxl' || type === 'sd15' || type === 'unknown'
}
export function isVideoModelType(type: ModelType): boolean {
@@ -451,6 +484,13 @@ export const MODEL_TYPE_DEFAULTS: Record<string, ModelTypeDefaults> = {
// KSampler widgets: 25 steps, cfg 1, euler, simple; canvas 1024x1024 at
// 1 megapixel). Native 2K is available by raising width/height.
qwenimage: { steps: 25, cfg: 1.0, sampler: 'euler', scheduler: 'simple', width: 1024, height: 1024, frames: 1, fps: 1 },
+ // Numbers from the official Comfy-Org templates (image_qwen_image, image_qwen_image_edit_2509,
+ // image_chroma_text_to_image, hidream_i1_fast, sd3.5_simple_example) and nodes_lumina2.
+ qwenimage1: { steps: 20, cfg: 4.0, sampler: 'euler', scheduler: 'simple', width: 1328, height: 1328, frames: 1, fps: 1 },
+ chroma: { steps: 26, cfg: 3.5, sampler: 'euler', scheduler: 'beta', width: 1024, height: 1024, frames: 1, fps: 1 },
+ hidream: { steps: 16, cfg: 1.0, sampler: 'lcm', scheduler: 'normal', width: 1024, height: 1024, frames: 1, fps: 1 },
+ sd3: { steps: 20, cfg: 4.0, sampler: 'euler', scheduler: 'sgm_uniform', width: 1024, height: 1024, frames: 1, fps: 1 },
+ lumina2: { steps: 25, cfg: 4.0, sampler: 'res_multistep', scheduler: 'simple', width: 1024, height: 1024, frames: 1, fps: 1 },
unknown:{ steps: 25, cfg: 7.0, sampler: 'euler', scheduler: 'normal', width: 1024, height: 1024, frames: 1, fps: 1 },
// ── Video ──
wan: { steps: 30, cfg: 6.0, sampler: 'euler', scheduler: 'normal', width: 832, height: 480, frames: 81, fps: 16 },
@@ -897,6 +937,71 @@ export async function filterPartialFiles(filenames: string[]): Promise<Set<strin
* The catalogue card keeps its own verdict (discover.ts filters there) and goes
* on saying honestly that the package is not fully downloaded.
*/
+/** A VAE that landed in a main model folder (Discord 2026-09-26: a CivitAI
+ * download of minimax_h3_video_vae_fp16 showed up as an IMAGE model). It can
+ * never run as one, so the picker leaves it out. Deliberately narrow: only a
+ * name that ENDS in vae (plus a precision tag). */
+export function isStrayAddonFile(name: string): boolean {
+ const base = name.split(/[\\/]/).pop()!.toLowerCase()
+ // "bakedvae", "realvisxl_v40_vae": checkpoints that carry their VAE.
+ if (base.includes('baked') || /v\d+[a-z0-9]*[._-]vae/.test(base)) return false
+ return /[._-]vae([._-](fp16|fp32|bf16|fp8[a-z0-9_]*))?\.(safetensors|sft|pt|pth|ckpt|bin|gguf)$/.test(base)
+}
+
+/** Header families that map straight onto a ModelType. */
+const SNIFF_TYPES: Record<string, ModelType> = {
+ flux: 'flux', flux2: 'flux2', krea2: 'krea2', zimage: 'zimage', ernie_image: 'ernie_image',
+ qwenimage: 'qwenimage', qwenimage1: 'qwenimage1', chroma: 'chroma', hidream: 'hidream',
+ sd3: 'sd3', lumina2: 'lumina2', sdxl: 'sdxl', sd15: 'sd15', wan: 'wan',
+}
+
+/** Name types the header may overrule: the image families and 'unknown'. A
+ * video or lane name keeps its name type, because Wan 2.1 and 2.2 (and S2V,
+ * Animate, VACE) share one tensor layout and only the name tells them apart. */
+const SNIFF_OVERRULES = (t: ModelType) => isImageModelType(t)
+
+/**
+ * Discord 2026-09-26..28 (boromirofgeo, haschbar, s3aldra): a CivitAI name
+ * says nothing reliable about the architecture, and every name LU could not
+ * place went to the checkpoint loader ("Node 1 (CheckpointLoaderSimple):
+ * Value not in list"). The file header does say it. Rewrites `type` in place
+ * from the header, drops files that are a bare VAE or text encoder, and
+ * records which parts an all-in-one file carries. Best effort: a ComfyUI on
+ * another machine, a GGUF, or a browser build keeps the name-based answer.
+ */
+export async function applyHeaderSniff(models: ClassifiedModel[]): Promise<void> {
+ const ask = models.filter((m) => SNIFF_OVERRULES(m.type) && !m.name.toLowerCase().endsWith('.gguf'))
+ if (ask.length === 0) return
+ let answers: Array<{ folder: string; name: string; arch?: string | null; hasTextEncoder?: boolean; hasVae?: boolean }>
+ try {
+ const { backendCall, isTauri } = await import('./backend')
+ if (!isTauri()) return
+ answers = await backendCall('sniff_model_files', {
+ files: ask.map((m) => ({ folder: m.source === 'checkpoint' ? 'checkpoints' : 'diffusion_models', name: m.name })),
+ })
+ } catch (err) {
+ log.warn('comfyui.header_sniff_failed', { err })
+ return
+ }
+ const byKey = new Map(answers.map((a) => [`${a.folder}|${a.name}`, a]))
+ const drop = new Set<ClassifiedModel>()
+ for (const m of ask) {
+ const a = byKey.get(`${m.source === 'checkpoint' ? 'checkpoints' : 'diffusion_models'}|${m.name}`)
+ if (!a?.arch) continue
+ if (a.arch === 'vae' || a.arch === 'text_encoder') { drop.add(m); continue }
+ const type = SNIFF_TYPES[a.arch]
+ if (type && type !== m.type) {
+ log.info('comfyui.header_sniff_retyped', { name: m.name, from: m.type, to: type })
+ m.type = type
+ }
+ m.parts = { textEncoder: !!a.hasTextEncoder, vae: !!a.hasVae }
+ }
+ if (drop.size > 0) {
+ const kept = models.filter((m) => !drop.has(m))
+ models.splice(0, models.length, ...kept)
+ }
+}
+
async function mainModelLane(
keep: (type: ModelType) => boolean,
hidePartialDownloads: boolean,
@@ -917,29 +1022,27 @@ async function mainModelLane(
: null
const result: ClassifiedModel[] = []
+ const candidates: ClassifiedModel[] = []
for (const name of checkpoints) {
if (complete && !complete.has(name)) continue
- const type = classifyModel(name)
- // One predicate for both loops. isImageModelType lets 'unknown' through, so
- // a checkpoint the classifier cannot name is still offered, while the video
- // types (SVD) and the lane architectures (ACE audio, Wan S2V/Animate/VACE)
- // stay in their own pickers. The old branch renamed anything unmatched to
- // sdxl instead of skipping it, which put an ACE-Step music checkpoint at
- // the top of the image picker on a real box.
- if (!keep(type)) continue
- result.push({ name, type, source: 'checkpoint' })
+ if (isStrayAddonFile(name)) continue
+ candidates.push({ name, type: classifyModel(name), source: 'checkpoint' })
}
-
for (const name of unets) {
if (complete && !complete.has(name)) continue
- const type = classifyModel(name)
- // isImageModelType already lets 'unknown' through, so a UNET the classifier
- // cannot name is still offered. The lane-specific architectures (ACE audio,
- // Wan S2V/Animate/VACE) are excluded by that same predicate and stay in
- // their own pickers.
- if (keep(type)) {
- result.push({ name, type, source: 'diffusion_model' })
- }
+ if (isStrayAddonFile(name)) continue
+ candidates.push({ name, type: classifyModel(name), source: 'diffusion_model' })
+ }
+ await applyHeaderSniff(candidates)
+
+ // One predicate for both folders. isImageModelType lets 'unknown' through,
+ // so a file neither the name nor the header can place is still offered,
+ // while the video types (SVD) and the lane architectures (ACE audio, Wan
+ // S2V/Animate/VACE) stay in their own pickers. The old branch renamed
+ // anything unmatched to sdxl instead of skipping it, which put an ACE-Step
+ // music checkpoint at the top of the image picker on a real box.
+ for (const m of candidates) {
+ if (keep(m.type)) result.push(m)
}
return result
@@ -1795,7 +1898,14 @@ export async function submitWorkflow(workflow: ComfyApiGraph, clientId?: string)
if (isRecord(nodeErrors)) {
for (const [nodeId, data] of Object.entries(nodeErrors)) {
const errs = asRecordArray(isRecord(data) ? data.errors : undefined)
- .map((e) => asString(e.message) ?? asString(e.details) ?? '')
+ // "Value not in list" alone names no value; the details say which
+ // one ("ckpt_name: 'x.safetensors' not in [...]"). The list itself
+ // can be hundreds of file names, so it is cut off.
+ .map((e) => {
+ const message = asString(e.message) ?? ''
+ const details = asString(e.details)?.split(' not in [')[0].slice(0, 200)
+ return details && message ? `${message} (${details})` : message || details || ''
+ })
.filter(Boolean)
.join(', ') || 'unknown'
const cls = (isRecord(data) ? asString(data.class_type) : undefined) ?? '?'
diff --git a/src/api/component-registry.ts b/src/api/component-registry.ts
index e9f74cd4..0f31aa48 100644
--- a/src/api/component-registry.ts
+++ b/src/api/component-registry.ts
@@ -28,6 +28,8 @@ export interface ComponentSpec {
downloadUrl?: string
/** ComfyUI\models subfolder this component's download lands in. */
subfolder?: string
+ /** Size, for the "download N GB now?" question in Create. */
+ sizeGB?: number
}
export interface ComponentRequirements {
diff --git a/src/api/discover.ts b/src/api/discover.ts
index 72e6f83d..49992145 100644
--- a/src/api/discover.ts
+++ b/src/api/discover.ts
@@ -259,6 +259,42 @@ export async function checkDownloadSpace(
}
}
+// ─── A ComfyUI on another machine (GH #143) ───
+
+/** Where ComfyUI models land. `remote`: the ComfyUI LU talks to runs on
+ * another machine, so the files go to `root` on this one, in ComfyUI's own
+ * folder layout, for the user to copy over (download.rs remote_comfy). */
+export interface ComfyModelTarget {
+ remote: boolean
+ host?: string
+ root?: string
+}
+
+export async function comfyModelTarget(): Promise<ComfyModelTarget> {
+ try {
+ const t = await backendCall<ComfyModelTarget>('comfy_model_target')
+ return t && t.remote && t.host && t.root ? t : { remote: false }
+ } catch {
+ // An older backend, or the dev server: the files go where they always went.
+ return { remote: false }
+ }
+}
+
+/** What a bundle install onto a remote ComfyUI leaves for the user to do. */
+export interface RemoteBundleReport {
+ host: string
+ root: string
+ /** Node packs the bundle needs, to install on that machine. */
+ customNodes: string[]
+}
+
+export function remoteBundleNotice(bundleName: string, r: RemoteBundleReport): string {
+ const nodes = r.customNodes.length > 0
+ ? ` It also needs ${r.customNodes.length === 1 ? 'this node pack' : 'these node packs'} on that machine: ${r.customNodes.join(', ')}. Install ${r.customNodes.length === 1 ? 'it' : 'them'} there and restart ComfyUI.`
+ : ''
+ return `${bundleName}: your ComfyUI runs on ${r.host}, so LU saves the files here, in ${r.root}, in ComfyUI's own folder layout. Once they are done, copy the folders in there into the models folder of ComfyUI on that machine (or share the folder with it), then refresh the models.${nodes}`
+}
+
// ─── Custom Node Installation ───
/** Check if ALL files in a bundle are completely downloaded (size validated) */
@@ -652,8 +688,12 @@ export function bundleBytesToFetch(
return { bytes: Math.round(bytes), subfolder: pending[0].subfolder, files: pending.length }
}
-export async function installBundleComplete(bundle: ModelBundle): Promise<void> {
+export async function installBundleComplete(bundle: ModelBundle): Promise<{ remote?: RemoteBundleReport }> {
const errors: string[] = []
+ // GH #143: a ComfyUI on another machine. The files land here for the user
+ // to copy over, so there is no engine to wait for and no node pack LU could
+ // install; the report says what is left instead.
+ const target = await comfyModelTarget()
// Pre-check: which files already exist on disk (skip re-downloading them)
const installedFiles = new Set<string>()
@@ -734,6 +774,10 @@ export async function installBundleComplete(bundle: ModelBundle): Promise<void>
for (const file of bundle.files) {
if (!file.downloadUrl || !file.filename || !file.subfolder) continue
if (installedFiles.has(file.filename)) {
+ if (target.remote) {
+ window.dispatchEvent(new CustomEvent('comfyui-download-exists', { detail: { filename: file.filename } }))
+ continue
+ }
const visible = (await judgeable).has(file.subfolder) ? await comfyCanSee(file.filename) : null
// The file is on disk at its full size. That much is certain right now,
// so it is what the card is told, and an engine that has not caught up
@@ -765,7 +809,7 @@ export async function installBundleComplete(bundle: ModelBundle): Promise<void>
// builder went on recommending the pack this very call had just installed
// (T-67), and its restart was a hand-rolled sleep that could not tell a
// ComfyUI LU owns from one it does not.
- if (bundle.customNodes && bundle.customNodes.length > 0) {
+ if (bundle.customNodes && bundle.customNodes.length > 0 && !target.remote) {
void installCustomNodes([...bundle.customNodes], { keepGoing: true, restart: true })
.catch((err) => log.warn('[discover] Custom node install/restart failed', { err }))
}
@@ -788,6 +832,16 @@ export async function installBundleComplete(bundle: ModelBundle): Promise<void>
if (errors.length > 0) {
throw new Error(`Bundle install had ${errors.length} issue(s): ${errors.join('; ')}`)
}
+ if (target.remote && target.host && target.root) {
+ return {
+ remote: {
+ host: target.host,
+ root: target.root,
+ customNodes: (bundle.customNodes ?? []).map((k) => CUSTOM_NODE_REGISTRY[k]?.name ?? k),
+ },
+ }
+ }
+ return {}
}
// ─── Component Registry: What each model type needs to work ───
diff --git a/src/api/dynamic-workflow.ts b/src/api/dynamic-workflow.ts
index 5279231d..43616e8b 100644
--- a/src/api/dynamic-workflow.ts
+++ b/src/api/dynamic-workflow.ts
@@ -5,7 +5,9 @@ import {
import type { ModelType, GenerateParams, VideoParams } from './comfyui'
import { log } from '../lib/logger'
import { resolveRunSeed } from '../lib/run-seed'
-import { readComboOptions } from './comfyui-enum'
+import { nodeComboOptions, readComboOptions } from './comfyui-enum'
+import { COMPONENT_REGISTRY, type ComponentSpec } from './component-registry'
+import { MissingComponentsError, resolveFamilyParts, type SniffedFamily } from './family-components'
import {
getAllNodeInfo,
categorizeNodes,
@@ -65,6 +67,15 @@ export type WorkflowStrategy =
| 'unet_zimage' // Z-Image: UNETLoader + CLIPLoader(qwen_image) + VAELoader + EmptySD3LatentImage
| 'unet_ernie_image' // ERNIE-Image: UNETLoader + CLIPLoader(flux2) + VAELoader + EmptyFlux2LatentImage + ConditioningZeroOut
| 'unet_qwenimage' // Qwen-Image 2.1: UNETLoader + CLIPLoader(qwen_image) + VAELoader + TextEncodeQwenImage21 (generate and edit)
+ // The families below came in with the header sniff (Discord 2026-09-28).
+ // Graphs follow the official Comfy-Org templates, see family-components.ts.
+ | 'unet_qwenimage1' // Qwen-Image 1 / Edit: CLIPLoader(qwen_image, Qwen2.5-VL) + qwen_image_vae + AuraFlow shift 3.1 (edit: TextEncodeQwenImageEditPlus)
+ | 'unet_chroma' // Chroma: CLIPLoader(chroma, T5) + ae + AuraFlow shift 1
+ | 'unet_hidream' // HiDream I1: QuadrupleCLIPLoader + ae + ModelSamplingSD3
+ | 'unet_sd3' // SD 3.5: TripleCLIPLoader (or the checkpoint's own) + SD3 latent
+ | 'unet_lumina2' // Lumina 2: CLIPLoader(lumina2, Gemma 2 2B) + ae + AuraFlow shift 6 + system prompt
+ | 'unet_sdxl' // SDXL transformer in diffusion_models: DualCLIPLoader(sdxl) + sdxl_vae
+ | 'unet_sd15' // SD 1.5 unet in diffusion_models: CLIPLoader(stable_diffusion) + ft-mse VAE
| 'unet_video' // Wan/Hunyuan: UNETLoader + CLIPLoader + VAELoader + EmptyHunyuanLatentVideo
| 'wan22' // Wan 2.2 TI2V-5B: UNET + CLIP + Wan 2.2 VAE + Wan22ImageToVideoLatent (unified T2V/I2V)
| 'unet_ltx' // LTX Video: UNETLoader + CLIPLoader + EmptyLTXVLatentVideo
@@ -141,6 +152,19 @@ export function determineStrategy(
return { strategy: 'unavailable', reason: 'Z-Image requires UNETLoader + CLIPLoader + VAELoader nodes' }
}
+ // Header-sniffed families (Discord 2026-09-28). Their graphs are built in
+ // one place further down; the loaders are checked there, per graph.
+ const sniffed: Partial<Record<ModelType, WorkflowStrategy>> = {
+ chroma: 'unet_chroma', hidream: 'unet_hidream', sd3: 'unet_sd3', lumina2: 'unet_lumina2', qwenimage1: 'unet_qwenimage1',
+ }
+ const sniffedStrategy = sniffed[modelType]
+ if (sniffedStrategy) {
+ if ((hasUNET || hasCheckpoint) && hasVAELoader) {
+ return { strategy: sniffedStrategy, reason: `${modelType} → its own loader set (official Comfy-Org template)` }
+ }
+ return { strategy: 'unavailable', reason: `${modelType} needs UNETLoader and VAELoader. Update ComfyUI in Settings.` }
+ }
+
// FLUX 2 → UNET + Flux2LatentImage
if (modelType === 'flux2') {
if (hasUNET && hasCLIPLoader && hasVAELoader) {
@@ -330,14 +354,56 @@ export function determineStrategy(
export class WorkflowUnavailableError extends Error {
readonly strategy: WorkflowStrategy
readonly installHint?: { pack: string; url: string }
- constructor(message: string, strategy: WorkflowStrategy, installHint?: { pack: string; url: string }) {
+ /** Companion files LU can download itself; Create offers them in place. */
+ readonly missing?: ComponentSpec[]
+ /** The local ComfyUI is too old for this graph; Create offers the update. */
+ readonly needsComfyUpdate?: boolean
+ constructor(
+ message: string,
+ strategy: WorkflowStrategy,
+ installHint?: { pack: string; url: string },
+ extra?: { missing?: ComponentSpec[]; needsComfyUpdate?: boolean },
+ ) {
super(message)
this.name = 'WorkflowUnavailableError'
this.strategy = strategy
this.installHint = installHint
+ this.missing = extra?.missing
+ this.needsComfyUpdate = extra?.needsComfyUpdate
}
}
+/** The families built from family-components.ts, by strategy. */
+const SNIFFED_FAMILY: Partial<Record<WorkflowStrategy, SniffedFamily>> = {
+ unet_chroma: 'chroma', unet_hidream: 'hidream', unet_sd3: 'sd3', unet_lumina2: 'lumina2',
+ unet_qwenimage1: 'qwenimage1', unet_sdxl: 'sdxl_unet', unet_sd15: 'sd15_unet',
+}
+
+/** Latent spaces that start from EmptySD3LatentImage (16 channels). */
+const SD3_LATENT_STRATEGIES = new Set<WorkflowStrategy>(['unet_chroma', 'unet_hidream', 'unet_sd3', 'unet_lumina2', 'unet_qwenimage1'])
+
+/** Qwen-Image-Edit (2509/2511) and FireRed edit files take the source image
+ * through TextEncodeQwenImageEditPlus; plain Qwen-Image does latent img2img. */
+export function isQwenImageEditModel(name: string): boolean {
+ const lower = name.toLowerCase()
+ return lower.includes('edit') && (lower.includes('qwen') || lower.includes('firered'))
+}
+
+/** Verbatim from comfy_extras/nodes_lumina2.py (SYSTEM_PROMPT["superior"]) and
+ * the negative of the NetaYume Lumina template. */
+const LUMINA2_POSITIVE_SYSTEM = 'You are an assistant designed to generate superior images with the superior degree of image-text alignment based on textual prompts or user prompts.'
+const LUMINA2_NEGATIVE_SYSTEM = 'You are an assistant designed to generate low-quality images based on textual prompts'
+
+/** A resolver's "download X" message, turned into the registry spec that can
+ * fetch X, so Create can offer it instead of pointing at the Model Manager. */
+function registrySpecsNamedIn(type: ModelType, message: string): ComponentSpec[] {
+ const req = COMPONENT_REGISTRY[type]
+ if (!req) return []
+ return [req.vae, req.clip, req.clipSecondary].filter(
+ (s): s is ComponentSpec => !!s?.downloadUrl && message.includes(s.downloadFilename),
+ )
+}
+
/**
* Probe ComfyUI for the video output node we need. When neither VHS nor
* SaveAnimatedWEBP is present, the workflow will fall back to SaveImage
@@ -508,12 +574,36 @@ export async function buildDynamicWorkflow(
return buildRemoveBgWorkflow(gp, rmbgMeta)
}
- const { strategy, reason, installHint } = determineStrategy(type, isVideo, nodes, models)
+ const determined = determineStrategy(type, isVideo, nodes, models)
+ const { reason, installHint } = determined
+ let strategy = determined.strategy
log.info(`[dynamic-workflow] Strategy: ${strategy} (${reason})`)
if (strategy === 'unavailable') {
- throw new WorkflowUnavailableError(reason, strategy, installHint)
- }
+ // "Update ComfyUI" reasons are fixable in place (lib/render-fixups.ts).
+ throw new WorkflowUnavailableError(reason, strategy, installHint, { needsComfyUpdate: /update comfyui/i.test(reason) })
+ }
+
+ // The loader follows the FOLDER the file sits in, not what its family
+ // usually ships as (Discord 2026-09-28). CheckpointLoaderSimple only lists
+ // models/checkpoints, UNETLoader only diffusion_models/unet, and a name in
+ // the wrong one is ComfyUI's "Value not in list".
+ const listedCheckpoints = nodeComboOptions(allNodes, 'CheckpointLoaderSimple', 'ckpt_name')
+ const listedUnets = [
+ ...nodeComboOptions(allNodes, 'UNETLoader', 'unet_name'),
+ ...nodeComboOptions(allNodes, 'UnetLoaderGGUF', 'unet_name'),
+ ]
+ const inCheckpoints = listedCheckpoints.includes(params.model)
+ const inUnets = listedUnets.includes(params.model)
+ if (strategy === 'checkpoint' && !inCheckpoints && inUnets && (type === 'sdxl' || type === 'sd15')) {
+ // A bare SDXL / SD 1.5 unet: its text encoders and VAE come separately.
+ strategy = type === 'sdxl' ? 'unet_sdxl' : 'unet_sd15'
+ }
+ // An all-in-one file of a UNET family in models/checkpoints (the FLUX fp8
+ // and SD 3.5 checkpoints, NetaYume Lumina, CivitAI merges): MODEL comes from
+ // CheckpointLoaderSimple, and its own CLIP/VAE when it carries them.
+ const fromCheckpoint = strategy !== 'checkpoint' && strategy !== 'animatediff'
+ && listedCheckpoints.length > 0 && inCheckpoints && !inUnets
// Local Edit (mask inpaint) runs on the SDXL/SD1.5 checkpoint pipeline only.
// Reject other strategies explicitly instead of silently dropping the mask —
@@ -527,7 +617,8 @@ export async function buildDynamicWorkflow(
// check exists to prevent. The model's own route for a local change is a
// marking drawn into the picture plus a prompt that names it, which is a
// different surface from the mask editor and is not built in this cut.
- if (!isVideo && gp.inputImage && gp.maskImage && strategy !== 'checkpoint') {
+ const sdCheckpointFamily = strategy === 'checkpoint' || strategy === 'unet_sdxl' || strategy === 'unet_sd15'
+ if (!isVideo && gp.inputImage && gp.maskImage && !sdCheckpointFamily) {
throw new WorkflowUnavailableError(
'Local image editing needs an SD 1.5 / SDXL checkpoint. Pick a checkpoint model for Edit. FLUX and video models are not wired for local inpaint.',
strategy,
@@ -563,6 +654,7 @@ export async function buildDynamicWorkflow(
let samplerModelId: string
if (strategy === 'checkpoint') {
+ assertCheckpointListed(params.model, allNodes)
// Single loader: outputs MODEL (0), CLIP (1), VAE (2)
modelNodeId = String(n++)
workflow[modelNodeId] = {
@@ -575,6 +667,76 @@ export async function buildDynamicWorkflow(
vaeOutputSlot = 2
samplerModelId = modelNodeId
+ } else if (SNIFFED_FAMILY[strategy]) {
+ // ─── Header-sniffed families (Discord 2026-09-28) ───
+ const family = SNIFFED_FAMILY[strategy]!
+ const modelId = String(n++)
+ const clipId = String(n++)
+ if (fromCheckpoint) {
+ workflow[modelId] = { class_type: 'CheckpointLoaderSimple', inputs: { ckpt_name: params.model } }
+ } else {
+ addUnetLoader(workflow, modelId, params.model, allNodes)
+ }
+ // An all-in-one checkpoint brings its own encoder / VAE. Known from the
+ // header; when the header was not readable, the separate files are tried
+ // first and the checkpoint's own outputs are the fallback.
+ const parts = gp.modelParts
+ const ownClip = fromCheckpoint && !!parts?.textEncoder
+ const ownVae = fromCheckpoint && !!parts?.vae
+ let resolved: { encoders: string[]; vae?: string }
+ try {
+ resolved = resolveFamilyParts(family, models.clips, models.vaes, { encoders: !ownClip, vae: !ownVae })
+ } catch (err) {
+ if (!(err instanceof MissingComponentsError)) throw err
+ if (fromCheckpoint && !parts) {
+ resolved = { encoders: [], vae: undefined }
+ } else {
+ throw new WorkflowUnavailableError(err.message, strategy, undefined, { missing: err.missing })
+ }
+ }
+ const useOwnClip = ownClip || (fromCheckpoint && resolved.encoders.length === 0)
+ const useOwnVae = ownVae || (fromCheckpoint && !resolved.vae)
+
+ if (!useOwnClip) {
+ const [e1, e2, e3, e4] = resolved.encoders
+ const clipNode: { class_type: string; inputs: ComfyNodeInputs } =
+ family === 'hidream' ? { class_type: 'QuadrupleCLIPLoader', inputs: { clip_name1: e1, clip_name2: e2, clip_name3: e3, clip_name4: e4 } }
+ : family === 'sd3' ? { class_type: 'TripleCLIPLoader', inputs: { clip_name1: e1, clip_name2: e2, clip_name3: e3 } }
+ : family === 'sdxl_unet' ? { class_type: 'DualCLIPLoader', inputs: { clip_name1: e1, clip_name2: e2, type: 'sdxl' } }
+ : {
+ class_type: 'CLIPLoader',
+ inputs: {
+ clip_name: e1,
+ type: family === 'chroma' ? 'chroma' : family === 'lumina2' ? 'lumina2' : family === 'qwenimage1' ? 'qwen_image' : 'stable_diffusion',
+ device: 'default',
+ },
+ }
+ if (!allNodes[clipNode.class_type]) {
+ throw new WorkflowUnavailableError(
+ `Your ComfyUI is too old for this model (it has no ${clipNode.class_type} node). Update ComfyUI, then try again.`,
+ strategy, undefined, { needsComfyUpdate: true },
+ )
+ }
+ if (clipNode.class_type === 'CLIPLoader') assertClipTypeKnown(String(clipNode.inputs.type), type, strategy, allNodes)
+ workflow[clipId] = clipNode
+ clipSourceId = clipId
+ clipOutputSlot = 0
+ } else {
+ clipSourceId = modelId
+ clipOutputSlot = 1
+ }
+ if (!useOwnVae) {
+ const vaeId = String(n++)
+ workflow[vaeId] = { class_type: 'VAELoader', inputs: { vae_name: resolved.vae! } }
+ vaeSourceId = vaeId
+ vaeOutputSlot = 0
+ } else {
+ vaeSourceId = modelId
+ vaeOutputSlot = 2
+ }
+ modelNodeId = modelId
+ samplerModelId = modelId
+
} else if (strategy === 'unet_flux' || strategy === 'unet_flux2' || strategy === 'unet_krea2' || strategy === 'unet_zimage' || strategy === 'unet_ernie_image' || strategy === 'unet_qwenimage' || strategy === 'unet_video' || strategy === 'unet_ltx'
|| strategy === 'unet_mochi' || strategy === 'unet_cosmos') {
// Separate loaders
@@ -614,25 +776,37 @@ export async function buildDynamicWorkflow(
// below.
const useDualFluxClip = type === 'flux' && nodes.loaders.includes('DualCLIPLoader')
+ // An all-in-one file in models/checkpoints (see fromCheckpoint): its own
+ // encoder / VAE are used when the header says it carries them, and are the
+ // fallback when the header could not be read.
+ const parts = gp.modelParts
+ const carriesClip = fromCheckpoint && (parts ? parts.textEncoder : true)
+ const carriesVae = fromCheckpoint && (parts ? parts.vae : true)
+ const skipClipLookup = fromCheckpoint && !!parts?.textEncoder
+
let clip = ''
let fluxPair: { t5: string; clipL: string } | null = null
- if (useDualFluxClip) {
+ if (skipClipLookup) {
+ // nothing to look up
+ } else if (useDualFluxClip) {
try {
fluxPair = await findFluxCLIPPair()
} catch (clipErr) {
- throw new WorkflowUnavailableError(
- clipErr instanceof Error ? clipErr.message : 'Required text encoder not found in ComfyUI.',
- strategy,
- )
+ if (!carriesClip) {
+ const message = clipErr instanceof Error ? clipErr.message : 'Required text encoder not found in ComfyUI.'
+ throw new WorkflowUnavailableError(message, strategy, undefined, { missing: registrySpecsNamedIn(type, message) })
+ }
+ clip = ''
}
} else {
try {
clip = await findMatchingCLIP(type, params.model)
} catch (clipErr) {
- throw new WorkflowUnavailableError(
- clipErr instanceof Error ? clipErr.message : 'Required text encoder not found in ComfyUI.',
- strategy,
- )
+ if (!carriesClip) {
+ const message = clipErr instanceof Error ? clipErr.message : 'Required text encoder not found in ComfyUI.'
+ throw new WorkflowUnavailableError(message, strategy, undefined, { missing: registrySpecsNamedIn(type, message) })
+ }
+ clip = ''
}
}
@@ -641,19 +815,26 @@ export async function buildDynamicWorkflow(
// no-silent-fallback rule) only when it will actually be used.
const needsVAELoader = strategy !== 'unet_ltx'
let vae = ''
- if (needsVAELoader) {
+ if (needsVAELoader && !(fromCheckpoint && parts?.vae)) {
try {
vae = await findMatchingVAE(type)
} catch (vaeErr) {
- throw new WorkflowUnavailableError(
- vaeErr instanceof Error ? vaeErr.message : 'Required VAE not found in ComfyUI.',
- strategy,
- )
+ if (!carriesVae) {
+ const message = vaeErr instanceof Error ? vaeErr.message : 'Required VAE not found in ComfyUI.'
+ throw new WorkflowUnavailableError(message, strategy, undefined, { missing: registrySpecsNamedIn(type, message) })
+ }
}
}
+ const clipFromFile = !clip && !fluxPair
+ const vaeFromFile = needsVAELoader && !vae
- addUnetLoader(workflow, unetId, params.model, allNodes)
- workflow[clipId] = useDualFluxClip && fluxPair
+ if (!useDualFluxClip && !clipFromFile) assertClipTypeKnown(clipType, type, strategy, allNodes)
+ if (fromCheckpoint) {
+ workflow[unetId] = { class_type: 'CheckpointLoaderSimple', inputs: { ckpt_name: params.model } }
+ } else {
+ addUnetLoader(workflow, unetId, params.model, allNodes)
+ }
+ if (!clipFromFile) workflow[clipId] = useDualFluxClip && fluxPair
? {
class_type: 'DualCLIPLoader',
inputs: { clip_name1: fluxPair.t5, clip_name2: fluxPair.clipL, type: 'flux' },
@@ -664,7 +845,7 @@ export async function buildDynamicWorkflow(
}
let vaeId: string
- if (needsVAELoader) {
+ if (needsVAELoader && !vaeFromFile) {
vaeId = String(n++)
workflow[vaeId] = {
class_type: 'VAELoader',
@@ -675,10 +856,10 @@ export async function buildDynamicWorkflow(
}
modelNodeId = unetId
- clipSourceId = clipId
- clipOutputSlot = 0
+ clipSourceId = clipFromFile ? unetId : clipId
+ clipOutputSlot = clipFromFile ? 1 : 0
vaeSourceId = vaeId
- vaeOutputSlot = 0
+ vaeOutputSlot = vaeFromFile ? 2 : 0
samplerModelId = unetId
} else {
@@ -824,6 +1005,17 @@ export async function buildDynamicWorkflow(
// isI2I test in Phase 3, which would otherwise claim the image and turn an
// edit instruction into ordinary latent img2img.
const isQwenEdit = !isVideo && strategy === 'unet_qwenimage' && !!gp.inputImage
+ // Qwen-Image-Edit 2509/2511 (official template image_qwen_image_edit_2509):
+ // the source goes through TextEncodeQwenImageEditPlus on both sides and is
+ // the latent itself, sampled at denoise 1.0 like the template.
+ const isQwen1Edit = !isVideo && strategy === 'unet_qwenimage1' && !!gp.inputImage && isQwenImageEditModel(params.model)
+ if (isQwen1Edit && !allNodes['TextEncodeQwenImageEditPlus']) {
+ throw new WorkflowUnavailableError(
+ 'Qwen-Image-Edit needs a newer ComfyUI (TextEncodeQwenImageEditPlus). Update ComfyUI, then try again.',
+ strategy, undefined, { needsComfyUpdate: true },
+ )
+ }
+ let qwen1EditImageRef: [string, number] | null = null
const posId = String(n++)
const negId = String(n++)
@@ -864,10 +1056,30 @@ export async function buildDynamicWorkflow(
qwenInputs.vae = [vaeSourceId, vaeOutputSlot]
}
workflow[posId] = { class_type: 'TextEncodeQwenImage21', inputs: qwenInputs }
+ } else if (isQwen1Edit) {
+ const loadId = String(n++)
+ workflow[loadId] = { class_type: 'LoadImage', inputs: { image: gp.inputImage } }
+ qwen1EditImageRef = [loadId, 0]
+ if (allNodes['FluxKontextImageScale']) {
+ // The template scales the source to a size the model was trained on.
+ const scaleId = String(n++)
+ workflow[scaleId] = { class_type: 'FluxKontextImageScale', inputs: { image: [loadId, 0] } }
+ qwen1EditImageRef = [scaleId, 0]
+ }
+ const editInputs = (prompt: string): ComfyNodeInputs => ({
+ clip: [clipSourceId, clipOutputSlot], prompt, vae: [vaeSourceId, vaeOutputSlot], image1: qwen1EditImageRef!,
+ })
+ workflow[posId] = { class_type: 'TextEncodeQwenImageEditPlus', inputs: editInputs(params.prompt) }
+ workflow[negId] = { class_type: 'TextEncodeQwenImageEditPlus', inputs: editInputs(params.negativePrompt || '') }
} else {
workflow[posId] = {
class_type: 'CLIPTextEncode',
- inputs: { text: params.prompt, clip: [clipSourceId, clipOutputSlot] },
+ inputs: {
+ // Lumina 2 is trained on a system prompt ahead of the user's; without
+ // it the output drifts badly (CLIPTextEncodeLumina2 does the same join).
+ text: strategy === 'unet_lumina2' ? `${LUMINA2_POSITIVE_SYSTEM} <Prompt Start> ${params.prompt}` : params.prompt,
+ clip: [clipSourceId, clipOutputSlot],
+ },
}
if (strategy === 'unet_ernie_image' || (strategy === 'unet_krea2' && params.cfgScale === 1)) {
@@ -882,7 +1094,9 @@ export async function buildDynamicWorkflow(
workflow[negId] = {
class_type: 'CLIPTextEncode',
inputs: {
- text: params.negativePrompt || '',
+ text: strategy === 'unet_lumina2'
+ ? `${LUMINA2_NEGATIVE_SYSTEM} <Prompt Start> ${params.negativePrompt || ''}`
+ : params.negativePrompt || '',
clip: [clipSourceId, clipOutputSlot],
},
}
@@ -894,12 +1108,12 @@ export async function buildDynamicWorkflow(
// Takes precedence over plain I2I — a mask means "repaint THIS area", never
// "repaint everything". Ported 1:1 from the web app's tested builder
// (create-workflows.ts): same node classes, same defaults.
- const isInpaint = !isVideo && !!gp.inputImage && !!gp.maskImage && strategy === 'checkpoint'
+ const isInpaint = !isVideo && !!gp.inputImage && !!gp.maskImage && sdCheckpointFamily
// I2I mode: LoadImage → VAEEncode instead of empty latent. A Qwen-Image 2.1
// edit is excluded: its reference image is already wired into the text
// encoder above, and its sampler runs at denoise 1.0 like the official
// template (instruction editing, not a partial re-noise of the source).
- const isI2I = !isVideo && !isInpaint && !isQwenEdit && params.inputImage && (params.denoise ?? 1.0) < 1.0
+ const isI2I = !isVideo && !isInpaint && !isQwenEdit && !isQwen1Edit && params.inputImage && (params.denoise ?? 1.0) < 1.0
const latentId = String(n++)
@@ -967,6 +1181,13 @@ export async function buildDynamicWorkflow(
class_type: 'EmptyLatentImage',
inputs: { width: params.width, height: params.height, batch_size: params.batchSize },
}
+ } else if (SD3_LATENT_STRATEGIES.has(strategy)) {
+ // Chroma, HiDream, SD 3.5, Lumina 2 and Qwen-Image 1: EmptySD3LatentImage,
+ // as in every one of their official templates.
+ workflow[latentId] = {
+ class_type: nodes.latentInit.includes('EmptySD3LatentImage') ? 'EmptySD3LatentImage' : 'EmptyLatentImage',
+ inputs: { width: params.width, height: params.height, batch_size: params.batchSize },
+ }
} else if (strategy === 'unet_zimage') {
// Z-Image uses SD3 latent (same architecture family)
const latentNode = nodes.latentInit.includes('EmptySD3LatentImage')
@@ -1010,6 +1231,13 @@ export async function buildDynamicWorkflow(
}
}
+ if (isQwen1Edit && qwen1EditImageRef) {
+ const encId = String(n++)
+ workflow[encId] = { class_type: 'VAEEncode', inputs: { pixels: qwen1EditImageRef, vae: [vaeSourceId, vaeOutputSlot] } }
+ latentRef = [encId, 0]
+ delete workflow[latentId]
+ }
+
// I2I override: replace empty latent with LoadImage → VAEEncode
if (isI2I) {
const loadImageId = String(n++)
@@ -1097,6 +1325,8 @@ export async function buildDynamicWorkflow(
throw new WorkflowUnavailableError(
`Animating with this model family needs the ${i2vNode} node, which your ComfyUI doesn't have. Update ComfyUI, then try again.`,
strategy,
+ undefined,
+ { needsComfyUpdate: true },
)
}
const loadId = String(n++)
@@ -1157,6 +1387,30 @@ export async function buildDynamicWorkflow(
// apart (filename convention, a CivitAI metadata field, ...), gate this
// node on that signal rather than reintroducing it unconditionally.
+ // Sampling patches of the header-sniffed families, straight from their
+ // official templates: AuraFlow shift 1 (Chroma), 6 (Lumina 2), 3.1 / 3
+ // (Qwen-Image / -Edit); ModelSamplingSD3 shift 3 (HiDream fast/full) or 6
+ // (dev). Qwen-Image-Edit also runs CFGNorm at strength 1.
+ const auraShift = strategy === 'unet_chroma' ? 1
+ : strategy === 'unet_lumina2' ? 6
+ : strategy === 'unet_qwenimage1' ? (isQwenImageEditModel(params.model) ? 3 : 3.1)
+ : null
+ if (auraShift !== null && allNodes['ModelSamplingAuraFlow']) {
+ const id = String(n++)
+ workflow[id] = { class_type: 'ModelSamplingAuraFlow', inputs: { model: [samplerModelId, 0], shift: auraShift } }
+ samplerModelId = id
+ }
+ if (strategy === 'unet_hidream' && allNodes['ModelSamplingSD3']) {
+ const id = String(n++)
+ workflow[id] = { class_type: 'ModelSamplingSD3', inputs: { model: [samplerModelId, 0], shift: /dev/i.test(params.model) ? 6 : 3 } }
+ samplerModelId = id
+ }
+ if (isQwen1Edit && allNodes['CFGNorm']) {
+ const id = String(n++)
+ workflow[id] = { class_type: 'CFGNorm', inputs: { model: [samplerModelId, 0], strength: 1 } }
+ samplerModelId = id
+ }
+
// ─── Phase 4: Sampling ───
const samplerId = String(n++)
@@ -1173,7 +1427,7 @@ export async function buildDynamicWorkflow(
cfg: params.cfgScale,
sampler_name: params.sampler,
scheduler: params.scheduler,
- denoise: isInpaint ? (params.denoise ?? 0.85) : isI2I ? (params.denoise ?? 0.7) : 1.0,
+ denoise: isInpaint ? (params.denoise ?? 0.85) : isI2I ? (params.denoise ?? 0.7) : 1.0, // Qwen-Image-Edit: 1.0, like its template
},
}
@@ -1548,6 +1802,41 @@ function requireNodes(allNodes: NodePresence, needed: string[], lane: string): v
/** UNET loader that understands GGUF quants: .gguf files load through the
* city96 GGUF pack's UnetLoaderGGUF, everything else through core UNETLoader. */
+/** Discord 2026-09-26/28 (boromirofgeo, haschbar): "Node 1
+ * (CheckpointLoaderSimple): Value not in list". The strategy comes from the
+ * file NAME, and a name LU cannot place ('unknown') falls to the checkpoint
+ * pipeline. For a file that sits in diffusion_models that is a guaranteed
+ * rejection, because CheckpointLoaderSimple only lists models/checkpoints.
+ * Say what is wrong instead. An unreadable enum stays silent, as before. */
+function assertCheckpointListed(model: string, allNodes: NodePresence): void {
+ const checkpoints = nodeComboOptions(allNodes, 'CheckpointLoaderSimple', 'ckpt_name')
+ if (checkpoints.length === 0 || checkpoints.includes(model)) return
+ const unets = [
+ ...nodeComboOptions(allNodes, 'UNETLoader', 'unet_name'),
+ ...nodeComboOptions(allNodes, 'UnetLoaderGGUF', 'unet_name'),
+ ]
+ throw new WorkflowUnavailableError(
+ unets.includes(model)
+ ? `LU does not recognize which model family ${model} belongs to, so it has no pipeline for it. It sits in models/diffusion_models, where an SD 1.5 / SDXL checkpoint does not work. Pick another model, or report the file name so LU can learn it.`
+ : `${model} is no longer in ComfyUI's model list. It may have been moved or deleted. Pick another model, or restart ComfyUI after adding files.`,
+ 'checkpoint',
+ )
+}
+
+/** Discord 2026-09-26 (tbjdrw): "Node 2 (CLIPLoader): Value not in list".
+ * Newer model families need a CLIPLoader type an older ComfyUI does not have
+ * yet (flux2, krea2, qwen_image). Only checked when the enum is readable. */
+function assertClipTypeKnown(clipType: string, type: ModelType, strategy: WorkflowStrategy, allNodes: NodePresence): void {
+ const types = nodeComboOptions(allNodes, 'CLIPLoader', 'type')
+ if (types.length === 0 || types.includes(clipType)) return
+ throw new WorkflowUnavailableError(
+ `Your ComfyUI is too old for ${type} models (its text encoder loader has no "${clipType}" type). Update ComfyUI, then try again.`,
+ strategy,
+ undefined,
+ { needsComfyUpdate: true },
+ )
+}
+
function addUnetLoader(workflow: ComfyApiGraph, id: string, model: string, allNodes: NodePresence): void {
if (model.toLowerCase().endsWith('.gguf')) {
if (!allNodes['UnetLoaderGGUF']) {
diff --git a/src/api/family-components.ts b/src/api/family-components.ts
new file mode 100644
index 00000000..46bc3a44
--- /dev/null
+++ b/src/api/family-components.ts
@@ -0,0 +1,153 @@
+// ─── Text encoders and VAEs of the families the header sniff brought in ───
+//
+// Discord 2026-09-26..28: Chroma, HiDream, SD 3.5, Lumina 2, Qwen-Image 1 /
+// Qwen-Image-Edit, and SDXL / SD 1.5 files that sit in diffusion_models all
+// used to fall to the checkpoint loader and fail with "Value not in list".
+// Each now has its own pipeline in dynamic-workflow.ts, and this file says
+// which companion files that pipeline needs, how to find them in the live
+// ComfyUI lists, and where to download them when they are missing.
+//
+// Every filename and address below is the one the official Comfy-Org
+// template for that family names (image_chroma_text_to_image, hidream_i1_*,
+// sd3.5_simple_example, image_qwen_image, image_qwen_image_edit_2509,
+// Lumina_Image_2.0_Repackaged), checked reachable on 2026-09-28. Pure: the
+// builder hands in the enums it already read, so tests need no mocks.
+
+import type { ComponentSpec } from './component-registry'
+
+export type SniffedFamily = 'chroma' | 'hidream' | 'sd3' | 'lumina2' | 'qwenimage1' | 'sdxl_unet' | 'sd15_unet'
+
+interface Part {
+ spec: ComponentSpec
+ pick: (names: string[]) => string | undefined
+}
+
+const lc = (s: string) => s.toLowerCase()
+const base = (s: string) => lc(s.split(/[\\/]/).pop() ?? s)
+const find = (names: string[], ...tests: Array<(n: string) => boolean>) => {
+ for (const t of tests) {
+ const hit = names.find((n) => t(base(n)))
+ if (hit) return hit
+ }
+ return undefined
+}
+
+const HF = 'https://huggingface.co'
+const spec = (downloadFilename: string, url: string | undefined, subfolder: 'vae' | 'text_encoders', sizeGB: number, matchPatterns: string[]): ComponentSpec =>
+ ({ downloadFilename, downloadUrl: url, subfolder, sizeGB, matchPatterns })
+
+const T5: Part = {
+ spec: spec('t5xxl_fp8_e4m3fn_scaled.safetensors', `${HF}/comfyanonymous/flux_text_encoders/resolve/main/t5xxl_fp8_e4m3fn_scaled.safetensors`, 'text_encoders', 5.16, ['t5xxl']),
+ pick: (n) => find(n, (b) => b === 't5xxl_fp8_e4m3fn_scaled.safetensors', (b) => b.includes('t5xxl'), (b) => b.includes('t5') && !b.includes('umt5') && !b.includes('oldt5')),
+}
+const CLIP_L: Part = {
+ spec: spec('clip_l.safetensors', `${HF}/comfyanonymous/flux_text_encoders/resolve/main/clip_l.safetensors`, 'text_encoders', 0.25, ['clip_l']),
+ pick: (n) => find(n, (b) => b === 'clip_l.safetensors', (b) => b.includes('clip_l')),
+}
+const CLIP_G: Part = {
+ spec: spec('clip_g.safetensors', `${HF}/Comfy-Org/stable-diffusion-3.5-fp8/resolve/main/text_encoders/clip_g.safetensors`, 'text_encoders', 1.39, ['clip_g']),
+ pick: (n) => find(n, (b) => b === 'clip_g.safetensors', (b) => b.includes('clip_g')),
+}
+const AE: Part = {
+ spec: spec('ae.safetensors', `${HF}/Comfy-Org/Lumina_Image_2.0_Repackaged/resolve/main/split_files/vae/ae.safetensors`, 'vae', 0.34, ['ae']),
+ // The 16-channel FLUX autoencoder. Never the FLUX 2 one (32 channels).
+ pick: (n) => find(n, (b) => b === 'ae.safetensors', (b) => /(^|[._-])ae[._-]/.test(b) && !b.includes('flux2'), (b) => b.includes('flux') && !b.includes('flux2')),
+}
+
+const HIDREAM_CLIP_L: Part = {
+ spec: spec('clip_l_hidream.safetensors', `${HF}/Comfy-Org/HiDream-I1_ComfyUI/resolve/main/split_files/text_encoders/clip_l_hidream.safetensors`, 'text_encoders', 0.25, ['clip_l_hidream', 'clip_l']),
+ pick: (n) => find(n, (b) => b.includes('clip_l_hidream'), (b) => b.includes('clip_l')),
+}
+const HIDREAM_CLIP_G: Part = {
+ spec: spec('clip_g_hidream.safetensors', `${HF}/Comfy-Org/HiDream-I1_ComfyUI/resolve/main/split_files/text_encoders/clip_g_hidream.safetensors`, 'text_encoders', 1.39, ['clip_g_hidream', 'clip_g']),
+ pick: (n) => find(n, (b) => b.includes('clip_g_hidream'), (b) => b.includes('clip_g')),
+}
+const LLAMA: Part = {
+ spec: spec('llama_3.1_8b_instruct_fp8_scaled.safetensors', `${HF}/Comfy-Org/HiDream-I1_ComfyUI/resolve/main/split_files/text_encoders/llama_3.1_8b_instruct_fp8_scaled.safetensors`, 'text_encoders', 9.08, ['llama_3.1']),
+ pick: (n) => find(n, (b) => /llama[._-]?3[._]1/.test(b), (b) => b.includes('llama') && !b.includes('llava')),
+}
+const GEMMA_2B: Part = {
+ spec: spec('gemma_2_2b_fp16.safetensors', `${HF}/Comfy-Org/Lumina_Image_2.0_Repackaged/resolve/main/split_files/text_encoders/gemma_2_2b_fp16.safetensors`, 'text_encoders', 5.23, ['gemma_2_2b']),
+ pick: (n) => find(n, (b) => b.includes('gemma_2_2b') || b.includes('gemma-2-2b'), (b) => b.includes('gemma') && b.includes('2b') && !/gemma[._-]?3/.test(b)),
+}
+const QWEN25_VL: Part = {
+ spec: spec('qwen_2.5_vl_7b_fp8_scaled.safetensors', `${HF}/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/text_encoders/qwen_2.5_vl_7b_fp8_scaled.safetensors`, 'text_encoders', 9.38, ['qwen_2.5_vl']),
+ pick: (n) => find(n, (b) => /qwen[._-]?2[._]5[._-]?vl/.test(b)),
+}
+const QWEN_IMAGE_VAE: Part = {
+ spec: spec('qwen_image_vae.safetensors', `${HF}/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/vae/qwen_image_vae.safetensors`, 'vae', 0.25, ['qwen_image_vae']),
+ // The 16-channel Qwen-Image 1 autoencoder, never the 64-channel 2.1 one.
+ pick: (n) => find(n, (b) => b === 'qwen_image_vae.safetensors', (b) => b.includes('qwen_image') && b.includes('vae') && !/2[._-]?1/.test(b)),
+}
+const SDXL_VAE: Part = {
+ spec: spec('sdxl_vae.safetensors', `${HF}/stabilityai/sdxl-vae/resolve/main/sdxl_vae.safetensors`, 'vae', 0.33, ['sdxl']),
+ pick: (n) => find(n, (b) => b.includes('sdxl') || b.includes('sd_xl')),
+}
+const SD15_VAE: Part = {
+ spec: spec('vae-ft-mse-840000-ema-pruned.safetensors', `${HF}/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.safetensors`, 'vae', 0.33, ['ft-mse']),
+ pick: (n) => find(n, (b) => b.includes('ft-mse') || b.includes('840000'), (b) => b.includes('sd15') || b.includes('v1-5') || b.includes('sd-v1')),
+}
+// No ungated standalone SD 3.5 VAE exists; SD 3.5 ships as all-in-one
+// checkpoints that carry it, and only a bare transformer needs this.
+const SD3_VAE: Part = {
+ spec: spec('sd3_vae.safetensors', undefined, 'vae', 0.17, ['sd3']),
+ pick: (n) => find(n, (b) => b.includes('sd3') || b.includes('sd3.5')),
+}
+
+/** Encoders in loader order, then the VAE. */
+export const FAMILY_PARTS: Record<SniffedFamily, { encoders: Part[]; vae: Part }> = {
+ chroma: { encoders: [T5], vae: AE },
+ hidream: { encoders: [HIDREAM_CLIP_L, HIDREAM_CLIP_G, T5, LLAMA], vae: AE },
+ sd3: { encoders: [CLIP_L, CLIP_G, T5], vae: SD3_VAE },
+ lumina2: { encoders: [GEMMA_2B], vae: AE },
+ qwenimage1: { encoders: [QWEN25_VL], vae: QWEN_IMAGE_VAE },
+ sdxl_unet: { encoders: [CLIP_L, CLIP_G], vae: SDXL_VAE },
+ sd15_unet: { encoders: [CLIP_L], vae: SD15_VAE },
+}
+
+const LABEL: Record<SniffedFamily, string> = {
+ chroma: 'Chroma', hidream: 'HiDream', sd3: 'SD 3.5', lumina2: 'Lumina 2',
+ qwenimage1: 'Qwen-Image', sdxl_unet: 'SDXL', sd15_unet: 'SD 1.5',
+}
+
+/** Thrown when companion files are missing. Carries what to fetch, so Create
+ * can offer the download in place instead of sending people to the Model
+ * Manager. */
+export class MissingComponentsError extends Error {
+ readonly missing: ComponentSpec[]
+ constructor(message: string, missing: ComponentSpec[]) {
+ super(message)
+ this.name = 'MissingComponentsError'
+ this.missing = missing
+ }
+}
+
+export function resolveFamilyParts(
+ family: SniffedFamily,
+ clips: string[],
+ vaes: string[],
+ need: { encoders: boolean; vae: boolean } = { encoders: true, vae: true },
+): { encoders: string[]; vae?: string } {
+ const parts = FAMILY_PARTS[family]
+ const missing: ComponentSpec[] = []
+ const encoders: string[] = []
+ if (need.encoders) {
+ for (const p of parts.encoders) {
+ const hit = p.pick(clips)
+ if (hit) encoders.push(hit)
+ else missing.push(p.spec)
+ }
+ }
+ let vae: string | undefined
+ if (need.vae) {
+ vae = parts.vae.pick(vaes)
+ if (!vae) missing.push(parts.vae.spec)
+ }
+ if (missing.length > 0) {
+ throw new MissingComponentsError(
+ `${LABEL[family]} needs ${missing.map((m) => `"${m.downloadFilename}"`).join(', ')}.`,
+ missing,
+ )
+ }
+ return { encoders, vae }
+}
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index 42440151..7d0d4783 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -228,6 +228,20 @@ function asUnfiltered(u: unknown): 'full' | 'partial' | undefined {
return u === 'full' || u === 'partial' ? u : undefined
}
+/**
+ * llama.cpp's context refusal (`exceed_context_size_error`) carries its two
+ * numbers beside the sentence, and the sentence alone drops them. Keep them in
+ * the text: the Code Agent cuts its history by exactly that much and sends the
+ * step again (GH #140, hooks/codex/context-overflow.ts).
+ */
+function withContextNumbers(message: string, err: unknown): string {
+ const nCtx = prop(err, 'n_ctx')
+ const nPrompt = prop(err, 'n_prompt_tokens')
+ return typeof nCtx === 'number' && typeof nPrompt === 'number'
+ ? `${message} (request (${nPrompt} tokens), context size (${nCtx} tokens))`
+ : message
+}
+
// ── Known context lengths for popular models ───────────────────
const KNOWN_CONTEXT: Record<string, number> = {
@@ -898,7 +912,7 @@ export class OpenAIProvider implements ProviderClient {
throw new Error(
typeof streamErr === 'string'
? streamErr
- : (asString(prop(streamErr, 'message')) || 'Streaming error'),
+ : withContextNumbers(asString(prop(streamErr, 'message')) || 'Streaming error', streamErr),
)
}
@@ -1695,7 +1709,7 @@ export class OpenAIProvider implements ProviderClient {
} else if (err && typeof err === 'object') {
const eo = err as { message?: string; code?: string }
if (eo.message) {
- message = eo.message
+ message = withContextNumbers(eo.message, err)
hasServerMessage = true
}
if (eo.code) code = eo.code
diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.ts
index 3f53d669..c3f89498 100644
--- a/src/api/vram-handoff.ts
+++ b/src/api/vram-handoff.ts
@@ -51,6 +51,7 @@ import { listRunningModels, loadModel, unloadModel } from './ollama'
import { startBundledEngine } from './engine'
import { getAmdGpuArch } from '../lib/hardware'
import { useSettingsStore } from '../stores/settingsStore'
+import { portraitFrame, wantsFullFigure } from '../lib/subject-framing'
import {
getImageModels,
getVideoModels,
@@ -71,6 +72,7 @@ import {
buildTxt2VidWorkflow,
snapToVideoGrid,
MODEL_TYPE_DEFAULTS,
+ hidreamSampling,
isPromptQueued,
type VideoBackend,
} from './comfyui'
@@ -1251,16 +1253,31 @@ async function generateImage(
// Capability-aware: read this model's REAL limits/enums from ComfyUI and
// REJECT (not clamp) any explicit user value beyond them (decision 2).
const caps = await fetchCaps(model, 'image')
+ // The family from the file header, the same list Create picks from
+ // (Discord 2026-09-26..28): the name alone sent every file it could not
+ // place to the checkpoint loader, and ComfyUI refused a model that sits in
+ // diffusion_models. The header also says whether the file carries its own
+ // text encoder and VAE.
+ const listed = (await getImageModels().catch(() => [])).find((m) => m.name === model)
+ const type = listed?.type ?? classifyModel(model)
// Per-architecture defaults instead of one hardcoded cfg 7 / 1024² for every
// image model: Flux/Flux2 are distilled and need cfg 1.0 (cfg 7 fries them),
// Z-Image Turbo wants ~3.5 / 12 steps, SD1.5 must default to 512² not 1024².
- const idef = MODEL_TYPE_DEFAULTS[classifyModel(model)] ?? MODEL_TYPE_DEFAULTS.unknown
+ const idef = type === 'hidream'
+ ? { ...MODEL_TYPE_DEFAULTS.hidream, ...hidreamSampling(model) }
+ : MODEL_TYPE_DEFAULTS[type] ?? MODEL_TYPE_DEFAULTS.unknown
const tun = resolveTunables(args, caps, { steps: idef.steps, cfg: idef.cfg, sampler: idef.sampler, scheduler: idef.scheduler })
if (tun.reject) return `Cannot generate: ${tun.reject}`
const a = args as Record<string, unknown>
- const width = clampInt(a.width, idef.width, 64, 4096)
- const height = clampInt(a.height, idef.height, 64, 4096)
+ // GH #142: a whole figure in the model's square default comes out as a
+ // close-up. Nobody named a size and the prompt wants the full figure, so
+ // it gets the portrait frame the model was trained on (lib/subject-framing).
+ const frame = a.width == null && a.height == null && !args.inputImage && wantsFullFigure(prompt)
+ ? portraitFrame(idef.width)
+ : { width: idef.width, height: idef.height }
+ const width = clampInt(a.width, frame.width, 64, 4096)
+ const height = clampInt(a.height, frame.height, 64, 4096)
const seed = (typeof a.seed === 'number' && Number.isFinite(a.seed)) ? Math.floor(a.seed) : -1
const batchSize = clampInt(a.batchSize ?? a.batch_size, 1, 1, 8)
@@ -1301,8 +1318,9 @@ async function generateImage(
...(typeof a.vae === 'string' && a.vae ? { vae: a.vae as string } : {}),
...(typeof a.clipSkip === 'number' ? { clipSkip: a.clipSkip as number } : {}),
...(inputImage ? { inputImage, denoise } : {}),
+ ...(listed?.parts ? { modelParts: listed.parts } : {}),
},
- classifyModel(model),
+ type,
)
// Phase markers (chat-agent hang 2026-06-03): make it obvious in the log
// whether a stall is in the workflow build (/object_info) or the submit
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index f131ec3b..cf1014b8 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -17,6 +17,7 @@ import { COMPOSER_MAX_W } from './composer-width'
import { consumeComposerFocusPending } from '../../hooks/useKeyboardShortcuts'
import { useChatNoticeStore, CHAT_NOTICE_MS } from '../../stores/chatNoticeStore'
import { MONOGRAM, MONOGRAM_INVERT } from '../layout/brand'
+import { fitTextarea } from '../../lib/fit-textarea'
interface Props {
onSend: (content: string, images?: ImageAttachment[]) => void
@@ -65,6 +66,9 @@ interface Props {
/** How long the synchronous double-fire guard below stays shut. */
const SEND_LOCK_MS = 700
+/** The field grows with its text up to this height, then scrolls (matches `max-h-[200px]`). */
+const COMPOSER_MAX_PX = 200
+
/**
* The double-fire guard's clock read, deliberately OUTSIDE the component.
*
@@ -233,11 +237,12 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
}
}, [conversationId])
- useEffect(() => {
- if (textareaRef.current) {
- textareaRef.current.style.height = 'auto'
- textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 200) + 'px'
- }
+ // GH #139: measured on a copy outside the page, and written only when the
+ // height really changes, so a key within a line lays out nothing but the
+ // field (lib/fit-textarea.ts). Before paint, so a new line and its height
+ // show up in the same frame.
+ useLayoutEffect(() => {
+ if (textareaRef.current) fitTextarea(textareaRef.current, COMPOSER_MAX_PX)
// conversationId mit in der Abhaengigkeit: `key={conversationId}` unten
// montiert das Textfeld beim Wechsel neu, der frische Knoten startet aber
// auf `rows={1}`. Ist der uebernommene Entwurf identisch mit dem der
@@ -327,18 +332,12 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
}
// Write a dictation transcript (interim or final) into the input as
- // base + transcript, then resize the textarea. NEVER sends, because the user
- // reviews and presses Send (David 2026-06-06).
+ // base + transcript; the layout effect above sizes the field. NEVER sends,
+ // because the user reviews and presses Send (David 2026-06-06).
const applyDictation = (text: string) => {
const base = dictationBaseRef.current
const sep = base && !/\s$/.test(base) ? ' ' : ''
setInput(base + sep + text)
- requestAnimationFrame(() => {
- if (textareaRef.current) {
- textareaRef.current.style.height = 'auto'
- textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 200) + 'px'
- }
- })
}
// Synchronous double-fire guard (David 2026-06-20: "ok generiere jetzt" landed
@@ -355,7 +354,6 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
setInput('')
setImages([])
setCmdMenu([])
- if (textareaRef.current) textareaRef.current.style.height = 'auto'
}
// Update the input + the slash-command typeahead together. The menu shows
@@ -741,7 +739,8 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
<div className="shrink-0 w-[var(--control-h-sm)] h-[var(--control-h-sm)]" data-testid="composer-send-slot">
{isGenerating ? (
<button
- onClick={onStop}
+ // Called bare: the click event is not an argument of Stop (GH #140).
+ onClick={() => onStop()}
// Neutral, nicht rot: Stop ist der Normalabschluss und die
// haeufigste Aktion waehrend eines Streams. `data-active`
// gibt ihm den Behaelter des neutralen Rezepts, damit er
diff --git a/src/components/chat/LoopBar.tsx b/src/components/chat/LoopBar.tsx
index 81bbbd56..191f5729 100644
--- a/src/components/chat/LoopBar.tsx
+++ b/src/components/chat/LoopBar.tsx
@@ -50,7 +50,8 @@ export function LoopBar({ onStop }: Props) {
{secs > 0 ? `next in ${secs}s` : 'running'}
</span>
<button
- onClick={onStop}
+ // Called bare: the click event is not an argument of Stop (GH #140).
+ onClick={() => onStop()}
title="Stop the loop"
className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[0.55rem] text-gray-600 dark:text-gray-300 hover:bg-gray-200/60 dark:hover:bg-white/10 transition-colors shrink-0"
>
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index af319d51..c7a90314 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -27,6 +27,7 @@ import { MONOGRAM, MONOGRAM_INVERT } from '../layout/brand'
import { AVATAR_SLOT } from './avatar-slot'
import { MOTION_S } from '../ui/motion'
import { Hinweis } from '../ui/Hinweis'
+import { fitTextarea } from '../../lib/fit-textarea'
interface Props {
message: Message
@@ -143,8 +144,7 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o
useEffect(() => {
if (isEditing && editRef.current) {
editRef.current.focus()
- editRef.current.style.height = 'auto'
- editRef.current.style.height = editRef.current.scrollHeight + 'px'
+ fitTextarea(editRef.current)
}
}, [isEditing])
@@ -430,8 +430,10 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o
value={editContent}
onChange={(e) => {
setEditContent(e.target.value)
- e.target.style.height = 'auto'
- e.target.style.height = e.target.scrollHeight + 'px'
+ // Measured off-page (GH #139): this field sits INSIDE the
+ // transcript, so the old auto/scrollHeight toggle laid out
+ // the whole list on every key.
+ fitTextarea(e.target)
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); confirmEdit() }
diff --git a/src/components/chat/RecentChats.tsx b/src/components/chat/RecentChats.tsx
index 94361458..35630e17 100644
--- a/src/components/chat/RecentChats.tsx
+++ b/src/components/chat/RecentChats.tsx
@@ -16,28 +16,44 @@ import { useCodexStore } from '../../stores/codexStore'
import { timeAgo } from '../../lib/time-ago'
import { conversationMode } from '../../lib/conversation-mode'
-/** Same cut as the web list: plain chats only, newest first, eight rows. */
+/** Same cut as the web list: newest first, eight rows. */
const MAX_ROWS = 8
+/** GH #141 (Wruktarr): the list follows the mode picked in the rail, exactly
+ * like the expanded panel does (Sidebar.tsx filters its rows by chatMode).
+ * It used to show plain chats under Code and Remote too. */
+const HEADING: Record<string, string> = {
+ lu: 'Recent chats',
+ codex: 'Recent code chats',
+ remote: 'Recent remote chats',
+ openclaw: 'Recent agent chats',
+}
+const EMPTY: Record<string, string> = {
+ lu: 'No chats yet.',
+ codex: 'No code chats yet.',
+ remote: 'No remote chats yet.',
+ openclaw: 'No agent chats yet.',
+}
+
export function RecentChats() {
const conversations = useChatStore((s) => s.conversations)
const activeConversationId = useChatStore((s) => s.activeConversationId)
const setActiveConversation = useChatStore((s) => s.setActiveConversation)
const setView = useUIStore((s) => s.setView)
- const setChatMode = useCodexStore((s) => s.setChatMode)
+ const chatMode = useCodexStore((s) => s.chatMode)
const recents = conversations
// The chat you are already looking at is not a place to go back to. On the
// no-chat screen nothing is active, so nothing is dropped there.
.filter((c) => c.id !== activeConversationId)
- .filter((c) => conversationMode(c) === 'lu')
+ .filter((c) => conversationMode(c) === chatMode)
.sort((a, b) => b.updatedAt - a.updatedAt)
.slice(0, MAX_ROWS)
- // Opening a row is the same three steps as in the web launcher: back to
- // plain chat mode, select the conversation, land on the chat view.
+ // Opening a row is what a click on the same row in the panel does: the
+ // mode is already the right one (the list is filtered by it), so select the
+ // conversation and land on the chat view.
const openChat = (id: string) => {
- setChatMode('lu')
setActiveConversation(id)
setView('chat')
}
@@ -45,7 +61,7 @@ export function RecentChats() {
if (recents.length === 0) {
return (
<p data-testid="home-recent-chats" className="t-micro text-gray-400 dark:text-gray-500">
- No chats yet.
+ {EMPTY[chatMode] ?? EMPTY.lu}
</p>
)
}
@@ -59,7 +75,7 @@ export function RecentChats() {
transition={{ duration: MOTION_S.base, ease: 'easeOut' }}
>
<div className="mb-1 px-1 t-label font-medium text-gray-400 dark:text-gray-600">
- Recent chats
+ {HEADING[chatMode] ?? HEADING.lu}
</div>
<ul>
{recents.map((c, i) => (
diff --git a/src/components/chat/__tests__/home-recent-chats.test.ts b/src/components/chat/__tests__/home-recent-chats.test.ts
index e5d19eed..329fa0df 100644
--- a/src/components/chat/__tests__/home-recent-chats.test.ts
+++ b/src/components/chat/__tests__/home-recent-chats.test.ts
@@ -25,6 +25,7 @@ import { ChatView } from '../ChatView'
import { useUIStore } from '../../../stores/uiStore'
import { useChatStore } from '../../../stores/chatStore'
import { useCompareStore } from '../../../stores/compareStore'
+import { useCodexStore } from '../../../stores/codexStore'
import type { Conversation, Message } from '../../../types/chat'
// The composer's dictation button reaches for the microphone and the Tauri
@@ -42,6 +43,7 @@ const said = (text: string): Message => ({
})
beforeEach(() => {
+ useCodexStore.setState({ chatMode: 'lu' })
useUIStore.setState({ currentView: 'chat', sidebarOpen: false })
useCompareStore.setState({ isComparing: false })
useChatStore.setState({
@@ -75,6 +77,33 @@ describe('the latest chats on the home screen', () => {
expect(useChatStore.getState().activeConversationId).toBe('a')
})
+ // GH #141 (Wruktarr): with Code or Remote picked in the collapsed rail the
+ // list showed the plain chats. It follows the mode now, like the panel.
+ it('Code picked in the rail: the code chats, and opening one stays in Code', () => {
+ useChatStore.setState({
+ conversations: [
+ conv('a', 'Yesterdays thread', NOW - 3600_000),
+ { ...conv('c', 'Refactor the parser', NOW - 7200_000), mode: 'codex' },
+ ],
+ })
+ useCodexStore.setState({ chatMode: 'codex' })
+ render(createElement(ChatView))
+ const list = screen.getByTestId('home-recent-chats')
+ expect(list.textContent).toContain('Recent code chats')
+ expect(list.textContent).toContain('Refactor the parser')
+ expect(list.textContent).not.toContain('Yesterdays thread')
+ fireEvent.click(screen.getByText('Refactor the parser'))
+ expect(useChatStore.getState().activeConversationId).toBe('c')
+ expect(useCodexStore.getState().chatMode).toBe('codex')
+ })
+
+ it('Remote picked in the rail with no remote chats: says so, lists no plain chats', () => {
+ useCodexStore.setState({ chatMode: 'remote' })
+ render(createElement(ChatView))
+ const list = screen.getByTestId('home-recent-chats')
+ expect(list.textContent).toBe('No remote chats yet.')
+ })
+
})
describe('an open but still empty chat', () => {
diff --git a/src/components/chat/__tests__/the-code-composer-is-one-quiet-row.test.ts b/src/components/chat/__tests__/the-code-composer-is-one-quiet-row.test.ts
index 1e7aa57d..fd3d1233 100644
--- a/src/components/chat/__tests__/the-code-composer-is-one-quiet-row.test.ts
+++ b/src/components/chat/__tests__/the-code-composer-is-one-quiet-row.test.ts
@@ -140,7 +140,10 @@ describe('Stop never opens a second line', () => {
it('Stop is the running state of the send button, one ternary, one handler', () => {
expect(INPUT).toMatch(/\{isGenerating \? \(/)
- expect(INPUT.match(/onClick=\{onStop\}/g)).toHaveLength(1)
+ // Called bare (GH #140): handed to onClick as is, Stop got the click
+ // event as the conversation to stop and stopped nothing in the Code view.
+ expect(INPUT.match(/onClick=\{\(\) => onStop\(\)\}/g)).toHaveLength(1)
+ expect(INPUT).not.toMatch(/onClick=\{onStop\}/)
})
})
diff --git a/src/components/create/experimental/Composer.tsx b/src/components/create/experimental/Composer.tsx
index 1ec3f86f..9f9e0849 100644
--- a/src/components/create/experimental/Composer.tsx
+++ b/src/components/create/experimental/Composer.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Sparkles, X, SlidersHorizontal, Square, Workflow } from 'lucide-react'
-import { useCreateStore, MODEL_TYPE_DEFAULTS } from '../../../stores/createStore'
+import { useCreateStore, MODEL_TYPE_DEFAULTS, EDIT_MAX_DENOISE } from '../../../stores/createStore'
import { classifyModel } from '../../../api/comfyui'
import { useCreateExp } from './CreateContext'
import { intentToJob } from '../../../lib/render/cloud-jobs'
@@ -600,7 +600,7 @@ function LaneControls() {
{meta.id === 'edit' && (
<div className="w-44">
- <Slider label="Edit strength" min={0.05} max={1} step={0.05} value={denoise} onChange={setDenoise} format={(v) => v.toFixed(2)} />
+ <Slider label="Edit strength" min={0.05} max={EDIT_MAX_DENOISE} step={0.05} value={Math.min(denoise, EDIT_MAX_DENOISE)} onChange={setDenoise} format={(v) => v.toFixed(2)} />
</div>
)}
</div>
diff --git a/src/components/create/experimental/CreateExperimental.tsx b/src/components/create/experimental/CreateExperimental.tsx
index 5c88e523..b8be29c6 100644
--- a/src/components/create/experimental/CreateExperimental.tsx
+++ b/src/components/create/experimental/CreateExperimental.tsx
@@ -20,6 +20,7 @@ import { Hinweis } from '../../ui/Hinweis'
import { BannerText } from './BannerText'
import { MaskEditor } from './MaskEditor'
import { VhsInstallModal } from './VhsInstallModal'
+import { RenderFixupModal } from './RenderFixupModal'
import { PresetShelf } from './PresetShelf'
import type { CreatePreset } from '../../../lib/render/create-presets'
import { Modal } from '../../ui/Modal'
@@ -490,6 +491,7 @@ function CreateExperimentalInner() {
<Lightbox item={lightbox} onClose={() => setLightbox(null)} />
<VhsInstallModal />
+ <RenderFixupModal />
</div>
)
}
diff --git a/src/components/create/experimental/CreatePanel.tsx b/src/components/create/experimental/CreatePanel.tsx
index 5b06235e..55a1e4a5 100644
--- a/src/components/create/experimental/CreatePanel.tsx
+++ b/src/components/create/experimental/CreatePanel.tsx
@@ -3,7 +3,7 @@ import { Images, Play, PanelRightClose, Trash2, Download, MonitorOff, AudioLines
import { downloadMediaUrl } from '../../../lib/download-media'
import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
import { galleryLabel } from '../../../lib/render/gallery-label'
-import { galleryItemUrl } from './galleryUrl'
+import { GALLERY_DRAG_TYPE, galleryItemUrl } from './galleryUrl'
import { useComfyMedia } from './useComfyMedia'
import { cn } from '../ui/cn'
@@ -107,6 +107,11 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {
<div key={g.id} className="relative group">
<button
onClick={() => onSelect(g.id)}
+ draggable={g.type === 'image' && !g.unavailable}
+ onDragStart={(e) => {
+ e.dataTransfer.setData(GALLERY_DRAG_TYPE, g.id)
+ e.dataTransfer.effectAllowed = 'copy'
+ }}
className={cn(
'w-full aspect-square rounded-lg overflow-hidden border-2 transition-colors relative',
(activeId ?? gallery[0]?.id) === g.id ? 'border-white/60' : 'border-transparent hover:border-white/20',
@@ -117,7 +122,7 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {
{g.unavailable && (
<span
className="absolute inset-0 flex items-center justify-center bg-black/50 text-gray-500"
- title="Local render, but the local engine isn't reachable"
+ title={g.unavailableReason === 'gone' ? 'No longer in the ComfyUI output folder' : "Local render, but the local engine isn't reachable"}
>
<MonitorOff size={16} />
</span>
@@ -126,7 +131,7 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {
<button
onClick={() => removeFromGallery(g.id)}
className="absolute -top-1.5 -right-1.5 w-6 h-6 rounded-full bg-red-600/90 hover:bg-red-600 text-gray-100 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center shadow-sm"
- title="Delete"
+ title="Delete (moves the file to the Recycle Bin)"
>
<Trash2 size={12} />
</button>
diff --git a/src/components/create/experimental/OutputView.tsx b/src/components/create/experimental/OutputView.tsx
index cc99adc0..1f8edcaf 100644
--- a/src/components/create/experimental/OutputView.tsx
+++ b/src/components/create/experimental/OutputView.tsx
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'
import { motion } from 'framer-motion'
-import { Cpu, Sparkles, ImageDown, Maximize2, Download, Wand2, MonitorOff, AudioLines, Film } from 'lucide-react'
+import { Cpu, Sparkles, ImageDown, Maximize2, Download, Wand2, MonitorOff, AudioLines, Film, Trash2 } from 'lucide-react'
import { coldLoadHint } from '../../../lib/cold-load-notice'
import { useCreateStore, type GalleryItem, type ProgressPhase } from '../../../stores/createStore'
import { backendCall, downloadComfyFile, isTauri } from '../../../api/backend'
@@ -273,7 +273,11 @@ export function ResultView({ item, onFullscreen, onSendToEditor, onAnimate }: Re
{item.unavailable && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-[var(--radius-panel)] bg-black/60 text-gray-400 p-6 text-center">
<MonitorOff size={ICON_LG} />
- <span className="t-body">This render lives on the local engine, which isn't reachable right now.</span>
+ <span className="t-body">
+ {item.unavailableReason === 'gone'
+ ? 'This file is no longer in the ComfyUI output folder.'
+ : 'This render lives on the local engine, which isn\'t reachable right now. It shows up again as soon as ComfyUI is running.'}
+ </span>
</div>
)}
<div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
@@ -293,6 +297,12 @@ export function ResultView({ item, onFullscreen, onSendToEditor, onAnimate }: Re
{!isAudio && (
<IconBtn title="Fullscreen" onClick={onFullscreen}><Maximize2 size={14} /></IconBtn>
)}
+ {/* Discord 2026-09-28 (lapbo, #feature-requests "DELETE BUTTON"):
+ delete from the big view too, not only from the tile's corner.
+ The file goes to the Recycle Bin (lib/gallery-trash.ts). */}
+ <IconBtn title="Delete (moves the file to the Recycle Bin)" onClick={() => useCreateStore.getState().removeFromGallery(item.id)}>
+ <Trash2 size={14} />
+ </IconBtn>
</div>
</div>
<div className="flex items-center gap-3 mt-3 t-mono text-gray-600">
diff --git a/src/components/create/experimental/RenderFixupModal.tsx b/src/components/create/experimental/RenderFixupModal.tsx
new file mode 100644
index 00000000..852e340b
--- /dev/null
+++ b/src/components/create/experimental/RenderFixupModal.tsx
@@ -0,0 +1,36 @@
+import { Download } from 'lucide-react'
+import { useCreateStore } from '../../../stores/createStore'
+import { Modal } from '../../ui/Modal'
+
+/**
+ * Discord 2026-09-28: a model that needs a text encoder / VAE that is not on
+ * disk, or a newer ComfyUI, gets the fix offered right here instead of a
+ * sentence pointing at the Model Manager. Same pattern as VhsInstallModal:
+ * useCreate sets `fixupPrompt`, this resolves it.
+ */
+export function RenderFixupModal() {
+ const prompt = useCreateStore((s) => s.fixupPrompt)
+ const choose = (go: boolean) => prompt?.resolve(go)
+ return (
+ <Modal open={prompt !== null} onClose={() => choose(false)} title={prompt?.title ?? ''}>
+ <div className="space-y-4 text-sm text-gray-200">
+ <p className="text-[12px] text-gray-300 leading-relaxed">{prompt?.detail}</p>
+ <div className="flex flex-col gap-2 pt-1">
+ <button
+ onClick={() => choose(true)}
+ className="w-full px-4 py-2 rounded-lg bg-blue-500/20 hover:bg-blue-500/30 border border-blue-500/30 text-blue-200 text-sm font-medium transition-colors flex items-center justify-center gap-2"
+ >
+ <Download size={14} />
+ {prompt?.confirm}
+ </button>
+ <button
+ onClick={() => choose(false)}
+ className="w-full px-4 py-1.5 rounded-lg hover:bg-white/5 text-gray-500 hover:text-gray-300 text-xs transition-colors"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ </Modal>
+ )
+}
diff --git a/src/components/create/experimental/Stage.tsx b/src/components/create/experimental/Stage.tsx
index c7cd1a83..6d5f41e4 100644
--- a/src/components/create/experimental/Stage.tsx
+++ b/src/components/create/experimental/Stage.tsx
@@ -16,7 +16,7 @@ import { mediaRefFrom } from './mediaRef'
import {
subscribeInstallRuns, getInstallRun, startInstallRun, cancelInstallRun, clearInstallRun,
} from '../../../lib/model-install-runs'
-import { galleryItemUrl, fetchGalleryItemBlob, recoverGalleryUrl } from './galleryUrl'
+import { GALLERY_DRAG_TYPE, galleryItemUrl, fetchGalleryItemBlob, recoverGalleryUrl } from './galleryUrl'
import { InstallCancelled } from '../../../lib/bundle-install'
import { isMlxImageHost } from '../../../api/mlx-image'
import { bundleForVideoIntent } from '../../../api/comfyui'
@@ -254,7 +254,14 @@ function InputSlot() {
onClick={() => inputRef.current?.click()}
onDragOver={(e) => { e.preventDefault(); setDrag(true) }}
onDragLeave={() => setDrag(false)}
- onDrop={(e) => { e.preventDefault(); setDrag(false); const f = e.dataTransfer.files[0]; if (f) handleFile(f) }}
+ onDrop={(e) => {
+ e.preventDefault()
+ setDrag(false)
+ const f = e.dataTransfer.files[0]
+ if (f) { void handleFile(f); return }
+ const item = gallery.find((g) => g.id === e.dataTransfer.getData(GALLERY_DRAG_TYPE))
+ if (item && !loading) void adoptFromGallery(item)
+ }}
className={cn(
// max-h trimmed 44vh→36vh so the "or pick from your gallery" strip
// below stays visible without scrolling at typical window heights
diff --git a/src/components/create/experimental/__tests__/galleryUrl.test.ts b/src/components/create/experimental/__tests__/galleryUrl.test.ts
index 9390ffce..b8c95090 100644
--- a/src/components/create/experimental/__tests__/galleryUrl.test.ts
+++ b/src/components/create/experimental/__tests__/galleryUrl.test.ts
@@ -54,6 +54,7 @@ vi.mock('../../../../api/comfyui', () => ({
type: string = 'output',
) =>
`http://127.0.0.1:8188/view?filename=${filename}&subfolder=${subfolder ?? ''}&type=${type}`),
+ checkComfyConnection: vi.fn(async () => false),
}))
vi.mock('../../../../api/cloud/jobs', () => ({
@@ -247,5 +248,18 @@ describe('recoverGalleryUrl — local MLX renders on disk', () => {
await flush()
expect(vi.mocked(backendCall)).not.toHaveBeenCalled()
expect(useCreateStore.getState().gallery[0].unavailable).toBe(true)
+ // The engine did not answer, so the tile says offline (and comes back
+ // with it, see gallery-engine-recovery.test.ts).
+ expect(useCreateStore.getState().gallery[0].unavailableReason).toBe('offline')
+ })
+
+ it('an engine that answers but lacks the file says the file is gone', async () => {
+ const { checkComfyConnection } = await import('../../../../api/comfyui')
+ vi.mocked(checkComfyConnection).mockResolvedValueOnce(true)
+ const item = { ...baseItem, id: 'comfy-gone' }
+ useCreateStore.setState({ gallery: [item] })
+ recoverGalleryUrl(item)
+ await flush()
+ expect(useCreateStore.getState().gallery[0].unavailableReason).toBe('gone')
})
})
diff --git a/src/components/create/experimental/badges.ts b/src/components/create/experimental/badges.ts
index 38ae1032..0e7cc447 100644
--- a/src/components/create/experimental/badges.ts
+++ b/src/components/create/experimental/badges.ts
@@ -34,6 +34,13 @@ export const TYPE_BADGE: Record<ModelType, { label: string; color: string }> = {
// yellow are ruled out by the file header, and slate/stone/zinc already
// carry ernie_image/cogvideo/krea2. neutral is the one remaining row.
qwenimage: { label: 'Qwen Image 2.1', color: 'bg-neutral-500/15 text-neutral-300' },
+ // Families that arrived with the header sniff. Every free tone is taken, so
+ // they share the neutral row with their nearest relative's label.
+ qwenimage1: { label: 'Qwen Image', color: 'bg-neutral-500/15 text-neutral-300' },
+ chroma: { label: 'Chroma', color: 'bg-purple-500/15 text-purple-300' },
+ hidream: { label: 'HiDream', color: 'bg-zinc-500/15 text-zinc-300' },
+ sd3: { label: 'SD 3.5', color: 'bg-blue-500/15 text-blue-300' },
+ lumina2: { label: 'Lumina 2', color: 'bg-slate-500/15 text-slate-300' },
sdxl: { label: 'SDXL', color: 'bg-blue-500/15 text-blue-300' },
sd15: { label: 'SD 1.5', color: 'bg-green-500/15 text-green-300' },
wan: { label: 'Wan', color: 'bg-orange-500/15 text-orange-300' },
diff --git a/src/components/create/experimental/galleryUrl.ts b/src/components/create/experimental/galleryUrl.ts
index 68cf3a09..84d185c1 100644
--- a/src/components/create/experimental/galleryUrl.ts
+++ b/src/components/create/experimental/galleryUrl.ts
@@ -1,4 +1,4 @@
-import { getImageUrl } from '../../../api/comfyui'
+import { checkComfyConnection, getImageUrl } from '../../../api/comfyui'
import { refreshResultUrl, resolveResultUrl } from '../../../api/cloud/jobs'
import { backendCall, fetchLocalhostBytes, isTauri } from '../../../api/backend'
import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
@@ -7,13 +7,10 @@ import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
* remoteUrl (cloud signed URL) → dataUrl (in-memory self-contained fallback)
* → ComfyUI /view path (filename/subfolder). */
export function galleryItemUrl(item: GalleryItem): string {
- return item.remoteUrl
- ?? item.dataUrl
- ?? getImageUrl(
- item.filename,
- item.subfolder,
- item.comfyType ?? 'output',
- )
+ if (item.remoteUrl ?? item.dataUrl) return (item.remoteUrl ?? item.dataUrl)!
+ const view = getImageUrl(item.filename, item.subfolder, item.comfyType ?? 'output')
+ // A new URL per retry, or the element never asks again (setComfyRunning).
+ return item.reloadKey ? `${view}${view.includes('?') ? '&' : '?'}lu_retry=${item.reloadKey}` : view
}
// Cloud signed URLs expire ~1 h after the last read, so a persisted item's
@@ -41,10 +38,19 @@ export function recoverGalleryUrl(item: GalleryItem): void {
void restoreFromDisk(item)
return
}
- // Local ComfyUI item whose /view fetch failed (engine not running /
- // output pruned) — nothing to re-sign. Flag it so the tiles can render
- // an honest "engine offline" state instead of a silently dead <img>.
- if (!item.unavailable) useCreateStore.getState().updateGalleryItem(item.id, { unavailable: true })
+ // Local ComfyUI item whose /view fetch failed — nothing to re-sign. Say
+ // which of the two it is: an engine that does not answer (the tile comes
+ // back by itself when it does, see setComfyRunning), or an engine that
+ // answers and no longer has the file.
+ if (!item.unavailable) {
+ void checkComfyConnection().catch(() => false).then((up) => {
+ useCreateStore.getState().updateGalleryItem(item.id, { unavailable: true, unavailableReason: up ? 'gone' : 'offline' })
+ if (!up) {
+ useCreateStore.getState().setComfyRunning(false)
+ watchForEngine()
+ }
+ })
+ }
return
}
const last = recovered.get(item.id)
@@ -69,6 +75,26 @@ export function recoverGalleryUrl(item: GalleryItem): void {
})
}
+// While tiles wait for an engine that did not answer, ask again every 10 s
+// and let setComfyRunning(true) bring them back. Nothing else polls the
+// connection, so without this they stayed dark until the next app start.
+// Stops by itself as soon as no tile is waiting.
+let engineWatch: ReturnType<typeof setInterval> | null = null
+function watchForEngine(): void {
+ if (engineWatch) return
+ engineWatch = setInterval(() => {
+ const waiting = useCreateStore.getState().gallery.some((g) => g.unavailable && g.unavailableReason === 'offline')
+ if (!waiting) {
+ clearInterval(engineWatch!)
+ engineWatch = null
+ return
+ }
+ void checkComfyConnection().catch(() => false).then((up) => {
+ if (up) useCreateStore.getState().setComfyRunning(true)
+ })
+ }, 10_000)
+}
+
/**
* Re-read a local render from disk and hand the tile a fresh blob: URL.
*
@@ -175,3 +201,9 @@ export async function fetchGalleryItemBlob(item: GalleryItem): Promise<Blob> {
throw err
}
}
+
+/** Discord 2026-09-26 (boromirofgeo): dragging a gallery tile onto the Edit
+ * drop zone did nothing. An in-page <img> drag carries a URL, never a File,
+ * so the zone's `dataTransfer.files[0]` was always empty. The tile now names
+ * its gallery item under this type, and the zone adopts it like a click. */
+export const GALLERY_DRAG_TYPE = 'application/x-lu-gallery-item'
diff --git a/src/components/create/ui/PromptField.tsx b/src/components/create/ui/PromptField.tsx
index 0a156cd9..da6bc395 100644
--- a/src/components/create/ui/PromptField.tsx
+++ b/src/components/create/ui/PromptField.tsx
@@ -1,6 +1,7 @@
-import { useEffect, useRef } from 'react'
+import { useLayoutEffect, useRef } from 'react'
import { cn } from './cn'
+import { fitTextarea } from '../../../lib/fit-textarea'
interface Props {
value: string
@@ -16,11 +17,10 @@ interface Props {
export function PromptField({ value, onChange, placeholder, onSubmit, maxHeight = 220, autoFocus, className }: Props) {
const ref = useRef<HTMLTextAreaElement>(null)
- useEffect(() => {
- const el = ref.current
- if (!el) return
- el.style.height = 'auto'
- el.style.height = Math.min(el.scrollHeight, maxHeight) + 'px'
+ // Measured off-page and written only on a real change (GH #139), so a key
+ // within a line does not lay out the Create page around the field.
+ useLayoutEffect(() => {
+ if (ref.current) fitTextarea(ref.current, maxHeight)
}, [value, maxHeight])
return (
diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsx
index dc5b6898..8d7e7e0a 100644
--- a/src/components/models/DiscoverModels.tsx
+++ b/src/components/models/DiscoverModels.tsx
@@ -10,7 +10,7 @@ import {
getUncensoredTextModels, getMainstreamTextModels,
detectProviderModelPath, startModelDownloadToPath, luEngineDownloadDir,
startModelDownload,
- installBundleComplete, checkBundlesInstalled, resolveHfGgufFiles, planModelDownload,
+ installBundleComplete, remoteBundleNotice, checkBundlesInstalled, resolveHfGgufFiles, planModelDownload,
type DiscoverModel, type DownloadProgress, type ModelBundle, type HfGgufFile,
} from '../../api/discover'
import { getSystemVRAM } from '../../api/comfyui'
@@ -462,7 +462,10 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:
// Start polling BEFORE install so progress is tracked immediately
dlStore.getState().startPolling()
try {
- await installBundleComplete(bundle)
+ const report = await installBundleComplete(bundle)
+ // GH #143: a ComfyUI on another machine. Not an error, the downloads
+ // run; the notice says where they go and what is left to do over there.
+ if (report.remote) setInstallNotice(remoteBundleNotice(bundle.name, report.remote))
} catch (err) {
log.error('[DiscoverModels] Bundle install failed', { err })
setInstallError(`${bundle.name}: ${err instanceof Error ? err.message : String(err)}`)
diff --git a/src/hooks/__tests__/code-stop-nimmt-kein-klickereignis.test.tsx b/src/hooks/__tests__/code-stop-nimmt-kein-klickereignis.test.tsx
new file mode 100644
index 00000000..a7ca62d7
--- /dev/null
+++ b/src/hooks/__tests__/code-stop-nimmt-kein-klickereignis.test.tsx
@@ -0,0 +1,118 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * GH #140 (Code Agent, Windows 3.0.2): neither Stop worked, not the big one
+ * next to the prompt box and not the one in the blue /loop bar. Both buttons
+ * got `stopCodex` handed straight to `onClick`, so React called it with the
+ * click EVENT, `stopCodex` took that for the conversation to stop, and the
+ * event matched no run, no loop and no timer. The plain chat was fine only
+ * because its `stopGeneration` takes no argument at all.
+ *
+ * The second half of the report: a loop whose pass ended before it reached
+ * its driver kept the bar on "running" and the working folder locked.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, fireEvent, render, renderHook, screen } from '@testing-library/react'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+import { useCodex } from '../useCodex'
+import { LoopBar } from '../../components/chat/LoopBar'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useCodexStore } from '../../stores/codexStore'
+import { endLoopUnlessRearmed, useAgentLoopStore } from '../../stores/agentLoopStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { __resetRunStopsForTests, isRunStopped } from '../../lib/run-stop'
+
+const MODEL = 'ollama::qwen3:14b'
+
+function standingLoop(conversationId: string) {
+ useAgentLoopStore.getState().start({
+ conversationId, pass: 3, cap: 0, task: 'fix the tests', intervalMs: 30_000, nextAt: Date.now() - 1000,
+ })
+}
+
+beforeEach(() => {
+ __resetRunStopsForTests()
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useCodexStore.setState({ sendsInFlight: 0, threads: {}, workingDirectory: '' })
+ useAgentLoopStore.setState({ loops: {} })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useModelStore.setState({ models: [], activeModel: MODEL })
+})
+afterEach(() => vi.restoreAllMocks())
+
+describe('Stop in the Code view', () => {
+ it('stops the run and the loop when handed the click event (the #140 wiring)', () => {
+ const convId = useChatStore.getState().createConversation(MODEL, '', 'codex')
+ useChatStore.getState().setActiveConversation(convId)
+ const abort = vi.fn()
+ useGenerationStore.getState().registerAborter(convId, abort)
+ standingLoop(convId)
+
+ const { result } = renderHook(() => useCodex())
+ // Exactly what `onClick={stopCodex}` did: React passes the event.
+ const click = new MouseEvent('click') as unknown as string
+ act(() => { result.current.stopCodex(click) })
+
+ expect(abort).toHaveBeenCalled()
+ expect(isRunStopped(convId)).toBe(true)
+ expect(useAgentLoopStore.getState().loops[convId]).toBeUndefined()
+ })
+
+ it('COUNTER-CHECK: a named conversation is still the one stopped', () => {
+ const convA = useChatStore.getState().createConversation(MODEL, '', 'codex')
+ const convB = useChatStore.getState().createConversation(MODEL, '', 'codex')
+ useChatStore.getState().setActiveConversation(convB)
+ standingLoop(convA)
+ const { result } = renderHook(() => useCodex())
+ act(() => { result.current.stopCodex(convA) })
+ expect(isRunStopped(convA)).toBe(true)
+ expect(isRunStopped(convB)).toBe(false)
+ expect(useAgentLoopStore.getState().loops[convA]).toBeUndefined()
+ })
+
+ it('the loop bar calls Stop with no argument', () => {
+ const convId = useChatStore.getState().createConversation(MODEL, '', 'codex')
+ useChatStore.getState().setActiveConversation(convId)
+ standingLoop(convId)
+ const onStop = vi.fn()
+ render(<LoopBar onStop={onStop} />)
+ fireEvent.click(screen.getByTitle('Stop the loop'))
+ expect(onStop).toHaveBeenCalledTimes(1)
+ expect(onStop.mock.calls[0]).toEqual([])
+ })
+
+ it('the prompt box Stop does not hand its event on either', () => {
+ const src = readFileSync(join(__dirname, '..', '..', 'components', 'chat', 'ChatInput.tsx'), 'utf8')
+ expect(src).not.toMatch(/onClick=\{onStop\}/)
+ expect(src).toContain('onClick={() => onStop()}')
+ })
+})
+
+describe('a loop whose pass ended early does not stay "running"', () => {
+ it('a pass that settles without arming the next one ends the loop', async () => {
+ standingLoop('conv-1')
+ await endLoopUnlessRearmed('conv-1', Promise.resolve(), () => false)
+ expect(useAgentLoopStore.getState().loops['conv-1']).toBeUndefined()
+ })
+
+ it('also when the pass threw, and the throw still reaches the caller', async () => {
+ standingLoop('conv-1')
+ await expect(endLoopUnlessRearmed('conv-1', Promise.reject(new Error('boom')), () => false)).rejects.toThrow('boom')
+ expect(useAgentLoopStore.getState().loops['conv-1']).toBeUndefined()
+ })
+
+ it('also when there was no pass to start at all', async () => {
+ standingLoop('conv-1')
+ await endLoopUnlessRearmed('conv-1', undefined, () => false)
+ expect(useAgentLoopStore.getState().loops['conv-1']).toBeUndefined()
+ })
+
+ it('COUNTER-CHECK: a pass that armed the next one keeps its bar', async () => {
+ standingLoop('conv-1')
+ await endLoopUnlessRearmed('conv-1', Promise.resolve(), () => true)
+ expect(useAgentLoopStore.getState().loops['conv-1']).toBeDefined()
+ })
+})
diff --git a/src/hooks/__tests__/decay-wiring.test.ts b/src/hooks/__tests__/decay-wiring.test.ts
index 30f9a2b7..50daaddd 100644
--- a/src/hooks/__tests__/decay-wiring.test.ts
+++ b/src/hooks/__tests__/decay-wiring.test.ts
@@ -59,9 +59,12 @@ describe.each([
// The catalog is its own field on the wire, so the message estimate above
// cannot see it. It is picked after the build, which is why it arrives as
// a second call instead of riding in the report.
- expect(source).toMatch(
- /reportTools\(convId, estimateTokens\(JSON\.stringify\(tools\)\)\)/,
- )
+ // useCodex measures it once into a variable since GH #140: its
+ // context-overflow retry reads the same number to size the cut.
+ const direct = /reportTools\(convId, estimateTokens\(JSON\.stringify\(tools\)\)\)/.test(source)
+ const viaVariable = /stepToolsEstimate = estimateTokens\(JSON\.stringify\(tools\)\)/.test(source)
+ && /reportTools\(convId, stepToolsEstimate\)/.test(source)
+ expect(direct || viaVariable).toBe(true)
})
it('leaves a decay row in the tool audit so support can see it', () => {
diff --git a/src/hooks/codex/__tests__/context-overflow.test.ts b/src/hooks/codex/__tests__/context-overflow.test.ts
new file mode 100644
index 00000000..fe819e58
--- /dev/null
+++ b/src/hooks/codex/__tests__/context-overflow.test.ts
@@ -0,0 +1,131 @@
+/**
+ * GH #140: under /loop the Code Agent ended pass after pass on HTTP 400 "the
+ * request exceeds the available context size" and never compacted. The step
+ * now reads the refusal, cuts the history to a budget that fits and goes out
+ * again; the budget is remembered for the model and its window.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ __resetLearnedWindowsForTests,
+ capToLearnedWindow,
+ contextOverflowOf,
+ learnSendWindow,
+ MIN_SEND_WINDOW,
+ shrunkSendWindow,
+} from '../context-overflow'
+import { isThinkingUnsupportedError, shouldDowngradeThinking } from '../thinking-downgrade'
+import { OpenAIProvider } from '../../../api/providers/openai-provider'
+
+afterEach(() => {
+ __resetLearnedWindowsForTests()
+ vi.restoreAllMocks()
+})
+
+const status400 = (message: string) => Object.assign(new Error(message), { status: 400 })
+
+describe('contextOverflowOf', () => {
+ it('reads llama.cpp / the built-in engine, numbers included', () => {
+ const e = status400('the request exceeds the available context size, try increasing it (request (34567 tokens), context size (32768 tokens))')
+ expect(contextOverflowOf(e)).toEqual({ window: 32768, promptTokens: 34567 })
+ })
+
+ it('recognises the sentence without numbers too (a streamed error chunk)', () => {
+ expect(contextOverflowOf(new Error('the request exceeds the available context size, try increasing it')))
+ .toEqual({ window: undefined, promptTokens: undefined })
+ })
+
+ it('reads LM Studio, vLLM / OpenAI and Anthropic wording', () => {
+ expect(contextOverflowOf(new Error(
+ 'Trying to keep the first 17392 tokens when context the overflows. However, the model is loaded with context length of only 4096 tokens, which is not enough.',
+ ))?.window).toBe(4096)
+ expect(contextOverflowOf(new Error(
+ "This model's maximum context length is 32768 tokens. However, you requested 40000 tokens (39000 in the messages, 1000 in the completion).",
+ ))).toEqual({ window: 32768, promptTokens: 40000 })
+ expect(contextOverflowOf(new Error('prompt is too long: 210000 tokens > 200000 maximum')))
+ .toEqual({ window: 200000, promptTokens: 210000 })
+ })
+
+ it('leaves every other failure alone', () => {
+ expect(contextOverflowOf(status400('model does not support thinking'))).toBeNull()
+ expect(contextOverflowOf(new Error('Failed to fetch'))).toBeNull()
+ expect(contextOverflowOf(null)).toBeNull()
+ // Asking for a longer window in the chat text is not a refusal.
+ expect(contextOverflowOf(new Error('Tool file_read failed: ENOENT'))).toBeNull()
+ })
+})
+
+describe('shrunkSendWindow', () => {
+ it('with both numbers: under the window by the margin', () => {
+ const next = shrunkSendWindow(26000, { window: 32768, promptTokens: 34567 }, 30000)!
+ // The history scaled by what the server counted, with 15 % room.
+ expect(next).toBe(Math.floor(26000 * (32768 / 34567) * 0.85))
+ expect(next).toBeLessThan(26000)
+ })
+
+ it('with only the window: scaled by our own count', () => {
+ expect(shrunkSendWindow(12000, { window: 4096 }, 16000)).toBe(Math.floor(12000 * (4096 / 16000) * 0.75))
+ })
+
+ it('with nothing: 40 % off', () => {
+ expect(shrunkSendWindow(20000, {}, 24000)).toBe(12000)
+ })
+
+ it('always strictly below what was refused', () => {
+ // An estimate that ran LOW: the window is above our own count, and the
+ // step was refused all the same. It still goes out smaller.
+ expect(shrunkSendWindow(10000, { window: 64000 }, 12000)).toBe(7500)
+ // And never less than a tenth off, whatever the numbers say.
+ expect(shrunkSendWindow(10000, { window: 64000, promptTokens: 60000 }, 12000)).toBe(9000)
+ })
+
+ it('gives up where the instructions alone would not fit', () => {
+ expect(shrunkSendWindow(MIN_SEND_WINDOW + 10, {}, 5000)).toBeNull()
+ expect(shrunkSendWindow(0, {}, 0)).toBeNull()
+ })
+})
+
+describe('the learned budget', () => {
+ it('holds the next step and the next pass under what fit', () => {
+ expect(capToLearnedWindow(26000, 'openai::qwen-coder', 32768)).toBe(26000)
+ learnSendWindow('openai::qwen-coder', 32768, 20000)
+ expect(capToLearnedWindow(26000, 'openai::qwen-coder', 32768)).toBe(20000)
+ // Never raises a window that is already smaller.
+ expect(capToLearnedWindow(8000, 'openai::qwen-coder', 32768)).toBe(8000)
+ })
+
+ it('does not follow the model to a different window', () => {
+ learnSendWindow('openai::qwen-coder', 32768, 20000)
+ expect(capToLearnedWindow(52000, 'openai::qwen-coder', 65536)).toBe(52000)
+ expect(capToLearnedWindow(26000, 'openai::other', 32768)).toBe(26000)
+ })
+})
+
+describe('a context refusal is not a thinking refusal', () => {
+ it('no wasted retry without thinking, no model marked as unable to think', () => {
+ const e = status400('the request exceeds the available context size, try increasing it')
+ expect(isThinkingUnsupportedError(e)).toBe(false)
+ expect(shouldDowngradeThinking(true, e)).toBe(false)
+ // Unchanged for a real 400 from a server that does not know the switch.
+ expect(shouldDowngradeThinking(true, status400('unknown field: think'))).toBe(true)
+ })
+})
+
+describe('the provider keeps llama.cpp\'s numbers', () => {
+ it('a 400 exceed_context_size_error reaches the agent with both numbers', async () => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify({
+ error: {
+ code: 400,
+ message: 'the request exceeds the available context size, try increasing it',
+ type: 'exceed_context_size_error',
+ n_prompt_tokens: 34567,
+ n_ctx: 32768,
+ },
+ }), { status: 400, headers: { 'content-type': 'application/json' } }))
+ const provider = new OpenAIProvider({
+ id: 'openai', name: 'llama.cpp', enabled: true,
+ baseUrl: 'https://llama.test/v1', apiKey: '', isLocal: false,
+ })
+ const err = await provider.chatWithTools('qwen-coder', [{ role: 'user', content: 'hi' }], []).catch((e) => e)
+ expect(contextOverflowOf(err)).toEqual({ window: 32768, promptTokens: 34567 })
+ })
+})
diff --git a/src/hooks/codex/context-overflow.ts b/src/hooks/codex/context-overflow.ts
new file mode 100644
index 00000000..f94faec1
--- /dev/null
+++ b/src/hooks/codex/context-overflow.ts
@@ -0,0 +1,98 @@
+// ─── A request the server's context could not hold ───
+//
+// GH #140 (Code Agent, /loop): long runs ended pass after pass on HTTP 400
+// "the request exceeds the available context size" and never compacted. LU
+// sizes each step against the window it resolved for the model, estimated at
+// four characters a token, and the tool catalogue rides on top of that. When
+// the server holds less (a model loaded with a smaller context than it was
+// trained for, a tokenizer that packs code denser than four characters), every
+// step was refused the same way, and the loop fired the same refusal again on
+// the next pass.
+//
+// The refusal names the numbers more often than not. This reads them, and the
+// step goes out again with the history cut to a budget that fits, instead of
+// ending the pass. The budget is remembered for the model and the window it
+// runs with, so the next step and the next pass start inside it.
+
+import { errorText } from '../../types/json-guards'
+
+export interface ContextOverflow {
+ /** What the server can hold, when it said so. */
+ window?: number
+ /** What it counted for the refused request, when it said so. */
+ promptTokens?: number
+}
+
+// llama.cpp / the built-in engine, LM Studio, vLLM and OpenAI-style servers,
+// Anthropic via LU Cloud, and Ollama's own wording, in that order.
+const OVERFLOW = /exceed(?:s|ed)? the available context|exceed_context_size|context length of only|context the overflows|maximum context length|context[_ ]length[_ ]exceeded|prompt is too long|input length exceeds the (?:maximum )?context/i
+
+const num = (text: string, re: RegExp): number | undefined => {
+ const m = text.match(re)
+ const n = m ? Number(m[1]) : NaN
+ return Number.isFinite(n) && n > 0 ? n : undefined
+}
+
+/** The overflow a failed request reports, or null for any other failure. */
+export function contextOverflowOf(err: unknown): ContextOverflow | null {
+ const text = errorText(err)
+ if (!OVERFLOW.test(text)) return null
+ return {
+ window:
+ num(text, /n_ctx[":= ]+(\d+)/) ??
+ num(text, /context size \((\d+) tokens\)/i) ??
+ num(text, /maximum context length is (\d+)/i) ??
+ num(text, /context length of only (\d+)/i) ??
+ num(text, /tokens > (\d+)/),
+ promptTokens:
+ num(text, /n_prompt_tokens[":= ]+(\d+)/) ??
+ num(text, /request \((\d+) tokens\)/i) ??
+ num(text, /(?:you requested|resulted in) (\d+) tokens/i) ??
+ num(text, /too long: (\d+) tokens/i),
+ }
+}
+
+/** Below this the system prompt alone does not fit; another cut cannot help. */
+export const MIN_SEND_WINDOW = 1024
+
+/**
+ * The history budget for the retry, strictly below what was just refused, or
+ * null when there is nothing left to cut.
+ *
+ * `sent` is the estimated size of the history that went out, `sentTotal` the
+ * same with the tool catalogue. With both numbers from the server the cut is
+ * exact up to the estimate (and 15 % room for the answer and for estimates that
+ * run short); with only the window it scales our own count; with neither it
+ * takes 40 % off and tries again.
+ */
+export function shrunkSendWindow(sent: number, overflow: ContextOverflow, sentTotal: number): number | null {
+ if (!(sent > 0)) return null
+ const { window, promptTokens } = overflow
+ const raw = window && promptTokens
+ ? sent * (window / promptTokens) * 0.85
+ : window && sentTotal > 0
+ ? sent * Math.min(1, window / sentTotal) * 0.75
+ : sent * 0.6
+ const next = Math.floor(Math.min(raw, sent * 0.9))
+ return next >= MIN_SEND_WINDOW ? next : null
+}
+
+/** model + window it runs with → the history budget that fit last time. */
+const learned = new Map<string, number>()
+
+const keyOf = (model: string, numCtx: number) => `${model}@${numCtx}`
+
+/** The send window, held under what this model's server showed it can take. */
+export function capToLearnedWindow(sendWindow: number, model: string, numCtx: number): number {
+ const cap = learned.get(keyOf(model, numCtx))
+ return cap && cap < sendWindow ? cap : sendWindow
+}
+
+export function learnSendWindow(model: string, numCtx: number, budget: number): void {
+ learned.set(keyOf(model, numCtx), budget)
+}
+
+/** Test-only. */
+export function __resetLearnedWindowsForTests(): void {
+ learned.clear()
+}
diff --git a/src/hooks/codex/thinking-downgrade.ts b/src/hooks/codex/thinking-downgrade.ts
index 11de1f1b..eaff6784 100644
--- a/src/hooks/codex/thinking-downgrade.ts
+++ b/src/hooks/codex/thinking-downgrade.ts
@@ -1,5 +1,6 @@
import { httpStatusOf } from '../../lib/http-status'
import { errorText } from '../../types/json-guards'
+import { contextOverflowOf } from './context-overflow'
/**
* "Dieses Modell kann nicht denken" — die eine Frage, DREIMAL gestellt.
@@ -93,6 +94,10 @@ import { errorText } from '../../types/json-guards'
* "muss der Denkmodus herabgestuft werden?" beantwortet wird.
*/
export function isThinkingUnsupportedError(err: unknown): boolean {
+ // A context refusal is a 400 too, and dropping the thinking flag cannot
+ // shrink the request; the agent loops cut the history for it instead
+ // (GH #140, codex/context-overflow.ts).
+ if (contextOverflowOf(err)) return false
const status = httpStatusOf(err)
// 400 und 422 sind hier EINE Klasse — siehe den Modulkopf, Abschnitt
// "DIE 422-FRAGE". Dieselbe Paarung steht an der Quelle des 422, in
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index d5a00212..b61902de 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -73,7 +73,7 @@ import { setExplicitFanout, buildSubAgentGates } from '../api/agents/sub-agent'
import { appendTaskReport } from '../lib/agent-task-report'
import { useAgentTaskStore } from '../stores/agentTaskStore'
import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
-import { useAgentLoopStore } from '../stores/agentLoopStore'
+import { endLoopUnlessRearmed, useAgentLoopStore } from '../stores/agentLoopStore'
import { beginRun, isRunStopped, stopRun } from '../lib/run-stop'
import { buildLoopRecheck, loopPassSaysDone } from '../lib/agent-commands'
import { applyStoredCompaction } from '../lib/compact-summary'
@@ -3082,10 +3082,16 @@ export function useAgentChat() {
useAgentLoopStore.getState().clear(convForLoop)
return
}
- void sendRef.current?.(buildLoopRecheck(loopState.task, nextPass), undefined, {
- displayContent: cap > 0 ? `pass ${nextPass} of ${cap}` : `pass ${nextPass}`,
- loop: { ...loopState, pass: nextPass },
- })
+ // A pass that ends before it reaches this driver must not leave
+ // the bar "running" (GH #140, same gap as the Code view's).
+ void endLoopUnlessRearmed(
+ convForLoop,
+ sendRef.current?.(buildLoopRecheck(loopState.task, nextPass), undefined, {
+ displayContent: cap > 0 ? `pass ${nextPass} of ${cap}` : `pass ${nextPass}`,
+ loop: { ...loopState, pass: nextPass },
+ }),
+ () => agentLoopTimers.has(convForLoop),
+ )
}, loopState.intervalMs))
}
}
@@ -3124,7 +3130,9 @@ export function useAgentChat() {
// caller (useChat.ts's stopGeneration) already resolved it that way. A
// future caller that stops a run the user is NOT looking at (a per-item
// Stop in a task list, say) would otherwise silently stop the wrong one.
- const stoppedConvId = conversationId !== undefined
+ // Only a real id counts: handed to an onClick as is, this got the click
+ // event as the id and stopped nothing (GH #140, the Code view's copy).
+ const stoppedConvId = typeof conversationId === 'string' || conversationId === null
? conversationId
: useChatStore.getState().activeConversationId
stopRun(stoppedConvId)
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 1f6fe678..968326d7 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -26,7 +26,7 @@ import { setExplicitFanout } from '../api/agents/sub-agent'
import { appendTaskReport } from '../lib/agent-task-report'
import { useAgentTaskStore } from '../stores/agentTaskStore'
import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
-import { useAgentLoopStore } from '../stores/agentLoopStore'
+import { endLoopUnlessRearmed, useAgentLoopStore } from '../stores/agentLoopStore'
import { beginRun, isRunStopped, stopRun } from '../lib/run-stop'
import { CODEX_CONFIRM_TOOLS, renderApprovalPreview } from './codexShellGate'
import { buildHermesToolPrompt, buildHermesToolResult, buildHermesToolCall, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
@@ -77,6 +77,7 @@ import { generateEmbeddings } from '../api/rag'
import { truncateToolResult } from '../lib/truncate-tool-result'
import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'
import { getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
+import { capToLearnedWindow, contextOverflowOf, learnSendWindow, shrunkSendWindow } from './codex/context-overflow'
import { buildRequestMessages, trimWorkingHistory, decayRestoredToolResult, isToolResult } from '../lib/context-decay'
import { effectiveSendWindow } from '../lib/send-window'
import { sendsToALanBackend } from '../lib/lan-openai-slot'
@@ -1112,6 +1113,11 @@ export function useCodex() {
// letting them surface as the assistant's reply. Cap silent
// retries so we never loop forever.
let echoRetriesRemaining = 3
+ // GH #140: a step the server refused as larger than its context goes out
+ // again with a shorter history (codex/context-overflow.ts), at most this
+ // many times in a row. Reset by every step that gets through.
+ let overflowRetries = 0
+ const MAX_OVERFLOW_RETRIES = 3
// Agentic harness for SMALL local models (v2.5.0). qwen2.5-coder:7b and
// similar 7B/8B models frequently NARRATE the next step ("I'm about to
// read the source file.") or ASK for info they could discover themselves
@@ -1228,14 +1234,19 @@ export function useCodex() {
// fear is largely a myth). effectiveSendWindow carries that profile,
// and on a paid provider it also carries the send cap.
const decayOn = settings.contextDecay !== false
- const sendWindow = effectiveSendWindow({
+ const sendWindow = capToLearnedWindow(effectiveSendWindow({
providerId,
modelWindow: numCtx,
sendWindowTokens: settings.codexSendWindowTokens,
capEnabled: decayOn,
smallModelMode: settings.smallModelMode,
localBackend: sendsToALanBackend(providerId),
- })
+ }), modelToUse, numCtx)
+ // What this step sends, estimated: the history, and the catalogue that
+ // rides beside it on the native transport. Read when the server
+ // refuses the step as too large (GH #140).
+ let stepPromptEstimate = 0
+ let stepToolsEstimate = 0
let sendMessages: ChatMessage[] = messages.slice()
let trimmedReadKeys: ReadonlySet<string> = NO_TRIMMED_KEYS
try {
@@ -1253,6 +1264,7 @@ export function useCodex() {
keyOf: (m) => guardKeyOfResult.get(m as unknown as object),
})
sendMessages = built.messages
+ stepPromptEstimate = built.promptTokens
trimmedReadKeys = new Set(built.trimmedKeys)
if (convId) {
useSendSizeStore.getState().report(convId, {
@@ -1326,6 +1338,8 @@ export function useCodex() {
const settleLivePaint = livePaint.settle
const liveContent = livePaint.feed
+ // The three transports, in one try for the context refusal below.
+ try {
if (strategy === 'native') {
// Route on the USER's instruction, never on the newest user-role
// message (audit B6): steers, nudges and blocked-tool notes are
@@ -1404,8 +1418,9 @@ export function useCodex() {
// provider bills for it, and it is chosen here, after the request was
// built. Without this the meter showed the messages alone: 732 tokens
// on the first coding step against 2.400 on the wire.
+ stepToolsEstimate = estimateTokens(JSON.stringify(tools))
if (convId) {
- useSendSizeStore.getState().reportTools(convId, estimateTokens(JSON.stringify(tools)))
+ useSendSizeStore.getState().reportTools(convId, stepToolsEstimate)
}
void diagLog('iter-start', {
iter: i,
@@ -1672,6 +1687,30 @@ export function useCodex() {
turnContent = raw
}
}
+ overflowRetries = 0
+ } catch (stepErr) {
+ // GH #140: the server held less than this step. Cut the history to
+ // what fits and send the step again, instead of ending the pass on
+ // HTTP 400 and, under /loop, firing the same refusal every interval.
+ const overflow = contextOverflowOf(stepErr)
+ const sent = stepPromptEstimate > 0 ? Math.min(sendWindow, stepPromptEstimate) : sendWindow
+ const next = overflow && overflowRetries < MAX_OVERFLOW_RETRIES && !abort.signal.aborted
+ ? shrunkSendWindow(sent, overflow, sent + stepToolsEstimate)
+ : null
+ if (!overflow || next === null) throw stepErr
+ overflowRetries++
+ settleLivePaint()
+ learnSendWindow(modelToUse, numCtx, next)
+ void diagLog('context-overflow-retry', { iter: i, sent, next, window: overflow.window, promptTokens: overflow.promptTokens })
+ addBlock({
+ id: uuid(),
+ phase: 'reflection',
+ content: `↻ Context full${overflow.window ? ` (the model holds ${overflow.window} tokens)` : ''}: shortened the history to about ${next} tokens and sent the step again.`,
+ timestamp: Date.now(),
+ })
+ i--
+ continue
+ }
// End-of-turn settlement, through the ONE shared routine every path
// uses now (lib/thinking-stripper settleThinking): balanced blocks,
@@ -2437,6 +2476,12 @@ export function useCodex() {
hint = '\n\nHint: this model does not support tool calling, so Code mode cannot use it. Pick a model that supports tool calling (Qwen 3, Llama 3.1+, Gemma 4) or an LU Cloud model shown with the tools badge.'
} else if (/timed out/i.test(msg)) {
hint = '\n\nHint: a tool call exceeded its time budget. For long builds, raise the command timeout, split the work, or start the command with background: true and poll it with task: "status".'
+ } else if (contextOverflowOf(err)) {
+ // Refused even after the history was cut (GH #140): the fixed part
+ // of the request (instructions and tools) is already too large, and
+ // another /loop pass would only be refused the same way.
+ loopHalt = "too large for the model's context window"
+ hint = "\n\nHint: this step does not fit the model's context window, even with the history shortened. Give the model a larger context window (Settings, or where the server loads the model), or start a new chat for the next task."
}
// An empty wallet is not a crash and no retry fixes it. Replace the
// status-code line with the plain explanation the other surfaces use.
@@ -2653,10 +2698,16 @@ export function useCodex() {
codexLoopTimers.set(convForLoop, setTimeout(fireLoopPass, 5000))
return
}
- void sendRef.current?.(buildLoopRecheck(loopState.task, nextPass), {
- displayContent: cap > 0 ? `pass ${nextPass} of ${cap}` : `pass ${nextPass}`,
- loop: { ...loopState, pass: nextPass },
- })
+ // A pass that ends before it reaches this driver must not leave
+ // the bar "running" and the folder locked (GH #140).
+ void endLoopUnlessRearmed(
+ convForLoop,
+ sendRef.current?.(buildLoopRecheck(loopState.task, nextPass), {
+ displayContent: cap > 0 ? `pass ${nextPass} of ${cap}` : `pass ${nextPass}`,
+ loop: { ...loopState, pass: nextPass },
+ }),
+ () => codexLoopTimers.has(convForLoop),
+ )
}
codexLoopTimers.set(convForLoop, setTimeout(fireLoopPass, loopState.intervalMs))
}
@@ -2719,7 +2770,12 @@ export function useCodex() {
// B2 Commit 5: the caller names the run, see useAgentChat.ts's stopAgent
// for why (today's one caller already resolves it this way, but the
// function itself should not have to assume that).
- const stoppedConvId = conversationId !== undefined
+ //
+ // GH #140: only a real id counts. Both Stop buttons of the Code view
+ // handed this function straight to onClick, so the click EVENT arrived as
+ // the conversation to stop, matched nothing, and neither Stop did
+ // anything at all.
+ const stoppedConvId = typeof conversationId === 'string' || conversationId === null
? conversationId
: useChatStore.getState().activeConversationId
// Both of these reach a run a PREVIOUS hook instance started (the Code view
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index e3fce75c..2f90203d 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -52,14 +52,18 @@ import { buildDynamicWorkflow, buildLocalOpWorkflow, checkVideoOutputCapability
import { getAllNodeInfo, clearNodeCache } from '../api/comfyui-nodes'
import { apiNodes, type ComfyApiGraph, type ComfyExecutionMessage, type ComfyHistoryEntry } from '../types/comfy-graph'
import { restartComfyForNewNodes } from '../api/comfy-restart'
-import { installCustomNodes } from '../api/discover'
+import { installCustomNodes, startModelDownload, getDownloadProgress, modelsNotVisibleInComfy, comfyModelTarget } from '../api/discover'
+import { downloadBundleFiles, waitForModelsVisible } from '../lib/bundle-install'
+import { buildWithFixups, type FixupDeps } from '../lib/render-fixups'
+import { useDownloadStore } from '../stores/downloadStore'
+import { useComfyInstallStore } from '../stores/comfyInstallStore'
import { checkPromptSafety, SAFETY_BLOCK_MESSAGE } from '../lib/render/safety'
import { resolveRunSeed } from '../lib/run-seed'
import {
clearTrainingSet, stageTrainingImage, startCharacterTraining,
characterTrainingStatus, cancelCharacterTraining,
} from '../api/trainer'
-import { useCreateStore } from '../stores/createStore'
+import { useCreateStore, EDIT_MAX_DENOISE } from '../stores/createStore'
import { useWorkflowStore } from '../stores/workflowStore'
import { injectParameters } from '../api/workflows'
import { applyNativeHiresFix } from '../api/hires-fix'
@@ -87,6 +91,70 @@ function historyMessages(entry: ComfyHistoryEntry | null): [string, ComfyExecuti
return Array.isArray(raw) ? raw : []
}
+/** The side effects lib/render-fixups.ts needs, wired to the app. */
+function renderFixupDeps(onStatus: (line: string) => void, signal?: AbortSignal): FixupDeps {
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
+ const refreshLists = async () => {
+ await refreshComfyModels().catch(() => false)
+ clearNodeCache()
+ }
+ return {
+ ask: (prompt) => new Promise<boolean>((resolve) => {
+ useCreateStore.getState().setFixupPrompt({
+ ...prompt,
+ resolve: (go) => { useCreateStore.getState().setFixupPrompt(null); resolve(go) },
+ })
+ }),
+ download: async (files) => {
+ const dl = useDownloadStore.getState()
+ for (const f of files) dl.setMeta(f.downloadFilename, f.downloadUrl, f.subfolder)
+ dl.startPolling()
+ await downloadBundleFiles(
+ files.map((f) => ({ filename: f.downloadFilename, subfolder: f.subfolder, downloadUrl: f.downloadUrl, sizeGB: f.sizeGB })),
+ {
+ start: startModelDownload,
+ progress: getDownloadProgress,
+ onStatus,
+ keepTrayLive: () => useDownloadStore.getState().startPolling(),
+ stop: (filename) => { void useDownloadStore.getState().cancel(filename) },
+ signal,
+ },
+ )
+ // A ComfyUI on another machine cannot list them before they are copied
+ // over; buildWithFixups says so (GH #143).
+ if ((await comfyModelTarget()).remote) return
+ const wanted = files.map((f) => f.downloadFilename)
+ const left = await waitForModelsVisible({ missing: () => modelsNotVisibleInComfy(wanted), refresh: refreshLists, onStatus, signal })
+ if (left.length > 0) throw new Error(`Downloaded ${left.join(', ')}, but ComfyUI does not list ${left.length === 1 ? 'it' : 'them'} yet. Restart ComfyUI and hit Create again.`)
+ },
+ remote: async () => {
+ const t = await comfyModelTarget()
+ return t.remote && t.host && t.root ? { host: t.host, root: t.root } : null
+ },
+ updateComfy: async () => {
+ onStatus('Updating ComfyUI…')
+ await useComfyInstallStore.getState().runUpdate()
+ for (;;) {
+ await sleep(2000)
+ const st = useComfyInstallStore.getState()
+ if (st.phase === 'error') throw new Error(st.error || 'Updating ComfyUI did not finish.')
+ if (st.phase === 'idle') break
+ const last = st.logs[st.logs.length - 1]
+ if (last) onStatus(String(last))
+ }
+ onStatus('Starting the updated ComfyUI…')
+ await backendCall('start_comfyui').catch(() => undefined)
+ for (let i = 0; i < 90; i++) {
+ if (await checkComfyConnection()) return
+ onStatus(`Starting the updated ComfyUI… ${i * 2}s`)
+ await sleep(2000)
+ }
+ throw new Error('ComfyUI was updated but did not come back up. Start it from Settings and hit Create again.')
+ },
+ refresh: refreshLists,
+ }
+}
+
export function useCreate() {
const [connected, setConnected] = useState<boolean | null>(null)
const [imageModels, setImageModels] = useState<ClassifiedModel[]>([])
@@ -754,8 +822,13 @@ export function useCreate() {
setError('Video models are still loading. Give it a few seconds and hit Create again.')
return
}
- // Always re-classify from model name to avoid stale type
- const imageModelType = classifyModel(activeModel)
+ // The type comes from the freshly fetched list (never from the persisted
+ // store value, which can be stale): that list carries the header sniff,
+ // and a CivitAI name alone misroutes (Discord 2026-09-28). The name is the
+ // fallback for a model the list does not hold.
+ const listedModel = (mode === 'image' ? state.imageModelList : state.videoModelList)
+ .find((m) => m.name === activeModel)
+ const imageModelType = localOp ? classifyModel(activeModel) : (listedModel?.type ?? classifyModel(activeModel))
// Background removal is prompt-free and model-independent (RMBG node);
// lipsync/motion drive off their media inputs (the builder supplies a
@@ -885,7 +958,11 @@ export function useCreate() {
const baseParams = {
prompt, negativePrompt, model: activeModel, sampler, scheduler, steps, cfgScale, width, height, seed: runSeed, batchSize,
...(isRemoveBg && effInputImage ? { removebg: true, inputImage: effInputImage } : {}),
- ...(isI2I && !isRemoveBg && effInputImage ? { inputImage: effInputImage, denoise } : {}),
+ // Discord 2026-09-25 (tbjdrw: "a house becomes a tennis court"): at
+ // strength 1.00 the builder read denoise >= 1 as "no img2img" and
+ // dropped the source without a word. Edit always keeps the source;
+ // 0.95 is the most it repaints (the slider tops out there too).
+ ...(isI2I && !isRemoveBg && effInputImage ? { inputImage: effInputImage, denoise: Math.min(denoise, EDIT_MAX_DENOISE) } : {}),
...(!isRemoveBg && maskFilename ? { maskImage: maskFilename, growMaskBy } : {}),
// Advanced adjustments. LoRA feeds the builder's `lora`/`loraStrength`
// contract (string[] + number[]); the old `loras` key was read by nobody,
@@ -896,6 +973,7 @@ export function useCreate() {
: {}),
...(selectedVae && selectedVae !== 'auto' ? { vae: selectedVae } : {}),
...(clipSkip > 0 ? { clipSkip } : {}),
+ ...(listedModel?.parts ? { modelParts: listedModel.parts } : {}),
}
let workflow: ComfyApiGraph = {}
@@ -983,7 +1061,12 @@ export function useCreate() {
setProgress(5, 'Building workflow...')
try {
const genParams = mode === 'video' ? { ...baseParams, frames, fps, ...(effI2vImage ? { inputImage: effI2vImage } : {}) } : baseParams
- workflow = await buildDynamicWorkflow(genParams, imageModelType)
+ // A missing text encoder / VAE or a too-old ComfyUI is fixed in
+ // place after one question, then the build runs again.
+ workflow = await buildWithFixups(
+ () => buildDynamicWorkflow(genParams, imageModelType),
+ renderFixupDeps((line) => setProgress(5, line), abortRef.current?.signal),
+ )
builderUsed = 'dynamic'
} catch (dynErr) {
// A WorkflowUnavailableError carries an actionable message ("download
diff --git a/src/lib/__tests__/fit-textarea.test.ts b/src/lib/__tests__/fit-textarea.test.ts
new file mode 100644
index 00000000..08e5a231
--- /dev/null
+++ b/src/lib/__tests__/fit-textarea.test.ts
@@ -0,0 +1,141 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * GH #139: typing in the composer lagged ~1 s per key in larger chats, and
+ * the lag grew with the visible transcript. Each key collapsed the live field
+ * to `height: auto` to read its scrollHeight and then set it back, which laid
+ * out (and on WebKitGTK repainted) the whole transcript twice per key.
+ *
+ * jsdom has no layout, so the copy's scrollHeight is stood in by a line count
+ * (20 px a line plus 8 px padding). What is pinned here is the contract that
+ * fixes the lag: the live field is never collapsed, its height is written only
+ * when it really changes, and the measuring copy is invisible to the page.
+ */
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, beforeAll, afterAll, describe, expect, it, vi } from 'vitest'
+import { fitTextarea } from '../fit-textarea'
+
+const LINE = 20
+const PAD = 8
+let restore: PropertyDescriptor | undefined
+
+beforeAll(() => {
+ restore = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollHeight')
+ Object.defineProperty(HTMLTextAreaElement.prototype, 'scrollHeight', {
+ configurable: true,
+ get(this: HTMLTextAreaElement) {
+ const lines = Math.max(this.rows || 1, this.value.split('\n').length)
+ return lines * LINE + PAD
+ },
+ })
+})
+
+afterAll(() => {
+ delete (HTMLTextAreaElement.prototype as { scrollHeight?: number }).scrollHeight
+ if (restore) Object.defineProperty(HTMLElement.prototype, 'scrollHeight', restore)
+})
+
+afterEach(() => {
+ document.body.innerHTML = ''
+ vi.restoreAllMocks()
+})
+
+function field(value = ''): HTMLTextAreaElement {
+ const el = document.createElement('textarea')
+ el.rows = 1
+ el.style.width = '300px'
+ el.value = value
+ document.body.appendChild(el)
+ return el
+}
+
+function heightWrites(el: HTMLTextAreaElement): string[] {
+ const writes: string[] = []
+ const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el.style), 'height')!
+ Object.defineProperty(el.style, 'height', {
+ configurable: true,
+ get() { return desc.get!.call(this) },
+ set(v: string) { writes.push(v); desc.set!.call(this, v) },
+ })
+ return writes
+}
+
+describe('fitTextarea', () => {
+ it('sizes the field to its text', () => {
+ const el = field('one line')
+ fitTextarea(el, 200)
+ expect(el.style.height).toBe(`${LINE + PAD}px`)
+ })
+
+ it('typing within a line never writes the field height (the lag)', () => {
+ const el = field('')
+ fitTextarea(el, 200)
+ const writes = heightWrites(el)
+ for (const text of ['h', 'he', 'hel', 'hell', 'hello']) {
+ el.value = text
+ fitTextarea(el, 200)
+ }
+ expect(writes).toEqual([])
+ })
+
+ it('a new line writes the new height once, and never collapses to auto', () => {
+ const el = field('first')
+ fitTextarea(el, 200)
+ const writes = heightWrites(el)
+ el.value = 'first\nsecond'
+ fitTextarea(el, 200)
+ expect(writes).toEqual([`${2 * LINE + PAD}px`])
+ expect(writes).not.toContain('auto')
+ })
+
+ it('stops at the cap', () => {
+ const el = field(Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n'))
+ fitTextarea(el, 200)
+ expect(el.style.height).toBe('200px')
+ })
+
+ it('leaves a field that is not laid out alone', () => {
+ const el = field('x')
+ el.style.width = ''
+ fitTextarea(el, 200)
+ expect(el.style.height).toBe('')
+ })
+
+ it('the measuring copy is invisible to the page', () => {
+ const el = field('x')
+ fitTextarea(el, 200)
+ // Tests and page code that look for "the" textarea still find only one.
+ expect(document.querySelectorAll('textarea')).toHaveLength(1)
+ const host = document.querySelector('[data-lu-textarea-mirror]')
+ expect(host?.getAttribute('aria-hidden')).toBe('true')
+ // Closed: tools that look into open shadow roots (Playwright, CDP) must
+ // not find the copy either.
+ expect(host).toBeTruthy()
+ expect(host?.shadowRoot).toBeNull()
+ })
+
+ it('comes back after the page was cleared', () => {
+ field('x')
+ fitTextarea(document.querySelector('textarea')!, 200)
+ document.body.innerHTML = ''
+ const el = field('a\nb')
+ fitTextarea(el, 200)
+ expect(el.style.height).toBe(`${2 * LINE + PAD}px`)
+ })
+})
+
+describe('no field collapses itself to measure any more', () => {
+ const root = join(__dirname, '..', '..')
+ for (const file of [
+ 'components/chat/ChatInput.tsx',
+ 'components/chat/MessageBubble.tsx',
+ 'components/create/ui/PromptField.tsx',
+ ]) {
+ it(file, () => {
+ const src = readFileSync(join(root, file), 'utf8')
+ expect(src).not.toMatch(/style\.height\s*=\s*'auto'/)
+ expect(src).toContain('fitTextarea(')
+ })
+ }
+})
diff --git a/src/lib/__tests__/gallery-trash.test.ts b/src/lib/__tests__/gallery-trash.test.ts
new file mode 100644
index 00000000..f23bafbe
--- /dev/null
+++ b/src/lib/__tests__/gallery-trash.test.ts
@@ -0,0 +1,36 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const backend = vi.hoisted(() => ({ call: vi.fn(), tauri: vi.fn(() => true) }))
+vi.mock('../../api/backend', async (o) => ({ ...(await o<typeof import('../../api/backend')>()), backendCall: backend.call, isTauri: backend.tauri }))
+
+import { isTrashableRender, trashGalleryFile } from '../gallery-trash'
+import type { GalleryItem } from '../../stores/createStore'
+
+const item = (over: Partial<GalleryItem> = {}): GalleryItem => ({
+ id: 'a', type: 'image', filename: 'locally_uncensored_00001_.png', subfolder: '', prompt: '', negativePrompt: '',
+ model: 'm', modelType: 'sdxl', seed: 1, steps: 1, cfgScale: 1, sampler: 'euler', scheduler: 'normal',
+ width: 1, height: 1, batchSize: 1, createdAt: 1, ...over,
+}) as GalleryItem
+
+beforeEach(() => { backend.call.mockReset().mockResolvedValue({ trashed: true, missing: false }); backend.tauri.mockReturnValue(true) })
+
+describe('gallery delete reaches the file (Discord 2026-09-25)', () => {
+ it('a local ComfyUI render goes to the Recycle Bin', async () => {
+ expect(await trashGalleryFile(item({ subfolder: 'x' }), [])).toBeNull()
+ expect(backend.call).toHaveBeenCalledWith('trash_comfy_output', { filename: 'locally_uncensored_00001_.png', subfolder: 'x' })
+ })
+
+ it('cloud, MLX, input files and files another entry still shows are left alone', () => {
+ expect(isTrashableRender(item({ jobId: 'j' }), [])).toBe(false)
+ expect(isTrashableRender(item({ remoteUrl: 'https://x' }), [])).toBe(false)
+ expect(isTrashableRender(item({ localPath: '/x.mp4' }), [])).toBe(false)
+ expect(isTrashableRender(item({ comfyType: 'input' }), [])).toBe(false)
+ expect(isTrashableRender(item(), [item({ id: 'b' })])).toBe(false)
+ expect(isTrashableRender(item(), [item({ id: 'b', filename: 'other.png' })])).toBe(true)
+ })
+
+ it('a failed move is reported, the gallery entry is gone anyway', async () => {
+ backend.call.mockRejectedValue(new Error('access denied'))
+ expect(await trashGalleryFile(item(), [])).toMatch(/stayed in the ComfyUI output folder: access denied/)
+ })
+})
diff --git a/src/lib/__tests__/render-fixups.test.ts b/src/lib/__tests__/render-fixups.test.ts
new file mode 100644
index 00000000..2ec613cf
--- /dev/null
+++ b/src/lib/__tests__/render-fixups.test.ts
@@ -0,0 +1,88 @@
+import { describe, it, expect, vi } from 'vitest'
+import { buildWithFixups, downloadPrompt, remoteDownloadPrompt, UPDATE_PROMPT, type FixupDeps } from '../render-fixups'
+
+const unavailable = (extra: Record<string, unknown>) => Object.assign(new Error('needs files'), { name: 'WorkflowUnavailableError', ...extra })
+const T5 = { downloadFilename: 't5.safetensors', downloadUrl: 'https://huggingface.co/x/t5.safetensors', subfolder: 'text_encoders', sizeGB: 5.16, matchPatterns: [] }
+const deps = (go = true): FixupDeps & Record<string, ReturnType<typeof vi.fn>> => ({
+ ask: vi.fn(async () => go), download: vi.fn(async () => {}), updateComfy: vi.fn(async () => {}), refresh: vi.fn(async () => {}),
+}) as never
+
+describe('buildWithFixups', () => {
+ it('asks once, downloads what is missing, and runs the build again', async () => {
+ const build = vi.fn().mockRejectedValueOnce(unavailable({ missing: [T5] })).mockResolvedValueOnce('graph')
+ const d = deps()
+ await expect(buildWithFixups(build, d)).resolves.toBe('graph')
+ expect(d.ask).toHaveBeenCalledWith(downloadPrompt([T5]))
+ expect(d.download).toHaveBeenCalledWith([T5])
+ expect(d.refresh).toHaveBeenCalledOnce()
+ expect(build).toHaveBeenCalledTimes(2)
+ })
+
+ it('updates ComfyUI when the graph needs a newer one', async () => {
+ const build = vi.fn().mockRejectedValueOnce(unavailable({ needsComfyUpdate: true })).mockResolvedValueOnce('graph')
+ const d = deps()
+ await buildWithFixups(build, d)
+ expect(d.ask).toHaveBeenCalledWith(UPDATE_PROMPT)
+ expect(d.updateComfy).toHaveBeenCalledOnce()
+ })
+
+ it('a no leaves everything as it was and reports the original reason', async () => {
+ const err = unavailable({ missing: [T5] })
+ const d = deps(false)
+ await expect(buildWithFixups(vi.fn().mockRejectedValue(err), d)).rejects.toBe(err)
+ expect(d.download).not.toHaveBeenCalled()
+ })
+
+ it('never offers the same fix twice, and never touches errors it cannot fix', async () => {
+ const err = unavailable({ missing: [T5] })
+ const d = deps()
+ await expect(buildWithFixups(vi.fn().mockRejectedValue(err), d)).rejects.toBe(err)
+ expect(d.download).toHaveBeenCalledOnce()
+ const plain = new Error('boom')
+ await expect(buildWithFixups(vi.fn().mockRejectedValue(plain), deps())).rejects.toBe(plain)
+ const noUrl = unavailable({ missing: [{ ...T5, downloadUrl: undefined }] })
+ await expect(buildWithFixups(vi.fn().mockRejectedValue(noUrl), deps())).rejects.toBe(noUrl)
+ })
+
+ it('the question says what, how much, and where', () => {
+ const p = downloadPrompt([T5, { ...T5, downloadFilename: 'ae.safetensors', sizeGB: 0.34 }])
+ expect(p.title).toBe('2 more files are needed')
+ expect(p.detail).toContain('t5.safetensors, ae.safetensors (5.5 GB)')
+ expect(p.confirm).toBe('Download 5.5 GB and render')
+ })
+
+ // GH #143: ComfyUI as a service on another machine. Its models folder is
+ // over there, so the files land here and the user copies them; LU cannot
+ // update that ComfyUI either.
+ describe('a ComfyUI on another machine', () => {
+ const REMOTE = { host: '192.168.1.20', root: 'D:\\LU models' }
+ const remoteDeps = (go = true) => ({ ...deps(go), remote: vi.fn(async () => REMOTE) })
+
+ it('downloads to this computer after saying so, then says what to copy where', async () => {
+ const build = vi.fn().mockRejectedValue(unavailable({ missing: [T5] }))
+ const d = remoteDeps()
+ await expect(buildWithFixups(build, d)).rejects.toThrow(
+ 'Downloaded to D:\\LU models. Your ComfyUI runs on 192.168.1.20: copy text_encoders/t5.safetensors into the models folder of ComfyUI on that machine, then hit Create again.',
+ )
+ expect(d.ask).toHaveBeenCalledWith(remoteDownloadPrompt([T5], REMOTE))
+ expect(d.download).toHaveBeenCalledWith([T5])
+ // No second build: nothing on that machine can see the file yet.
+ expect(build).toHaveBeenCalledTimes(1)
+ })
+
+ it('the question names the machine and the folder, and promises no render', () => {
+ const p = remoteDownloadPrompt([T5], REMOTE)
+ expect(p.detail).toContain('Your ComfyUI runs on 192.168.1.20')
+ expect(p.detail).toContain('D:\\LU models')
+ expect(p.confirm).toBe('Download 5.2 GB')
+ })
+
+ it('never offers to update a ComfyUI that is not on this machine', async () => {
+ const build = vi.fn().mockRejectedValue(unavailable({ needsComfyUpdate: true }))
+ const d = remoteDeps()
+ await expect(buildWithFixups(build, d)).rejects.toThrow('This model needs a newer ComfyUI than the one on 192.168.1.20.')
+ expect(d.ask).not.toHaveBeenCalled()
+ expect(d.updateComfy).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/src/lib/__tests__/subject-framing.test.ts b/src/lib/__tests__/subject-framing.test.ts
new file mode 100644
index 00000000..8265f199
--- /dev/null
+++ b/src/lib/__tests__/subject-framing.test.ts
@@ -0,0 +1,46 @@
+/**
+ * GH #142: the chat image tool rendered every "full body" request in the
+ * model's square default, and portrait-trained models crop a whole figure in a
+ * square to the face. A prompt that asks for the whole figure now gets a tall
+ * frame when nobody named a size.
+ */
+import { describe, expect, it } from 'vitest'
+import { portraitFrame, wantsFullFigure } from '../subject-framing'
+
+describe('wantsFullFigure', () => {
+ it.each([
+ 'full body shot of a woman',
+ 'Full-body photo, studio light',
+ 'fullbody, standing',
+ 'a knight from head to toe',
+ 'head-to-feet view of a dancer',
+ 'whole body in frame',
+ 'entire body visible',
+ 'full length portrait of a man in a suit',
+ 'full shot, street',
+ 'long shot of a hiker',
+ ])('%s', (prompt) => expect(wantsFullFigure(prompt)).toBe(true))
+
+ it.each([
+ 'close-up portrait of a woman',
+ 'a bowl of fruit on a table',
+ 'headshot, soft light',
+ 'fully clothed woman sitting',
+ 'a bodybuilder flexing',
+ ])('not: %s', (prompt) => expect(wantsFullFigure(prompt)).toBe(false))
+})
+
+describe('portraitFrame', () => {
+ it('uses the trained portrait buckets', () => {
+ expect(portraitFrame(512)).toEqual({ width: 512, height: 768 })
+ expect(portraitFrame(1024)).toEqual({ width: 832, height: 1216 })
+ expect(portraitFrame(1328)).toEqual({ width: 1056, height: 1584 })
+ })
+
+ it('keeps the pixel budget at 2:3 beyond them, on the 64 grid', () => {
+ const f = portraitFrame(2048)
+ expect(f.width % 64).toBe(0)
+ expect(f.height % 64).toBe(0)
+ expect(f.height / f.width).toBeCloseTo(1.5, 1)
+ })
+})
diff --git a/src/lib/fit-textarea.ts b/src/lib/fit-textarea.ts
new file mode 100644
index 00000000..577e850c
--- /dev/null
+++ b/src/lib/fit-textarea.ts
@@ -0,0 +1,74 @@
+// ─── Grow a textarea to its text without laying out the page around it ───
+//
+// GH #139 (3.0.2, Linux AppImage, 3440x1440): typing in the composer lagged
+// about a second per key once a chat held a dozen messages, and the lag grew
+// with the visible part of the conversation, not with the text. Every key ran
+// the usual auto-grow on the live field: height 'auto', read scrollHeight, set
+// the height back. The first write collapses the field to one row, so the
+// column it shares with the transcript has to be laid out again before
+// scrollHeight can answer, and the second write undoes it. That is two layouts
+// of the whole transcript per key, and on WebKitGTK a repaint of the masked
+// message list at full window size.
+//
+// The text is now measured on a copy that lives outside the page: a hidden,
+// fixed textarea in its own closed shadow root, so neither page CSS nor a
+// `querySelector('textarea')` ever reaches it. Closed, because Playwright and
+// CDP tools look into open shadow roots: with an open one, a spec's
+// `locator('textarea').first()` picked the hidden copy and could not type
+// (e2e/cloud-create.spec.ts, 28.09.2026). The real field's height is
+// written only when the answer differs from what it already has, which within
+// a line it never does. Typing then touches nothing outside the field.
+
+/** Everything that decides where a textarea wraps and how tall its lines are. */
+const TEXT_LAYOUT = [
+ 'box-sizing', 'width',
+ 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
+ 'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width',
+ 'font-family', 'font-size', 'font-weight', 'font-style', 'font-stretch', 'font-variant',
+ 'font-feature-settings', 'font-variation-settings', 'font-kerning',
+ 'letter-spacing', 'word-spacing', 'line-height', 'text-transform', 'text-indent', 'tab-size',
+ 'white-space', 'word-break', 'overflow-wrap', 'hyphens', 'direction', 'text-rendering',
+]
+
+let mirror: HTMLTextAreaElement | null = null
+
+function measuringCopy(): HTMLTextAreaElement {
+ if (mirror?.isConnected) return mirror
+ const host = document.createElement('div')
+ host.setAttribute('aria-hidden', 'true')
+ host.setAttribute('data-lu-textarea-mirror', '')
+ // Out of flow, zero-sized and contained: writing into the copy lays out the
+ // copy and nothing else.
+ host.style.cssText = 'position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none;contain:strict'
+ const copy = document.createElement('textarea')
+ copy.tabIndex = -1
+ copy.readOnly = true
+ // Solid borders so the copied widths count; overflow hidden so no scrollbar
+ // narrows the line the way the field's own never does once it fits.
+ copy.style.cssText = 'display:block;margin:0;border-style:solid;appearance:none;overflow:hidden;resize:none;height:auto;min-height:0;max-height:none'
+ host.attachShadow({ mode: 'closed' }).appendChild(copy)
+ document.body.appendChild(host)
+ mirror = copy
+ return copy
+}
+
+/**
+ * Size `el` to its text, capped at `maxPx`. Same answer as the old
+ * `height = 'auto'; height = min(scrollHeight, max)`, without ever resizing
+ * the live field on the way there.
+ */
+export function fitTextarea(el: HTMLTextAreaElement, maxPx = Infinity): void {
+ const style = getComputedStyle(el)
+ // Not laid out (display: none, or not in the page yet): keep what it has.
+ if (!(parseFloat(style.width) > 0)) return
+ const copy = measuringCopy()
+ for (const prop of TEXT_LAYOUT) {
+ const value = style.getPropertyValue(prop)
+ if (copy.style.getPropertyValue(prop) !== value) copy.style.setProperty(prop, value)
+ }
+ if (copy.rows !== el.rows) copy.rows = el.rows
+ if (copy.placeholder !== el.placeholder) copy.placeholder = el.placeholder
+ copy.value = el.value
+ const next = `${Math.min(copy.scrollHeight, maxPx)}px`
+ if (el.style.height !== next) el.style.height = next
+}
diff --git a/src/lib/gallery-trash.ts b/src/lib/gallery-trash.ts
new file mode 100644
index 00000000..924e196f
--- /dev/null
+++ b/src/lib/gallery-trash.ts
@@ -0,0 +1,39 @@
+// Gallery delete reaches the file (Discord 2026-09-25, boromirofgeo: "when
+// deleting files in app from gallery, they are still in output folder, which
+// is getting bigger and bigger"). A local ComfyUI render goes to the Recycle
+// Bin / Trash through commands/gallery_files.rs, so a misclick stays
+// recoverable. Cloud renders, MLX files and anything another gallery entry
+// still shows are left alone.
+
+import { backendCall, isTauri } from '../api/backend'
+
+/**
+ * The fields of a gallery item read here. Declared locally rather than
+ * imported from createStore: the store loads this module, so even a type
+ * import back is a cycle for `npm run cycles`, which CI runs.
+ */
+interface GalleryRender {
+ filename?: string
+ subfolder?: string
+ comfyType?: string
+ jobId?: string
+ remoteUrl?: string
+ localPath?: string
+}
+
+export function isTrashableRender(item: GalleryRender, remaining: GalleryRender[]): boolean {
+ if (!item.filename || item.jobId || item.remoteUrl || item.localPath) return false
+ if ((item.comfyType ?? 'output') !== 'output') return false
+ return !remaining.some((g) => g.filename === item.filename && (g.subfolder ?? '') === (item.subfolder ?? ''))
+}
+
+/** Returns an error line for the user, or null when all went well. */
+export async function trashGalleryFile(item: GalleryRender, remaining: GalleryRender[]): Promise<string | null> {
+ if (!isTauri() || !isTrashableRender(item, remaining)) return null
+ try {
+ await backendCall('trash_comfy_output', { filename: item.filename, subfolder: item.subfolder ?? '' })
+ return null
+ } catch (err) {
+ return `Removed from the gallery, but the file stayed in the ComfyUI output folder: ${err instanceof Error ? err.message : String(err)}`
+ }
+}
diff --git a/src/lib/render-fixups.ts b/src/lib/render-fixups.ts
new file mode 100644
index 00000000..f2a76bcf
--- /dev/null
+++ b/src/lib/render-fixups.ts
@@ -0,0 +1,127 @@
+// ─── Fix what a render is missing, then run it ───
+//
+// Discord 2026-09-26..28 (David: "not just say what is wrong, make it work"):
+// a model whose text encoder or VAE is not on disk, or a ComfyUI too old for
+// the model's loader, used to end the run with a sentence that sent people to
+// the Model Manager or to Settings. The builder now says exactly what is
+// missing (WorkflowUnavailableError.missing / .needsComfyUpdate), and this
+// module asks once, fetches or updates, and hands the build back for one more
+// try. Pure orchestration: every side effect comes in through `deps`, so the
+// tests drive it without Tauri or ComfyUI.
+
+import type { ComponentSpec } from '../api/component-registry'
+
+export interface FixupPrompt {
+ title: string
+ detail: string
+ confirm: string
+}
+
+export interface FixupDeps {
+ /** Ask the user; true means go. */
+ ask: (prompt: FixupPrompt) => Promise<boolean>
+ /** Download these files and wait until ComfyUI lists them. */
+ download: (files: Array<ComponentSpec & { downloadUrl: string; subfolder: string }>) => Promise<void>
+ /** Update ComfyUI, start it again, and wait until it answers. */
+ updateComfy: () => Promise<void>
+ /** Drop the cached node catalogue so the next build reads the new state. */
+ refresh: () => Promise<void>
+ /** GH #143: the ComfyUI on another machine, when it is one. Files then land
+ * in `root` on this machine and have to be copied over before a render can
+ * find them, and its ComfyUI is not LU's to update. */
+ remote?: () => Promise<RemoteComfy | null>
+}
+
+export interface RemoteComfy {
+ host: string
+ root: string
+}
+
+interface FixableError {
+ name: string
+ message: string
+ missing?: ComponentSpec[]
+ needsComfyUpdate?: boolean
+}
+
+function fixable(err: unknown): FixableError | null {
+ if (!(err instanceof Error) || err.name !== 'WorkflowUnavailableError') return null
+ const e = err as FixableError
+ const downloadable = (e.missing ?? []).filter((m) => m.downloadUrl && m.subfolder)
+ if (downloadable.length > 0 || e.needsComfyUpdate) return e
+ return null
+}
+
+const gb = (n: number) => (n >= 1 ? `${n.toFixed(1)} GB` : `${Math.max(1, Math.round(n * 1024))} MB`)
+
+export function downloadPrompt(files: ComponentSpec[]): FixupPrompt {
+ const total = files.reduce((sum, f) => sum + (f.sizeGB ?? 0), 0)
+ const names = files.map((f) => f.downloadFilename).join(', ')
+ return {
+ title: files.length === 1 ? 'One more file is needed' : `${files.length} more files are needed`,
+ detail: `This model needs ${names}${total > 0 ? ` (${gb(total)})` : ''}. LU downloads ${files.length === 1 ? 'it' : 'them'} into your ComfyUI models folder, then starts the render.`,
+ confirm: total > 0 ? `Download ${gb(total)} and render` : 'Download and render',
+ }
+}
+
+export function remoteDownloadPrompt(files: ComponentSpec[], remote: RemoteComfy): FixupPrompt {
+ const local = downloadPrompt(files)
+ const names = files.map((f) => f.downloadFilename).join(', ')
+ const total = files.reduce((sum, f) => sum + (f.sizeGB ? f.sizeGB : 0), 0)
+ const it = files.length === 1 ? 'it' : 'them'
+ return {
+ title: local.title,
+ detail: `This model needs ${names}${total > 0 ? ` (${gb(total)})` : ''}. Your ComfyUI runs on ${remote.host}, so LU downloads ${it} to this computer, into ${remote.root}, in ComfyUI's folder layout. Copy ${it} over to that machine afterwards.`,
+ confirm: total > 0 ? `Download ${gb(total)}` : 'Download',
+ }
+}
+
+export function remoteCopyMessage(files: ComponentSpec[], remote: RemoteComfy): string {
+ const paths = files.map((f) => `${f.subfolder}/${f.downloadFilename}`).join(', ')
+ return `Downloaded to ${remote.root}. Your ComfyUI runs on ${remote.host}: copy ${paths} into the models folder of ComfyUI on that machine, then hit Create again.`
+}
+
+export function remoteUpdateMessage(remote: RemoteComfy): string {
+ return `This model needs a newer ComfyUI than the one on ${remote.host}. Update ComfyUI on that machine, restart it, then hit Create again.`
+}
+
+export const UPDATE_PROMPT: FixupPrompt = {
+ title: 'ComfyUI needs an update',
+ detail: 'This model needs a newer ComfyUI than the one installed. LU updates it (git pull plus its Python packages), restarts it, then starts the render. Takes a few minutes.',
+ confirm: 'Update ComfyUI and render',
+}
+
+/** A build that can be retried after its missing pieces are fixed. The same
+ * fix is never offered twice: a second identical failure is reported. */
+export async function buildWithFixups<T>(build: () => Promise<T>, deps: FixupDeps, maxRounds = 3): Promise<T> {
+ const done = new Set<string>()
+ for (let round = 0; ; round++) {
+ try {
+ return await build()
+ } catch (err) {
+ const e = fixable(err)
+ if (!e || round >= maxRounds) throw err
+ const remote = (await deps.remote?.()) ?? null
+ if (e.needsComfyUpdate) {
+ if (remote) throw new Error(remoteUpdateMessage(remote))
+ if (done.has('update')) throw err
+ done.add('update')
+ if (!(await deps.ask(UPDATE_PROMPT))) throw err
+ await deps.updateComfy()
+ } else {
+ const files = (e.missing ?? []).filter(
+ (m): m is ComponentSpec & { downloadUrl: string; subfolder: string } => !!m.downloadUrl && !!m.subfolder,
+ )
+ const key = files.map((f) => f.downloadFilename).sort().join('|')
+ if (done.has(key)) throw err
+ done.add(key)
+ if (!(await deps.ask(remote ? remoteDownloadPrompt(files, remote) : downloadPrompt(files)))) throw err
+ await deps.download(files)
+ // On another machine nothing can render with them until they are
+ // copied over, so the run ends here and says what to copy where.
+ if (remote) throw new Error(remoteCopyMessage(files, remote))
+ }
+ await deps.refresh()
+ }
+ }
+}
diff --git a/src/lib/subject-framing.ts b/src/lib/subject-framing.ts
new file mode 100644
index 00000000..976d6e7c
--- /dev/null
+++ b/src/lib/subject-framing.ts
@@ -0,0 +1,30 @@
+// ─── A full figure needs a tall frame ───
+//
+// GH #142 (Windows 11, chat image generation): "full body" came out as a
+// close-up nine times in ten, whatever the prompt or negative prompt said.
+// The chat's image tool rendered every picture as the model's square default
+// (1024 x 1024, 512 x 512 for SD 1.5), and the SDXL, Pony and Illustrious
+// families were trained mostly on portraits: asked for a whole person in a
+// square, they crop to the face. The chat model almost never passes a size of
+// its own. So when the prompt asks for a whole figure and nobody named a size,
+// the picture gets the portrait frame those models were trained on.
+
+const FULL_FIGURE = /\b(?:full[\s-]?body|whole[\s-]body|entire[\s-]body|full[\s-]figure|full[\s-]length|full[\s-]shot|long[\s-]shot|head[\s-]to[\s-](?:toes?|feet|foot))\b/i
+
+/** Does the prompt ask for the whole figure in frame? */
+export function wantsFullFigure(prompt: string): boolean {
+ return FULL_FIGURE.test(prompt)
+}
+
+/**
+ * The 2:3 portrait frame for a model whose square default is `square` px.
+ * The trained buckets where there is one (SD 1.5, SDXL / FLUX / Z-Image,
+ * Qwen-Image's own 2:3 preset), else the same pixel count at 2:3.
+ */
+export function portraitFrame(square: number): { width: number; height: number } {
+ if (square <= 576) return { width: 512, height: 768 }
+ if (square <= 1100) return { width: 832, height: 1216 }
+ if (square <= 1400) return { width: 1056, height: 1584 }
+ const snap = (n: number) => Math.round(n / 64) * 64
+ return { width: snap(square * Math.sqrt(2 / 3)), height: snap(square * Math.sqrt(3 / 2)) }
+}
diff --git a/src/stores/__tests__/download-visible-wait.test.ts b/src/stores/__tests__/download-visible-wait.test.ts
index 976557a3..134136b4 100644
--- a/src/stores/__tests__/download-visible-wait.test.ts
+++ b/src/stores/__tests__/download-visible-wait.test.ts
@@ -34,6 +34,8 @@ vi.mock('../../api/discover', () => ({
lookupFileMeta: (...a: unknown[]) => lookupFileMeta(...(a as [string])),
modelsNotVisibleInComfy: (...a: unknown[]) => modelsNotVisibleInComfy(...(a as [string[]])),
ENUM_SUBFOLDERS: new Set(['checkpoints', 'diffusion_models', 'vae', 'text_encoders']),
+ // The ComfyUI here is on this machine; a remote one skips the wait (GH #143).
+ comfyModelTarget: vi.fn(async () => ({ remote: false })),
}))
vi.mock('../../api/comfyui', () => ({
diff --git a/src/stores/__tests__/gallery-engine-recovery.test.ts b/src/stores/__tests__/gallery-engine-recovery.test.ts
new file mode 100644
index 00000000..ea213160
--- /dev/null
+++ b/src/stores/__tests__/gallery-engine-recovery.test.ts
@@ -0,0 +1,48 @@
+/**
+ * Discord 2026-09-26 (tbjdrw: "This render lives on the local engine, which
+ * isn't reachable right now. Why do I keep getting that?"): a tile that
+ * failed while ComfyUI was away stayed dark until the next app start. When
+ * the engine answers again every such tile gets a fresh URL and loads again.
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useCreateStore, type GalleryItem } from '../createStore'
+import { galleryItemUrl } from '../../components/create/experimental/galleryUrl'
+
+const tile = (id: string, over: Partial<GalleryItem> = {}): GalleryItem => ({
+ id, type: 'image', filename: `${id}.png`, subfolder: '', prompt: '', negativePrompt: '', model: 'm', modelType: 'sdxl',
+ seed: 1, steps: 1, cfgScale: 1, sampler: 'euler', scheduler: 'normal', width: 1, height: 1, batchSize: 1, createdAt: 1, ...over,
+}) as GalleryItem
+
+beforeEach(() => {
+ useCreateStore.setState({
+ comfyRunning: false,
+ gallery: [
+ tile('offline', { unavailable: true, unavailableReason: 'offline' }),
+ tile('gone', { unavailable: true, unavailableReason: 'gone' }),
+ tile('cloud', { unavailable: true, jobId: 'j' }),
+ tile('fine'),
+ ],
+ })
+})
+
+describe('tiles come back with the engine', () => {
+ it('only offline local tiles are retried, each with a new URL', () => {
+ const before = galleryItemUrl(useCreateStore.getState().gallery[0])
+ useCreateStore.getState().setComfyRunning(true)
+ const [offline, gone, cloud, fine] = useCreateStore.getState().gallery
+ expect(offline.unavailable).toBeUndefined()
+ expect(offline.reloadKey).toBe(1)
+ expect(galleryItemUrl(offline)).not.toBe(before)
+ expect(galleryItemUrl(offline)).toContain('lu_retry=1')
+ expect(gone.unavailable).toBe(true)
+ expect(cloud.unavailable).toBe(true)
+ expect(fine.reloadKey).toBeUndefined()
+ })
+
+ it('staying up does not retry again', () => {
+ useCreateStore.getState().setComfyRunning(true)
+ const once = useCreateStore.getState().gallery
+ useCreateStore.getState().setComfyRunning(true)
+ expect(useCreateStore.getState().gallery).toBe(once)
+ })
+})
diff --git a/src/stores/agentLoopStore.ts b/src/stores/agentLoopStore.ts
index 9ce144cc..11b4d998 100644
--- a/src/stores/agentLoopStore.ts
+++ b/src/stores/agentLoopStore.ts
@@ -78,3 +78,20 @@ export function useConversationLoop(conversationId: string | null | undefined):
export function useAnyAgentLoopActive(): boolean {
return useAgentLoopStore((s) => Object.keys(s.loops).length > 0)
}
+
+/**
+ * End the loop of a pass that settled without arming a next one (GH #140).
+ *
+ * A pass can end before it reaches the driver that re-arms or clears the loop:
+ * the run guard, a lane that was cancelled, no model picked, a throw before
+ * the tool loop. Such a pass left the bar saying "running" for a loop that was
+ * over, and the Code view kept the working folder locked behind it
+ * (useAnyAgentLoopActive). `rearmed` asks the caller's own timer map whether
+ * the driver scheduled the next pass meanwhile. A rejected pass still rejects
+ * the returned promise, so nothing that used to reach the console is hidden.
+ */
+export function endLoopUnlessRearmed(conversationId: string, pass: unknown, rearmed: () => boolean): Promise<unknown> {
+ return Promise.resolve(pass).finally(() => {
+ if (!rearmed()) useAgentLoopStore.getState().clear(conversationId)
+ })
+}
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index 5d39c8f1..016637fe 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -1,4 +1,5 @@
import { create } from 'zustand'
+import type { FixupPrompt } from '../lib/render-fixups'
import { persist } from 'zustand/middleware'
import { safeJSONStorage } from '../lib/storage-quota'
import { TRAIN_STEPS_DEFAULT } from '../lib/trainer-presets'
@@ -21,7 +22,7 @@ const RUNTIME_ONLY_KEYS: readonly string[] = [
'cloudFrames', 'cloudFps',
]
import type { ModelType, ClassifiedModel } from '../api/comfyui'
-import { classifyModel } from '../api/comfyui'
+import { classifyModel, hidreamSampling } from '../api/comfyui'
import type { HiresUpscaleMethod } from '../api/hires-fix'
import { releaseVideoBlobUrl } from '../api/mlx-video'
import { isMlxImageHost } from '../api/mlx-image'
@@ -136,6 +137,15 @@ export const MODEL_TYPE_DEFAULTS: Record<ModelType, {
// Qwen-Image 2.1: mirrors comfyui.ts MODEL_TYPE_DEFAULTS.qwenimage, which
// takes every number straight from the official Comfy-Org templates.
qwenimage: { steps: 25, cfgScale: 1.0, sampler: 'euler', scheduler: 'simple', width: 1024, height: 1024 },
+ // The five families below came in with the header sniff (Discord
+ // 2026-09-28); numbers mirror comfyui.ts MODEL_TYPE_DEFAULTS, which takes
+ // them from the official Comfy-Org templates. HiDream dev/full get their
+ // own numbers in hidreamDefaults().
+ qwenimage1: { steps: 20, cfgScale: 4.0, sampler: 'euler', scheduler: 'simple', width: 1328, height: 1328 },
+ chroma: { steps: 26, cfgScale: 3.5, sampler: 'euler', scheduler: 'beta', width: 1024, height: 1024 },
+ hidream: { steps: 16, cfgScale: 1.0, sampler: 'lcm', scheduler: 'normal', width: 1024, height: 1024 },
+ sd3: { steps: 20, cfgScale: 4.0, sampler: 'euler', scheduler: 'sgm_uniform', width: 1024, height: 1024 },
+ lumina2: { steps: 25, cfgScale: 4.0, sampler: 'res_multistep', scheduler: 'simple', width: 1024, height: 1024 },
wan: { steps: 25, cfgScale: 5.0, sampler: 'euler', scheduler: 'normal', width: 848, height: 480, frames: 49, fps: 16 },
wan22: { steps: 30, cfgScale: 5.0, sampler: 'euler', scheduler: 'simple', width: 1024, height: 576, frames: 49, fps: 24 },
hunyuan: { steps: 30, cfgScale: 6.0, sampler: 'euler', scheduler: 'normal', width: 848, height: 480, frames: 45, fps: 15 },
@@ -160,6 +170,17 @@ export const MODEL_TYPE_DEFAULTS: Record<ModelType, {
unknown: { steps: 20, cfgScale: 7.0, sampler: 'euler', scheduler: 'normal', width: 1024, height: 1024 },
}
+/** The strongest Edit repaint. At 1.0 an img2img sampler ignores the source
+ * entirely, which is never what Edit means (Discord 2026-09-25). */
+export const EDIT_MAX_DENOISE = 0.95
+
+/** HiDream I1 ships as fast, dev and full, three different samplers
+ * (hidream_i1_fast / _dev / _full templates). Fast is the type default. */
+export function hidreamDefaults(model: string): (typeof MODEL_TYPE_DEFAULTS)['hidream'] {
+ const s = hidreamSampling(model)
+ return { ...MODEL_TYPE_DEFAULTS.hidream, steps: s.steps, cfgScale: s.cfg, sampler: s.sampler, scheduler: s.scheduler }
+}
+
export interface GalleryItem {
id: string
type: 'image' | 'video' | 'audio'
@@ -214,6 +235,13 @@ export interface GalleryItem {
* is unreachable. Tiles render an honest offline state and Download
* disables instead of silently no-oping. */
unavailable?: boolean
+ /** Runtime-only: why. 'offline' = ComfyUI did not answer; 'gone' = ComfyUI
+ * answered and the file is not in its output any more. */
+ unavailableReason?: 'offline' | 'gone'
+ /** Runtime-only: bumped when ComfyUI comes back, so a tile that errored
+ * while it was down loads again (Discord 2026-09-26, tbjdrw: "why do I
+ * keep getting that?" — the flag never cleared until a restart). */
+ reloadKey?: number
}
interface CreateState {
@@ -363,6 +391,9 @@ interface CreateState {
* prompt. Runtime-only — useCreate sets it when a video gen would fall
* back to animated .webp; the modal resolves with the user's choice. */
vhsInstallPrompt: ((choice: 'install' | 'webp' | 'cancel') => void) | null
+ /** A render is missing files or a newer ComfyUI; Create asks before fixing
+ * it (lib/render-fixups.ts). Never persisted. */
+ fixupPrompt: (FixupPrompt & { resolve: (go: boolean) => void }) | null
setMode: (mode: 'image' | 'video') => void
setVideoBackend: (backend: VideoBackendKind) => void
@@ -438,6 +469,7 @@ interface CreateState {
setProgressPhase: (phase: ProgressPhase) => void
setCurrentPromptId: (id: string | null) => void
setVhsInstallPrompt: (resolver: ((choice: 'install' | 'webp' | 'cancel') => void) | null) => void
+ setFixupPrompt: (prompt: (FixupPrompt & { resolve: (go: boolean) => void }) | null) => void
setError: (error: string | null) => void
setLastGenTime: (time: string | null) => void
addToGallery: (item: GalleryItem) => void
@@ -617,6 +649,7 @@ export const useCreateStore = create<CreateState>()(
motionModelList: [],
comfyRunning: false,
vhsInstallPrompt: null,
+ fixupPrompt: null,
setVideoBackend: (videoBackend) => set({ videoBackend, videoBackendInitialized: true }),
setMode: (mode) => set((state) => {
@@ -649,7 +682,7 @@ export const useCreateStore = create<CreateState>()(
setPrompt: (prompt) => set({ prompt }),
setNegativePrompt: (negativePrompt) => set({ negativePrompt }),
setImageModel: (model, type) => {
- const defaults = MODEL_TYPE_DEFAULTS[type]
+ const defaults = type === 'hidream' ? hidreamDefaults(model) : MODEL_TYPE_DEFAULTS[type]
set({
imageModel: model, imageModelType: type,
steps: defaults.steps, cfgScale: defaults.cfgScale,
@@ -924,6 +957,7 @@ export const useCreateStore = create<CreateState>()(
setProgressPhase: (phase) => set({ progressPhase: phase }),
setCurrentPromptId: (id) => set({ currentPromptId: id }),
setVhsInstallPrompt: (resolver) => set({ vhsInstallPrompt: resolver }),
+ setFixupPrompt: (prompt) => set({ fixupPrompt: prompt }),
setError: (error) => set({ error }),
setLastGenTime: (time) => set({ lastGenTime: time }),
// Ein frisches Cloud-Ergebnis stellt den Wolken-Modellwaehler auf das
@@ -992,8 +1026,16 @@ export const useCreateStore = create<CreateState>()(
}),
removeFromGallery: (id) => set((s) => {
const gone = s.gallery.find((g) => g.id === id)
- if (gone) releaseItemMedia(gone)
- return { gallery: s.gallery.filter((g) => g.id !== id) }
+ const remaining = s.gallery.filter((g) => g.id !== id)
+ if (gone) {
+ releaseItemMedia(gone)
+ // The file goes too, into the Recycle Bin (lib/gallery-trash.ts).
+ void import('../lib/gallery-trash')
+ .then((m) => m.trashGalleryFile(gone, remaining))
+ .then((problem) => { if (problem) useCreateStore.getState().setError(problem) })
+ .catch(() => { /* the entry is gone either way */ })
+ }
+ return { gallery: remaining }
}),
clearGallery: () => set((s) => {
for (const g of s.gallery) releaseItemMedia(g)
@@ -1008,7 +1050,19 @@ export const useCreateStore = create<CreateState>()(
clearPromptHistory: () => set({ promptHistory: [] }),
setImageModelList: (list) => set({ imageModelList: list }),
setVideoModelList: (list) => set({ videoModelList: list }),
- setComfyRunning: (running) => set({ comfyRunning: running }),
+ setComfyRunning: (running) => set((s) => {
+ if (!running || s.comfyRunning) return { comfyRunning: running }
+ // ComfyUI is back: every local tile that failed while it was away
+ // gets another go instead of staying dark until the next restart.
+ const retry = (g: GalleryItem) => g.unavailable && g.unavailableReason !== 'gone' && !g.jobId && !g.localPath
+ if (!s.gallery.some(retry)) return { comfyRunning: running }
+ return {
+ comfyRunning: running,
+ gallery: s.gallery.map((g) => retry(g)
+ ? { ...g, unavailable: undefined, unavailableReason: undefined, reloadKey: (g.reloadKey ?? 0) + 1 }
+ : g),
+ }
+ }),
}),
{
name: 'create-store',
@@ -1039,7 +1093,7 @@ export const useCreateStore = create<CreateState>()(
// dataUrls would blow the origin quota (~5-10 MB in WebView2/WKWebView)
// and every subsequent set() would throw, killing ALL create-store
// persistence. Cloud items carry remoteUrl + jobId and re-sign lazily.
- gallery: state.gallery.map(({ dataUrl, unavailable, ...g }: GalleryItem) => g),
+ gallery: state.gallery.map(({ dataUrl, unavailable, unavailableReason, reloadKey, ...g }: GalleryItem) => g),
promptHistory: state.promptHistory,
// ── redesign additions (advanced params only; runtime inputs
// source/mask/backend/caps stay unpersisted). No version bump: these
diff --git a/src/stores/downloadStore.ts b/src/stores/downloadStore.ts
index 25b118c0..6e5a6d9e 100644
--- a/src/stores/downloadStore.ts
+++ b/src/stores/downloadStore.ts
@@ -4,7 +4,7 @@ import {
getDownloadProgress, pauseDownload, cancelDownload, clearDownloadEntry, resumeDownload,
startModelDownload, startModelDownloadToPath, lookupFileMeta, modelsNotVisibleInComfy,
isPermanentDownloadError, findOrphanDownloads, deleteOrphanDownload, orphanFilename,
- catalogFilenames, ENUM_SUBFOLDERS, type DownloadProgress, type OrphanDownload,
+ catalogFilenames, ENUM_SUBFOLDERS, comfyModelTarget, type DownloadProgress, type OrphanDownload,
} from '../api/discover'
import { isTauri } from '../api/backend'
import { coalescedJSONStorage } from '../lib/coalescedStorage'
@@ -46,6 +46,9 @@ async function announceUntilVisible(filename: string, subfolder: string | undefi
// One cheap probe first: with the engine down the wait would spend its
// whole budget on requests that cannot be answered.
if (!(await checkComfyConnection())) return
+ // A ComfyUI on another machine cannot see a file on this one until the
+ // user copies it over (GH #143); the Model Manager already said so.
+ if ((await comfyModelTarget()).remote) return
const left = await waitForModelsVisible({
missing: () => modelsNotVisibleInComfy([filename]),
refresh: async () => {