The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(video): fast Wan 14B, long local clips up to 30 s, Extend Video from frames (B18)
purpledfc3c8c5dfcb
diff --git a/dev-server/mlx-media-stubs.ts b/dev-server/mlx-media-stubs.tsindex 97a0ee8d..b8d298e3 100644--- a/dev-server/mlx-media-stubs.ts+++ b/dev-server/mlx-media-stubs.ts@@ -72,6 +72,7 @@ export function registerMlxMediaStubs(routes: RouteMount): void {'/local-api/video-generate','/local-api/video-progress','/local-api/video-cancel',+ '/local-api/video-color-settle','/local-api/read-media-file','/local-api/mlx-music-status','/local-api/mlx-music-install',diff --git a/src-tauri/src/commands/comfy_attention.rs b/src-tauri/src/commands/comfy_attention.rsnew file mode 100644index 00000000..161e2ef1--- /dev/null+++ b/src-tauri/src/commands/comfy_attention.rs@@ -0,0 +1,479 @@+//! Which attention flag a ComfyUI that LU starts gets.+//!+//! ComfyUI's `cli_args.py` puts the attention switches into one mutually+//! exclusive argparse group (`--use-split-cross-attention`,+//! `--use-quad-cross-attention`, `--use-pytorch-cross-attention`,+//! `--use-sage-attention`, `--use-flash-attention`, `--use-ck-attention`, ...).+//! Two of them on one command line and argparse exits before ComfyUI has+//! printed a single line of its own, so the decision below always yields at+//! most ONE flag.+//!+//! Order of preference:+//!+//! 1. `--use-ck-attention` (Comfy Kitchen, ComfyUI 0.32.0 and later). The+//! `comfy-kitchen` package is in ComfyUI's own requirements.txt, so on a+//! current install it is there without LU fetching anything. Only on a+//! CUDA (NVIDIA) or ROCm torch: not under `--cpu`, not under+//! `--directml`, not on Intel XPU, never on a Mac (LU starts no ComfyUI+//! there anyway).+//! 2. `--use-flash-attention` when flash-attn imports in this Python, the+//! rule that was here before (process.rs, `probe_flash_attention`).+//! 3. Nothing: ComfyUI picks its own default.+//!+//! A start with the ck flag that dies before the port answers is started+//! again without it, and that outcome is remembered per ComfyUI folder and+//! version in the app's config.json (the same read, change, write as+//! `remember_bound_python_in`). A newer ComfyUI gets a fresh try, because the+//! version is part of the key. `LU_COMFY_NO_CK=1` switches the flag off+//! entirely, for a support case that needs it gone without a rebuild.++use crate::python::python_command;+use std::collections::HashMap;+use std::fs;+use std::path::Path;+use std::process::Stdio;+use std::sync::Mutex;++#[cfg(target_os = "windows")]+use std::os::windows::process::CommandExt;++/// The Comfy Kitchen attention switch.+pub(crate) const CK_FLAG: &str = "--use-ck-attention";+/// The FlashAttention-2 switch, unchanged from before.+pub(crate) const FLASH_FLAG: &str = "--use-flash-attention";++/// The first ComfyUI release that knows `--use-ck-attention`. An older+/// ComfyUI would reject the unknown flag in argparse and never start.+pub(crate) const CK_MIN_VERSION: ComfyVersion = ComfyVersion(0, 32, 0);++/// Environment switch that keeps the ck flag off whatever else is true.+pub(crate) const NO_CK_ENV: &str = "LU_COMFY_NO_CK";++/// A ComfyUI release number, `major.minor.patch`. Ordered, so a minimum+/// version is a plain `>=`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub(crate) struct ComfyVersion(pub u32, pub u32, pub u32);++impl std::fmt::Display for ComfyVersion {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}.{}.{}", self.0, self.1, self.2)+ }+}++/// The version out of the text of ComfyUI's `comfyui_version.py`.+///+/// The file is generated by ComfyUI's release tooling and holds one line that+/// matters, `__version__ = "0.42.4"`. Single or double quotes, spaces or not+/// around the `=`, a leading `v`, and a suffix after the patch number+/// (`0.42.4rc1`) are all read; anything that does not give three numbers is+/// `None`, and `None` never unlocks the ck flag.+pub(crate) fn parse_comfyui_version(text: &str) -> Option<ComfyVersion> {+ for line in text.lines() {+ let line = line.trim();+ let Some(rest) = line.strip_prefix("__version__") else { continue };+ let Some(value) = rest.trim_start().strip_prefix('=') else { continue };+ let value = value.trim().trim_matches(|c| c == '"' || c == '\'');+ let value = value.strip_prefix('v').unwrap_or(value);+ let mut parts = value.split('.');+ let mut number = || -> Option<u32> {+ let part = parts.next()?;+ let digits: String = part.chars().take_while(|c| c.is_ascii_digit()).collect();+ digits.parse().ok()+ };+ let (major, minor, patch) = (number()?, number()?, number()?);+ return Some(ComfyVersion(major, minor, patch));+ }+ None+}++/// The installed ComfyUI's version, read from `<comfy_dir>/comfyui_version.py`.+/// A portable or very old ComfyUI without the file reads as `None`.+pub(crate) fn read_comfyui_version(comfy_dir: &Path) -> Option<ComfyVersion> {+ parse_comfyui_version(&fs::read_to_string(comfy_dir.join("comfyui_version.py")).ok()?)+}++/// Everything the ck decision depends on, gathered by the start before it+/// builds the command line. Plain data, so the rule is testable without a+/// GPU, a Python or a ComfyUI.+#[derive(Debug, Clone, Copy)]+pub(crate) struct CkFacts<'a> {+ /// `std::env::consts::OS` of this build.+ pub os: &'a str,+ /// The start passes `--cpu`.+ pub needs_cpu: bool,+ /// The device flag the start passes besides `--cpu`, today only+ /// `--directml` (process.rs, `comfy_device_flag`).+ pub device_flag: Option<&'a str>,+ /// An NVIDIA driver answers (`needs_cpu_fallback()` is false).+ pub nvidia_driver: bool,+ /// What the environment's torch reports when there is no NVIDIA driver:+ /// `"cuda"` is a ROCm (or ZLUDA) build, `"xpu"` Intel, `"directml"`.+ /// Ignored when `nvidia_driver` is true.+ pub torch_device: Option<&'a str>,+ /// The installed ComfyUI's version, `None` when unreadable.+ pub comfy_version: Option<ComfyVersion>,+ /// `LU_COMFY_NO_CK` is set.+ pub switched_off: bool,+ /// What an earlier start of this folder and version taught us:+ /// `Some(false)` = it died with the flag before the port answered.+ pub remembered: Option<bool>,+}++/// May this start try `--use-ck-attention`? Everything except the import+/// test, which costs a torch import and is therefore asked last and only+/// when this says yes.+pub(crate) fn ck_attention_eligible(f: &CkFacts) -> bool {+ if f.switched_off || f.remembered == Some(false) {+ return false;+ }+ if f.os == "macos" || f.needs_cpu || f.device_flag.is_some() {+ return false;+ }+ let cuda_or_rocm = f.nvidia_driver || f.torch_device == Some("cuda");+ if !cuda_or_rocm {+ return false;+ }+ matches!(f.comfy_version, Some(v) if v >= CK_MIN_VERSION)+}++/// The one attention flag this start passes, or none.+///+/// Both import tests are closures so each runs only when its answer can still+/// change the result: the ck probe only for an eligible start, the flash+/// probe only when ck is not taken. CPU mode passes neither (flash-attn is+/// CUDA-only, and ck is excluded by the eligibility above).+pub(crate) fn pick_attention_flag(+ needs_cpu: bool,+ ck_eligible: bool,+ ck_imports: impl FnOnce() -> bool,+ flash_imports: impl FnOnce() -> bool,+) -> Option<&'static str> {+ if needs_cpu {+ return None;+ }+ if ck_eligible && ck_imports() {+ return Some(CK_FLAG);+ }+ flash_imports().then_some(FLASH_FLAG)+}++/// Is `LU_COMFY_NO_CK` set to something that means yes?+pub(crate) fn ck_switched_off_by_env(value: Option<&str>) -> bool {+ matches!(+ value.map(|v| v.trim().to_ascii_lowercase()).as_deref(),+ Some("1") | Some("true") | Some("yes") | Some("on")+ )+}++/// The process environment's answer to [`ck_switched_off_by_env`].+pub(crate) fn ck_switched_off() -> bool {+ ck_switched_off_by_env(std::env::var(NO_CK_ENV).ok().as_deref())+}++/// Set once a start with the ck flag died before its port answered. The+/// config.json memory below is the lasting record; this is the one that+/// cannot fail, so the retry without the flag never loops back into it, even+/// on a machine whose config folder is read-only.+static CK_FAILED_THIS_RUN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++pub(crate) fn note_ck_failed_this_run() {+ CK_FAILED_THIS_RUN.store(true, std::sync::atomic::Ordering::SeqCst);+}++pub(crate) fn ck_failed_this_run() -> bool {+ CK_FAILED_THIS_RUN.load(std::sync::atomic::Ordering::SeqCst)+}++// ── The import test ─────────────────────────────────────────────────────++/// Per (python, ComfyUI version) cache of DEFINITIVE answers, the same rule+/// as `flash_attention_cached`: a timeout is not cached, so one slow boot does+/// not switch ck off for the session. The version is part of the key because+/// an Update ComfyUI run installs `comfy-kitchen` into the same interpreter.+static CK_PROBE_CACHE: Mutex<Option<HashMap<(String, String), bool>>> = Mutex::new(None);++/// Does `import comfy_kitchen` succeed in `python`? Real import, `-I` so+/// neither the working directory nor PYTHONPATH can put a different module of+/// that name in front. Some(true/false) = the process answered, None =+/// timeout or no spawn.+pub(crate) fn probe_comfy_kitchen(python: &str) -> Option<bool> {+ if python.is_empty() {+ return Some(false);+ }+ let mut cmd = python_command(python);+ cmd.args(["-I", "-c", "import comfy_kitchen"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(crate::commands::install::CREATE_NO_WINDOW);+ let mut child = cmd.spawn().ok()?;+ // 90 s, the flash probe's ceiling: comfy_kitchen imports torch, which is+ // a few seconds warm and far longer in a boot-time disk storm, while an+ // absent package fails within seconds.+ for _ in 0..450 {+ match child.try_wait() {+ Ok(Some(status)) => return Some(status.success()),+ Ok(None) => std::thread::sleep(std::time::Duration::from_millis(200)),+ Err(_) => return None,+ }+ }+ let _ = child.kill();+ let _ = child.wait();+ None+}++/// [`probe_comfy_kitchen`] with the cache. A timeout reads as "no" for this+/// start only.+pub(crate) fn comfy_kitchen_cached(python: &str, version: Option<ComfyVersion>) -> bool {+ let key = (python.to_string(), version.map(|v| v.to_string()).unwrap_or_default());+ if let Some(v) = CK_PROBE_CACHE.lock().ok().and_then(|c| c.as_ref().and_then(|m| m.get(&key).copied())) {+ return v;+ }+ match probe_comfy_kitchen(python) {+ Some(v) => {+ if let Ok(mut c) = CK_PROBE_CACHE.lock() {+ c.get_or_insert_with(HashMap::new).insert(key, v);+ }+ v+ }+ None => {+ println!("[ComfyUI] comfy_kitchen probe timed out, starting without {CK_FLAG} (will retry next start)");+ false+ }+ }+}++// ── What earlier starts taught us ───────────────────────────────────────++/// The config.json key: `{"comfyui": <folder>, "version": "0.42.4",+/// "works": true|false}`. One entry, the ComfyUI LU starts; a second folder+/// or a new version simply replaces it.+const CK_MEMORY_KEY: &str = "comfyui_ck_attention";++/// What is remembered about the ck flag for exactly this folder and version.+pub(crate) fn remembered_ck_in(config: &Path, comfy_dir: &Path, version: ComfyVersion) -> Option<bool> {+ let json: serde_json::Value = serde_json::from_str(&fs::read_to_string(config).ok()?).ok()?;+ let entry = json.get(CK_MEMORY_KEY)?;+ let folder = entry.get("comfyui")?.as_str()?;+ let stored = entry.get("version")?.as_str()?;+ if Path::new(folder) != comfy_dir || stored != version.to_string() {+ return None;+ }+ entry.get("works")?.as_bool()+}++/// Remember how a start with the ck flag ended. Every other key in the file+/// stays.+pub(crate) fn remember_ck_in(config: &Path, comfy_dir: &Path, version: ComfyVersion, works: bool) {+ if let Some(parent) = config.parent() {+ let _ = fs::create_dir_all(parent);+ }+ let mut json: serde_json::Value = fs::read_to_string(config)+ .ok()+ .and_then(|s| serde_json::from_str(&s).ok())+ .filter(serde_json::Value::is_object)+ .unwrap_or_else(|| serde_json::json!({}));+ json[CK_MEMORY_KEY] = serde_json::json!({+ "comfyui": comfy_dir.to_string_lossy(),+ "version": version.to_string(),+ "works": works,+ });+ let _ = fs::write(config, serde_json::to_string_pretty(&json).unwrap_or_default());+}++/// How a start with the ck flag that has not proven itself yet ended.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum CkWatch {+ /// The port answered: the flag works with this ComfyUI.+ Proven,+ /// The process exited before the port answered.+ DiedEarly,+ /// Neither within the watch, or the child was taken away (Stop pressed).+ /// Nothing is remembered.+ Undecided,+}++/// How long a first start with the ck flag is watched for its port. The+/// slowest honest start measured is about a minute; custom-node-heavy+/// installs take longer, and an undecided watch costs only that the next+/// start watches again.+pub(crate) const CK_PROOF_WATCH: std::time::Duration = std::time::Duration::from_secs(180);++/// Watch an unproven ck start until it either answers on the port or dies.+///+/// `exited` is asked first on every round and returns `Some(true)` when the+/// child is gone by itself, `Some(false)` while it lives and `None` when the+/// handle is no longer ours to watch. Closures, so the rule is testable+/// without a process or a port.+pub(crate) fn watch_ck_start(+ mut exited: impl FnMut() -> Option<bool>,+ mut port_answers: impl FnMut() -> bool,+ budget: std::time::Duration,+ step: std::time::Duration,+) -> CkWatch {+ let mut waited = std::time::Duration::ZERO;+ loop {+ match exited() {+ Some(true) => return CkWatch::DiedEarly,+ None => return CkWatch::Undecided,+ Some(false) => {}+ }+ if port_answers() {+ return CkWatch::Proven;+ }+ if waited >= budget {+ return CkWatch::Undecided;+ }+ std::thread::sleep(step);+ waited += step;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn nvidia(version: Option<ComfyVersion>) -> CkFacts<'static> {+ CkFacts {+ os: "windows",+ needs_cpu: false,+ device_flag: None,+ nvidia_driver: true,+ torch_device: None,+ comfy_version: version,+ switched_off: false,+ remembered: None,+ }+ }++ #[test]+ fn the_version_file_is_read_in_every_spelling_comfyui_has_used() {+ assert_eq!(parse_comfyui_version("# auto\n__version__ = \"0.42.4\"\n"), Some(ComfyVersion(0, 42, 4)));+ assert_eq!(parse_comfyui_version("__version__='0.32.0'"), Some(ComfyVersion(0, 32, 0)));+ assert_eq!(parse_comfyui_version("__version__ = \"v1.2.3rc1\""), Some(ComfyVersion(1, 2, 3)));+ assert_eq!(parse_comfyui_version("__version__ = \"0.3\""), None, "two numbers are not a version");+ assert_eq!(parse_comfyui_version("version = \"0.42.4\""), None);+ assert_eq!(parse_comfyui_version(""), None);+ }++ #[test]+ fn versions_compare_as_numbers_not_as_text() {+ assert!(ComfyVersion(0, 42, 4) > CK_MIN_VERSION);+ assert!(ComfyVersion(0, 32, 0) >= CK_MIN_VERSION);+ assert!(ComfyVersion(0, 31, 99) < CK_MIN_VERSION);+ // "0.4.0" sorts after "0.32.0" as text and must not here.+ assert!(ComfyVersion(0, 4, 0) < CK_MIN_VERSION);+ }++ #[test]+ fn read_comfyui_version_finds_the_file_in_the_comfy_folder() {+ let tmp = tempfile::tempdir().unwrap();+ assert_eq!(read_comfyui_version(tmp.path()), None);+ fs::write(tmp.path().join("comfyui_version.py"), "__version__ = \"0.42.4\"\n").unwrap();+ assert_eq!(read_comfyui_version(tmp.path()), Some(ComfyVersion(0, 42, 4)));+ }++ #[test]+ fn ck_is_tried_on_nvidia_and_rocm_with_a_new_enough_comfyui() {+ assert!(ck_attention_eligible(&nvidia(Some(ComfyVersion(0, 42, 4)))));+ let rocm = CkFacts { os: "linux", nvidia_driver: false, torch_device: Some("cuda"), ..nvidia(Some(ComfyVersion(0, 32, 0))) };+ assert!(ck_attention_eligible(&rocm));+ }++ #[test]+ fn ck_is_never_tried_where_it_cannot_work() {+ let v = Some(ComfyVersion(0, 42, 4));+ let cases = [+ ("old comfyui", CkFacts { comfy_version: Some(ComfyVersion(0, 31, 9)), ..nvidia(v) }),+ ("unknown version", nvidia(None)),+ ("cpu", CkFacts { needs_cpu: true, ..nvidia(v) }),+ ("directml", CkFacts { nvidia_driver: false, device_flag: Some("--directml"), torch_device: Some("directml"), ..nvidia(v) }),+ ("intel xpu", CkFacts { nvidia_driver: false, torch_device: Some("xpu"), ..nvidia(v) }),+ ("no gpu torch", CkFacts { nvidia_driver: false, torch_device: None, ..nvidia(v) }),+ ("mac", CkFacts { os: "macos", ..nvidia(v) }),+ ("switched off", CkFacts { switched_off: true, ..nvidia(v) }),+ ("died before", CkFacts { remembered: Some(false), ..nvidia(v) }),+ ];+ for (name, facts) in cases {+ assert!(!ck_attention_eligible(&facts), "ck was allowed for: {name}");+ }+ // A start that proved the flag keeps it.+ assert!(ck_attention_eligible(&CkFacts { remembered: Some(true), ..nvidia(v) }));+ }++ #[test]+ fn at_most_one_attention_flag_and_ck_wins() {+ assert_eq!(pick_attention_flag(false, true, || true, || true), Some(CK_FLAG));+ assert_eq!(pick_attention_flag(false, true, || false, || true), Some(FLASH_FLAG));+ assert_eq!(pick_attention_flag(false, false, || true, || true), Some(FLASH_FLAG));+ assert_eq!(pick_attention_flag(false, false, || true, || false), None);+ assert_eq!(pick_attention_flag(true, true, || true, || true), None, "--cpu gets no attention flag");+ }++ #[test]+ fn the_probes_run_only_when_their_answer_matters() {+ // ck taken: the flash probe (a torch import) must not run.+ let flag = pick_attention_flag(false, true, || true, || panic!("flash probed although ck was taken"));+ assert_eq!(flag, Some(CK_FLAG));+ // Not eligible: the ck probe must not run.+ let flag = pick_attention_flag(false, false, || panic!("ck probed although not eligible"), || false);+ assert_eq!(flag, None);+ // CPU: neither.+ let flag = pick_attention_flag(true, true, || panic!("ck probed under --cpu"), || panic!("flash probed under --cpu"));+ assert_eq!(flag, None);+ }++ #[test]+ fn the_env_switch_reads_the_usual_yes_values() {+ for yes in ["1", "true", "YES", " on "] {+ assert!(ck_switched_off_by_env(Some(yes)), "{yes}");+ }+ for no in ["0", "", "false", "nope"] {+ assert!(!ck_switched_off_by_env(Some(no)), "{no}");+ }+ assert!(!ck_switched_off_by_env(None));+ }++ #[test]+ fn the_memory_is_per_folder_and_version_and_keeps_other_keys() {+ let tmp = tempfile::tempdir().unwrap();+ let config = tmp.path().join("cfg").join("config.json");+ let dir = tmp.path().join("ComfyUI");+ let v = ComfyVersion(0, 42, 4);+ assert_eq!(remembered_ck_in(&config, &dir, v), None);++ fs::create_dir_all(config.parent().unwrap()).unwrap();+ fs::write(&config, r#"{"comfyui_path": "X"}"#).unwrap();+ remember_ck_in(&config, &dir, v, false);+ assert_eq!(remembered_ck_in(&config, &dir, v), Some(false));+ let json: serde_json::Value = serde_json::from_str(&fs::read_to_string(&config).unwrap()).unwrap();+ assert_eq!(json["comfyui_path"], "X", "another key was lost");++ // A new ComfyUI version gets a fresh try, another folder too.+ assert_eq!(remembered_ck_in(&config, &dir, ComfyVersion(0, 43, 0)), None);+ assert_eq!(remembered_ck_in(&config, &tmp.path().join("Other"), v), None);++ remember_ck_in(&config, &dir, v, true);+ assert_eq!(remembered_ck_in(&config, &dir, v), Some(true));+ }++ #[test]+ fn the_watch_tells_a_crash_from_a_start() {+ let step = std::time::Duration::ZERO;+ let budget = std::time::Duration::from_millis(1);+ // Dies on the third look, port never answers.+ let mut n = 0;+ let died = watch_ck_start(|| { n += 1; Some(n >= 3) }, || false, std::time::Duration::from_secs(5), step);+ assert_eq!(died, CkWatch::DiedEarly);+ // Port answers while alive.+ let mut m = 0;+ let up = watch_ck_start(|| Some(false), || { m += 1; m >= 2 }, std::time::Duration::from_secs(5), step);+ assert_eq!(up, CkWatch::Proven);+ // Stop took the child: nothing is decided.+ assert_eq!(watch_ck_start(|| None, || false, budget, step), CkWatch::Undecided);+ // Alive, silent, out of time.+ let slow = watch_ck_start(|| Some(false), || false, budget, std::time::Duration::from_millis(1));+ assert_eq!(slow, CkWatch::Undecided);+ }+}diff --git a/src-tauri/src/commands/install/comfy_install.rs b/src-tauri/src/commands/install/comfy_install.rsindex 71ad3a70..6cf0b92b 100644--- a/src-tauri/src/commands/install/comfy_install.rs+++ b/src-tauri/src/commands/install/comfy_install.rs@@ -337,8 +337,11 @@ pub fn install_comfyui(println!("[Install] Cloning ComfyUI to {:?}", target_dir);update("downloading", "Step 1/4: Downloading ComfyUI repository...");+ // 3.0.9: the release LU tested (comfy_pin.rs), not whatever master+ // is at this minute. Full history, so a later pin is a local move.let mut cmd = crate::process_util::foreign_system_command("git");- cmd.args(["clone", "https://github.com/comfyanonymous/ComfyUI.git"])+ cmd.args(["clone"])+ .args(super::comfy_pin::pinned_clone_args()).arg(&target_dir).stdout(Stdio::piped()).stderr(Stdio::piped());@@ -377,7 +380,16 @@ pub fn install_comfyui(if clone_exit.success() {println!("[Install] Git clone successful");- update("installing", "Repository cloned successfully.");+ update(+ "installing",+ &format!("Repository cloned successfully (ComfyUI {}).", super::comfy_pin::COMFYUI_PINNED_TAG),+ );+ // The marker that lets Update keep exactly this folder on the pin+ // later on, and nothing the customer brought along. Not fatal:+ // an unmarked install still works, it updates the old way.+ if let Err(e) = super::comfy_pin::mark_lu_installed(&target_dir) {+ println!("[Install] Could not mark the ComfyUI as installed by LU: {e}");+ }} else {let mut stderr = String::new();if let Some(mut e) = clone_child.stderr.take() {@@ -396,11 +408,29 @@ pub fn install_comfyui(return;}println!("[Install] ComfyUI directory already exists, updating...");- update("installing", "ComfyUI already exists, pulling latest...");if cancelled() {update("cancelled", "Install cancelled.");return;}+ // A ComfyUI LU cloned earlier sits on a tag without a branch,+ // so a pull has nothing to update: it is set to the pin+ // instead. Everything else keeps the pull it always got.+ if super::comfy_pin::is_lu_installed(&target_dir) {+ let tag = super::comfy_pin::COMFYUI_PINNED_TAG;+ update("installing", &format!("ComfyUI already exists, setting it to the tested release {tag}..."));+ match super::comfy_pin::checkout_pinned_tag(&target_dir, tag, true) {+ Ok(_) => update("installing", &format!("ComfyUI is on {tag}.")),+ Err(e) => update(+ "installing",+ &format!(+ "Could not set ComfyUI to {tag}, continuing with the ComfyUI already \+ on disk.\n{}",+ e.chars().take(400).collect::<String>()+ ),+ ),+ }+ } else {+ update("installing", "ComfyUI already exists, pulling latest...");let mut pull = crate::process_util::foreign_system_command("git");pull.args(["pull"]).current_dir(&target_dir).stdout(Stdio::piped()).stderr(Stdio::piped());@@ -441,6 +471,7 @@ pub fn install_comfyui();}}+ }} else {let err = format!("Git clone failed: {}", stderr);println!("[Install] {}", err);diff --git a/src-tauri/src/commands/install/comfy_pin.rs b/src-tauri/src/commands/install/comfy_pin.rsnew file mode 100644index 00000000..b76e56a6--- /dev/null+++ b/src-tauri/src/commands/install/comfy_pin.rs@@ -0,0 +1,244 @@+//! The ComfyUI release LU installs, and how an LU install stays on it.+//!+//! Until 3.0.9 the installer cloned whatever `master` was at that minute and+//! Update ran `git pull --ff-only`, so two customers who installed a day+//! apart ran different ComfyUIs, and a bad commit upstream reached every new+//! install the moment it landed. Now a fresh install clones the tag below+//! (full history, so a later move to a newer tag is a local checkout) and+//! Update sets an LU install to that tag again, fetching it first.+//!+//! Only a ComfyUI that LU itself cloned is pinned. It is recognised by a+//! marker file inside its `.git` folder, written right after LU's clone:+//! inside `.git` so `git status` never lists it (Update refuses a dirty tree,+//! see `git_dirty_lines`) and it moves with the folder when the customer+//! moves it. A ComfyUI the customer brought along (a portable, Stability+//! Matrix, their own clone) has no marker and keeps the old behaviour, a+//! fast-forward pull of its own branch, or no update at all without git.+//!+//! Model gates on the TypeScript side (`dynamic-workflow.ts`) ask for up to+//! ComfyUI 0.37.0 today; the pin has to stay at or above the highest of them.++use std::path::Path;++/// Where ComfyUI comes from.+pub(crate) const COMFYUI_REPO_URL: &str = "https://github.com/comfyanonymous/ComfyUI.git";++/// The ComfyUI release LU installs and updates its own install to. v0.42.4+/// is the release of 22.10.2026; it carries `--use-ck-attention` (0.32.0+,+/// see commands/comfy_attention.rs) and every node the model gates ask for.+pub(crate) const COMFYUI_PINNED_TAG: &str = "v0.42.4";++/// The marker's name inside `.git`.+const LU_INSTALL_MARKER: &str = "lu-installed";++/// The arguments after `git clone` for a pinned install, without the target+/// folder. `--branch` takes a tag as well and leaves the checkout detached on+/// it; without `--depth` or `--single-branch` the whole history and every+/// branch come along, so an update to a later tag needs no reclone.+pub(crate) fn pinned_clone_args() -> [&'static str; 3] {+ ["--branch", COMFYUI_PINNED_TAG, COMFYUI_REPO_URL]+}++/// Note in `comfy_dir/.git` that LU cloned this ComfyUI. An error only when+/// `.git` is not a folder or cannot be written; the caller logs it and goes+/// on, an unmarked install simply keeps updating the old way.+pub(crate) fn mark_lu_installed(comfy_dir: &Path) -> Result<(), String> {+ let git_dir = comfy_dir.join(".git");+ if !git_dir.is_dir() {+ return Err(format!("{} is not a git folder", git_dir.display()));+ }+ std::fs::write(+ git_dir.join(LU_INSTALL_MARKER),+ format!("Installed by LU on ComfyUI {COMFYUI_PINNED_TAG}. LU keeps this ComfyUI on its tested release.\n"),+ )+ .map_err(|e| crate::os_error::english(&e))+}++/// Did LU clone this ComfyUI? Only then may Update move it to the pin.+pub(crate) fn is_lu_installed(comfy_dir: &Path) -> bool {+ comfy_dir.join(".git").join(LU_INSTALL_MARKER).is_file()+}++/// `git` inside `dir`, output captured, never waiting for a password.+fn git_ok(dir: &Path, args: &[&str]) -> Result<String, String> {+ let output = super::custom_nodes::git_in(dir, args)?;+ if !output.status.success() {+ return Err(String::from_utf8_lossy(&output.stderr).trim().to_string());+ }+ Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())+}++/// The commit a tag points at, if the checkout knows the tag.+fn tag_commit(dir: &Path, tag: &str) -> Option<String> {+ git_ok(dir, &["rev-parse", "--verify", "--quiet", &format!("refs/tags/{tag}^{{commit}}")]).ok()+}++/// What [`checkout_pinned_tag`] did.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum PinOutcome {+ /// HEAD already was the tag's commit; nothing moved.+ AlreadyThere,+ /// HEAD moved to the tag's commit.+ Moved,+}++/// Put an LU install on `tag`, detached.+///+/// `fetch` is the Update case: `git fetch --tags origin` first, so a newer+/// LU with a newer pin finds its tag. A fetch that fails (offline box, a+/// firewall) is not fatal while the tag is already known locally, the+/// install case where the clone brought it; without the tag it is the error.+pub(crate) fn checkout_pinned_tag(dir: &Path, tag: &str, fetch: bool) -> Result<PinOutcome, String> {+ let mut fetch_error = None;+ if fetch || tag_commit(dir, tag).is_none() {+ if let Err(e) = git_ok(dir, &["fetch", "--tags", "origin"]) {+ fetch_error = Some(e);+ }+ }+ let Some(target) = tag_commit(dir, tag) else {+ return Err(match fetch_error {+ Some(e) => format!("Could not fetch the ComfyUI release {tag}: {e}"),+ None => format!("The ComfyUI release {tag} does not exist in this checkout's origin."),+ });+ };+ if git_ok(dir, &["rev-parse", "HEAD"]).is_ok_and(|head| head.eq_ignore_ascii_case(&target)) {+ return Ok(PinOutcome::AlreadyThere);+ }+ git_ok(dir, &["-c", "advice.detachedHead=false", "checkout", "--detach", &target])?;+ Ok(PinOutcome::Moved)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::PathBuf;++ fn git(dir: &Path, args: &[&str]) -> String {+ let mut all = vec!["-c", "user.name=t", "-c", "[email protected]", "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"];+ all.extend_from_slice(args);+ git_ok(dir, &all).unwrap_or_else(|e| panic!("git {args:?} failed: {e}"))+ }++ /// An origin with three commits: `v0.41.0`, then the pinned tag, then a+ /// newer master commit nobody tested. Returns the temp dir, the origin and+ /// the three commit ids in that order.+ fn origin() -> (tempfile::TempDir, PathBuf, [String; 3]) {+ let tmp = tempfile::tempdir().unwrap();+ let origin = tmp.path().join("origin");+ std::fs::create_dir(&origin).unwrap();+ git(&origin, &["init", "-b", "master"]);+ git(&origin, &["config", "core.autocrlf", "false"]);+ let mut ids = Vec::new();+ for (content, tag) in [("old", Some("v0.41.0")), ("pinned", Some(COMFYUI_PINNED_TAG)), ("untested", None)] {+ std::fs::write(origin.join("main.py"), content).unwrap();+ git(&origin, &["add", "."]);+ git(&origin, &["commit", "-m", content]);+ if let Some(t) = tag {+ git(&origin, &["tag", t]);+ }+ ids.push(git(&origin, &["rev-parse", "HEAD"]));+ }+ (tmp, origin, ids.try_into().unwrap())+ }++ fn clone_pinned(origin: &Path, target: &Path) {+ // The real argument list with the test origin in place of GitHub.+ let mut args: Vec<&str> = pinned_clone_args().to_vec();+ assert_eq!(args[2], COMFYUI_REPO_URL);+ let origin_str = origin.to_string_lossy().to_string();+ args[2] = &origin_str;+ let target_str = target.to_string_lossy().to_string();+ let mut all = vec!["clone"];+ all.extend(args);+ all.push(&target_str);+ git(origin.parent().unwrap(), &all);+ }++ #[test]+ fn the_pin_is_the_checked_release() {+ assert_eq!(COMFYUI_PINNED_TAG, "v0.42.4");+ assert_eq!(pinned_clone_args(), ["--branch", "v0.42.4", "https://github.com/comfyanonymous/ComfyUI.git"]);+ // Never shallow: an update to a later tag must not need a reclone.+ assert!(!pinned_clone_args().iter().any(|a| a.starts_with("--depth") || *a == "--single-branch"));+ }++ #[test]+ fn a_pinned_clone_sits_on_the_tag_with_the_full_history() {+ let (tmp, origin, [old, pinned, untested]) = origin();+ let target = tmp.path().join("ComfyUI");+ clone_pinned(&origin, &target);+ assert_eq!(git(&target, &["rev-parse", "HEAD"]), pinned, "the clone is not on the pinned tag");+ assert_eq!(std::fs::read_to_string(target.join("main.py")).unwrap(), "pinned");+ // History before and after the tag came along.+ git(&target, &["cat-file", "-e", &format!("{old}^{{commit}}")]);+ git(&target, &["cat-file", "-e", &format!("{untested}^{{commit}}")]);+ assert_eq!(checkout_pinned_tag(&target, COMFYUI_PINNED_TAG, false).unwrap(), PinOutcome::AlreadyThere);+ }++ #[test]+ fn update_moves_an_lu_install_to_the_pin_and_not_to_master() {+ let (tmp, origin, [_old, pinned, untested]) = origin();+ let target = tmp.path().join("ComfyUI");+ // The state every install before the pin left behind: master.+ git(tmp.path(), &["clone", &origin.to_string_lossy(), &target.to_string_lossy()]);+ assert_eq!(git(&target, &["rev-parse", "HEAD"]), untested);+ assert_eq!(checkout_pinned_tag(&target, COMFYUI_PINNED_TAG, true).unwrap(), PinOutcome::Moved);+ assert_eq!(git(&target, &["rev-parse", "HEAD"]), pinned);+ // A second update has nothing to do.+ assert_eq!(checkout_pinned_tag(&target, COMFYUI_PINNED_TAG, true).unwrap(), PinOutcome::AlreadyThere);+ }++ #[test]+ fn a_tag_that_arrives_later_is_fetched() {+ let (tmp, origin, _) = origin();+ let target = tmp.path().join("ComfyUI");+ clone_pinned(&origin, &target);+ // A newer LU pins a release that did not exist at install time.+ std::fs::write(origin.join("main.py"), "next").unwrap();+ git(&origin, &["commit", "-am", "next"]);+ git(&origin, &["tag", "v9.0.0"]);+ let next = git(&origin, &["rev-parse", "HEAD"]);+ assert_eq!(checkout_pinned_tag(&target, "v9.0.0", true).unwrap(), PinOutcome::Moved);+ assert_eq!(git(&target, &["rev-parse", "HEAD"]), next);+ }++ #[test]+ fn a_missing_tag_is_an_error_and_moves_nothing() {+ let (tmp, origin, [_, pinned, _]) = origin();+ let target = tmp.path().join("ComfyUI");+ clone_pinned(&origin, &target);+ let err = checkout_pinned_tag(&target, "v99.0.0", true).unwrap_err();+ assert!(err.contains("v99.0.0"), "{err}");+ assert_eq!(git(&target, &["rev-parse", "HEAD"]), pinned, "a failed pin moved the checkout");+ }++ #[test]+ fn an_offline_update_still_pins_with_a_tag_the_clone_brought() {+ let (tmp, origin, [_, pinned, _]) = origin();+ let target = tmp.path().join("ComfyUI");+ git(tmp.path(), &["clone", &origin.to_string_lossy(), &target.to_string_lossy()]);+ // Origin gone: every fetch fails from here on.+ std::fs::remove_dir_all(&origin).unwrap();+ assert_eq!(checkout_pinned_tag(&target, COMFYUI_PINNED_TAG, true).unwrap(), PinOutcome::Moved);+ assert_eq!(git(&target, &["rev-parse", "HEAD"]), pinned);+ let err = checkout_pinned_tag(&target, "v99.0.0", true).unwrap_err();+ assert!(err.contains("Could not fetch"), "{err}");+ }++ #[test]+ fn only_a_folder_lu_marked_counts_as_an_lu_install_and_the_marker_stays_out_of_git_status() {+ let (tmp, origin, _) = origin();+ let target = tmp.path().join("ComfyUI");+ clone_pinned(&origin, &target);+ assert!(!is_lu_installed(&target), "a clone without the marker counts as LU's");+ mark_lu_installed(&target).unwrap();+ assert!(is_lu_installed(&target));+ assert_eq!(git(&target, &["status", "--porcelain"]), "", "the marker made the tree dirty, Update would refuse it");++ // A folder without git (a portable) cannot be marked and is never LU's.+ let portable = tmp.path().join("portable");+ std::fs::create_dir(&portable).unwrap();+ assert!(mark_lu_installed(&portable).is_err());+ assert!(!is_lu_installed(&portable));+ }+}diff --git a/src-tauri/src/commands/install/comfy_repair.rs b/src-tauri/src/commands/install/comfy_repair.rsindex dfe60a9a..3ec2617f 100644--- a/src-tauri/src/commands/install/comfy_repair.rs+++ b/src-tauri/src/commands/install/comfy_repair.rs@@ -936,7 +936,9 @@ fn reset_install_status_for_new_run(state: &AppState) {}/// Update an existing ComfyUI install in place: `git pull --ff-only` plus a-/// venv-aware `pip install -r requirements.txt`. The 2.5.8 local Create lanes+/// venv-aware `pip install -r requirements.txt`. Since 3.0.9 a ComfyUI that+/// LU cloned itself is set to the pinned release instead of pulled+/// (comfy_pin.rs); a ComfyUI the customer brought keeps the pull. The 2.5.8 local Create lanes/// (music / talking character / extend / motion) need node classes that ship/// with current ComfyUI cores, and the UI gates on node PRESENCE, so when the/// nodes are missing this command is the one-click "Update ComfyUI" path.@@ -1228,6 +1230,31 @@ pub fn update_comfyui(state: State<'_, AppState>, app: tauri::AppHandle) -> Resu}};+ // 3.0.9: a ComfyUI LU cloned itself is set to the release LU tested+ // (comfy_pin.rs: fetch the tags, check the pinned one out), never+ // pulled to master. A ComfyUI the customer brought along has no LU+ // marker and keeps the fast-forward pull of its own branch below.+ if super::comfy_pin::is_lu_installed(&comfy_dir) {+ let tag = super::comfy_pin::COMFYUI_PINNED_TAG;+ update("installing", &format!("Step 1/3: Setting ComfyUI to the tested release {tag}..."));+ match super::comfy_pin::checkout_pinned_tag(&comfy_dir, tag, true) {+ Ok(super::comfy_pin::PinOutcome::AlreadyThere) => {+ update("installing", &format!("ComfyUI is already on {tag}."));+ }+ Ok(super::comfy_pin::PinOutcome::Moved) => {+ update("installing", &format!("ComfyUI moved to {tag}."));+ }+ Err(e) => {+ // Nothing moved: checkout_pinned_tag only checks out a tag+ // it found, so the checkout is still on `old_commit`.+ update(+ "error",+ &format!("Could not set ComfyUI to {tag}. Nothing was changed.\n\n{e}"),+ );+ return;+ }+ }+ } else {update("installing", "Step 1/3: Pulling the latest ComfyUI...");let mut pull = crate::process_util::foreign_system_command("git");// --ff-only: a user-modified checkout must not silently merge; surface@@ -1264,6 +1291,7 @@ pub fn update_comfyui(state: State<'_, AppState>, app: tauri::AppHandle) -> Resureturn;}}+ }update("installing",diff --git a/src-tauri/src/commands/install/mod.rs b/src-tauri/src/commands/install/mod.rsindex 99c708e0..a79d5149 100644--- a/src-tauri/src/commands/install/mod.rs+++ b/src-tauri/src/commands/install/mod.rs@@ -63,6 +63,7 @@ mod download;pub(crate) mod git;mod comfy_job;mod comfy_install;+mod comfy_pin;mod comfy_repair;mod env_check;mod ollama;@@ -105,6 +106,7 @@ mod tests {("children.rs", include_str!("children.rs")),("comfy_install.rs", include_str!("comfy_install.rs")),("comfy_job.rs", include_str!("comfy_job.rs")),+ ("comfy_pin.rs", include_str!("comfy_pin.rs")),("comfy_repair.rs", include_str!("comfy_repair.rs")),("custom_node_packs.rs", include_str!("custom_node_packs.rs")),("custom_nodes.rs", include_str!("custom_nodes.rs")),diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 1a34c60b..f0960fe4 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -7,6 +7,8 @@ pub mod character_files;#[cfg(desktop)]pub mod cloud_file;pub mod repo_map;+// Which attention flag a ComfyUI that LU starts gets (Comfy Kitchen, flash).+pub mod comfy_attention;pub mod comfy_folders;pub mod comfy_user_paths;pub mod comfy_ws;@@ -80,6 +82,10 @@ pub mod remote;pub mod remote_chats;pub mod remote_create;pub mod video_thumb;+// Colour settle across the seams of a long video, on ComfyUI's Python.+// Desktop only: it starts a process.+#[cfg(desktop)]+pub mod video_settle;pub mod win_firewall;pub mod remote_sealed;pub mod runtime_folder;diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rsindex c0c0ae51..dc55a6f7 100644--- a/src-tauri/src/commands/process.rs+++ b/src-tauri/src/commands/process.rs@@ -1,4 +1,5 @@use crate::os_error;+use crate::commands::comfy_attention;use crate::python::python_command;use std::collections::HashMap;use std::fs;@@ -931,6 +932,23 @@ pub(crate) fn launch_python(}}+/// The interpreter a ComfyUI start in `comfy_dir` would use, for a helper+/// script that needs ComfyUI's packages (numpy, av) and nothing of its own,+/// such as the colour settle of a long video (commands/video_settle.rs). The+/// same order as both start paths: the portable's `python_embeded` (beside+/// the folder or inside it), the install's venv, the Python that holds its+/// torch. Errors carry the same sentences the start would show.+pub(crate) fn comfy_tool_python(state: &AppState, comfy_dir: &Path) -> Result<String, String> {+ let embedded = |base: &Path| {+ let candidate = base.join("python_embeded").join("python.exe");+ candidate.exists().then(|| candidate.to_string_lossy().to_string())+ };+ let bundled = comfy_dir.parent().and_then(embedded).or_else(|| embedded(comfy_dir));+ let venv_state = crate::python::comfy_venv_state(comfy_dir);+ let system_python = state.python_bin.lock().unwrap().clone();+ launch_python(bundled.as_deref(), &venv_state, comfy_dir, || bound_comfy_python(comfy_dir, &system_python))+}+/// Collect the system Python paths we might want to probe. Mirrors the/// search order in `python::get_python_bin` but returns *all* hits, not/// just the first — so the carcass check works even when the user has@@ -2009,7 +2027,7 @@ pub async fn start_comfyui(app: tauri::AppHandle) -> Result<serde_json::Value, S}pub(crate) fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String> {- let _gate = start_gate(&COMFY_START);+ let gate = start_gate(&COMFY_START);// If user pointed LU at a remote ComfyUI, we have no local process to spawn.// Just report status — the remote side is responsible for running ComfyUI.{@@ -2176,6 +2194,7 @@ pub(crate) fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Val"--port", &port_str,"--enable-cors-header", comfy_cors_origin(),];+ let mut device_flag: Option<&'static str> = None;if needs_cpu_fallback {comfy_args.push("--cpu");if let Some(reason) = cpu_flag_reason(gpu_mode, cpu_decision.baseline, cpu_decision.torch_gpu) {@@ -2185,18 +2204,32 @@ pub(crate) fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Valcomfy_launch_device_flag(&python, gpu_mode, cpu_decision.baseline, Some(&state.comfy_gpu_cache)){comfy_args.push(flag);+ device_flag = Some(flag);println!("[ComfyUI] torch-directml found in this environment, starting ComfyUI with {flag}");}- // Auto-enable Flash Attention when the package actually imports in THIS- // python (2026-06-11: measured 4-5x faster WAN video sampling vs- // pytorch SDPA on a 12 GB 3060). ComfyUI only uses FA2 with the flag, so- // an installed wheel does nothing without this. The real-import probe- // guarantees we never pass the flag on a broken install (ComfyUI would- // error at startup); probe result is cached per python path. CPU mode- // skips it — flash-attn is CUDA-only.- if !needs_cpu_fallback && flash_attention_cached(state, &python) {- comfy_args.push("--use-flash-attention");- println!("[ComfyUI] flash-attn detected in {} — enabling Flash Attention", python);+ // One attention flag at most (comfy_attention.rs): Comfy Kitchen on a+ // CUDA or ROCm torch with ComfyUI 0.32.0+, otherwise Flash Attention when+ // the package actually imports in THIS python (2026-06-11: measured 4-5x+ // faster WAN video sampling vs pytorch SDPA on a 12 GB 3060). ComfyUI only+ // uses FA2 with the flag, so an installed wheel does nothing without it.+ // The real-import probes guarantee we never pass a flag on a broken+ // install (ComfyUI would error at startup); results are cached per python+ // path. CPU mode skips both, flash-attn is CUDA-only.+ let attention = comfy_attention_choice(+ state,+ &python,+ comfy_dir,+ needs_cpu_fallback,+ device_flag,+ cpu_decision.baseline,+ );+ if let Some(flag) = attention.flag {+ comfy_args.push(flag);+ if flag == comfy_attention::CK_FLAG {+ println!("[ComfyUI] comfy_kitchen imports in {python}, enabling Comfy Kitchen attention ({flag})");+ } else {+ println!("[ComfyUI] flash-attn detected in {python}, enabling Flash Attention");+ }}// The folder under Settings -> Storage, when it holds ComfyUI-shaped// subfolders (GH #122). ComfyUI lists only what sits under its own models@@ -2360,6 +2393,20 @@ pub(crate) fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Val};if let Some(code) = early_exit {wait_for_output_readers(&readers_done, COMFY_READER_SETTLE);+ // The same fallback as the longer watch further down, for a ComfyUI+ // that refused the ck flag right in argparse: one start without it.+ if attention.ck_unproven {+ attention.remember(comfy_dir, false);+ *state.comfy_start_at.lock().unwrap() = None;+ error!(python = %python, "comfyui exited at once with the ck attention flag, starting again without it");+ println!(+ "[ComfyUI] Exited within the first seconds with {}, starting again without it",+ comfy_attention::CK_FLAG+ );+ // Gate handed back for the second start, as further down.+ drop(gate);+ return start_comfyui_blocking(state);+ }let tail: Vec<String> = state.comfy_output.lock()@@ -2378,11 +2425,140 @@ pub(crate) fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Val}*state.comfy_start_at.lock().unwrap() = Some(std::time::Instant::now());+ // A ck start that has not proven itself on this folder and version is+ // watched until its port answers. The two second watch above cannot see+ // the failure: ComfyUI rejects the attention backend only after the torch+ // import, many seconds in. The child already sits in `comfy_process`, so+ // the panel reads "starting" meanwhile and Stop still reaches it.+ if attention.ck_unproven {+ match watch_own_ck_start(state, port) {+ comfy_attention::CkWatch::Proven => attention.remember(comfy_dir, true),+ comfy_attention::CkWatch::DiedEarly => {+ wait_for_output_readers(&readers_done, COMFY_READER_SETTLE);+ attention.remember(comfy_dir, false);+ *state.comfy_start_at.lock().unwrap() = None;+ error!(python = %python, "comfyui died with the ck attention flag, starting again without it");+ println!(+ "[ComfyUI] Exited before the port answered with {}, starting again without it",+ comfy_attention::CK_FLAG+ );+ // `remember` also marks the flag failed for this run, so the+ // second start goes without it even when config.json could+ // not be written. The gate is handed back first, the second+ // start takes it again: a click that slips in between finds+ // the same "no ck" and the second start then reports it.+ drop(gate);+ return start_comfyui_blocking(state);+ }+ comfy_attention::CkWatch::Undecided => {}+ }+ }+println!("[ComfyUI] Started");info!("comfyui started");Ok(serde_json::json!({"status": "started", "path": comfy_path}))}+/// What the start decided about attention, and what it must remember after.+struct AttentionChoice {+ /// The one attention flag on the command line, if any.+ flag: Option<&'static str>,+ /// The flag is `--use-ck-attention` and no earlier start of this folder+ /// and version has shown whether it works.+ ck_unproven: bool,+ /// The ComfyUI version the decision was made for.+ version: Option<comfy_attention::ComfyVersion>,+}++impl AttentionChoice {+ /// Write the outcome of an unproven ck start to the app's config.json.+ /// A failure is also noted for the rest of this run, which is what keeps+ /// the retry from looping when the file cannot be written.+ fn remember(&self, comfy_dir: &Path, works: bool) {+ if !works {+ comfy_attention::note_ck_failed_this_run();+ }+ if let Some(v) = self.version {+ comfy_attention::remember_ck_in(&crate::os_paths::app_config_json(), comfy_dir, v, works);+ }+ }+}++/// The attention decision both start paths share (comfy_attention.rs has the+/// rule). Gathers the facts, asks the cheap ones first and probes an import+/// only when the answer still matters.+fn comfy_attention_choice(+ state: &AppState,+ python: &str,+ comfy_dir: &Path,+ needs_cpu: bool,+ device_flag: Option<&str>,+ baseline_needs_cpu: bool,+) -> AttentionChoice {+ let version = comfy_attention::read_comfyui_version(comfy_dir);+ let remembered = version+ .and_then(|v| comfy_attention::remembered_ck_in(&crate::os_paths::app_config_json(), comfy_dir, v));+ // Without an NVIDIA driver the torch device tells ROCm ("cuda") from XPU+ // and the rest. Same cache as the --cpu decision, so Auto pays nothing+ // extra; only asked when it can still change the answer.+ let torch_device = if baseline_needs_cpu && !needs_cpu && device_flag.is_none() {+ comfy_gpu_device_cached(python, Some(&state.comfy_gpu_cache)).flatten()+ } else {+ None+ };+ let facts = comfy_attention::CkFacts {+ os: std::env::consts::OS,+ needs_cpu,+ device_flag,+ nvidia_driver: !baseline_needs_cpu,+ torch_device,+ comfy_version: version,+ switched_off: comfy_attention::ck_switched_off() || comfy_attention::ck_failed_this_run(),+ remembered,+ };+ if remembered == Some(false) {+ println!(+ "[ComfyUI] {} is off for this ComfyUI: an earlier start with it exited before the port answered",+ comfy_attention::CK_FLAG+ );+ }+ let flag = comfy_attention::pick_attention_flag(+ needs_cpu,+ comfy_attention::ck_attention_eligible(&facts),+ || comfy_attention::comfy_kitchen_cached(python, version),+ || flash_attention_cached(state, python),+ );+ AttentionChoice {+ flag,+ ck_unproven: flag == Some(comfy_attention::CK_FLAG) && remembered != Some(true),+ version,+ }+}++/// Watch the ComfyUI in `comfy_process` until the port answers or the child+/// exits, for [`comfy_attention::CK_PROOF_WATCH`] at most. The lock is held+/// only for one `try_wait` per round, never across the HTTP probe or the+/// sleep. A child that Stop took away reads as undecided.+fn watch_own_ck_start(state: &AppState, port: u16) -> comfy_attention::CkWatch {+ comfy_attention::watch_ck_start(+ || {+ let mut proc = state.comfy_process.lock().unwrap();+ let child = proc.as_mut()?;+ match child.try_wait() {+ Ok(Some(_)) => {+ *proc = None;+ Some(true)+ }+ Ok(None) => Some(false),+ Err(_) => None,+ }+ },+ || is_comfyui_running_on_port(port),+ comfy_attention::CK_PROOF_WATCH,+ std::time::Duration::from_secs(1),+ )+}+// ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread.// The State borrow cannot cross into the blocking pool, so the handle is// re-resolved there from the AppHandle (same pattern as engine.rs/whisper.rs).@@ -3341,6 +3517,7 @@ pub fn auto_start_comfyui(state: &AppState) {"--port", &port_str,"--enable-cors-header", comfy_cors_origin(),];+ let mut auto_device_flag: Option<&'static str> = None;if auto_needs_cpu {comfy_args.push("--cpu");if let Some(reason) = cpu_flag_reason(auto_gpu_mode, auto_decision.baseline, auto_decision.torch_gpu) {@@ -3353,17 +3530,27 @@ pub fn auto_start_comfyui(state: &AppState) {Some(&state.comfy_gpu_cache),) {comfy_args.push(flag);+ auto_device_flag = Some(flag);println!("[ComfyUI] Auto-start: torch-directml found, starting with {flag}");}- // Mirror start_comfyui: auto-enable Flash Attention (FA2) when it- // actually imports in this python. Boot auto-start previously never- // passed the flag, so auto-started ComfyUI ran WAN video 4-5x slower- // than a manual start even with flash-attn installed. The probe is- // cached per python; an absent package fails fast, so the rare cost- // is one slow first-probe on a cold boot with flash-attn present.- if !auto_needs_cpu && flash_attention_cached(state, &python) {- comfy_args.push("--use-flash-attention");- println!("[ComfyUI] Auto-start: flash-attn detected — enabling Flash Attention");+ // Mirror start_comfyui: the same single attention flag (Comfy+ // Kitchen, else Flash Attention when it actually imports in this+ // python). Boot auto-start previously never passed the flash flag,+ // so auto-started ComfyUI ran WAN video 4-5x slower than a manual+ // start even with flash-attn installed. The probes are cached per+ // python; an absent package fails fast, so the rare cost is one+ // slow first-probe on a cold boot with the package present.+ let auto_attention = comfy_attention_choice(+ state,+ &python,+ comfy_dir,+ auto_needs_cpu,+ auto_device_flag,+ auto_decision.baseline,+ );+ if let Some(flag) = auto_attention.flag {+ comfy_args.push(flag);+ println!("[ComfyUI] Auto-start: enabling {flag}");}if let Some(file) = &auto_extra {comfy_args.push("--extra-model-paths-config");@@ -3418,6 +3605,25 @@ pub fn auto_start_comfyui(state: &AppState) {}*state.comfy_process.lock().unwrap() = Some(child);+ // Same proof as the manual start: an unproven ck start is+ // watched until its port answers. This runs on the setup+ // thread, so the wait blocks nothing the user sees.+ if auto_attention.ck_unproven {+ match watch_own_ck_start(state, port) {+ comfy_attention::CkWatch::Proven => auto_attention.remember(comfy_dir, true),+ comfy_attention::CkWatch::DiedEarly => {+ auto_attention.remember(comfy_dir, false);+ println!(+ "[ComfyUI] Auto-start: exited before the port answered with {}, starting again without it",+ comfy_attention::CK_FLAG+ );+ // `remember` marked the flag failed for this+ // run, so this second pass goes without it.+ return auto_start_comfyui(state);+ }+ comfy_attention::CkWatch::Undecided => {}+ }+ }println!("[ComfyUI] Started");}Err(e) => println!("[ComfyUI] Failed to start: {}", e),diff --git a/src-tauri/src/commands/video_settle.py b/src-tauri/src/commands/video_settle.pynew file mode 100644index 00000000..8bc31ee8--- /dev/null+++ b/src-tauri/src/commands/video_settle.py@@ -0,0 +1,255 @@+"""Colour settle for a video made of several sections laid end to end.++LU writes this file into a private temp folder and runs it with ComfyUI's own+Python (``python -I video_settle.py --input A --output B --boundaries 81,157+--window 5``). Only numpy and PyAV (``av``) are imported besides the standard+library; both are in ComfyUI's requirements.txt.++Every boundary is the index of the first frame of a new section. Each section+is matched to the one before it, as that one looks AFTER its own correction:+the last ``window`` corrected frames before the boundary are the reference,+the first ``window`` frames of the new section the sample. Per channel++ gain = clamp(std_ref / std_cur, 0.8, 1.25)+ f' = (f - mean_cur) * gain + mean_ref++is applied to every frame from the boundary to the next one (or the end).+Chained like this, every section hangs on the first one and the corrections+do not add up their own errors.++The video is streamed: at most ``window`` corrected frames and ``window``+uncorrected ones are held at a time, so the length of the video does not+decide the memory it needs. Frames above MAX_PIXELS are refused outright.++The result goes to stdout as one JSON line, the last line printed. An error+is the same shape with ``ok: false`` and exit code 2.+"""++import argparse+import json+import sys+from collections import deque+from fractions import Fraction++import av+import numpy as np++GAIN_MIN = 0.8+GAIN_MAX = 1.25+# 4096 x 2304: far above anything LU renders, low enough that 2 x window+# frames in float stay well under a gigabyte.+MAX_PIXELS = 4096 * 2304+MAX_WINDOW = 60+++def fail(message):+ print(json.dumps({"ok": False, "error": message}))+ sys.exit(2)+++def parse_boundaries(text):+ out = set()+ for part in (text or "").split(","):+ part = part.strip()+ if not part:+ continue+ try:+ out.add(int(part))+ except ValueError:+ fail("Boundary is not a frame number: %r" % part)+ return sorted(out)+++def channel_stats(frames):+ """Mean and standard deviation per channel over a list of HxWx3 uint8."""+ stack = np.stack(frames).astype(np.float64)+ flat = stack.reshape(-1, 3)+ return flat.mean(axis=0), flat.std(axis=0)+++def make_transform(ref_frames, cur_frames):+ ref_mean, ref_std = channel_stats(ref_frames)+ cur_mean, cur_std = channel_stats(cur_frames)+ gain = np.ones(3)+ for c in range(3):+ if cur_std[c] > 1e-6:+ gain[c] = ref_std[c] / cur_std[c]+ gain = np.clip(gain, GAIN_MIN, GAIN_MAX)+ seam = {+ "refMean": [round(float(v), 3) for v in ref_mean],+ "curMean": [round(float(v), 3) for v in cur_mean],+ "refStd": [round(float(v), 3) for v in ref_std],+ "curStd": [round(float(v), 3) for v in cur_std],+ "gain": [round(float(v), 4) for v in gain],+ "refFrames": len(ref_frames),+ "curFrames": len(cur_frames),+ }+ return (cur_mean, gain, ref_mean), seam+++def apply_transform(frame, transform):+ if transform is None:+ return frame+ cur_mean, gain, ref_mean = transform+ out = (frame.astype(np.float32) - cur_mean.astype(np.float32)) * gain.astype(np.float32)+ out += ref_mean.astype(np.float32)+ np.clip(out, 0.0, 255.0, out=out)+ return np.rint(out).astype(np.uint8)+++def add_audio_stream(output, in_audio):+ """A remux copy of the input's audio stream, or None with the reason."""+ try:+ if hasattr(output, "add_stream_from_template"):+ return output.add_stream_from_template(in_audio), None+ return output.add_stream(template=in_audio), None+ except Exception as exc: # the container may not take this codec+ return None, "audio not copied: %s" % exc+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("--input", required=True)+ parser.add_argument("--output", required=True)+ parser.add_argument("--boundaries", default="")+ parser.add_argument("--window", type=int, default=5)+ parser.add_argument("--crf", type=int, default=18)+ args = parser.parse_args()++ window = args.window+ if window < 1 or window > MAX_WINDOW:+ fail("window must be between 1 and %d" % MAX_WINDOW)+ requested = parse_boundaries(args.boundaries)++ try:+ source = av.open(args.input)+ except Exception as exc:+ fail("Cannot open the video: %s" % exc)+ if not source.streams.video:+ fail("The file has no video stream.")+ in_video = source.streams.video[0]+ in_audio = source.streams.audio[0] if source.streams.audio else None+ width = in_video.codec_context.width+ height = in_video.codec_context.height+ if width * height > MAX_PIXELS:+ fail("Frames of %dx%d are larger than this step handles." % (width, height))+ rate = in_video.average_rate or in_video.guessed_rate or Fraction(24, 1)+ rate = Fraction(rate)+ # yuv420p needs even sides; an odd one loses its last row or column.+ out_w, out_h = width - (width % 2), height - (height % 2)++ output = av.open(args.output, mode="w")+ out_video = output.add_stream("h264", rate=rate)+ out_video.width = out_w+ out_video.height = out_h+ out_video.pix_fmt = "yuv420p"+ try:+ out_video.options = {"crf": str(args.crf)}+ except Exception:+ pass+ time_base = Fraction(1, 1) / rate+ out_audio, audio_note = (None, None)+ if in_audio is not None:+ out_audio, audio_note = add_audio_stream(output, in_audio)++ written = 0++ def write(frame_array):+ nonlocal written+ if frame_array.shape[1] != out_w or frame_array.shape[0] != out_h:+ frame_array = frame_array[:out_h, :out_w]+ vf = av.VideoFrame.from_ndarray(np.ascontiguousarray(frame_array), format="rgb24")+ vf.pts = written+ vf.time_base = time_base+ for packet in out_video.encode(vf):+ output.mux(packet)+ written += 1++ pending = deque(requested)+ while pending and pending[0] <= 0:+ pending.popleft()+ ignored = [b for b in requested if b <= 0]+ seams = []+ recent = deque(maxlen=window) # last corrected frames+ transform = None+ sample = None # raw frames collected after a boundary+ sample_start = None+ sample_end = None+ index = 0++ def close_sample():+ nonlocal transform, sample, sample_start+ new_transform, seam = make_transform(list(recent), sample)+ seam["frame"] = sample_start+ seams.append(seam)+ transform = new_transform+ for raw in sample:+ fixed = apply_transform(raw, transform)+ write(fixed)+ recent.append(fixed)+ sample = None+ sample_start = None++ try:+ for frame in source.decode(in_video):+ raw = frame.to_ndarray(format="rgb24")+ if pending and index == pending[0]:+ if sample is not None:+ close_sample()+ pending.popleft()+ sample, sample_start = [], index+ # The sample stays inside its own section.+ sample_end = min(index + window, pending[0] if pending else index + window)+ if sample is not None:+ sample.append(raw)+ if index + 1 >= sample_end:+ close_sample()+ else:+ fixed = apply_transform(raw, transform)+ write(fixed)+ recent.append(fixed)+ index += 1+ if sample is not None:+ close_sample()+ for packet in out_video.encode():+ output.mux(packet)+ except SystemExit:+ raise+ except Exception as exc:+ output.close()+ fail("Processing failed at frame %d: %s" % (index, exc))++ ignored.extend(pending)+ source.close()++ audio_copied = False+ if out_audio is not None:+ try:+ with av.open(args.input) as again:+ stream = again.streams.audio[0]+ for packet in again.demux(stream):+ if packet.dts is None:+ continue+ packet.stream = out_audio+ output.mux(packet)+ audio_copied = True+ except Exception as exc:+ audio_note = "audio not copied: %s" % exc+ output.close()++ print(json.dumps({+ "ok": True,+ "frames": written,+ "width": out_w,+ "height": out_h,+ "fps": float(rate),+ "window": window,+ "seams": seams,+ "ignoredBoundaries": ignored,+ "audio": audio_copied,+ "note": audio_note,+ }))+++if __name__ == "__main__":+ main()diff --git a/src-tauri/src/commands/video_settle.rs b/src-tauri/src/commands/video_settle.rsnew file mode 100644index 00000000..5b0f99cc--- /dev/null+++ b/src-tauri/src/commands/video_settle.rs@@ -0,0 +1,526 @@+//! Colour settle for a long video made of several sections (3.0.9).+//!+//! A 30 second clip is rendered as sections that each continue from the last+//! frame of the one before. Every section drifts a little in brightness,+//! contrast and tint, and over five or six sections that adds up to a visible+//! jump at every seam. `video_color_settle` takes the finished, already+//! concatenated clip and matches each section to the corrected one before it+//! (the rule is in video_settle.py, which runs on ComfyUI's own Python with+//! numpy and PyAV, both in ComfyUI's requirements).+//!+//! The frontend only knows ComfyUI's own file names (filename, subfolder,+//! type), the same triple the gallery shows. The file is resolved here inside+//! the output or input folder of the ComfyUI LU manages, by the same rules as+//! the gallery delete (gallery_files.rs) plus a canonical check against+//! symlinks pointing out of the folder. The result lands beside the source as+//! `<stem>_settled.mp4` (`_settled_2`, `_3`, ... when taken), so the original+//! stays untouched.+//!+//! Without a local ComfyUI that LU manages (a remote host, a Mac, none found)+//! the answer starts with [`NOT_AVAILABLE`], which the frontend skips quietly.++use std::ffi::OsString;+use std::io::Read;+use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::time::{Duration, Instant};++use serde::{Deserialize, Serialize};+use tauri::Manager;++use crate::state::AppState;++/// The script, embedded so it cannot be missing or swapped on disk between+/// releases. Written to a private temp folder for each run.+const SCRIPT: &str = include_str!("video_settle.py");++/// Every refusal that means "this machine cannot do it" starts with this, so+/// the frontend can skip the step without showing an error.+pub const NOT_AVAILABLE: &str = "not available";++/// Default frames on each side of a seam that the statistics are taken over.+pub(crate) const DEFAULT_WINDOW: u32 = 5;+/// Upper bound, the same as the script's own.+pub(crate) const MAX_WINDOW: u32 = 60;+/// A 30 second 832x480 clip takes well under a minute; ten minutes covers a+/// slow disk and a long clip and still ends a hung decoder.+const RUN_TIMEOUT: Duration = Duration::from_secs(600);+/// Video containers a section render can come out as.+const VIDEO_EXTENSIONS: &[&str] = &["mp4", "webm", "mov", "mkv"];++/// One seam as the script measured it. Means and deviations are per RGB+/// channel on the 0..255 scale.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct SettleSeam {+ /// First frame of the section this seam starts.+ pub frame: u32,+ pub ref_mean: [f64; 3],+ pub cur_mean: [f64; 3],+ pub ref_std: [f64; 3],+ pub cur_std: [f64; 3],+ /// The contrast factor applied, already clamped to 0.8..1.25.+ pub gain: [f64; 3],+ pub ref_frames: u32,+ pub cur_frames: u32,+}++/// What the script prints as its last line.+#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+struct ScriptReport {+ ok: bool,+ #[serde(default)]+ error: Option<String>,+ #[serde(default)]+ frames: u32,+ #[serde(default)]+ width: u32,+ #[serde(default)]+ height: u32,+ #[serde(default)]+ fps: f64,+ #[serde(default)]+ seams: Vec<SettleSeam>,+ #[serde(default)]+ ignored_boundaries: Vec<i64>,+ #[serde(default)]+ audio: bool,+ #[serde(default)]+ note: Option<String>,+}++/// What the command returns.+#[derive(Debug, Clone, Serialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct SettleReport {+ /// The new file's name, in the same folder and subfolder as the source.+ pub filename: String,+ pub subfolder: String,+ /// "output" or "input", as passed in.+ pub folder_type: String,+ pub frames: u32,+ pub width: u32,+ pub height: u32,+ pub fps: f64,+ pub window: u32,+ pub seams: Vec<SettleSeam>,+ /// Boundaries that fell outside the clip and were skipped.+ pub ignored_boundaries: Vec<i64>,+ /// The source's audio track was copied over unchanged.+ pub audio: bool,+ pub note: Option<String>,+}++/// The ComfyUI folder a file triple names: `output` or `input`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ComfyFolder {+ Output,+ Input,+}++impl ComfyFolder {+ pub(crate) fn parse(s: &str) -> Result<Self, String> {+ match s {+ "output" => Ok(Self::Output),+ "input" => Ok(Self::Input),+ other => Err(format!("Unknown ComfyUI folder type {other:?}, expected \"output\" or \"input\".")),+ }+ }+}++/// The video a (filename, subfolder) pair names inside `base`, proven to be+/// an existing file that stays inside `base` after every symlink is resolved.+pub(crate) fn resolve_source(base: &Path, filename: &str, subfolder: &str) -> Result<PathBuf, String> {+ use crate::commands::download::{safe_subfolder, sanitize_filename};+ if filename.is_empty() || sanitize_filename(filename) != filename || filename.starts_with('.') {+ return Err("That file name is not a plain file name.".to_string());+ }+ if !subfolder.is_empty() {+ safe_subfolder(subfolder)?;+ }+ let ext = Path::new(filename)+ .extension()+ .and_then(|e| e.to_str())+ .map(str::to_ascii_lowercase)+ .unwrap_or_default();+ if !VIDEO_EXTENSIONS.contains(&ext.as_str()) {+ return Err("Only a video file (mp4, webm, mov, mkv) can be settled.".to_string());+ }+ let dir = if subfolder.is_empty() { base.to_path_buf() } else { base.join(subfolder.replace('\\', "/")) };+ let candidate = dir.join(filename);+ let real_base = base+ .canonicalize()+ .map_err(|_| format!("The ComfyUI folder {} does not exist.", base.display()))?;+ let real = candidate+ .canonicalize()+ .map_err(|_| format!("The video {filename} is not in the ComfyUI folder."))?;+ if !real.starts_with(&real_base) {+ return Err("That file lies outside the ComfyUI folder.".to_string());+ }+ if !real.is_file() {+ return Err(format!("The video {filename} is not a file."));+ }+ Ok(real)+}++/// `<stem>_settled.mp4` in `dir`, or the first `<stem>_settled_<n>.mp4` that+/// is free. Never a name that exists.+pub(crate) fn settled_name(dir: &Path, source_name: &str) -> String {+ let stem = Path::new(source_name).file_stem().and_then(|s| s.to_str()).unwrap_or("video");+ let first = format!("{stem}_settled.mp4");+ if !dir.join(&first).exists() {+ return first;+ }+ (2u32..)+ .map(|n| format!("{stem}_settled_{n}.mp4"))+ .find(|name| !dir.join(name).exists())+ .expect("an unbounded counter always finds a free name")+}++/// Sorted, without duplicates and without frame 0 (the first section has+/// nothing before it to match).+pub(crate) fn normalize_boundaries(mut boundaries: Vec<u32>) -> Vec<u32> {+ boundaries.retain(|b| *b > 0);+ boundaries.sort_unstable();+ boundaries.dedup();+ boundaries+}++/// The window the script runs with: the default when none is given, an+/// error outside 1..=MAX_WINDOW.+pub(crate) fn effective_window(window: Option<u32>) -> Result<u32, String> {+ match window.unwrap_or(DEFAULT_WINDOW) {+ w @ 1..=MAX_WINDOW => Ok(w),+ w => Err(format!("window {w} is outside 1..={MAX_WINDOW}")),+ }+}++/// The interpreter's argument list: isolated mode, the script, then every+/// path as its own argument. No shell ever sees these.+pub(crate) fn script_args(script: &Path, input: &Path, output: &Path, boundaries: &[u32], window: u32) -> Vec<OsString> {+ let list = boundaries.iter().map(u32::to_string).collect::<Vec<_>>().join(",");+ vec![+ "-I".into(),+ script.as_os_str().to_owned(),+ "--input".into(),+ input.as_os_str().to_owned(),+ "--output".into(),+ output.as_os_str().to_owned(),+ "--boundaries".into(),+ list.into(),+ "--window".into(),+ window.to_string().into(),+ ]+}++/// The report out of the script's stdout: the last line that is JSON. Lines+/// before it (a library warning) are ignored.+fn parse_script_output(stdout: &str) -> Result<ScriptReport, String> {+ stdout+ .lines()+ .rev()+ .map(str::trim)+ .filter(|l| l.starts_with('{'))+ .find_map(|l| serde_json::from_str::<ScriptReport>(l).ok())+ .ok_or_else(|| "The colour settle printed no report.".to_string())+}++/// The ComfyUI folder this machine manages, or the NOT_AVAILABLE refusal.+fn managed_comfy_dir(state: &AppState) -> Result<PathBuf, String> {+ if !crate::commands::process::comfy_supported_here() {+ return Err(format!("{NOT_AVAILABLE}: no local ComfyUI on this platform"));+ }+ let host = state.comfy_host.lock().map(|h| h.clone()).unwrap_or_default();+ if !crate::commands::process::is_local_host(&host) {+ return Err(format!("{NOT_AVAILABLE}: ComfyUI runs on another machine ({host})"));+ }+ let path = {+ let mut slot = state.comfy_path.lock().map_err(|e| e.to_string())?;+ if slot.is_none() {+ *slot = crate::commands::process::find_comfyui_path();+ }+ slot.clone()+ };+ let dir = path.map(PathBuf::from).filter(|p| p.is_dir());+ dir.ok_or_else(|| format!("{NOT_AVAILABLE}: no local ComfyUI found"))+}++/// Run `python args...` with a deadline, collecting stdout and stderr.+fn run_with_timeout(python: &str, args: &[OsString], timeout: Duration) -> Result<(bool, String, String), String> {+ let mut cmd = crate::python::python_command(python);+ cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());+ let mut child = cmd+ .spawn()+ .map_err(|e| format!("Could not start ComfyUI's Python ({python}): {}", crate::os_error::english(&e)))?;+ let drain = |pipe: Option<Box<dyn Read + Send>>| {+ std::thread::spawn(move || {+ let mut text = String::new();+ if let Some(mut p) = pipe {+ let _ = p.read_to_string(&mut text);+ }+ text+ })+ };+ let out = drain(child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>));+ let err = drain(child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>));+ let started = Instant::now();+ let status = loop {+ match child.try_wait() {+ Ok(Some(s)) => break s,+ Ok(None) if started.elapsed() >= timeout => {+ crate::commands::shell::kill_tree(child.id());+ let _ = child.kill();+ let _ = child.wait();+ return Err(format!("The colour settle took longer than {} minutes and was stopped.", timeout.as_secs() / 60));+ }+ Ok(None) => std::thread::sleep(Duration::from_millis(200)),+ Err(e) => return Err(format!("Waiting for the colour settle failed: {}", crate::os_error::english(&e))),+ }+ };+ Ok((status.success(), out.join().unwrap_or_default(), err.join().unwrap_or_default()))+}++fn settle_blocking(+ state: &AppState,+ filename: &str,+ subfolder: &str,+ folder_type: &str,+ boundaries: Vec<u32>,+ window: Option<u32>,+) -> Result<SettleReport, String> {+ let folder = ComfyFolder::parse(folder_type)?;+ let window = effective_window(window)?;+ let boundaries = normalize_boundaries(boundaries);+ let comfy_dir = managed_comfy_dir(state)?;+ let paths = crate::commands::comfy_user_paths::UserComfyPaths::discover(&comfy_dir);+ let base = match folder {+ ComfyFolder::Output => paths.output_dir_or(&comfy_dir),+ ComfyFolder::Input => paths.input_dir_or(&comfy_dir),+ };+ let input = resolve_source(&base, filename, subfolder)?;+ let python = crate::commands::process::comfy_tool_python(state, &comfy_dir)+ .map_err(|e| format!("{NOT_AVAILABLE}: {e}"))?;++ let out_dir = input.parent().ok_or("The video has no folder.")?.to_path_buf();+ // Written under a hidden name first and renamed at the end, so a failed or+ // stopped run never leaves a half file under the name the gallery shows.+ let partial = out_dir.join(format!(".lu-settle-{}-{}.mp4", std::process::id(), uuid::Uuid::new_v4().simple()));+ let (_script_dir, script) = crate::private_tmp::write_private_temp("lu-settle-", "video_settle.py", SCRIPT.as_bytes())?;+ let args = script_args(&script, &input, &partial, &boundaries, window);++ let run = run_with_timeout(&python, &args, RUN_TIMEOUT);+ let finish = || {+ let _ = std::fs::remove_file(&partial);+ };+ let (success, stdout, stderr) = run.inspect_err(|_| finish())?;+ let report = match parse_script_output(&stdout) {+ Ok(r) => r,+ Err(e) => {+ finish();+ let tail: String = stderr.lines().rev().take(6).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n");+ return Err(if tail.is_empty() { e } else { format!("{e}\n{tail}") });+ }+ };+ if !success || !report.ok {+ finish();+ return Err(report.error.unwrap_or_else(|| "The colour settle failed.".to_string()));+ }+ let name = settled_name(&out_dir, filename);+ if let Err(e) = std::fs::rename(&partial, out_dir.join(&name)) {+ finish();+ return Err(format!("Could not save {name}: {}", crate::os_error::english(&e)));+ }+ tracing::info!(target: "video", frames = report.frames, seams = report.seams.len(), "video colour settle done");+ Ok(SettleReport {+ filename: name,+ subfolder: subfolder.to_string(),+ folder_type: folder_type.to_string(),+ frames: report.frames,+ width: report.width,+ height: report.height,+ fps: report.fps,+ window,+ seams: report.seams,+ ignored_boundaries: report.ignored_boundaries,+ audio: report.audio,+ note: report.note,+ })+}++/// Settle the colour across the seams of a long video in ComfyUI's output+/// (or input) folder. `boundaries` are the frame indices where a new section+/// starts, `window` the frames per side the statistics use (default 5).+// ASYNC + spawn_blocking, like start_comfyui: the run takes seconds to+// minutes and must not sit on the main thread.+#[tauri::command]+pub async fn video_color_settle(+ app: tauri::AppHandle,+ filename: String,+ subfolder: String,+ folder_type: String,+ boundaries: Vec<u32>,+ window: Option<u32>,+) -> Result<SettleReport, String> {+ tokio::task::spawn_blocking(move || {+ let state = app.state::<AppState>();+ settle_blocking(&state, &filename, &subfolder, &folder_type, boundaries, window)+ })+ .await+ .map_err(|e| format!("video_color_settle task: {e}"))?+}++#[cfg(test)]+mod tests {+ use super::*;++ fn folder_with(files: &[&str]) -> tempfile::TempDir {+ let tmp = tempfile::tempdir().unwrap();+ for f in files {+ let p = tmp.path().join(f);+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();+ std::fs::write(p, b"x").unwrap();+ }+ tmp+ }++ #[test]+ fn a_gallery_triple_resolves_inside_the_folder() {+ let tmp = folder_with(&["long_00001.mp4", "video/long_00002.mp4"]);+ let base = tmp.path();+ let real = base.canonicalize().unwrap();+ assert_eq!(resolve_source(base, "long_00001.mp4", "").unwrap(), real.join("long_00001.mp4"));+ assert_eq!(resolve_source(base, "long_00002.mp4", "video").unwrap(), real.join("video").join("long_00002.mp4"));+ }++ #[test]+ fn nothing_leaves_the_folder() {+ let tmp = folder_with(&["out/a.mp4", "secret.mp4"]);+ let base = tmp.path().join("out");+ for (name, sub) in [+ ("../secret.mp4", ""),+ ("secret.mp4", ".."),+ ("secret.mp4", "x/../.."),+ ("a.mp4", "/etc"),+ ("a.mp4", "C:/Windows"),+ ("/etc/passwd", ""),+ ("..\\secret.mp4", ""),+ ] {+ assert!(resolve_source(&base, name, sub).is_err(), "{name:?} in {sub:?} was accepted");+ }+ }++ #[cfg(unix)]+ #[test]+ fn a_symlink_out_of_the_folder_is_refused() {+ let tmp = folder_with(&["out/keep.mp4", "elsewhere/clip.mp4"]);+ let base = tmp.path().join("out");+ std::os::unix::fs::symlink(tmp.path().join("elsewhere"), base.join("link")).unwrap();+ std::os::unix::fs::symlink(tmp.path().join("elsewhere/clip.mp4"), base.join("clip.mp4")).unwrap();+ assert!(resolve_source(&base, "clip.mp4", "link").is_err());+ assert!(resolve_source(&base, "clip.mp4", "").is_err());+ }++ #[test]+ fn only_existing_videos_are_taken() {+ let tmp = folder_with(&["a.png", "dir.mp4/inner.mp4"]);+ assert!(resolve_source(tmp.path(), "a.png", "").is_err(), "an image was accepted");+ assert!(resolve_source(tmp.path(), "missing.mp4", "").is_err(), "a missing file was accepted");+ assert!(resolve_source(tmp.path(), "dir.mp4", "").is_err(), "a folder was accepted");+ assert!(resolve_source(tmp.path(), "", "").is_err());+ assert!(resolve_source(tmp.path(), ".hidden.mp4", "").is_err());+ }++ #[test]+ fn the_new_name_never_overwrites() {+ let tmp = folder_with(&["clip.mp4"]);+ assert_eq!(settled_name(tmp.path(), "clip.mp4"), "clip_settled.mp4");+ std::fs::write(tmp.path().join("clip_settled.mp4"), b"x").unwrap();+ assert_eq!(settled_name(tmp.path(), "clip.mp4"), "clip_settled_2.mp4");+ std::fs::write(tmp.path().join("clip_settled_2.mp4"), b"x").unwrap();+ assert_eq!(settled_name(tmp.path(), "clip.mp4"), "clip_settled_3.mp4");+ // Always .mp4, whatever the source container was.+ assert_eq!(settled_name(tmp.path(), "take.webm"), "take_settled.mp4");+ }++ #[test]+ fn folder_type_window_and_boundaries() {+ assert_eq!(ComfyFolder::parse("output").unwrap(), ComfyFolder::Output);+ assert_eq!(ComfyFolder::parse("input").unwrap(), ComfyFolder::Input);+ assert!(ComfyFolder::parse("temp").is_err());+ assert!(ComfyFolder::parse("../output").is_err());+ assert_eq!(effective_window(None).unwrap(), 5);+ assert_eq!(effective_window(Some(12)).unwrap(), 12);+ assert!(effective_window(Some(0)).is_err());+ assert!(effective_window(Some(MAX_WINDOW + 1)).is_err());+ assert_eq!(normalize_boundaries(vec![157, 0, 81, 157]), vec![81, 157]);+ }++ #[test]+ fn every_path_is_its_own_argument_and_python_runs_isolated() {+ let args = script_args(+ Path::new("/tmp/lu-settle-x/video_settle.py"),+ Path::new("/c/out/my clip; rm -rf ~.mp4"),+ Path::new("/c/out/.lu-settle-1.mp4"),+ &[81, 157],+ 5,+ );+ let text: Vec<String> = args.iter().map(|a| a.to_string_lossy().to_string()).collect();+ assert_eq!(+ text,+ [+ "-I",+ "/tmp/lu-settle-x/video_settle.py",+ "--input",+ "/c/out/my clip; rm -rf ~.mp4",+ "--output",+ "/c/out/.lu-settle-1.mp4",+ "--boundaries",+ "81,157",+ "--window",+ "5",+ ]+ );+ }++ #[test]+ fn the_report_is_the_last_json_line() {+ let out = "some warning\n{\"ok\": true, \"frames\": 240, \"width\": 832, \"height\": 480, \"fps\": 16.0, \"window\": 5, \+ \"seams\": [{\"refMean\": [1,2,3], \"curMean\": [1,2,3], \"refStd\": [1,1,1], \"curStd\": [1,1,1], \+ \"gain\": [1,1,1], \"refFrames\": 5, \"curFrames\": 5, \"frame\": 80}], \"ignoredBoundaries\": [9999], \+ \"audio\": true, \"note\": null}\n";+ let r = parse_script_output(out).unwrap();+ assert!(r.ok);+ assert_eq!(r.frames, 240);+ assert_eq!(r.seams[0].frame, 80);+ assert_eq!(r.ignored_boundaries, vec![9999]);+ let err = parse_script_output("{\"ok\": false, \"error\": \"Cannot open the video\"}").unwrap();+ assert_eq!(err.error.as_deref(), Some("Cannot open the video"));+ assert!(parse_script_output("Traceback ...").is_err());+ }++ #[test]+ fn the_script_imports_nothing_but_numpy_av_and_the_standard_library() {+ let allowed = ["argparse", "json", "sys", "collections", "fractions", "av", "numpy"];+ for line in SCRIPT.lines().map(str::trim) {+ let module = if let Some(rest) = line.strip_prefix("import ") {+ rest.split([' ', ',', '.']).next()+ } else if let Some(rest) = line.strip_prefix("from ") {+ rest.split([' ', '.']).next()+ } else {+ None+ };+ if let Some(m) = module {+ assert!(allowed.contains(&m), "video_settle.py imports {m}");+ }+ }+ }++ #[test]+ fn the_command_is_registered_for_the_desktop_only() {+ const LIB: &str = include_str!("../lib.rs");+ let at = LIB.find("commands::video_settle::video_color_settle").expect("video_color_settle is not in generate_handler!");+ let before = LIB[..at].trim_end();+ assert!(before.ends_with("#[cfg(desktop)]"), "video_color_settle runs a Python process and must not reach a phone");+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 83f5d4ed..9c52dcc4 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1001,6 +1001,9 @@ pub fn run() {commands::media_cmds::video_stage_motion_video,#[cfg(desktop)]commands::media_cmds::video_stage_voice,+ // Colour settle across the seams of a long ComfyUI video (3.0.9).+ #[cfg(desktop)]+ commands::video_settle::video_color_settle,// The music engine of the Mac (ACE-Step 1.5). See commands/music.rs.#[cfg(desktop)]commands::media_cmds::mlx_music_status,diff --git a/src/api/__tests__/comfyui-bundles.test.ts b/src/api/__tests__/comfyui-bundles.test.tsindex e8b6ae97..c0b73037 100644--- a/src/api/__tests__/comfyui-bundles.test.ts+++ b/src/api/__tests__/comfyui-bundles.test.ts@@ -19,8 +19,9 @@ describe('Video Bundle Definitions', () => {// (21 GB each) and Pyramid Flow, whose builders emitted node class names no// wrapper registers. See wrapper-node-names.test.ts. 2026-10-01 adds// MiniMax H3 (video with sound). 2026-10-02 adds LTX 2.5 and FastH3.- // 2026-10-03 adds the MiniMax H3 turbo LoRA as an add-on.- expect(bundles.length).toBe(18)+ // 2026-10-03 adds the MiniMax H3 turbo LoRA as an add-on. 3.0.9 (B18)+ // adds Wan 2.2 A14B I2V and T2V Fast and the Wan 2.1 speed LoRAs.+ expect(bundles.length).toBe(21)})it('every bundle has required fields', () => {@@ -76,8 +77,9 @@ describe('Video Bundle Definitions', () => {it('I2V bundles have i2v: true', () => {const i2vBundles = bundles.filter(b => b.i2v)// SVD + FramePack + Wan 2.2 TI2V-5B + Rapid AIO (2.5.8). The CogVideoX 5B- // I2V bundle was pulled 2026-07-24 with the rest of its lane.- expect(i2vBundles.length).toBe(4)+ // I2V bundle was pulled 2026-07-24 with the rest of its lane. B18 adds+ // Wan 2.2 A14B I2V Fast.+ expect(i2vBundles.length).toBe(5)const i2vNames = i2vBundles.map(b => b.name)expect(i2vNames.some(n => n.includes('SVD'))).toBe(true)expect(i2vNames.some(n => n.includes('FramePack'))).toBe(true)diff --git a/src/api/__tests__/long-and-fast-video-graphs.test.ts b/src/api/__tests__/long-and-fast-video-graphs.test.tsnew file mode 100644index 00000000..96bf005f--- /dev/null+++ b/src/api/__tests__/long-and-fast-video-graphs.test.ts@@ -0,0 +1,219 @@+/**+ * B18 (3.0.9): the graphs behind Fast mode and long local clips.+ *+ * Fast Wan 14B with lightx2v's 4 step LoRAs: the high noise LoRA on+ * the high noise half, the low noise LoRA on the low half, each+ * half through ModelSamplingSD3 at shift 5. A fast run without+ * its LoRA stops with the file names instead of making mush.+ * Shift A quality Wan run gets the template's shift 8 (it had none).+ * Continue A later section loads the clip so far (LoadVideo,+ * GetVideoComponents), starts on its last frames, pads with its+ * first frame (ref_pad_image) and saves the whole clip: the+ * section without the repeated frames behind the clip so far.+ * Windows One pass past the native length: the family's context window+ * node on the model.+ *+ * Every class here is a core ComfyUI node (no custom node pack).+ *+ * Run: npx vitest run src/api/__tests__/long-and-fast-video-graphs.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++vi.mock('../comfyui-nodes', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../comfyui-nodes')>()+ return { ...actual, getAllNodeInfo: vi.fn() }+})+vi.mock('../backend', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../backend')>()+ return { ...actual, localFetch: vi.fn(), comfyuiUrl: (p: string) => `http://test${p}` }+})++import { buildDynamicWorkflow, WorkflowUnavailableError } from '../dynamic-workflow'+import { getAllNodeInfo } from '../comfyui-nodes'+import { localFetch } from '../backend'+import { classTypes, nodeAt, nodeOf, nodesOf } from './graph-test-support'+import type { ComfyApiGraph } from '../../types/comfy-graph'++const HIGH = 'Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf'+const LOW = 'Wan2.2-I2V-A14B-LowNoise-Q4_K_S.gguf'+const T2V_HIGH = 'Wan2.2-T2V-A14B-HighNoise-Q4_K_S.gguf'+const T2V_LOW = 'Wan2.2-T2V-A14B-LowNoise-Q4_K_S.gguf'+const LORA_HIGH = 'wan2.2_i2v_A14b_high_noise_lora_rank64_lightx2v_4step_1022.safetensors'+const LORA_LOW = 'wan2.2_i2v_A14b_low_noise_lora_rank64_lightx2v_4step_1022.safetensors'+const WAN21 = 'wan2.1_t2v_14B_fp8_e4m3fn.safetensors'+const WAN21_LORA = 'wan2.1_t2v_14b_lora_rank64_lightx2v_4step.safetensors'+const TI2V = 'wan2.2_ti2v_5B_fp16.safetensors'++const base = (loras: string[]): Record<string, unknown> => ({+ UNETLoader: { input: { required: { unet_name: [[WAN21, TI2V]] } } },+ UnetLoaderGGUF: { input: { required: { unet_name: [[HIGH, LOW, T2V_HIGH, T2V_LOW]] } } },+ CLIPLoader: { input: { required: { clip_name: [['umt5_xxl_fp8_e4m3fn_scaled.safetensors']] } } },+ VAELoader: { input: { required: { vae_name: [['wan_2.1_vae.safetensors', 'wan2.2_vae.safetensors']] } } },+ LoraLoader: { input: { required: { lora_name: [loras] } } },+ LoraLoaderModelOnly: { input: { required: { lora_name: [loras] } } },+ WanImageToVideo: {+ input: {+ required: { positive: ['CONDITIONING'], negative: ['CONDITIONING'], vae: ['VAE'], width: ['INT'], height: ['INT'], length: ['INT'], batch_size: ['INT'] },+ optional: { start_image: ['IMAGE'], clip_vision_output: ['CLIP_VISION_OUTPUT'], ref_pad_image: ['IMAGE'] },+ },+ output: ['CONDITIONING', 'CONDITIONING', 'LATENT'],+ },+ Wan22ImageToVideoLatent: { input: { required: {} } },+ WanContextWindowsManual: {+ input: {+ required: {+ model: ['MODEL'], context_length: ['INT', { default: 81 }], context_overlap: ['INT', { default: 30 }],+ context_schedule: [['standard_static', 'standard_uniform'], { default: 'standard_uniform' }],+ fuse_method: [['flat', 'pyramid'], { default: 'pyramid' }],+ freenoise: ['BOOLEAN', { default: true }], retain_first_frame: ['BOOLEAN', { default: false }],+ },+ },+ },+ EmptyHunyuanLatentVideo: { input: { required: {} } },+ ModelSamplingSD3: { input: { required: {} } },+ KSampler: { input: { required: {} } },+ KSamplerAdvanced: { input: { required: {} } },+ CLIPTextEncode: { input: { required: {} } },+ VAEDecodeTiled: { input: { required: {} } },+ ImageScale: { input: { required: {} } },+ LoadImage: { input: { required: {} } },+ LoadVideo: { input: { required: {} } },+ GetVideoComponents: { input: { required: {} } },+ ImageFromBatch: { input: { required: {} } },+ BatchImagesNode: { input: { required: {} } },+ CreateVideo: { input: { required: {} } },+ SaveVideo: { input: { required: {} } },+})++const serve = (nodes: Record<string, unknown>) => {+ vi.mocked(getAllNodeInfo).mockResolvedValue(nodes as never)+ vi.mocked(localFetch).mockImplementation((async () => ({+ ok: true, status: 200, json: async () => nodes, text: async () => JSON.stringify(nodes),+ })) as never)+}++const run = (model: string, extra: Record<string, unknown> = {}) => ({+ model, prompt: 'a fox runs through snow', negativePrompt: '',+ sampler: 'euler', scheduler: 'simple', steps: 4, cfgScale: 1,+ width: 832, height: 480, seed: 3, batchSize: 1, frames: 81, fps: 16, ...extra,+}) as never++/** The chain of model nodes a sampler reads from, down to the loader. */+function modelChain(wf: ComfyApiGraph, ref: unknown): string[] {+ const out: string[] = []+ let at = ref as [string, number] | undefined+ while (Array.isArray(at)) {+ const node = nodeAt(wf, at[0])!+ out.push(node.class_type === 'LoraLoaderModelOnly' ? `Lora(${node.inputs.lora_name})` : node.class_type === 'ModelSamplingSD3' ? `Shift(${node.inputs.shift})` : node.class_type)+ at = node.inputs.model as [string, number] | undefined+ }+ return out+}++describe('Fast mode: Wan 2.2 A14B with the lightx2v 4 step LoRAs', () => {+ beforeEach(() => serve(base([LORA_HIGH, LORA_LOW, WAN21_LORA])))++ it('each half gets its own LoRA and shift 5, split 2 + 2', async () => {+ const wf = await buildDynamicWorkflow(run(HIGH, { inputImage: 'start.png' }))+ const [high, low] = nodesOf(wf, 'KSamplerAdvanced').map(([, n]) => n)+ expect(modelChain(wf, high.inputs.model)).toEqual(['Shift(5)', `Lora(${LORA_HIGH})`, 'UnetLoaderGGUF'])+ expect(modelChain(wf, low.inputs.model)).toEqual(['Shift(5)', `Lora(${LORA_LOW})`, 'UnetLoaderGGUF'])+ expect(high.inputs).toMatchObject({ steps: 4, cfg: 1, start_at_step: 0, end_at_step: 2 })+ expect(low.inputs).toMatchObject({ steps: 4, cfg: 1, start_at_step: 2 })+ const loaders = nodesOf(wf, 'UnetLoaderGGUF').map(([, n]) => n.inputs.unet_name)+ expect(loaders.sort()).toEqual([HIGH, LOW].sort())+ })++ it('stops with the file names when a speed LoRA is missing', async () => {+ serve(base([LORA_HIGH]))+ await expect(buildDynamicWorkflow(run(HIGH, { inputImage: 'start.png' }))).rejects.toThrow(WorkflowUnavailableError)+ await expect(buildDynamicWorkflow(run(HIGH, { inputImage: 'start.png' }))).rejects.toThrow(/lightx2v.*low_noise.*Quality/s)+ })++ it('Wan 2.1 14B takes its one LoRA on the single model', async () => {+ const wf = await buildDynamicWorkflow(run(WAN21))+ const sampler = nodeOf(wf, 'KSampler')![1]+ expect(modelChain(wf, sampler.inputs.model)).toEqual(['Shift(5)', `Lora(${WAN21_LORA})`, 'UNETLoader'])+ })++ it('a quality run takes no LoRA and the template shift 8', async () => {+ const wf = await buildDynamicWorkflow(run(HIGH, { inputImage: 'start.png', steps: 20, cfgScale: 3.5 }))+ const [high, low] = nodesOf(wf, 'KSamplerAdvanced').map(([, n]) => n)+ expect(modelChain(wf, high.inputs.model)).toEqual(['Shift(8)', 'UnetLoaderGGUF'])+ expect(modelChain(wf, low.inputs.model)).toEqual(['Shift(8)', 'UnetLoaderGGUF'])+ expect(classTypes(wf)).not.toContain('LoraLoaderModelOnly')+ })++ it('a merged fast model (Rapid AIO) gets no second LoRA', async () => {+ serve({ ...base([LORA_HIGH, LORA_LOW]), UnetLoaderGGUF: { input: { required: { unet_name: [['wan2.2-i2v-rapid-aio-v10-nsfw-Q4_K_M.gguf']] } } } })+ const wf = await buildDynamicWorkflow(run('wan2.2-i2v-rapid-aio-v10-nsfw-Q4_K_M.gguf', { inputImage: 'start.png', steps: 6 }))+ expect(classTypes(wf)).not.toContain('LoraLoaderModelOnly')+ })+})++describe('a later section continues the clip so far (core nodes only)', () => {+ beforeEach(() => serve(base([LORA_HIGH, LORA_LOW])))++ it('Wan A14B: last 5 frames in, first frame as padding, whole clip out', async () => {+ const wf = await buildDynamicWorkflow(run(HIGH, { continueFrom: { video: 'lu_long_1.mp4', overlap: 5 } }))+ expect(nodeOf(wf, 'LoadVideo')![1].inputs.file).toBe('lu_long_1.mp4')+ expect(classTypes(wf)).not.toContain('LoadImage')+ const i2v = nodeOf(wf, 'WanImageToVideo')![1]+ const tail = nodeAt(wf, (i2v.inputs.start_image as [string, number])[0])!+ expect(tail.class_type).toBe('ImageFromBatch')+ expect(tail.inputs).toMatchObject({ batch_index: -5, length: 5 })+ const pad = nodeAt(wf, (i2v.inputs.ref_pad_image as [string, number])[0])!+ expect(pad.inputs).toMatchObject({ batch_index: 0, length: 1 })+ // The save gets the joined frames: clip so far + section from frame 5.+ const create = nodeOf(wf, 'CreateVideo')![1]+ const join = nodeAt(wf, (create.inputs.images as [string, number])[0])!+ expect(join.class_type).toBe('BatchImagesNode')+ const parts = nodeOf(wf, 'GetVideoComponents')![0]+ expect(join.inputs['images.image0']).toEqual([parts, 0])+ const rest = nodeAt(wf, (join.inputs['images.image1'] as [string, number])[0])!+ expect(rest.inputs).toMatchObject({ batch_index: 5 })+ expect(nodeAt(wf, (rest.inputs.image as [string, number])[0])!.class_type).toBe('VAEDecodeTiled')+ })++ it('falls back to ImageBatch on a core without BatchImagesNode', async () => {+ const nodes = base([LORA_HIGH, LORA_LOW])+ delete nodes.BatchImagesNode+ nodes.ImageBatch = { input: { required: {} } }+ serve(nodes)+ const wf = await buildDynamicWorkflow(run(HIGH, { continueFrom: { video: 'c.mp4', overlap: 5 } }))+ expect(classTypes(wf)).toContain('ImageBatch')+ })++ it('a core without the video nodes is told to update', async () => {+ const nodes = base([LORA_HIGH, LORA_LOW])+ delete nodes.LoadVideo+ serve(nodes)+ await expect(buildDynamicWorkflow(run(HIGH, { continueFrom: { video: 'c.mp4', overlap: 5 } }))).rejects.toThrow(/Update ComfyUI/)+ })++ it('Wan 2.2 5B continues through Wan22ImageToVideoLatent', async () => {+ const wf = await buildDynamicWorkflow(run(TI2V, { steps: 20, cfgScale: 5, frames: 121, fps: 24, width: 1280, height: 704, continueFrom: { video: 'c.mp4', overlap: 5 } }))+ const latent = nodeOf(wf, 'Wan22ImageToVideoLatent')![1]+ const scale = nodeAt(wf, (latent.inputs.start_image as [string, number])[0])!+ expect(scale.class_type).toBe('ImageScale')+ expect(nodeAt(wf, (scale.inputs.image as [string, number])[0])!.inputs).toMatchObject({ batch_index: -5, length: 5 })+ expect(classTypes(wf)).toContain('BatchImagesNode')+ })+})++describe('one pass with context windows', () => {+ beforeEach(() => serve(base([LORA_HIGH, LORA_LOW])))++ it('long enough: both halves sample through WanContextWindowsManual', async () => {+ const wf = await buildDynamicWorkflow(run(HIGH, { inputImage: 's.png', frames: 241, contextWindows: true }))+ const [high, low] = nodesOf(wf, 'KSamplerAdvanced').map(([, n]) => n)+ expect(modelChain(wf, high.inputs.model)[0]).toBe('WanContextWindowsManual')+ expect(modelChain(wf, low.inputs.model)[0]).toBe('WanContextWindowsManual')+ expect(nodeOf(wf, 'WanContextWindowsManual')![1].inputs).toMatchObject({ context_length: 81, context_overlap: 30, fuse_method: 'pyramid', freenoise: true })+ })++ it('a clip inside one window gets none', async () => {+ const wf = await buildDynamicWorkflow(run(HIGH, { inputImage: 's.png', frames: 81, contextWindows: true }))+ expect(classTypes(wf)).not.toContain('WanContextWindowsManual')+ })+})diff --git a/src/api/__tests__/ltx-25-runs-past-ten-seconds.test.ts b/src/api/__tests__/ltx-25-runs-past-ten-seconds.test.tsnew file mode 100644index 00000000..13c7ec66--- /dev/null+++ b/src/api/__tests__/ltx-25-runs-past-ten-seconds.test.ts@@ -0,0 +1,120 @@+/**+ * B18 (3.0.9): LTX 2.5 past its 10 seconds. A later section pins the last 17+ * frames of the clip so far (three latent frames) at full strength in both+ * passes, and saves the whole clip with the whole sound: the section's sound+ * past the overlap behind the sound so far (TrimAudioDuration, AudioConcat).+ * One pass instead puts LTXVContextWindows on the model. Core nodes only.+ *+ * Run: npx vitest run src/api/__tests__/ltx-25-runs-past-ten-seconds.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++vi.mock('../comfyui-nodes', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../comfyui-nodes')>()+ return { ...actual, getAllNodeInfo: vi.fn() }+})+vi.mock('../backend', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../backend')>()+ return { ...actual, localFetch: vi.fn(), comfyuiUrl: (p: string) => `http://test${p}` }+})++import { buildDynamicWorkflow } from '../dynamic-workflow'+import { getAllNodeInfo } from '../comfyui-nodes'+import { localFetch } from '../backend'+import { classTypes, nodeAt, nodeOf, nodesOf } from './graph-test-support'++const DIT = 'ltx-2.5-22b-distilled-transformer-comfy-int8-convrot.safetensors'+const DEV = 'ltx-2.5-22b-dev-transformer-comfy-int8-convrot.safetensors'+const ENCODER = 'gemma4-12b-with-proj-ltx-2.5-comfy-int8-convrot.safetensors'+const VIDEO_VAE = 'ltx-2.5-video-vae-bf16.safetensors'+const AUDIO_VAE = 'ltx-2.5-audio-vae-bf16.safetensors'+const UPSCALER = 'ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors'++const LTX25_NODES: Record<string, unknown> = {+ UNETLoader: { input: { required: { unet_name: [[DIT, DEV]] } } },+ CLIPLoader: { input: { required: { clip_name: [[ENCODER]] } } },+ VAELoader: { input: { required: { vae_name: [[VIDEO_VAE, AUDIO_VAE]] } } },+ LatentUpscaleModelLoader: { input: { required: { model_name: [[UPSCALER]] } } },+ CLIPTextEncode: { input: { required: {} } },+ LTXVConditioning: { input: { required: {} } },+ EmptyLTXVLatentVideo: { input: { required: {} } },+ LTXVEmptyLatentAudio: { input: { required: {} } },+ LTXVConcatAVLatent: { input: { required: {} } },+ LTXVSeparateAVLatent: { input: { required: {} } },+ LTXVLatentUpsampler: { input: { required: {} } },+ LTXVAudioVAEDecode: { input: { required: {} } },+ LTXVDualCFGGuider: { input: { required: {} } },+ LTXVImgToVideoInplace: { input: { required: {} } },+ LTXVPreprocess: { input: { required: {} } },+ ManualSigmas: { input: { required: {} } },+ KSamplerSelect: { input: { required: {} } },+ RandomNoise: { input: { required: {} } },+ SamplerCustomAdvanced: { input: { required: {} } },+ VAEDecodeTiled: { input: { required: {} } },+ LoadImage: { input: { required: {} } },+ ImageScale: { input: { required: {} } },+ CreateVideo: { input: { required: {} } },+ SaveVideo: { input: { required: {} } },+ LoadVideo: { input: { required: {} } },+ GetVideoComponents: { input: { required: {} } },+ ImageFromBatch: { input: { required: {} } },+ BatchImagesNode: { input: { required: {} } },+ TrimAudioDuration: { input: { required: {} } },+ AudioConcat: { input: { required: {} } },+ LTXVContextWindows: { input: { required: {} } },+}++function serveEnums(vaes: string[], clips: string[]) {+ vi.mocked(localFetch).mockResolvedValue({+ ok: true,+ json: async () => ({+ CLIPLoader: { input: { required: { clip_name: [clips] } } },+ VAELoader: { input: { required: { vae_name: [vaes] } } },+ }),+ } as never)+}++const run = (model: string, extra: Record<string, unknown> = {}) => ({+ model, prompt: 'two rangers argue at a campfire, then a cut to the lake at dawn', negativePrompt: '',+ sampler: 'euler_ancestral', scheduler: 'simple', steps: 8, cfgScale: 1,+ width: 1280, height: 704, seed: 7, batchSize: 1, frames: 121, fps: 24, ...extra,+}) as never++beforeEach(() => {+ vi.mocked(getAllNodeInfo).mockResolvedValue(LTX25_NODES as never)+ serveEnums([VIDEO_VAE, AUDIO_VAE], [ENCODER])+})++describe('a later LTX 2.5 section', () => {+ it('pins the last 17 frames at strength 1 in both passes', async () => {+ const wf = await buildDynamicWorkflow(run(DIT, { frames: 241, continueFrom: { video: 'so_far.mp4', overlap: 17 } }))+ expect(nodeOf(wf, 'LoadVideo')![1].inputs.file).toBe('so_far.mp4')+ expect(classTypes(wf)).not.toContain('LoadImage')+ const pins = nodesOf(wf, 'LTXVImgToVideoInplace').map(([, n]) => n.inputs.strength)+ expect(pins).toEqual([1, 1])+ const pre = nodeOf(wf, 'LTXVPreprocess')![1]+ const scale = nodeAt(wf, (pre.inputs.image as [string, number])[0])!+ expect(nodeAt(wf, (scale.inputs.image as [string, number])[0])!.inputs).toMatchObject({ batch_index: -17, length: 17 })+ })++ it('saves the whole clip with the whole sound', async () => {+ const wf = await buildDynamicWorkflow(run(DIT, { frames: 241, continueFrom: { video: 'so_far.mp4', overlap: 17 } }))+ const create = nodeOf(wf, 'CreateVideo')![1]+ expect(nodeAt(wf, (create.inputs.images as [string, number])[0])!.class_type).toBe('BatchImagesNode')+ const sound = nodeAt(wf, (create.inputs.audio as [string, number])[0])!+ expect(sound.class_type).toBe('AudioConcat')+ const parts = nodeOf(wf, 'GetVideoComponents')![0]+ expect(sound.inputs.audio1).toEqual([parts, 1])+ const trim = nodeAt(wf, (sound.inputs.audio2 as [string, number])[0])!+ expect(trim.class_type).toBe('TrimAudioDuration')+ expect(trim.inputs.start_index).toBeCloseTo(17 / 24)+ expect(nodeAt(wf, (trim.inputs.audio as [string, number])[0])!.class_type).toBe('LTXVAudioVAEDecode')+ })++ it('one pass puts LTXVContextWindows under both guiders', async () => {+ const wf = await buildDynamicWorkflow(run(DIT, { frames: 721, contextWindows: true }))+ const win = nodeOf(wf, 'LTXVContextWindows')!+ expect(win[1].inputs).toMatchObject({ context_length: 145, context_overlap: 40 })+ for (const [, g] of nodesOf(wf, 'LTXVDualCFGGuider')) expect(g.inputs.model).toEqual([win[0], 0])+ })+})diff --git a/src/api/__tests__/wan22-a14b-vae.test.ts b/src/api/__tests__/wan22-a14b-vae.test.tsindex b7030d59..569f9369 100644--- a/src/api/__tests__/wan22-a14b-vae.test.ts+++ b/src/api/__tests__/wan22-a14b-vae.test.ts@@ -184,9 +184,13 @@ describe('the A14B pair runs high noise, then low noise', () => {const loaders = nodesOf(wf, 'UNETLoader').map(([, node]) => node.inputs.unet_name)expect(loaders).toEqual([REPORTED, 'wan2.2_i2v_low_noise_14B_fp8_scaled.safetensors'])// The low stage samples the low half and continues the high stage's latent.+ // Since 3.0.9 (B18) each half goes through the template's sampling shift+ // first (ModelSamplingSD3, 8 for a quality run).const lowLoaderId = nodesOf(wf, 'UNETLoader')[1][0]const highId = nodesOf(wf, 'KSamplerAdvanced')[0][0]- expect(low.inputs.model).toEqual([lowLoaderId, 0])+ const lowShift = wf[(low.inputs.model as [string, number])[0]]+ expect(lowShift.class_type).toBe('ModelSamplingSD3')+ expect(lowShift.inputs).toMatchObject({ model: [lowLoaderId, 0], shift: 8 })expect(low.inputs.latent_image).toEqual([highId, 0])expect(nodeOf(wf, 'VAEDecode')?.[1].inputs.samples ?? nodeOf(wf, 'VAEDecodeTiled')?.[1].inputs.samples).toEqual([nodesOf(wf, 'KSamplerAdvanced')[1][0], 0])diff --git a/src/api/backend.ts b/src/api/backend.tsindex 54b2e177..edaa133b 100644--- a/src/api/backend.ts+++ b/src/api/backend.ts@@ -571,6 +571,9 @@ export async function backendCall<T = unknown>(video_generate: { path: "/local-api/video-generate", method: "POST" },video_progress: { path: "/local-api/video-progress" },video_cancel: { path: "/local-api/video-cancel", method: "POST" },+ // B18: the colour settle of a long clip runs in the desktop app only+ // (commands/video_settle.rs); the dev server answers 501.+ video_color_settle: { path: "/local-api/video-color-settle", method: "POST" },read_media_file: { path: "/local-api/read-media-file", method: "POST" },// The music engine of the Mac (commands/music.rs), desktop only like the// MLX commands above: the dev server answers 501 (mlx-media-stubs.ts).diff --git a/src/api/comfyui.ts b/src/api/comfyui.tsindex 10078a61..6f31bb8f 100644--- a/src/api/comfyui.ts+++ b/src/api/comfyui.ts@@ -103,6 +103,12 @@ export interface VideoParams extends GenerateParams {// source still / calmer motion; 127 (SVD default) drifts hard. We default ~90// for I2V fidelity (2026-06-11). Honoured only by the SVD path.motionBucketId?: number+ /** A later section of a long clip (B18): the clip so far in ComfyUI's input+ * folder and how many of its last frames this section repeats. The graph+ * starts on those frames and outputs the whole clip (api/video-continue). */+ continueFrom?: { video: string; overlap: number }+ /** One pass with sliding context windows instead of sections (B18). */+ contextWindows?: boolean}export interface ComfyUIOutput {diff --git a/src/api/dynamic-workflow.ts b/src/api/dynamic-workflow.tsindex 67e012f9..00bbf549 100644--- a/src/api/dynamic-workflow.ts+++ b/src/api/dynamic-workflow.ts@@ -63,6 +63,8 @@ import { promptFilenamePrefix, videoDecodeNode, addVideoSave } from './comfyui-gimport { extraReferenceSlots, isQwenImageEditModel, referenceSide } from '../lib/edit-references'import { canonicalImageRefs } from '../lib/image-ref-names'import { nativeUpscaleScale, upscaleTarget, type UpscaleFactor } from '../lib/local-upscale'+import { WAN_FAST, findWanSpeedLora, isFastSampling, wanSamplingFor, wanSpeedKind, wanSpeedLoraNames } from '../lib/wan-speed'+import { addAudioStitch, addContextWindows, addContinueSource, addStitch, CONTINUE_NEEDS_UPDATE, type ContinueSource } from './video-continue'// ─── Strategy Detection ───@@ -1436,7 +1438,11 @@ export async function buildDynamicWorkflow(// builders above. Wiring is schema-driven — we only feed inputs the live// node declares and map outputs by their declared types — so version drift// in these nodes degrades to a ComfyUI validation error, not a bad graph.- const isI2V = isVideo && !!(params as GenerateParams).inputImage+ // A later section of a long clip (B18) is an I2V run too: it starts on the+ // last frames of the clip so far instead of on one picture.+ const continueFrom = isVideo ? videoParams.continueFrom : undefined+ let continued: ContinueSource | null = null+ const isI2V = isVideo && (!!(params as GenerateParams).inputImage || !!continueFrom)if (isI2V && ['unet_video', 'unet_ltx', 'unet_cosmos', 'unet_mochi'].includes(strategy)) {if (strategy === 'unet_mochi') {throw new WorkflowUnavailableError(@@ -1458,8 +1464,20 @@ export async function buildDynamicWorkflow({ needsComfyUpdate: true },)}- const loadId = String(n++)- workflow[loadId] = { class_type: 'LoadImage', inputs: { image: (params as GenerateParams).inputImage } }+ if (continueFrom && i2vNode !== 'WanImageToVideo') {+ throw new WorkflowUnavailableError('Continuing a clip in sections works with Wan, Wan 2.2 and LTX 2.5. Pick one of those models, or make this clip in one run.', strategy)+ }+ let startRef: [string, number]+ if (continueFrom) {+ requireContinueNodes(allNodes, strategy)+ continued = addContinueSource(workflow, n, continueFrom, allNodes)+ n = continued.n+ startRef = continued.tail+ } else {+ const loadId = String(n++)+ workflow[loadId] = { class_type: 'LoadImage', inputs: { image: (params as GenerateParams).inputImage } }+ startRef = [loadId, 0]+ }const required = meta.input?.required ?? {}const optional = meta.input?.optional ?? {}const decl = { ...required, ...optional }@@ -1471,9 +1489,13 @@ export async function buildDynamicWorkflow(if (decl.height) inputs.height = params.heightif (decl.length) inputs.length = videoParams.framesif (decl.batch_size) inputs.batch_size = 1- if (decl.start_image) inputs.start_image = [loadId, 0]- else if (decl.image) inputs.image = [loadId, 0]- else if (decl.init_image) inputs.init_image = [loadId, 0]+ if (decl.start_image) inputs.start_image = startRef+ else if (decl.image) inputs.image = startRef+ else if (decl.init_image) inputs.init_image = startRef+ // SVI-style anti-drift padding (core WanImageToVideo, 2026): the empty+ // frames of a continued section are filled with the clip's first picture+ // instead of grey, so faces and colours stay where the clip started.+ if (continued && decl.ref_pad_image) inputs.ref_pad_image = continued.first// Remaining REQUIRED widgets we don't model: take the schema default,// for a combo the first option. Same live-schema pattern as the RMBG// builder, and the combo read goes through the one shared reader so the@@ -1552,10 +1574,77 @@ export async function buildDynamicWorkflow(? wan22LowNoisePartner(params.model, listedUnets): nulllet highNoiseStage: { id: string; lowId: string; split: number } | null = null+ let lowModelRef: [string, number] | null = nullif (lowNoisePartner) {- highNoiseStage = { lowId: String(n++), id: String(n++), split: Math.max(1, Math.floor(params.steps / 2)) }- const { id, lowId, split } = highNoiseStage- addUnetLoader(workflow, lowId, lowNoisePartner, allNodes)+ const lowLoaderId = String(n++)+ addUnetLoader(workflow, lowLoaderId, lowNoisePartner, allNodes)+ lowModelRef = [lowLoaderId, 0]+ }++ // Wan (B18, 3.0.9): the sampling shift of the official templates, which the+ // main path never set, and the lightx2v speed LoRAs for a fast run (4 steps+ // at cfg 1, lib/wan-speed). The LoRAs go on each half its own: the high+ // noise LoRA on the high noise model, the low noise one on the low. A fast+ // run without its LoRA would come out as mush, so it stops with the file+ // names instead.+ if (isVideo && type === 'wan' && strategy === 'unet_video' && !fromCheckpoint) {+ const kind = wanSpeedKind(params.model)+ const fast = !!kind && isFastSampling(params.steps, params.cfgScale)+ if (fast && kind) {+ const listedLoras = [+ ...nodeComboOptions(allNodes, 'LoraLoaderModelOnly', 'lora_name'),+ ...nodeComboOptions(allNodes, 'LoraLoader', 'lora_name'),+ ]+ const halves: Array<'high' | 'low' | 'single'> = kind.startsWith('a14b') ? ['high', 'low'] : ['single']+ const picks = halves.map((h) => findWanSpeedLora(kind, h, listedLoras))+ if (picks.some((p) => !p) || (kind.startsWith('a14b') && !lowModelRef)) {+ const need = wanSpeedLoraNames(kind)+ throw new WorkflowUnavailableError(+ kind.startsWith('a14b') && !lowModelRef && picks.every(Boolean)+ ? `Fast mode runs both halves of ${params.model}: the matching low noise file is not installed. Install the whole Wan 2.2 A14B bundle, or switch Speed to Quality.`+ : `Fast mode (4 steps) needs the lightx2v speed LoRA${need.length > 1 ? 's' : ''} ${need.join(' and ')} in ComfyUI/models/loras. Download "Wan speed LoRAs" in the Model Manager, or switch Speed to Quality.`,+ strategy,+ )+ }+ const loraNode = allNodes['LoraLoaderModelOnly'] ? 'LoraLoaderModelOnly' : null+ const patch = (model: [string, number], lora: string): [string, number] => {+ const id = String(n++)+ workflow[id] = loraNode+ ? { class_type: loraNode, inputs: { lora_name: lora, strength_model: 1.0, model }, _meta: { title: 'Speed LoRA' } }+ : { class_type: 'LoraLoader', inputs: { lora_name: lora, strength_model: 1.0, strength_clip: 0, model, clip: [clipSourceId, clipOutputSlot] }, _meta: { title: 'Speed LoRA' } }+ return [id, 0]+ }+ samplerModelId = patch([samplerModelId, 0], picks[0]!)[0]+ if (lowModelRef && picks[1]) lowModelRef = patch(lowModelRef, picks[1])+ }+ if (allNodes['ModelSamplingSD3']) {+ const shift = fast ? WAN_FAST.shift : (wanSamplingFor(params.model, 'quality')?.shift ?? 8)+ const shiftOf = (model: [string, number]): [string, number] => {+ const id = String(n++)+ workflow[id] = { class_type: 'ModelSamplingSD3', inputs: { model, shift } }+ return [id, 0]+ }+ samplerModelId = shiftOf([samplerModelId, 0])[0]+ if (lowModelRef) lowModelRef = shiftOf(lowModelRef)+ }+ }++ // One pass past the native length (B18): sliding context windows on the+ // model(s), when asked for and the core has the node.+ if (isVideo && videoParams.contextWindows && !continueFrom) {+ const win = addContextWindows(workflow, n, [samplerModelId, 0], type, videoParams.frames, allNodes)+ n = win.n+ samplerModelId = win.model[0]+ if (lowModelRef) {+ const low = addContextWindows(workflow, n, lowModelRef, type, videoParams.frames, allNodes)+ n = low.n+ lowModelRef = low.model+ }+ }++ if (lowNoisePartner && lowModelRef) {+ highNoiseStage = { lowId: lowModelRef[0], id: String(n++), split: Math.max(1, Math.floor(params.steps / 2)) }+ const { id, split } = highNoiseStageworkflow[id] = {class_type: 'KSamplerAdvanced',inputs: {@@ -1613,8 +1702,16 @@ export async function buildDynamicWorkflow(// ─── Phase 6: Output ───if (isVideo) {+ // A continued section goes behind the clip so far, without the frames it+ // repeats, and the whole clip is saved (B18).+ let frames: [string, number] = [decodeId, 0]+ if (continued && continueFrom) {+ const joined = addStitch(workflow, n, continued.frames, frames, continueFrom.overlap, allNodes)+ n = joined.n+ frames = joined.images+ }// Video output: core SaveVideo (mp4) > VHS > SaveAnimatedWEBP > SaveImage (A19)- addVideoSave(workflow, n, [decodeId, 0], videoParams.fps, promptFilenamePrefix(params.prompt, true), (c) => nodes.videoSavers.includes(c))+ addVideoSave(workflow, n, frames, videoParams.fps, promptFilenamePrefix(params.prompt, true), (c) => nodes.videoSavers.includes(c))} else {workflow[String(n)] = {class_type: 'SaveImage',@@ -1914,10 +2011,27 @@ async function buildWan22Workflow(params: VideoParams, seed: number, nodes: Cate// SD3), so the sampler reads from it to match the official 5B workflow's motion.const shiftId = String(n++)workflow[shiftId] = { class_type: 'ModelSamplingSD3', inputs: { model: [wanModelSrc, 0], shift: 8.0 } }+ let samplerModel: [string, number] = [shiftId, 0]+ if (params.contextWindows && !params.continueFrom) {+ const win = addContextWindows(workflow, n, samplerModel, 'wan22', length, allNodes)+ n = win.n+ samplerModel = win.model+ }- // Unified latent: a start_image is attached ONLY for an I2V request.+ // Unified latent: a start_image is attached ONLY for an I2V request. A+ // continued section (B18) attaches the last frames of the clip so far; the+ // node masks every latent frame they cover, so the section picks the+ // motion up where it stopped.const latentInputs: ComfyNodeInputs = { vae: [vaeId, 0], width, height, length, batch_size: 1 }- if (params.inputImage) {+ let continued: ContinueSource | null = null+ if (params.continueFrom) {+ requireContinueNodes(allNodes, 'unet_video')+ continued = addContinueSource(workflow, n, params.continueFrom, allNodes)+ n = continued.n+ const scaleId = String(n++)+ workflow[scaleId] = { class_type: 'ImageScale', inputs: { image: continued.tail, upscale_method: 'lanczos', width, height, crop: 'center' } }+ latentInputs.start_image = [scaleId, 0]+ } else if (params.inputImage) {const imageId = String(n++)const scaleId = String(n++)workflow[imageId] = { class_type: 'LoadImage', inputs: { image: params.inputImage } }@@ -1931,13 +2045,18 @@ async function buildWan22Workflow(params: VideoParams, seed: number, nodes: Cateworkflow[samplerId] = {class_type: 'KSampler',inputs: {- model: [shiftId, 0], positive: [posId, 0], negative: [negId, 0], latent_image: [latentId, 0],+ model: samplerModel, positive: [posId, 0], negative: [negId, 0], latent_image: [latentId, 0],seed, steps: params.steps, cfg: params.cfgScale, sampler_name: params.sampler, scheduler: params.scheduler, denoise: 1.0,},}const decodeId = String(n++)workflow[decodeId] = videoDecodeNode([samplerId, 0], [vaeId, 0], nodes.decoders.includes('VAEDecodeTiled'))+ if (continued && params.continueFrom) {+ const joined = addStitch(workflow, n, continued.frames, [decodeId, 0], params.continueFrom.overlap, allNodes)+ addVideoSave(workflow, joined.n, joined.images, params.fps, promptFilenamePrefix(params.prompt, true), (c) => nodes.videoSavers.includes(c))+ return workflow+ }addVideoOutput(workflow, n, decodeId, params.fps, nodes, params.prompt)return workflow}@@ -2130,7 +2249,8 @@ async function buildLtx25Workflow(params: VideoParams, seed: number, allNodes: N'LTXVLatentUpsampler', 'LatentUpscaleModelLoader', 'LTXVAudioVAEDecode', 'ManualSigmas', 'KSamplerSelect','RandomNoise', 'SamplerCustomAdvanced', 'VAEDecodeTiled', 'CLIPTextEncode',], 'LTX 2.5')- if (params.inputImage) requireNodes(allNodes, ['LTXVImgToVideoInplace', 'LTXVPreprocess', 'LoadImage', 'ImageScale'], 'LTX 2.5 image to video')+ if (params.inputImage || params.continueFrom) requireNodes(allNodes, ['LTXVImgToVideoInplace', 'LTXVPreprocess', 'LoadImage', 'ImageScale'], 'LTX 2.5 image to video')+ if (params.continueFrom) requireContinueNodes(allNodes, 'ltx25')// The graph is the distilled one. The dev weights need a different schedule// and guidance, and running them on this one gives noise.@@ -2180,23 +2300,40 @@ async function buildLtx25Workflow(params: VideoParams, seed: number, allNodes: Nconst negId = add('CLIPTextEncode', { text: params.negativePrompt || '', clip: [clipId, 0] })const condId = add('LTXVConditioning', { positive: [posId, 0], negative: [negId, 0], frame_rate: fps })+ // A continued section (B18) pins the last frames of the clip so far, an+ // 8n+1 run (17 frames are three latent frames), instead of one picture,+ // and pins them fully in both passes: they are frames that already exist.let imageSrc: string | null = null- if (params.inputImage) {+ let continued: ContinueSource | null = null+ if (params.continueFrom) {+ continued = addContinueSource(workflow, n, params.continueFrom, allNodes)+ n = continued.n+ const scaleId = add('ImageScale', { image: continued.tail, upscale_method: 'lanczos', width, height, crop: 'center' })+ imageSrc = add('LTXVPreprocess', { image: [scaleId, 0], img_compression: 18 })+ } else if (params.inputImage) {const loadId = add('LoadImage', { image: params.inputImage })const scaleId = add('ImageScale', { image: [loadId, 0], upscale_method: 'lanczos', width, height, crop: 'center' })imageSrc = add('LTXVPreprocess', { image: [scaleId, 0], img_compression: 18 })}const pin = (latent: string, strength: number): string =>imageSrc- ? add('LTXVImgToVideoInplace', { vae: [vaeId, 0], image: [imageSrc, 0], latent: [latent, 0], strength, bypass: false })+ ? add('LTXVImgToVideoInplace', { vae: [vaeId, 0], image: [imageSrc, 0], latent: [latent, 0], strength: continued ? 1 : strength, bypass: false }): latent+ // One pass past one window: context windows on the model (LTXVContextWindows).+ let model: [string, number] = [unetId, 0]+ if (params.contextWindows && !continued) {+ const win = addContextWindows(workflow, n, model, 'ltx25', length, allNodes)+ n = win.n+ model = win.model+ }+// Pass 1: half size.const emptyId = add('EmptyLTXVLatentVideo', { width: width / 2, height: height / 2, length, batch_size: 1 })const videoLatent1 = pin(emptyId, 0.7)const audioLatentId = add('LTXVEmptyLatentAudio', { frames_number: length, frame_rate: fps, batch_size: 1, audio_vae: [audioVaeId, 0] })const joint1 = add('LTXVConcatAVLatent', { video_latent: [videoLatent1, 0], audio_latent: [audioLatentId, 0] })- const guider1 = add('LTXVDualCFGGuider', { model: [unetId, 0], positive: [condId, 0], negative: [condId, 1], video_cfg: 1, audio_cfg: 1 })+ const guider1 = add('LTXVDualCFGGuider', { model, positive: [condId, 0], negative: [condId, 1], video_cfg: 1, audio_cfg: 1 })const sampler1 = add('KSamplerSelect', { sampler_name: 'euler_ancestral' })const sigmas1 = add('ManualSigmas', { sigmas: LTX25_SIGMAS_FIRST })const noise1 = add('RandomNoise', { noise_seed: seed })@@ -2211,7 +2348,7 @@ async function buildLtx25Workflow(params: VideoParams, seed: number, allNodes: Nconst joint2 = add('LTXVConcatAVLatent', { video_latent: [videoLatent2, 0], audio_latent: [split1, 1] })// Pass 2: full size.- const guider2 = add('LTXVDualCFGGuider', { model: [unetId, 0], positive: [condId, 0], negative: [condId, 1], video_cfg: 1, audio_cfg: 1 })+ const guider2 = add('LTXVDualCFGGuider', { model, positive: [condId, 0], negative: [condId, 1], video_cfg: 1, audio_cfg: 1 })const sampler2 = add('KSamplerSelect', { sampler_name: 'euler_ancestral' })const sigmas2 = add('ManualSigmas', { sigmas: LTX25_SIGMAS_SECOND })const noise2 = add('RandomNoise', { noise_seed: seed })@@ -2223,6 +2360,16 @@ async function buildLtx25Workflow(params: VideoParams, seed: number, allNodes: Nconst decodeId = add('VAEDecodeTiled', { samples: [split2, 0], vae: [vaeId, 0], tile_size: 512, overlap: 64, temporal_size: 64, temporal_overlap: 16 })const audioDecodeId = add('LTXVAudioVAEDecode', { samples: [split2, 1], audio_vae: [audioVaeId, 0] })+ if (continued && params.continueFrom) {+ const joined = addStitch(workflow, n, continued.frames, [decodeId, 0], params.continueFrom.overlap, allNodes)+ n = joined.n+ // The sound so far plus the new sound past the overlap. A clip so far+ // without sound (made elsewhere) keeps only the new part's sound.+ const sound = addAudioStitch(workflow, n, continued.audio, [audioDecodeId, 0], params.continueFrom.overlap / fps, allNodes)+ if (sound) n = sound.n+ addVideoWithAudioOutput(workflow, n, joined.images[0], fps, sound ? sound.audio : [audioDecodeId, 0], allNodes, params.prompt)+ return workflow+ }addVideoWithAudioOutput(workflow, n, decodeId, fps, [audioDecodeId, 0], allNodes, params.prompt)return workflow}@@ -2262,6 +2409,11 @@ export interface LocalOpParams {const UPDATE_COMFY_HINT ='Update ComfyUI (Settings, AI Backends, Update ComfyUI), restart it, then generate again.'+/** The core video nodes a continued section is built from (B18). */+function requireContinueNodes(allNodes: NodePresence, strategy: WorkflowStrategy): void {+ requireRelease(allNodes, ['LoadVideo', 'GetVideoComponents', 'ImageFromBatch'], CONTINUE_NEEDS_UPDATE, strategy)+}+function requireNodes(allNodes: NodePresence, needed: string[], lane: string): void {const missing = needed.filter((n) => !allNodes[n])if (missing.length > 0) {diff --git a/src/api/model-bundles.ts b/src/api/model-bundles.tsindex be722709..4cdf5142 100644--- a/src/api/model-bundles.ts+++ b/src/api/model-bundles.ts@@ -131,6 +131,22 @@ const QWEN21_VAE: DiscoverModel = {sha256: 'bb21f7473051e1ac368515dd3f2e15cd44d7a11748ee8823e1ddca3e4876b7c9',}+// The Wan VAE and text encoder every Wan 2.1 / 2.2 14B bundle loads.+const WAN21_VAE_FILE: DiscoverModel = {+ name: 'Wan 2.1 VAE',+ description: 'Required video encoder/decoder.',+ pulls: '', tags: ['VAE', '250 MB'], updated: '',+ downloadUrl: 'https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/resolve/main/split_files/vae/wan_2.1_vae.safetensors',+ filename: 'wan_2.1_vae.safetensors', subfolder: 'vae', sizeGB: 0.24,+}+const WAN_UMT5_FILE: DiscoverModel = {+ name: 'Wan CLIP (UMT5-XXL FP8)',+ description: 'Required text encoder · shared with every Wan model, skipped if already installed.',+ pulls: '', tags: ['CLIP', '6.3 GB'], updated: '',+ downloadUrl: 'https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/resolve/main/split_files/text_encoders/umt5_xxl_fp8_e4m3fn_scaled.safetensors',+ filename: 'umt5_xxl_fp8_e4m3fn_scaled.safetensors', subfolder: 'text_encoders', sizeGB: 6.27,+}+// ─── Image Model Bundles ───export function getImageBundles(): ModelBundle[] {@@ -1026,6 +1042,150 @@ export function getVideoBundles(): ModelBundle[] {},],},+ // Wan 2.2 A14B, fast (B18, 3.0.9). The 14B pair as QuantStack's GGUF+ // (Q4_K_S, the quant A34 ran on the 12 GB box) plus lightx2v's own 4 step+ // speed LoRAs, both Apache-2.0 like Wan itself. Sizes and SHA-256 are the+ // Hugging Face LFS values, read from the tree API on 2026-10-27. Fast mode+ // (lib/wan-speed) runs 2 + 2 steps at cfg 1; Quality runs the official+ // 20 step template without the LoRAs.+ {+ name: 'Wan 2.2 A14B · Image to Video, Fast (4 steps)',+ description: 'The full Wan 2.2 14B image to video pair as GGUF, with the lightx2v 4 step LoRAs: a 5 s clip in minutes on a 12 GB card. Continues clips up to 30 s with Extend Video. Quality mode (20 steps) stays one switch away.',+ tags: ['Wan 2.2', '14B', 'I2V', 'GGUF', 'Fast', 'Long video'],+ uncensored: true,+ i2v: true,+ totalSizeGB: 24.1,+ vramRequired: '10-16 GB',+ workflow: 'wan',+ tier: 'standard',+ customNodes: ['gguf'],+ url: 'https://huggingface.co/lightx2v/Wan2.2-Distill-Loras',+ files: [+ {+ name: 'Wan 2.2 A14B I2V High Noise Q4_K_S (GGUF)',+ description: 'First half of the image to video pair: lays out the motion.',+ pulls: '', tags: ['Model', '8.15 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/QuantStack/Wan2.2-I2V-A14B-GGUF/resolve/main/HighNoise/Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf',+ filename: 'Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf', subfolder: 'diffusion_models', sizeGB: 8.15,+ sizeBytes: 8748151296,+ sha256: '8fc5f726ccf1214e43c6a599bdef1e63daf7fab06e71fb74081416c4b9ce200b',+ },+ {+ name: 'Wan 2.2 A14B I2V Low Noise Q4_K_S (GGUF)',+ description: 'Second half: finishes the detail.',+ pulls: '', tags: ['Model', '8.15 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/QuantStack/Wan2.2-I2V-A14B-GGUF/resolve/main/LowNoise/Wan2.2-I2V-A14B-LowNoise-Q4_K_S.gguf',+ filename: 'Wan2.2-I2V-A14B-LowNoise-Q4_K_S.gguf', subfolder: 'diffusion_models', sizeGB: 8.15,+ sizeBytes: 8748151296,+ sha256: '54e2313ef7fbb169e72ab1d7cecdc90a04db01097c86f9f39097b8caacea50fb',+ },+ {+ name: 'lightx2v 4 step LoRA, I2V high noise',+ description: 'Speed LoRA for the high noise half (lightx2v, Apache-2.0).',+ pulls: '', tags: ['LoRA', '0.59 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/lightx2v/Wan2.2-Distill-Loras/resolve/main/wan2.2_i2v_A14b_high_noise_lora_rank64_lightx2v_4step_1022.safetensors',+ filename: 'wan2.2_i2v_A14b_high_noise_lora_rank64_lightx2v_4step_1022.safetensors', subfolder: 'loras', sizeGB: 0.59,+ sizeBytes: 634645944,+ sha256: '887c3bdeb74e83859c920438e16ca31f39ab18ce189abc5f0e36f8348c5bbb19',+ },+ {+ name: 'lightx2v 4 step LoRA, I2V low noise',+ description: 'Speed LoRA for the low noise half (lightx2v, Apache-2.0).',+ pulls: '', tags: ['LoRA', '0.69 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/lightx2v/Wan2.2-Distill-Loras/resolve/main/wan2.2_i2v_A14b_low_noise_lora_rank64_lightx2v_4step_1022.safetensors',+ filename: 'wan2.2_i2v_A14b_low_noise_lora_rank64_lightx2v_4step_1022.safetensors', subfolder: 'loras', sizeGB: 0.69,+ sizeBytes: 739472104,+ sha256: '8833bd4fd7c8eabebf0bc8ee5cfaf47f4f310ce116928a02c1adf8941dd4b0f1',+ },+ WAN21_VAE_FILE,+ WAN_UMT5_FILE,+ ],+ },+ {+ name: 'Wan 2.2 A14B · Text to Video, Fast (4 steps)',+ description: 'The full Wan 2.2 14B text to video pair as GGUF, with the lightx2v 4 step LoRAs. For clips past 5 s, add the image to video bundle: later sections continue from the last frames.',+ tags: ['Wan 2.2', '14B', 'T2V', 'GGUF', 'Fast'],+ uncensored: true,+ totalSizeGB: 23.9,+ vramRequired: '10-16 GB',+ workflow: 'wan',+ tier: 'standard',+ customNodes: ['gguf'],+ url: 'https://huggingface.co/lightx2v/Wan2.2-Distill-Loras',+ files: [+ {+ name: 'Wan 2.2 A14B T2V High Noise Q4_K_S (GGUF)',+ description: 'First half of the text to video pair: lays out the motion.',+ pulls: '', tags: ['Model', '8.15 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/QuantStack/Wan2.2-T2V-A14B-GGUF/resolve/main/HighNoise/Wan2.2-T2V-A14B-HighNoise-Q4_K_S.gguf',+ filename: 'Wan2.2-T2V-A14B-HighNoise-Q4_K_S.gguf', subfolder: 'diffusion_models', sizeGB: 8.15,+ sizeBytes: 8746512896,+ sha256: '4943639d985db2aba0e6038daaca3cd244b6c86175d7ad8bf92182f4b2251bbf',+ },+ {+ name: 'Wan 2.2 A14B T2V Low Noise Q4_K_S (GGUF)',+ description: 'Second half: finishes the detail.',+ pulls: '', tags: ['Model', '8.15 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/QuantStack/Wan2.2-T2V-A14B-GGUF/resolve/main/LowNoise/Wan2.2-T2V-A14B-LowNoise-Q4_K_S.gguf',+ filename: 'Wan2.2-T2V-A14B-LowNoise-Q4_K_S.gguf', subfolder: 'diffusion_models', sizeGB: 8.15,+ sizeBytes: 8746512896,+ sha256: '55439a8ee4c56c609f1754581dafe4408dbffdc14d07c60f5921051794cd3c99',+ },+ {+ name: 'lightx2v 4 step LoRA, T2V high noise',+ description: 'Speed LoRA for the high noise half (lightx2v, Apache-2.0).',+ pulls: '', tags: ['LoRA', '0.57 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/lightx2v/Wan2.2-Distill-Loras/resolve/main/wan2.2_t2v_A14b_high_noise_lora_rank64_lightx2v_4step_1217.safetensors',+ filename: 'wan2.2_t2v_A14b_high_noise_lora_rank64_lightx2v_4step_1217.safetensors', subfolder: 'loras', sizeGB: 0.57,+ sizeBytes: 613518320,+ sha256: '89003385f8a9d53ba58fd6ede647fdc90292e8568a54683fcfe6db5556a31769',+ },+ {+ name: 'lightx2v 4 step LoRA, T2V low noise',+ description: 'Speed LoRA for the low noise half (lightx2v, Apache-2.0).',+ pulls: '', tags: ['LoRA', '0.57 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/lightx2v/Wan2.2-Distill-Loras/resolve/main/wan2.2_t2v_A14b_low_noise_lora_rank64_lightx2v_4step_1217.safetensors',+ filename: 'wan2.2_t2v_A14b_low_noise_lora_rank64_lightx2v_4step_1217.safetensors', subfolder: 'loras', sizeGB: 0.57,+ sizeBytes: 613518320,+ sha256: '4df7c206f3189472da2f92c0a42dcf308f04433d9c14302d08d56e99a3f51322',+ },+ WAN21_VAE_FILE,+ WAN_UMT5_FILE,+ ],+ },+ // Speed LoRAs for the Wan 2.1 14B models LU already offers (B18, 3.0.9).+ // Same lightx2v distill as the A14B pair; Fast mode in Create uses them.+ {+ name: 'Wan 2.1 14B Speed LoRAs · 4 Steps',+ description: 'Add-on for Wan 2.1 14B: 4 steps at cfg 1 instead of 30 at cfg 6. Create picks it up by itself in Fast mode.',+ tags: ['Wan 2.1', 'LoRA', 'Addon', 'Fast'],+ totalSizeGB: 1.28,+ vramRequired: '12+ GB',+ addonFor: 'Wan 2.1 14B',+ workflow: 'wan',+ tier: 'older',+ url: 'https://huggingface.co/lightx2v/Wan2.1-Distill-Loras',+ files: [+ {+ name: 'lightx2v 4 step LoRA, Wan 2.1 T2V 14B',+ description: 'Speed LoRA for Wan 2.1 T2V 14B (lightx2v, Apache-2.0).',+ pulls: '', tags: ['LoRA', '0.59 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/lightx2v/Wan2.1-Distill-Loras/resolve/main/wan2.1_t2v_14b_lora_rank64_lightx2v_4step.safetensors',+ filename: 'wan2.1_t2v_14b_lora_rank64_lightx2v_4step.safetensors', subfolder: 'loras', sizeGB: 0.59,+ sizeBytes: 631344264,+ sha256: '1c918df9eaa102766d8f99104209ce55fe7a892278a667a63d721c5d1c18efb1',+ },+ {+ name: 'lightx2v 4 step LoRA, Wan 2.1 I2V 14B',+ description: 'Speed LoRA for Wan 2.1 I2V 14B (lightx2v, Apache-2.0).',+ pulls: '', tags: ['LoRA', '0.69 GB'], updated: 'New',+ downloadUrl: 'https://huggingface.co/lightx2v/Wan2.1-Distill-Loras/resolve/main/wan2.1_i2v_lora_rank64_lightx2v_4step.safetensors',+ filename: 'wan2.1_i2v_lora_rank64_lightx2v_4step.safetensors', subfolder: 'loras', sizeGB: 0.69,+ sizeBytes: 739472104,+ sha256: '8833bd4fd7c8eabebf0bc8ee5cfaf47f4f310ce116928a02c1adf8941dd4b0f1',+ },+ ],+ },{name: 'Wan 2.2 · TI2V 5B (Image + Text to Video)',description: 'Wan 2.2 TI2V-5B · ONE model for both text to video and faithful image to video (the clip opens on your source image). Native 1280×704 @ 24 fps, smooth 2 to 7 s clips. The best quality video model that fits 12 GB.',diff --git a/src/api/video-continue.ts b/src/api/video-continue.tsnew file mode 100644index 00000000..088604d3--- /dev/null+++ b/src/api/video-continue.ts@@ -0,0 +1,141 @@+// Graph pieces for long local videos (B18, 3.0.9). Core ComfyUI nodes only;+// every class used here ships with ComfyUI itself (checked against+// comfy_extras/nodes_video.py, nodes_images.py, nodes_post_processing.py,+// nodes_audio.py and nodes_context_windows.py on master, 27.10.2026).+//+// continue LoadVideo → GetVideoComponents gives the clip so far as frames+// (and its sound). ImageFromBatch at index -overlap takes its last+// frames for the I2V node, index 0 its very first frame for Wan's+// ref_pad_image ("SVI-style anti-drift padding": the empty frames+// of the conditioning are filled with the first picture instead of+// grey, which keeps faces and colours where they started).+// stitch The new section repeats the overlap frames it was given. They+// are cut off (ImageFromBatch from index `overlap`) and the rest+// goes behind the clip so far (BatchImagesNode, or the older+// ImageBatch on a core without it). The output is the whole clip,+// so every step of a long run leaves one playable video.+// windows One pass with sliding context windows instead of sections.+//+// The lib side (lib/long-video.ts) says how many sections and how long.++import type { ComfyApiGraph, ComfyInputValue, ComfyNodeInputs } from '../types/comfy-graph'+import { readComboOptions } from './comfyui-enum'+import { contextWindowFor } from '../lib/long-video'++type Ref = [string, number]+type NodeTable = Record<string, unknown>++/** Where a section continues from: the clip so far, as ComfyUI's input+ * folder names it after the upload, and how many of its last frames the new+ * section repeats. */+export interface ContinueFrom {+ video: string+ overlap: number+}++/** The thrown text when the core is too old for these nodes. */+export const CONTINUE_NEEDS_UPDATE =+ 'Continuing a video needs ComfyUI\'s video nodes (LoadVideo, GetVideoComponents). Update ComfyUI, then try again.'++/** Inputs of a node from its live schema: the given values, plus the declared+ * default (or a combo's first option) for every other REQUIRED input, so a+ * newer core that adds a required widget still validates. Optional inputs+ * are only sent when given. */+export function inputsFromSchema(allNodes: NodeTable, classType: string, given: ComfyNodeInputs): ComfyNodeInputs {+ const meta = allNodes[classType] as { input?: { required?: Record<string, ComfyInputValue> } } | undefined+ const required = meta?.input?.required ?? {}+ const inputs: ComfyNodeInputs = { ...given }+ for (const [key, spec] of Object.entries(required)) {+ if (inputs[key] !== undefined) continue+ const cfg = Array.isArray(spec) && spec[1] && typeof spec[1] === 'object' && !Array.isArray(spec[1])+ ? (spec[1] as { default?: ComfyInputValue })+ : undefined+ if (cfg?.default !== undefined) { inputs[key] = cfg.default; continue }+ const combo = readComboOptions(spec)+ if (combo && combo.length) inputs[key] = combo[0]+ }+ return inputs+}++/** True when the node declares this input (required or optional). */+export function declaresInput(allNodes: NodeTable, classType: string, input: string): boolean {+ const meta = allNodes[classType] as { input?: { required?: Record<string, unknown>; optional?: Record<string, unknown> } } | undefined+ return !!(meta?.input?.required?.[input] ?? meta?.input?.optional?.[input])+}++export interface ContinueSource {+ n: number+ /** Every frame of the clip so far. */+ frames: Ref+ /** Its sound (GetVideoComponents' AUDIO output, empty for a silent clip). */+ audio: Ref+ /** The last `overlap` frames. */+ tail: Ref+ /** The clip's very first frame. */+ first: Ref+}++/** LoadVideo → GetVideoComponents → the tail and the first frame. */+export function addContinueSource(workflow: ComfyApiGraph, n: number, from: ContinueFrom, allNodes: NodeTable): ContinueSource {+ const missing = ['LoadVideo', 'GetVideoComponents', 'ImageFromBatch'].filter((c) => !allNodes[c])+ if (missing.length) throw new Error(CONTINUE_NEEDS_UPDATE)+ const loadId = String(n++)+ workflow[loadId] = { class_type: 'LoadVideo', inputs: { file: from.video }, _meta: { title: 'Clip so far' } }+ const partsId = String(n++)+ workflow[partsId] = { class_type: 'GetVideoComponents', inputs: { video: [loadId, 0] } }+ const tailId = String(n++)+ workflow[tailId] = {+ class_type: 'ImageFromBatch',+ inputs: { image: [partsId, 0], batch_index: -Math.max(1, from.overlap), length: Math.max(1, from.overlap) },+ _meta: { title: 'Last frames' },+ }+ const firstId = String(n++)+ workflow[firstId] = { class_type: 'ImageFromBatch', inputs: { image: [partsId, 0], batch_index: 0, length: 1 }, _meta: { title: 'First frame' } }+ return { n, frames: [partsId, 0], audio: [partsId, 1], tail: [tailId, 0], first: [firstId, 0] }+}++/** The new section without its repeated frames, behind the clip so far.+ * Returns the joined frames. */+export function addStitch(workflow: ComfyApiGraph, n: number, before: Ref, section: Ref, overlap: number, allNodes: NodeTable): { n: number; images: Ref } {+ const restId = String(n++)+ workflow[restId] = {+ class_type: 'ImageFromBatch',+ inputs: { image: section, batch_index: Math.max(0, overlap), length: 4096 },+ _meta: { title: 'New frames' },+ }+ const joinId = String(n++)+ workflow[joinId] = allNodes['BatchImagesNode']+ ? { class_type: 'BatchImagesNode', inputs: { 'images.image0': before, 'images.image1': [restId, 0] }, _meta: { title: 'Whole clip' } }+ : { class_type: 'ImageBatch', inputs: { image1: before, image2: [restId, 0] }, _meta: { title: 'Whole clip' } }+ return { n, images: [joinId, 0] }+}++/** The sound of a section without its repeated overlap, behind the sound so+ * far (LTX 2.5 makes picture and sound together). */+export function addAudioStitch(workflow: ComfyApiGraph, n: number, before: Ref, section: Ref, overlapSeconds: number, allNodes: NodeTable): { n: number; audio: Ref } | null {+ if (!allNodes['TrimAudioDuration'] || !allNodes['AudioConcat']) return null+ const trimId = String(n++)+ workflow[trimId] = { class_type: 'TrimAudioDuration', inputs: { audio: section, start_index: Math.max(0, overlapSeconds), duration: 3600 } }+ const joinId = String(n++)+ workflow[joinId] = { class_type: 'AudioConcat', inputs: { audio1: before, audio2: [trimId, 0], direction: 'after' } }+ return { n, audio: [joinId, 0] }+}++/** Context windows on a model, when the clip is longer than one window and+ * the core has the family's node. Returns the patched model, or the given+ * one untouched. */+export function addContextWindows(+ workflow: ComfyApiGraph, n: number, model: Ref, type: string, frames: number, allNodes: NodeTable,+): { n: number; model: Ref } {+ const win = contextWindowFor(type)+ if (!win || frames <= win.length || !allNodes[win.node]) return { n, model }+ const id = String(n++)+ workflow[id] = {+ class_type: win.node,+ inputs: inputsFromSchema(allNodes, win.node, {+ model, context_length: win.length, context_overlap: win.overlap,+ }),+ _meta: { title: 'Context windows' },+ }+ return { n, model: [id, 0] }+}diff --git a/src/api/video-settle.ts b/src/api/video-settle.tsnew file mode 100644index 00000000..9e5c33ba--- /dev/null+++ b/src/api/video-settle.ts@@ -0,0 +1,37 @@+// The colour settle at the seams of a long clip (B18, 3.0.9). The work is a+// numpy step in ComfyUI's own Python, started by the Rust command+// video_color_settle (src-tauri/src/commands/video_settle.rs): each section+// is matched to the settled one before it, so the whole clip keeps the+// colours of its first section. The command only reaches a ComfyUI LU manages+// on this machine; anywhere else this returns null and the clip stays as it+// came out.++import { backendCall, isTauri } from './backend'+import { log } from '../lib/logger'++export interface SettleReport {+ filename: string+ subfolder: string+ frames?: number+}++/** The settled copy of a ComfyUI output video, or null when it cannot be made. */+export async function settleSeams(+ item: { filename?: string; subfolder?: string; comfyType?: string },+ boundaries: number[],+): Promise<SettleReport | null> {+ if (!isTauri() || !item.filename || boundaries.length === 0) return null+ try {+ const report = await backendCall<SettleReport>('video_color_settle', {+ filename: item.filename,+ subfolder: item.subfolder ?? '',+ folderType: item.comfyType === 'input' ? 'input' : 'output',+ boundaries,+ window: 5,+ })+ return report?.filename ? report : null+ } catch (e) {+ log.info(`[video-settle] skipped: ${e instanceof Error ? e.message : String(e)}`)+ return null+ }+}diff --git a/src/components/create/experimental/LongVideoControls.tsx b/src/components/create/experimental/LongVideoControls.tsxnew file mode 100644index 00000000..5af7cd93--- /dev/null+++ b/src/components/create/experimental/LongVideoControls.tsx@@ -0,0 +1,150 @@+// Speed, length in seconds and the cost line for a local video run (B18,+// 3.0.9). Lives under the Frames slider on ComfyUI hosts.+//+// Speed Fast (lightx2v 4 steps) or Quality, for the Wan 14B models that+// have the speed LoRAs (lib/wan-speed). Hidden for every other model.+// Length Seconds up to 30 for the families that can continue a clip+// (lib/long-video): Wan, Wan 2.2 5B, LTX 2.5. Up to the native+// length it is one run; past it the clip is made in sections, and+// the line says how many. On Extend Video it is the time to add.+// How Sections (default) or one pass with context windows.+// Cost The estimate before the run (lib/video-estimate), with the card+// it is measured on, and what goes to system memory when it does+// not fit.+import { useMemo } from 'react'+import { useCreateStore } from '../../../stores/createStore'+import { classifyModel } from '../../../api/comfyui'+import { getVideoBundles } from '../../../api/model-bundles'+import { useGraphicsCardGb } from '../../../hooks/useGraphicsMemory'+import { hasWanFastMode, type VideoSpeed } from '../../../lib/wan-speed'+import { MAX_LONG_SECONDS, planLongVideo, sectionSpec, secondsOf, type LongVideoMode } from '../../../lib/long-video'+import { planExtension } from '../../../lib/long-video-run'+import { estimateVideoRun } from '../../../lib/video-estimate'+import { Slider } from '../ui/Slider'+import { cn } from '../ui/cn'++let weightTable: Map<string, number> | null = null+/** The largest file of the bundle a model file belongs to, in GB. */+function weightGbOf(model: string): number | null {+ if (!weightTable) {+ weightTable = new Map()+ for (const b of getVideoBundles()) {+ for (const f of b.files) if (f.filename && f.sizeGB && f.subfolder === 'diffusion_models') weightTable.set(f.filename, f.sizeGB)+ }+ }+ return weightTable.get(model) ?? null+}++function Choice<T extends string>({ label, value, options, onChange }: {+ label: string+ value: T+ options: { id: T; label: string; title?: string }[]+ onChange: (v: T) => void+}) {+ return (+ <div role="radiogroup" aria-label={label} className="flex flex-wrap items-center gap-1.5">+ <span className="w-full t-label text-gray-500">{label}</span>+ {options.map((o) => (+ <button+ key={o.id}+ type="button"+ role="radio"+ aria-checked={o.id === value}+ title={o.title}+ onClick={() => onChange(o.id)}+ className={cn(+ 'rounded-md border px-2 py-1 t-control transition-colors',+ o.id === value ? 'border-white/20 bg-white/[0.07] text-gray-200' : 'border-white/[0.07] text-gray-500 hover:text-gray-300',+ )}+ >+ {o.label}+ </button>+ ))}+ </div>+ )+}++export function LongVideoControls({ model, intent }: { model: string; intent: string }) {+ const s = useCreateStore()+ const cardGb = useGraphicsCardGb()+ const type = s.videoModelList.find((m) => m.name === model)?.type ?? classifyModel(model)+ const spec = sectionSpec(type)+ const fast = hasWanFastMode(model)+ const extend = intent === 'extend'+ const nativeSeconds = spec ? Math.round((spec.native / spec.fps) * 10) / 10 : 0+ const seconds = s.longVideoSeconds+ const long = !!spec && (extend ? !!s.extendClip : seconds * (s.fps || spec.fps) > spec.native)++ const plan = useMemo(() => {+ if (!spec) return null+ if (extend) return planExtension(type, seconds > 0 ? seconds : (spec.native - spec.overlap) / spec.fps, s.fps)+ return seconds > 0 ? planLongVideo(type, seconds, s.fps) : null+ }, [spec, extend, type, seconds, s.fps])++ const estimate = useMemo(() => estimateVideoRun({+ type, model,+ width: s.width, height: s.height,+ frames: s.frames, steps: s.steps, cfgScale: s.cfgScale,+ ...(long && plan ? { seconds: extend ? plan.seconds + nativeSeconds : plan.seconds, fps: plan.fps } : {}),+ weightGb: weightGbOf(model),+ cardGb,+ }), [type, model, s.width, s.height, s.frames, s.steps, s.cfgScale, long, plan, extend, nativeSeconds, cardGb])++ return (+ <div className="space-y-2" data-testid="long-video-controls">+ {fast && (+ <Choice<VideoSpeed>+ label="Speed"+ value={s.steps <= 8 && s.cfgScale <= 1.5 ? 'fast' : 'quality'}+ onChange={s.setVideoSpeed}+ options={[+ { id: 'fast', label: 'Fast · 4 steps', title: 'lightx2v speed LoRAs: 4 steps at cfg 1. Motion can come out a little calmer.' },+ { id: 'quality', label: 'Quality', title: 'The official template without speed LoRAs. About 10 times slower.' },+ ]}+ />+ )}+ {spec && (+ <Slider+ label={extend ? 'Add' : 'Length'}+ min={0}+ max={MAX_LONG_SECONDS}+ step={1}+ value={Math.min(MAX_LONG_SECONDS, Math.max(0, seconds))}+ onChange={s.setLongVideoSeconds}+ format={(v) => {+ if (extend) {+ const p = planExtension(type, v > 0 ? v : (spec.native - spec.overlap) / spec.fps, s.fps)+ return p ? `+${p.seconds.toFixed(1)} s · ${p.sections.length} section${p.sections.length > 1 ? 's' : ''}` : '—'+ }+ if (v === 0) return `Frames slider (${secondsOf(s.frames, s.fps)} s)`+ const p = planLongVideo(type, v, s.fps)+ return p && p.sections.length > 1 ? `${p.seconds.toFixed(1)} s · ${p.sections.length} sections` : `${v} s · one run`+ }}+ />+ )}+ {spec && !extend && long && (+ <Choice<LongVideoMode>+ label="Made as"+ value={s.longVideoMode}+ onChange={s.setLongVideoMode}+ options={[+ { id: 'sections', label: 'Sections', title: `Each ${nativeSeconds} s section continues from the last frames of the one before. Best for action.` },+ { id: 'one-pass', label: 'One pass', title: 'One run with sliding context windows. Even, but tends to repeat itself.' },+ ]}+ />+ )}+ {spec && long && (+ <p className="t-micro text-gray-500" data-testid="long-video-note">+ {extend+ ? 'Continues from the last frames of the clip, the result is the whole clip, longer.'+ : s.longVideoMode === 'one-pass'+ ? 'One run past the native length. Keeps the scene even; motion may repeat.'+ : `Past ${nativeSeconds} s the clip is made in sections. Each one continues from the last frames, colours are matched at every seam.`}+ </p>+ )}+ {estimate && (+ <p className="t-micro text-gray-500" data-testid="video-estimate">{estimate.line}</p>+ )}+ </div>+ )+}diff --git a/src/components/create/experimental/ParamGroups.tsx b/src/components/create/experimental/ParamGroups.tsxindex c257cfca..caba1542 100644--- a/src/components/create/experimental/ParamGroups.tsx+++ b/src/components/create/experimental/ParamGroups.tsx@@ -32,6 +32,7 @@ import { supportsTransparent } from '../../../lib/transparent-image'import { QWEN_ENCODER_HELP, pickQwenEncoder, qwenEncoderOptions, type QwenEncoderVariant } from '../../../lib/render/qwen-text-encoder'import { MAX_SHOTS, MAX_SHOT_CHARS, supportsMultishot } from '../../../lib/ltx-multishot'import { frameRangeFor, framesOnRange, lengthHint } from '../../../lib/video-length'+import { LongVideoControls } from './LongVideoControls'import { useMacMemoryGb } from '../../../lib/mac-memory'// Video families whose dynamic-workflow strategy actually wires a LoRA node:@@ -432,6 +433,11 @@ export function ParamGroups() {{framesHint && (<p className="col-span-2 t-micro text-gray-500" data-testid="video-length-hint">{framesHint}</p>)}+ {!isCloud && (+ <div className="col-span-2">+ <LongVideoControls model={laneModel} intent={meta.id} />+ </div>+ )}</div>)}{macClip && (diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsxindex 21c81a69..71f8789f 100644--- a/src/components/create/experimental/SpecialIntentControls.tsx+++ b/src/components/create/experimental/SpecialIntentControls.tsx@@ -1463,14 +1463,19 @@ function LocalExtendControls() {const panelRef = useRef<HTMLDivElement>(null)const panel = usePopoverPlatz(panelRef, open, { bevorzugt: 'oben', abstand: 6, deckel: 256 })- const adopt = async (getUrl: () => Promise<{ url: string; revoke?: () => void }>, label: string) => {+ const setExtendClip = useCreateStore((s) => s.setExtendClip)+ const adopt = async (getUrl: () => Promise<{ url: string; revoke?: () => void; blob?: Blob }>, label: string) => {setBusy(true)setError(null)try {- const { url, revoke } = await getUrl()+ const { url, revoke, blob } = await getUrl()try {const frame = await lastFrameFile(url, label)setSource(await loadImageRef(frame))+ // B18: the clip itself goes along too. Wan and LTX 2.5 continue from+ // its last frames instead of the one still, and the result is the+ // whole clip, longer (lib/long-video-run).+ setExtendClip(blob ?? null)setPickedLabel(label)} finally {revoke?.()@@ -1487,13 +1492,13 @@ function LocalExtendControls() {adopt(async () => {const blob = await fetchGalleryItemBlob(g)const url = URL.createObjectURL(blob)- return { url, revoke: () => URL.revokeObjectURL(url) }+ return { url, revoke: () => URL.revokeObjectURL(url), blob }}, g.prompt.slice(0, 40) || 'Local video')const fromFile = (f: File) =>adopt(async () => {const url = URL.createObjectURL(f)- return { url, revoke: () => URL.revokeObjectURL(url) }+ return { url, revoke: () => URL.revokeObjectURL(url), blob: f }}, f.name)const value = source && pickedLabel ? pickedLabel : null@@ -1528,7 +1533,7 @@ function LocalExtendControls() {</button>{value && (<button- onClick={() => { setSource(null); setPickedLabel(null) }}+ onClick={() => { setSource(null); setExtendClip(null); setPickedLabel(null) }}className="p-1 text-gray-500 hover:text-gray-300" title="Clear" aria-label="Clear"><X size={11} />diff --git a/src/components/create/experimental/__tests__/expert-visibility.test.ts b/src/components/create/experimental/__tests__/expert-visibility.test.tsindex b7396b98..343962ed 100644--- a/src/components/create/experimental/__tests__/expert-visibility.test.ts+++ b/src/components/create/experimental/__tests__/expert-visibility.test.ts@@ -7,7 +7,7 @@ import { ParamGroups } from '../ParamGroups'const host = vi.hoisted(() => ({ mlx: false }))vi.mock('../../../../api/mlx-image', () => ({ isMlxImageHost: () => host.mlx }))-vi.mock('../../../../api/comfyui', () => ({ classifyModel: (name?: string) => (name?.startsWith('wan') ? 'wan' : 'sdxl'), resolveLocalOpPick: (pick: string) => pick }))+vi.mock('../../../../api/comfyui', () => ({ classifyModel: (name?: string) => (name?.startsWith('wan') ? 'wan' : 'sdxl'), resolveLocalOpPick: (pick: string) => pick, getSystemVRAM: async () => null }))vi.mock('../CreateContext', () => ({ useCreateExp: () => ({samplerList: [], schedulerList: [], loraList: [], vaeList: [], refreshModelLists: vi.fn(),}) }))diff --git a/src/components/create/experimental/__tests__/qwen-text-encoder-oberflaeche.test.tsx b/src/components/create/experimental/__tests__/qwen-text-encoder-oberflaeche.test.tsxindex 859c4158..115d654d 100644--- a/src/components/create/experimental/__tests__/qwen-text-encoder-oberflaeche.test.tsx+++ b/src/components/create/experimental/__tests__/qwen-text-encoder-oberflaeche.test.tsx@@ -12,6 +12,8 @@ const host = vi.hoisted(() => ({ mlx: false }))vi.mock('../../../../api/mlx-image', () => ({ isMlxImageHost: () => host.mlx }))vi.mock('../../../../api/comfyui', () => ({classifyModel: (n: string) => (/qwen_image_2\.1/.test(n) ? 'qwenimage' : 'sdxl'),+ // B18: the video length controls ask for the card size.+ getSystemVRAM: async () => null,isI2VModel: () => false,isT2VCapable: () => true,getImageUrl: (f: string) => `http://127.0.0.1:8188/view?filename=${f}`,diff --git a/src/components/create/experimental/__tests__/transparent-background-oberflaeche.test.tsx b/src/components/create/experimental/__tests__/transparent-background-oberflaeche.test.tsxindex ffdb5a29..231cd949 100644--- a/src/components/create/experimental/__tests__/transparent-background-oberflaeche.test.tsx+++ b/src/components/create/experimental/__tests__/transparent-background-oberflaeche.test.tsx@@ -10,6 +10,8 @@ const host = vi.hoisted(() => ({ mlx: false }))vi.mock('../../../../api/mlx-image', () => ({ isMlxImageHost: () => host.mlx }))vi.mock('../../../../api/comfyui', () => ({classifyModel: (n: string) => (/qwen_image_2\.1/.test(n) ? 'qwenimage' : 'sdxl'),+ // B18: the video length controls ask for the card size.+ getSystemVRAM: async () => null,isI2VModel: () => false,isT2VCapable: () => true,getImageUrl: (f: string) => `http://127.0.0.1:8188/view?filename=${f}`,diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.tsindex 6165052f..883c16ad 100644--- a/src/hooks/useCreate.ts+++ b/src/hooks/useCreate.ts@@ -95,7 +95,7 @@ import {} from '../api/trainer'import { getMacTrainStatus, macTrainMissing } from '../api/mlx-train'import { buildTrainCaption } from '../lib/train-captions'-import { useCreateStore, EDIT_MAX_DENOISE, characterImageRun, deriveIntent, type CreateState } from '../stores/createStore'+import { useCreateStore, EDIT_MAX_DENOISE, characterImageRun, deriveIntent, type CreateState, type GalleryItem } from '../stores/createStore'import { useWorkflowStore } from '../stores/workflowStore'import { useSettingsStore } from '../stores/settingsStore'import { renderStallLimitMs, renderStallMessage } from '../lib/tool-timeout'@@ -120,6 +120,8 @@ import {} from '../lib/character-run'import { defaultLoraStrength } from '../lib/lora-strength'import { fetchGalleryItemBlob } from '../components/create/experimental/galleryUrl'+import { LongRunStopped, longVideoRequest, runLongVideo, type ClipItem } from '../lib/long-video-run'+import { settleSeams } from '../api/video-settle'import { loadImageRef } from '../components/create/experimental/loadImage'import { listMlxLoras } from '../api/mlx-loras'import {@@ -185,6 +187,19 @@ interface RunOpts {stepLabel?: string/** The character's trigger word, kept in a prompt the chat model rewrote. */trigger?: string+ /** A later section of a long clip (B18): the clip so far in ComfyUI's+ * input folder and the frames this section repeats from it. */+ continueFrom?: { video: string; overlap: number }+ /** One pass with context windows past the native length (B18). */+ contextWindows?: boolean+}++/** The long clip fields of one run, as the workflow builder takes them. */+function longVideoParams(opts: RunOpts): { continueFrom?: { video: string; overlap: number }; contextWindows?: boolean } {+ return {+ ...(opts.continueFrom ? { continueFrom: opts.continueFrom } : {}),+ ...(opts.contextWindows ? { contextWindows: true } : {}),+ }}/** The store as one run reads it: the live state with this run's fields@@ -1629,7 +1644,7 @@ export function useCreate() {// feeding a start image to a t2v-only checkpoint — that either errors in// ComfyUI or silently ignores the source. The ModelChip already filters// the picker; this guards a stale store selection reaching submit.- if (intent === 'animate' || intent === 'extend') {+ if ((intent === 'animate' || intent === 'extend') && !opts.continueFrom) {if (!effI2vImage) {setError(intent === 'extend'? 'Pick the clip to extend first. Its last frame becomes the starting point.'@@ -1907,7 +1922,7 @@ export function useCreate() {// Dynamic workflow builder — auto-detects nodes and builds the right pipelinesetProgress(5, 'Building workflow...')try {- const genParams = mode === 'video' ? { ...baseParams, frames, fps, ...(effI2vImage ? { inputImage: effI2vImage } : {}) } : baseParams+ const genParams = mode === 'video' ? { ...baseParams, frames, fps, ...(effI2vImage ? { inputImage: effI2vImage } : {}), ...longVideoParams(opts) } : baseParams// 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(@@ -1997,7 +2012,7 @@ export function useCreate() {return}// Re-build the workflow now that the new node is available- const genParams = { ...baseParams, frames, fps, ...(effI2vImage ? { inputImage: effI2vImage } : {}) }+ const genParams = { ...baseParams, frames, fps, ...(effI2vImage ? { inputImage: effI2vImage } : {}), ...longVideoParams(opts) }workflow = await buildDynamicWorkflow(genParams, imageModelType)setProgress(10, 'VHS installed, generating MP4...')} catch (instErr) {@@ -2495,6 +2510,59 @@ export function useCreate() {const generateInner = useCallback(async () => {const s = useCreateStore.getState()const mac = isMlxImageHost()+ // A long local clip (B18): several sections, each continuing the clip so+ // far, or one pass with context windows. ComfyUI only; the Mac's MLX+ // lanes keep their own lengths.+ if (!mac && s.backend === 'local' && !isLocalCharacter(s.selectedCharacter)) {+ const intent = s.intent()+ const lane = s.videoModelList.length > 0 ? videoLaneModels(s.videoModelList, intent) : []+ const model = lane.length > 0 && !lane.some((m) => m.name === s.videoModel) ? lane[0].name : s.videoModel+ const long = longVideoRequest({+ mode: s.mode, intent, model,+ type: s.videoModelList.find((m) => m.name === model)?.type ?? classifyModel(model),+ installed: s.videoModelList.map((m) => m.name),+ longVideoSeconds: s.longVideoSeconds, longVideoMode: s.longVideoMode,+ fps: s.fps, frames: s.frames, extendClip: s.extendClip,+ })+ if (long?.kind === 'error') { s.setError(long.message); return }+ if (long?.kind === 'one-pass') { await runOnce({ frames: long.frames }, { contextWindows: true }); return }+ if (long?.kind === 'sections') {+ const own = new AbortController()+ chainAbort.current = own+ s.setError(null)+ try {+ await runLongVideo(long.plan, long.start, {+ run: (override, opts) => runOnce(override as Partial<CreateState>, opts),+ gallery: () => useCreateStore.getState().gallery,+ error: () => useCreateStore.getState().error,+ fetchBlob: (item) => fetchGalleryItemBlob(item as GalleryItem),+ upload: (blob, name) => uploadMediaFile(blob, name),+ remove: (id) => useCreateStore.getState().removeFromGallery(id),+ settle: async (item: ClipItem, seams) => {+ const settled = await settleSeams(item, seams)+ if (!settled) return null+ const st = useCreateStore.getState()+ const old = st.gallery.find((g) => g.id === item.id)+ if (!old) return null+ const next = { ...old, id: uuid(), filename: settled.filename, subfolder: settled.subfolder }+ st.addToGallery(next)+ st.removeFromGallery(old.id)+ return next+ },+ aborted: () => own.signal.aborted,+ })+ } catch (e) {+ if (!(e instanceof LongRunStopped) || e.message !== 'Stopped.') {+ useCreateStore.getState().setError(e instanceof Error ? e.message : String(e))+ }+ } finally {+ if (chainAbort.current === own) chainAbort.current = null+ useCreateStore.getState().setIsGenerating(false)+ useCreateStore.getState().setProgress(0)+ }+ return+ }+ }if (s.backend !== 'local' || !isLocalCharacter(s.selectedCharacter)) {await runOnce()returndiff --git a/src/lib/__tests__/a-known-lora-is-offered-where-it-runs.test.ts b/src/lib/__tests__/a-known-lora-is-offered-where-it-runs.test.tsindex a0d6bae0..adc722b0 100644--- a/src/lib/__tests__/a-known-lora-is-offered-where-it-runs.test.ts+++ b/src/lib/__tests__/a-known-lora-is-offered-where-it-runs.test.ts@@ -36,7 +36,7 @@ describe('what the app knows about a LoRA', () => {it('every LoRA add-on of the catalogue is known, with its family and its catalogue name', () => {const addons = getLoraAddonBundles()- expect(addons.map((b) => b.name)).toEqual(['Pixel Art XL · SDXL LoRA', 'MiniMax H3 Turbo LoRA · 8 Steps'])+ expect(addons.map((b) => b.name)).toEqual(['Pixel Art XL · SDXL LoRA', 'Wan 2.1 14B Speed LoRAs · 4 Steps', 'MiniMax H3 Turbo LoRA · 8 Steps'])for (const b of addons) {for (const f of b.files) {expect(knownLora(f.filename!), f.filename).toEqual({ family: b.workflow, familyLabel: b.tags[0], catalogName: b.name })diff --git a/src/lib/__tests__/long-video.test.ts b/src/lib/__tests__/long-video.test.tsnew file mode 100644index 00000000..e9151cbd--- /dev/null+++ b/src/lib/__tests__/long-video.test.ts@@ -0,0 +1,242 @@+/**+ * B18 (3.0.9): long local clips and Fast mode, the parts without ComfyUI.+ *+ * Run: npx vitest run src/lib/__tests__/long-video.test.ts+ */+import { describe, it, expect } from 'vitest'+import { planLongVideo, framesForSeconds, secondsOf, canMakeLongVideo } from '../long-video'+import { continueModelFor, longVideoRequest, planExtension, runLongVideo, LongRunStopped, type ClipItem, type LongVideoAsk } from '../long-video-run'+import { findWanSpeedLora, hasWanFastMode, isFastSampling, wanSamplingFor, wanSpeedKind } from '../wan-speed'+import { estimateVideoRun, minutesText } from '../video-estimate'++describe('planLongVideo: sections on the family grid', () => {+ it('Wan: 30 s at 16 fps is 81 + six sections of 76 new frames, never shorter than asked', () => {+ const p = planLongVideo('wan', 30, 16)!+ expect(p.sections[0]).toBe(81)+ expect(p.overlap).toBe(5)+ for (const f of p.sections) expect((f - 1) % 4).toBe(0)+ expect(p.totalFrames).toBeGreaterThanOrEqual(480)+ expect(p.totalFrames - 480).toBeLessThan(4)+ expect(p.sections).toHaveLength(7)+ expect(p.seconds).toBeGreaterThanOrEqual(30)+ })++ it('a short clip is one run', () => {+ expect(planLongVideo('wan', 4, 16)!.sections).toEqual([65])+ })++ it('LTX 2.5: 10 s sections of 8n+1 frames with 17 repeated', () => {+ const p = planLongVideo('ltx25', 30, 24)!+ expect(p.sections[0]).toBe(241)+ for (const f of p.sections) expect((f - 1) % 8).toBe(0)+ expect(p.totalFrames).toBeGreaterThanOrEqual(720)+ expect(p.sections).toHaveLength(4)+ })++ it('families without a way to continue stay out', () => {+ for (const t of ['hunyuan', 'framepack', 'minimaxh3', 'mochi', 'svd']) {+ expect(canMakeLongVideo(t)).toBe(false)+ expect(planLongVideo(t, 30, 24)).toBeNull()+ }+ })++ it('seconds and frames agree', () => {+ expect(framesForSeconds('wan', 5, 16)).toBe(81)+ expect(framesForSeconds('ltx25', 10, 24)).toBe(241)+ expect(secondsOf(81, 16)).toBe(5.1)+ })+})++describe('planExtension: every section continues', () => {+ it('+5 s of Wan is one section of 81 frames (5 repeated + 76 new)', () => {+ const p = planExtension('wan', 4.75, 16)!+ expect(p.sections).toEqual([81])+ expect(p.totalFrames).toBe(76)+ })+ it('+25 s of Wan is six sections', () => {+ expect(planExtension('wan', 25, 16)!.sections.length).toBe(6)+ })+})++describe('continueModelFor: the image to video model of the same family', () => {+ const installed = ['Wan2.2-T2V-A14B-HighNoise-Q4_K_S.gguf', 'Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf', 'Wan2.2-I2V-A14B-LowNoise-Q4_K_S.gguf']+ it('a T2V A14B file continues with its I2V twin', () => {+ expect(continueModelFor('Wan2.2-T2V-A14B-HighNoise-Q4_K_S.gguf', 'wan', installed)).toBe('Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf')+ })+ it('an I2V file, the 5B and LTX 2.5 continue with themselves', () => {+ expect(continueModelFor('Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf', 'wan', installed)).toBe('Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf')+ expect(continueModelFor('wan2.2_ti2v_5B_fp16.safetensors', 'wan22', [])).toBe('wan2.2_ti2v_5B_fp16.safetensors')+ expect(continueModelFor('ltx-2.5-22b-distilled.safetensors', 'ltx25', [])).toBe('ltx-2.5-22b-distilled.safetensors')+ })+ it('null without an I2V model', () => {+ expect(continueModelFor('wan2.1_t2v_1.3B_bf16.safetensors', 'wan', ['wan2.1_t2v_1.3B_bf16.safetensors'])).toBeNull()+ })+})++describe('longVideoRequest: what a Create press means', () => {+ const ask = (over: Partial<LongVideoAsk> = {}): LongVideoAsk => ({+ mode: 'video', intent: 'video', model: 'Wan2.2-T2V-A14B-HighNoise-Q4_K_S.gguf', type: 'wan',+ installed: ['Wan2.2-T2V-A14B-HighNoise-Q4_K_S.gguf', 'Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf'],+ longVideoSeconds: 30, longVideoMode: 'sections', fps: 16, frames: 81, extendClip: null, ...over,+ })+ it('30 s: sections, first T2V, then I2V', () => {+ const r = longVideoRequest(ask())!+ expect(r.kind).toBe('sections')+ if (r.kind !== 'sections') return+ expect(r.start.firstModel).toBe('Wan2.2-T2V-A14B-HighNoise-Q4_K_S.gguf')+ expect(r.start.continueModel).toBe('Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf')+ })+ it('within the native length: an ordinary run', () => {+ expect(longVideoRequest(ask({ longVideoSeconds: 5 }))).toBeNull()+ expect(longVideoRequest(ask({ longVideoSeconds: 0 }))).toBeNull()+ })+ it('one pass: the whole length as frames', () => {+ const r = longVideoRequest(ask({ longVideoMode: 'one-pass' }))!+ expect(r).toMatchObject({ kind: 'one-pass' })+ })+ it('no I2V twin: says what to install', () => {+ const r = longVideoRequest(ask({ installed: ['Wan2.2-T2V-A14B-HighNoise-Q4_K_S.gguf'] }))!+ expect(r.kind).toBe('error')+ })+ it('Extend Video with a clip continues it', () => {+ const r = longVideoRequest(ask({ intent: 'extend', model: 'Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf', extendClip: new Blob(['x']), longVideoSeconds: 10 }))!+ expect(r.kind).toBe('sections')+ if (r.kind === 'sections') expect(r.start.clip).toBeDefined()+ })+ it('Hunyuan and the image tab stay ordinary', () => {+ expect(longVideoRequest(ask({ type: 'hunyuan' }))).toBeNull()+ expect(longVideoRequest(ask({ mode: 'image' }))).toBeNull()+ })+})++describe('runLongVideo: section after section, one clip in the gallery', () => {+ function fakeDeps(opts: { failAt?: number } = {}) {+ let gallery: ClipItem[] = []+ const calls: Array<{ override: Record<string, unknown>; opts: { stepLabel: string; continueFrom?: { video: string; overlap: number } } }> = []+ const uploads: string[] = []+ const removed: string[] = []+ let error: string | null = null+ let n = 0+ return {+ calls, uploads, removed,+ galleryNow: () => gallery,+ deps: {+ run: async (override: Record<string, unknown>, o: { stepLabel: string; continueFrom?: { video: string; overlap: number } }) => {+ calls.push({ override, opts: o })+ n+++ if (opts.failAt === n) { error = 'ComfyUI said no'; return }+ gallery = [{ id: `v${n}`, type: 'video', filename: `out_${n}.mp4` }, ...gallery]+ },+ gallery: () => gallery,+ error: () => error,+ fetchBlob: async (item: ClipItem) => new Blob([item.filename ?? '']),+ upload: async (_b: Blob, name: string) => { uploads.push(name); return name },+ remove: (id: string) => { removed.push(id); gallery = gallery.filter((g) => g.id !== id) },+ aborted: () => false,+ },+ }+ }++ it('runs every section, continues from the newest clip and keeps only the last', async () => {+ const f = fakeDeps()+ const plan = planLongVideo('wan', 15, 16)!+ const done = await runLongVideo(plan, { firstModel: 'T2V', continueModel: 'I2V' }, f.deps)+ expect(f.calls).toHaveLength(plan.sections.length)+ expect(f.calls[0].override).toMatchObject({ videoModel: 'T2V', frames: 81 })+ expect(f.calls[0].opts.continueFrom).toBeUndefined()+ for (const c of f.calls.slice(1)) {+ expect(c.override).toMatchObject({ videoModel: 'I2V', cloudOp: 'extend' })+ expect(c.opts.continueFrom?.overlap).toBe(5)+ }+ expect(f.galleryNow().map((g) => g.id)).toEqual([done!.id])+ expect(f.calls[2].opts.stepLabel).toBe(`Section 3 of ${plan.sections.length}`)+ })++ it('a brought clip is continued and never removed', async () => {+ const f = fakeDeps()+ const plan = planExtension('wan', 10, 16)!+ await runLongVideo(plan, { firstModel: 'I2V', continueModel: 'I2V', clip: new Blob(['mine']) }, f.deps)+ expect(f.calls).toHaveLength(plan.sections.length)+ expect(f.calls[0].opts.continueFrom).toBeDefined()+ expect(f.removed).not.toContain('mine')+ })++ it('stops at a failed section with its error and keeps what was made', async () => {+ const f = fakeDeps({ failAt: 3 })+ await expect(runLongVideo(planLongVideo('wan', 30, 16)!, { firstModel: 'T', continueModel: 'I' }, f.deps)).rejects.toThrow(LongRunStopped)+ expect(f.galleryNow()).toHaveLength(1)+ })++ it('settles the seams at the right frames when it can', async () => {+ const f = fakeDeps()+ const seen: number[][] = []+ await runLongVideo(planLongVideo('wan', 15, 16)!, { firstModel: 'T', continueModel: 'I' }, {+ ...f.deps,+ settle: async (item, seams) => { seen.push([...seams]); return item },+ })+ expect(seen[0]).toEqual([81])+ expect(seen[1]).toEqual([81, 157])+ })+})++describe('Fast mode for the Wan 14B models', () => {+ it('knows which models have a speed LoRA set', () => {+ expect(wanSpeedKind('Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf')).toBe('a14b-i2v')+ expect(wanSpeedKind('wan2.2_t2v_high_noise_14B_fp8_scaled.safetensors')).toBe('a14b-t2v')+ expect(wanSpeedKind('wan2.1_t2v_14B_fp8_e4m3fn.safetensors')).toBe('wan21-t2v')+ expect(wanSpeedKind('wan2.1_i2v_480p_14B_fp8_e4m3fn.safetensors')).toBe('wan21-i2v')+ expect(wanSpeedKind('wan2.1_t2v_1.3B_bf16.safetensors')).toBeNull()+ expect(wanSpeedKind('wan2.2_ti2v_5B_fp16.safetensors')).toBeNull()+ expect(wanSpeedKind('wan2.2-i2v-rapid-aio-v10-nsfw-Q4_K_M.gguf')).toBeNull()+ expect(hasWanFastMode('ltx-2.5-22b-distilled.safetensors')).toBe(false)+ })++ it('finds the LoRA of each half in both spellings, newest release first', () => {+ const listed = [+ 'wan2.2_i2v_lightx2v_4steps_lora_v1_high_noise.safetensors',+ 'wan2.2_i2v_A14b_high_noise_lora_rank64_lightx2v_4step_1022.safetensors',+ 'wan2.2_i2v_A14b_low_noise_lora_rank64_lightx2v_4step_1022.safetensors',+ 'wan2.2_t2v_A14b_high_noise_lora_rank64_lightx2v_4step_1217.safetensors',+ ]+ expect(findWanSpeedLora('a14b-i2v', 'high', listed)).toBe('wan2.2_i2v_A14b_high_noise_lora_rank64_lightx2v_4step_1022.safetensors')+ expect(findWanSpeedLora('a14b-i2v', 'low', listed)).toBe('wan2.2_i2v_A14b_low_noise_lora_rank64_lightx2v_4step_1022.safetensors')+ expect(findWanSpeedLora('a14b-t2v', 'low', listed)).toBeNull()+ expect(findWanSpeedLora('a14b-i2v', 'high', ['wan2.2_i2v_lightx2v_4steps_lora_v1_high_noise.safetensors'])).toBe('wan2.2_i2v_lightx2v_4steps_lora_v1_high_noise.safetensors')+ })++ it('fast is 4 steps at cfg 1, quality the official template', () => {+ expect(wanSamplingFor('Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf', 'fast')).toMatchObject({ steps: 4, cfgScale: 1, shift: 5 })+ expect(wanSamplingFor('Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf', 'quality')).toMatchObject({ steps: 20, cfgScale: 3.5, shift: 8 })+ expect(isFastSampling(4, 1)).toBe(true)+ expect(isFastSampling(20, 3.5)).toBe(false)+ })+})++describe('the estimate under the button', () => {+ it('a long clip costs about its sections, and says so', () => {+ const one = estimateVideoRun({ type: 'wan', model: 'Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf', width: 832, height: 480, frames: 81, steps: 4, cfgScale: 1, weightGb: 8.15, cardGb: 12 })!+ const long = estimateVideoRun({ type: 'wan', model: 'Wan2.2-I2V-A14B-HighNoise-Q4_K_S.gguf', width: 832, height: 480, frames: 81, steps: 4, cfgScale: 1, seconds: 30, fps: 16, weightGb: 8.15, cardGb: 12 })!+ expect(long.sections).toBe(7)+ expect(long.minutes[0]).toBeGreaterThan(one.minutes[0] * 5)+ expect(long.line).toMatch(/7 sections/)+ expect(long.line).toMatch(/estimate/)+ })+ it('quality at cfg 3.5 costs about ten times fast', () => {+ const fast = estimateVideoRun({ type: 'wan', model: 'x14b', width: 832, height: 480, frames: 81, steps: 4, cfgScale: 1 })!+ const quality = estimateVideoRun({ type: 'wan', model: 'x14b', width: 832, height: 480, frames: 81, steps: 20, cfgScale: 3.5 })!+ expect(quality.minutes[0] / fast.minutes[0]).toBeGreaterThan(4)+ })+ it('a card too small says how much goes to system memory', () => {+ const e = estimateVideoRun({ type: 'wan', model: 'x14b', width: 832, height: 480, frames: 81, steps: 4, cfgScale: 1, weightGb: 8.15, cardGb: 8 })!+ expect(e.offloadGb).toBeGreaterThan(0)+ expect(e.line).toMatch(/system memory/)+ })+ it('no numbers for a family without measurements', () => {+ expect(estimateVideoRun({ type: 'hunyuan', model: 'h', width: 848, height: 480, frames: 45, steps: 30, cfgScale: 6 })).toBeNull()+ })+ it('minutes read short', () => {+ expect(minutesText([0.2, 0.5])).toBe('under 1 min')+ expect(minutesText([3.2, 6.8])).toBe('3–7 min')+ expect(minutesText([21, 44])).toBe('20–45 min')+ })+})diff --git a/src/lib/__tests__/vram-fit.test.ts b/src/lib/__tests__/vram-fit.test.tsindex 66d81d8f..c100134d 100644--- a/src/lib/__tests__/vram-fit.test.ts+++ b/src/lib/__tests__/vram-fit.test.ts@@ -202,6 +202,12 @@ describe('every bundle in the catalogue carries the two numbers', () => {['Pixel Art XL · SDXL LoRA', 0, 1.7, 'fits fits fits fits'],['Wan 2.1 · 1.3B (Lightweight)', 8, 10, 'tight fits fits fits'],['Wan 2.1 · 14B FP8 (High Quality)', 12, 15.5, 'big tight fits fits'],+ // B18: the A14B pair as GGUF with its speed LoRAs. The halves take turns,+ // so the 8.1 GB half is what has to fit; past 10 GB it runs, from 16 GB+ // without moving weights out.+ ['Wan 2.2 A14B · Image to Video, Fast (4 steps)', 10, 16, 'big tight fits fits'],+ ['Wan 2.2 A14B · Text to Video, Fast (4 steps)', 10, 16, 'big tight fits fits'],+ ['Wan 2.1 14B Speed LoRAs · 4 Steps', 12, 12, 'big fits fits fits'],['Wan 2.2 · TI2V 5B (Image + Text to Video)', 12, 12, 'big fits fits fits'],['HunyuanVideo 1.5 T2V FP8 (High Quality)', 12, 12, 'big fits fits fits'],['LTX Video 2.3 · 22B FP8', 16, 29, 'big big tight tight'],@@ -236,6 +242,7 @@ describe('every bundle in the catalogue carries the two numbers', () => {['Krea 2 Companion Files (Text Encoder + VAE)', 'Krea 2 checkpoints'],['SDXL VAE (fp16-fix) · addon', 'SDXL models'],['Pixel Art XL · SDXL LoRA', 'SDXL models'],+ ['Wan 2.1 14B Speed LoRAs · 4 Steps', 'Wan 2.1 14B'],['MiniMax H3 Turbo LoRA · 8 Steps', 'MiniMax H3'],])// The box, 04.10.2026: the Krea 2 companion files had neither a verdictdiff --git a/src/lib/__tests__/wan-says-where-its-length-turns-restless.test.ts b/src/lib/__tests__/wan-says-where-its-length-turns-restless.test.tsindex f060f945..5eeb86bc 100644--- a/src/lib/__tests__/wan-says-where-its-length-turns-restless.test.ts+++ b/src/lib/__tests__/wan-says-where-its-length-turns-restless.test.ts@@ -15,11 +15,11 @@ describe('the length hint under the Frames slider', () => {expect(lengthHint('wan', WAN_STEADY_FRAMES)).toBeNull()})- it('names the steady length and Extend Video past it', () => {+ it('names the steady length and the Length control past it (B18)', () => {expect(frameRangeFor('wan').max).toBeGreaterThan(WAN_STEADY_FRAMES)const hint = lengthHint('wan', WAN_STEADY_FRAMES + 4)expect(hint).toMatch(/81 frames/)- expect(hint).toMatch(/Extend Video/)+ expect(hint).toMatch(/Length in seconds/)})it('is for Wan 2.1 only: Wan 2.2 and LTX learned longer clips', () => {diff --git a/src/lib/long-video-run.ts b/src/lib/long-video-run.tsnew file mode 100644index 00000000..60aa1be6--- /dev/null+++ b/src/lib/long-video-run.ts@@ -0,0 +1,217 @@+// The run of a long local clip (B18, 3.0.9): section after section, each one+// continuing the clip so far (lib/long-video plans them, api/video-continue+// builds the graph). Kept apart from the Create hook so the order of uploads,+// runs and gallery entries can be tested without ComfyUI.+//+// Every section leaves the WHOLE clip so far as one video, so a run stopped+// after section 3 still has a playable result. Only the newest stays in the+// gallery: the hook's run adds each one, this removes the one before it.+// A clip the user brought (Extend Video) is never removed.+//+// After each section the seam gets a colour settle when the backend can do it+// (a numpy step in ComfyUI's own Python, Rust command video_color_settle):+// the next section then starts from settled frames, so a drift cannot carry+// over and add up. Without it (a ComfyUI LU does not manage) the run goes on+// unsettled.++import type { ModelType } from '../api/comfyui'+import { planLongVideo, sectionSpec, type LongVideoPlan } from './long-video'++/** What the chain needs to know about a gallery entry. */+export interface ClipItem {+ id: string+ type: string+ filename?: string+ subfolder?: string+ comfyType?: string+}++export interface LongRunDeps {+ /** One render through the Create hook's normal path. */+ run: (override: Record<string, unknown>, opts: { stepLabel: string; continueFrom?: { video: string; overlap: number } }) => Promise<void>+ /** The gallery as it is now, newest first. */+ gallery: () => readonly ClipItem[]+ /** The error the last run left, or null. */+ error: () => string | null+ fetchBlob: (item: ClipItem) => Promise<Blob>+ /** Into ComfyUI's input folder; returns the name LoadVideo lists. */+ upload: (blob: Blob, name: string) => Promise<string>+ remove: (id: string) => void+ /** Settle the colours at the seams, in place of the item; null when the+ * backend cannot. */+ settle?: (item: ClipItem, boundaries: number[]) => Promise<ClipItem | null>+ aborted: () => boolean+}++export interface LongRunStart {+ /** The model of the first section (any T2V or I2V model of the family). */+ firstModel: string+ /** The model every later section runs: an image to video model. */+ continueModel: string+ /** A clip to continue (Extend Video); without it the first section is new. */+ clip?: Blob+ /** Its frame count, when known: the first seam for the colour settle. */+ clipFrames?: number+}++export class LongRunStopped extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'LongRunStopped'+ }+}++/** The image to video sibling of a text to video file, from the installed+ * list: the TI2V-5B and LTX 2.5 do both themselves; an A14B or Wan 2.1 T2V+ * file has an I2V twin with the same name but "i2v". Null when none is+ * installed. */+export function continueModelFor(model: string, type: ModelType | string, installed: readonly string[]): string | null {+ if (type === 'wan22' || type === 'ltx25') return model+ if (/(^|[^a-z])i2v([^a-z]|$)/i.test(model)) return model+ const want = model.replace(/t2v/i, (m) => (m === 'T2V' ? 'I2V' : 'i2v')).toLowerCase()+ const hit = installed.find((n) => n.toLowerCase() === want)+ if (hit) return hit+ // An A14B pair: the high noise half of the i2v pair, whatever the quant.+ const lower = model.toLowerCase()+ if (/wan[._-]?2[._-]?2/.test(lower)) {+ return installed.find((n) => /wan[._-]?2[._-]?2/i.test(n) && /i2v/i.test(n) && /high[._-]?noise/i.test(n)) ?? null+ }+ if (/wan[._-]?2[._-]?1/.test(lower)) {+ return installed.find((n) => /wan[._-]?2[._-]?1/i.test(n) && /i2v/i.test(n) && /14b/i.test(n)) ?? null+ }+ return null+}++/** The sections that add `seconds` to an existing clip: every one of them is+ * a continuation, each repeating the overlap. */+export function planExtension(type: ModelType | string, seconds: number, fps?: number): LongVideoPlan | null {+ const spec = sectionSpec(type)+ if (!spec) return null+ const rate = fps && fps > 0 ? fps : spec.fps+ // Plan as if the clip so far were the first section, then drop it.+ const asWhole = planLongVideo(type, (spec.native + Math.round(seconds * rate)) / rate, rate)+ if (!asWhole || asWhole.sections.length < 2) return null+ const sections = asWhole.sections.slice(1)+ const added = sections.reduce((sum, f) => sum + f - spec.overlap, 0)+ return { sections, overlap: spec.overlap, totalFrames: added, seconds: added / rate, fps: rate }+}++function newestVideo(before: Set<string>, gallery: readonly ClipItem[]): ClipItem | null {+ return gallery.find((g) => !before.has(g.id) && g.type === 'video') ?? null+}++/**+ * Runs the plan. `plan.sections[0]` is the first section when there is no+ * clip; with a clip every section continues it. Returns the finished item.+ */+export async function runLongVideo(plan: LongVideoPlan, start: LongRunStart, deps: LongRunDeps): Promise<ClipItem | null> {+ const total = plan.sections.length+ let current: ClipItem | null = null+ let blob: Blob | null = start.clip ?? null+ let index = 0+ // Frames of the clip so far, for the seams the colour settle works on.+ let frames = 0+ const seams: number[] = []++ const runAndTake = async (override: Record<string, unknown>, opts: Parameters<LongRunDeps['run']>[1]): Promise<ClipItem> => {+ const before = new Set(deps.gallery().map((g) => g.id))+ await deps.run(override, opts)+ if (deps.aborted()) throw new LongRunStopped('Stopped.')+ const err = deps.error()+ if (err) throw new LongRunStopped(err)+ const made = newestVideo(before, deps.gallery())+ if (!made) throw new LongRunStopped(`Section ${index + 1} of ${total} did not come out, so the clip stops here.`)+ return made+ }++ if (!blob) {+ current = await runAndTake(+ { videoModel: start.firstModel, frames: plan.sections[0] },+ { stepLabel: `Section 1 of ${total}` },+ )+ frames = plan.sections[0]+ index = 1+ } else {+ // Without its frame count the seams of a brought clip are unknown, and+ // the colour settle is skipped rather than aimed at the wrong frames.+ frames = start.clipFrames && start.clipFrames > 0 ? start.clipFrames : -1+ }++ for (; index < total; index++) {+ if (deps.aborted()) throw new LongRunStopped('Stopped.')+ if (current) blob = await deps.fetchBlob(current)+ if (!blob) throw new LongRunStopped('The clip so far could not be read.')+ const name = await deps.upload(blob, `lu_long_${Date.now()}_${index + 1}.mp4`)+ const sectionFrames = plan.sections[index]+ const made = await runAndTake(+ { videoModel: start.continueModel, frames: sectionFrames, cloudOp: 'extend', mode: 'video' },+ { stepLabel: `Section ${index + 1} of ${total}`, continueFrom: { video: name, overlap: plan.overlap } },+ )+ // Only our own in-between clips are taken out of the gallery.+ if (current) deps.remove(current.id)+ current = made+ if (frames >= 0) {+ seams.push(frames)+ frames += sectionFrames - plan.overlap+ }+ if (deps.settle && seams.length > 0) {+ const settled = await deps.settle(current, seams).catch(() => null)+ if (settled) current = settled+ }+ }+ return current+}++/** What the Create button asks for, read off the store. */+export interface LongVideoAsk {+ mode: string+ intent: string+ /** The model the run would use (the lane's pick). */+ model: string+ type: ModelType | string+ installed: readonly string[]+ longVideoSeconds: number+ longVideoMode: 'sections' | 'one-pass'+ fps: number+ /** Frames of a single run as the slider stands. */+ frames: number+ extendClip: Blob | null+}++export type LongVideoRequest =+ | { kind: 'sections'; plan: LongVideoPlan; start: LongRunStart }+ | { kind: 'one-pass'; frames: number }+ | { kind: 'error'; message: string }++/**+ * Whether this Create press is a long clip and how to make it, or null for an+ * ordinary single run. A long clip is asked for by the Seconds control going+ * past the family's native length, or by Extend Video on a family that can+ * continue from frames (then the Seconds control says how much to add, and+ * without it one native section is added).+ */+export function longVideoRequest(ask: LongVideoAsk): LongVideoRequest | null {+ if (ask.mode !== 'video' || !['video', 'animate', 'extend'].includes(ask.intent)) return null+ const spec = sectionSpec(ask.type)+ if (!spec) return null+ const fps = ask.fps > 0 ? ask.fps : spec.fps+ const continueModel = continueModelFor(ask.model, ask.type, ask.installed)+ const noI2v = (): LongVideoRequest => ({+ kind: 'error',+ message: `Clips past ${Math.round(spec.native / spec.fps)} s continue from their last frames, which needs an image to video model of the same family. Install the image to video bundle of ${ask.model.replace(/\.[^.]+$/, '')}, or make the clip shorter.`,+ })+ if (ask.intent === 'extend') {+ if (!ask.extendClip) return null+ const add = ask.longVideoSeconds > 0 ? ask.longVideoSeconds : (spec.native - spec.overlap) / spec.fps+ const plan = planExtension(ask.type, add, fps)+ if (!plan) return null+ if (!continueModel) return noI2v()+ return { kind: 'sections', plan, start: { firstModel: continueModel, continueModel, clip: ask.extendClip } }+ }+ if (!(ask.longVideoSeconds > 0) || ask.longVideoSeconds * fps <= spec.native) return null+ const plan = planLongVideo(ask.type, ask.longVideoSeconds, fps)+ if (!plan || plan.sections.length < 2) return null+ if (ask.longVideoMode === 'one-pass') return { kind: 'one-pass', frames: plan.totalFrames }+ if (!continueModel) return noI2v()+ return { kind: 'sections', plan, start: { firstModel: ask.model, continueModel } }+}diff --git a/src/lib/long-video.ts b/src/lib/long-video.tsnew file mode 100644index 00000000..b33898e1--- /dev/null+++ b/src/lib/long-video.ts@@ -0,0 +1,117 @@+// Long local videos (B18, 3.0.9): a clip up to 30 seconds, made of sections.+//+// No open video model holds 30 seconds in one run. Wan learned 81 frames+// (5 s at 16 fps), the TI2V-5B 121 at 24 fps, LTX 2.5 about 10 s. Past that+// the motion turns restless and starts over. So a long clip is made the way+// the model learned: a first section at the native length, then sections+// that each start on the last frames of what is already there.+//+// Each later section takes the last OVERLAP frames of the clip so far as its+// own first frames. The I2V conditioning holds them fixed (WanImageToVideo+// and Wan22ImageToVideoLatent mask the latent frames they cover, LTX pins+// them with LTXVImgToVideoInplace at strength 1), so the section continues+// the motion instead of restarting from one still. Those frames come out of+// the section a second time; the graph drops them before it appends the rest+// (api/video-continue.ts). Five frames for Wan are two latent frames (the+// VAE packs 1 + 4); seventeen for LTX are three (1 + 8 + 8).+//+// The other way to a long clip, one run with sliding context windows+// (ComfyUI's WanContextWindowsManual / LTXVContextWindows), keeps a scene+// even but tends to repeat itself and takes one prompt for everything. It is+// the "one pass" switch; sections are the default.++import type { ModelType } from '../api/comfyui'++/** The longest clip the Seconds control offers. */+export const MAX_LONG_SECONDS = 30++export interface SectionSpec {+ /** Frames of one section at the model's native length. */+ native: number+ /** Frames each later section repeats from the clip so far. */+ overlap: number+ /** Frames of a section snap to `grid * n + 1`. */+ grid: number+ /** The rate the family is made at. */+ fps: number+}++/** The families that can continue a clip, and how. A family missing here+ * (Hunyuan, FramePack, MiniMax H3, Mochi, SVD …) keeps its single run. */+const SECTIONS: Partial<Record<ModelType, SectionSpec>> = {+ wan: { native: 81, overlap: 5, grid: 4, fps: 16 },+ wan22: { native: 121, overlap: 5, grid: 4, fps: 24 },+ ltx25: { native: 241, overlap: 17, grid: 8, fps: 24 },+}++export function sectionSpec(type: ModelType | string): SectionSpec | null {+ return SECTIONS[type as ModelType] ?? null+}++/** True when the family can make a clip longer than one run. */+export function canMakeLongVideo(type: ModelType | string): boolean {+ return sectionSpec(type) !== null+}++const snapUp = (frames: number, grid: number) => Math.ceil((Math.max(1, frames) - 1) / grid) * grid + 1++export interface LongVideoPlan {+ /** Frames of each section as rendered, overlap included. */+ sections: number[]+ overlap: number+ /** Frames of the finished clip. */+ totalFrames: number+ /** Its length at `fps`. */+ seconds: number+ fps: number+}++/**+ * The sections for a clip of `seconds` at `fps`. The first section runs at+ * the native length (or shorter for a short clip), each later one adds up to+ * `native - overlap` new frames, and the last one is cut to what is left,+ * on the family's grid and never shorter than its overlap plus one grid step.+ * The clip never comes out shorter than asked; it may run up to one grid step+ * longer.+ */+export function planLongVideo(type: ModelType | string, seconds: number, fps?: number): LongVideoPlan | null {+ const spec = sectionSpec(type)+ if (!spec) return null+ const rate = fps && fps > 0 ? fps : spec.fps+ const want = snapUp(Math.round(Math.min(MAX_LONG_SECONDS, Math.max(1, seconds)) * rate), spec.grid)+ const first = Math.min(spec.native, want)+ const sections = [first]+ let total = first+ const step = spec.native - spec.overlap+ while (total < want) {+ const add = Math.min(step, want - total)+ const frames = Math.max(spec.overlap + spec.grid, snapUp(spec.overlap + add, spec.grid))+ sections.push(frames)+ total += frames - spec.overlap+ }+ return { sections, overlap: spec.overlap, totalFrames: total, seconds: total / rate, fps: rate }+}++/** Frames for a single run of `seconds`, on the family's grid. */+export function framesForSeconds(type: ModelType | string, seconds: number, fps: number): number {+ const grid = sectionSpec(type)?.grid ?? 4+ return snapUp(Math.round(Math.max(0.1, seconds) * Math.max(1, fps)), grid)+}++/** Seconds a frame count plays at `fps`, one decimal. */+export function secondsOf(frames: number, fps: number): number {+ if (!(frames > 0) || !(fps > 0)) return 0+ return Math.round((frames / fps) * 10) / 10+}++/** How a long clip is made. */+export type LongVideoMode = 'sections' | 'one-pass'++/** One pass with context windows: the window and its overlap per family,+ * ComfyUI's own defaults for WanContextWindowsManual (81 / 30) and+ * LTXVContextWindows (145 / 40). */+export function contextWindowFor(type: ModelType | string): { length: number; overlap: number; node: string } | null {+ if (type === 'wan' || type === 'wan22') return { length: 81, overlap: 30, node: 'WanContextWindowsManual' }+ if (type === 'ltx25') return { length: 145, overlap: 40, node: 'LTXVContextWindows' }+ return null+}diff --git a/src/lib/render/__tests__/local-model-tier.test.ts b/src/lib/render/__tests__/local-model-tier.test.tsindex e586d04f..ed93cc2c 100644--- a/src/lib/render/__tests__/local-model-tier.test.ts+++ b/src/lib/render/__tests__/local-model-tier.test.ts@@ -25,8 +25,9 @@ const mainFile = (b: ModelBundle) =>const tierOfFile = (name: string) => localTier({ name, type: classifyModel(name) })describe('jedes lokale Bundle traegt eine Stufe', () => {- it('alle 43 Bundles haben best, standard oder older', () => {- expect(ALL.length).toBe(43)+ it('alle 46 Bundles haben best, standard oder older', () => {+ // B18 (3.0.9): Wan 2.2 A14B I2V und T2V Fast, Wan 2.1 Speed-LoRAs.+ expect(ALL.length).toBe(46)for (const b of ALL) expect(['best', 'standard', 'older'], b.name).toContain(b.tier)})diff --git a/src/lib/video-estimate.ts b/src/lib/video-estimate.tsnew file mode 100644index 00000000..67ebd74b--- /dev/null+++ b/src/lib/video-estimate.ts@@ -0,0 +1,117 @@+// What a local video run will cost, said before it starts (B18, 3.0.9).+//+// An estimate, not a promise, and the line under the Create button says so.+// The time per step comes from runs on the owner's test box (RTX 3060 12 GB,+// 64 GB RAM, October 2026; see REFERENCE below for what each number is) and+// scales with the amount of picture a step has to look at. A step's cost+// grows a little faster than the number of latent tokens, because attention+// compares every token with every other one; 1.2 as the exponent matches the+// 480p versus 720p runs on the box within their own spread. Other cards are+// not modelled: the line names the card the numbers come from.+//+// Graphics memory: the largest weight file has to sit on the card while it+// samples (the A14B halves take turns), plus working memory that grows with+// the clip's latent. What does not fit is moved to system memory by ComfyUI+// (dynamic VRAM, async offload), which works but costs time, so the verdict+// says "moves X GB to system memory" instead of "does not fit".++import type { ModelType } from '../api/comfyui'+import { planLongVideo } from './long-video'++export interface VideoRunShape {+ type: ModelType | string+ model: string+ width: number+ height: number+ frames: number+ steps: number+ cfgScale: number+ /** Seconds the user asked for; more than one section when past native. */+ seconds?: number+ fps?: number+ /** The largest single weight file in GB, when known. */+ weightGb?: number | null+ /** The card in GB, when detected. */+ cardGb?: number | null+}++export interface VideoEstimate {+ /** Lower and upper end in minutes. */+ minutes: [number, number]+ sections: number+ /** Graphics memory the run wants in GB (weights + working memory). */+ vramGb: number+ /** How much of that ComfyUI has to keep in system memory, 0 when it fits. */+ offloadGb: number+ /** One line for under the button. */+ line: string+}++interface Reference {+ /** Seconds per sampling step at the reference picture, one model call. */+ secPerStep: number+ /** The reference picture: width × height × frames. */+ w: number; h: number; frames: number+ /** Spatial and temporal VAE compression, for the token count. */+ space: number; time: number+ /** Loading and decoding per section, in seconds. */+ overhead: number+ /** Working memory at the reference picture, GB. */+ workGb: number+}++/** Per family, measured or derived on the RTX 3060 12 GB box. Wan 14B: A14B+ * Q4_K_S GGUF at 832×480×81 (B18 box run). Wan 2.2 5B: fp16 at 1280×704×121.+ * LTX 2.5: the whole two pass graph counted as eleven steps at 1280×704×121. */+const REFERENCE: Partial<Record<string, Reference>> = {+ wan14b: { secPerStep: 42, w: 832, h: 480, frames: 81, space: 8, time: 4, overhead: 70, workGb: 2.5 },+ wan13b: { secPerStep: 7, w: 832, h: 480, frames: 81, space: 8, time: 4, overhead: 25, workGb: 1.5 },+ wan22: { secPerStep: 16, w: 1280, h: 704, frames: 121, space: 16, time: 4, overhead: 40, workGb: 3 },+ ltx25: { secPerStep: 22, w: 1280, h: 704, frames: 121, space: 32, time: 8, overhead: 60, workGb: 3 },+}++function referenceFor(type: string, model: string): Reference | null {+ if (type === 'wan') return /1[._-]?3b/i.test(model) ? REFERENCE.wan13b! : REFERENCE.wan14b!+ return REFERENCE[type] ?? null+}++const tokens = (w: number, h: number, frames: number, r: Reference) =>+ Math.max(1, Math.round(w / r.space) * Math.round(h / r.space) * (Math.floor((frames - 1) / r.time) + 1))++/** Minutes as a short range: "4–7 min", "under 1 min". */+export function minutesText([lo, hi]: [number, number]): string {+ if (hi < 1) return 'under 1 min'+ const r = (m: number) => (m < 10 ? Math.max(1, Math.round(m)) : Math.round(m / 5) * 5)+ const a = r(lo)+ const b = Math.max(a, r(hi))+ return a === b ? `about ${a} min` : `${a}–${b} min`+}++/** The estimate, or null for a family without numbers (it shows nothing+ * rather than a guess). */+export function estimateVideoRun(shape: VideoRunShape): VideoEstimate | null {+ const ref = referenceFor(String(shape.type), shape.model || '')+ if (!ref) return null+ const plan = shape.seconds && shape.fps ? planLongVideo(shape.type, shape.seconds, shape.fps) : null+ const sections = plan ? plan.sections : [shape.frames]+ const calls = shape.cfgScale > 1.01 ? 2 : 1+ const refTokens = tokens(ref.w, ref.h, ref.frames, ref)+ let seconds = 0+ let biggest = 0+ for (const frames of sections) {+ const scale = Math.pow(tokens(shape.width, shape.height, frames, ref) / refTokens, 1.2)+ biggest = Math.max(biggest, scale)+ seconds += ref.overhead + Math.max(1, shape.steps) * calls * ref.secPerStep * scale+ }+ const minutes: [number, number] = [(seconds * 0.7) / 60, (seconds * 1.5) / 60]+ const work = ref.workGb * Math.max(0.3, Math.pow(biggest, 1 / 1.2))+ const vramGb = Math.round(((shape.weightGb ?? 0) + work) * 10) / 10+ const card = shape.cardGb ?? null+ const offloadGb = card && vramGb > card - 0.5 ? Math.round((vramGb - (card - 0.5)) * 10) / 10 : 0+ const parts = [+ `≈ ${minutesText(minutes)}`,+ sections.length > 1 ? `${sections.length} sections` : null,+ card ? (offloadGb > 0 ? `${vramGb} GB on a ${card} GB card, ${offloadGb} GB in system memory` : `${vramGb} of ${card} GB`) : `${vramGb} GB graphics memory`,+ ].filter(Boolean)+ return { minutes, sections: sections.length, vramGb, offloadGb, line: `${parts.join(' · ')} (estimate, RTX 3060 numbers)` }+}diff --git a/src/lib/video-length.ts b/src/lib/video-length.tsindex b66b71b0..008aeafd 100644--- a/src/lib/video-length.ts+++ b/src/lib/video-length.ts@@ -50,5 +50,5 @@ export const WAN_STEADY_FRAMES = 81* holds steady, or null. */export function lengthHint(type: ModelType | string, frames: number): string | null {if (type !== 'wan' || !(frames > WAN_STEADY_FRAMES)) return null- return `Wan holds steady up to ${WAN_STEADY_FRAMES} frames. Longer clips tend to turn restless; for more, make ${WAN_STEADY_FRAMES} frames and continue with Extend Video.`+ return `Wan holds steady up to ${WAN_STEADY_FRAMES} frames. Longer clips tend to turn restless; for more, set Length in seconds below and LU makes it in sections.`}diff --git a/src/lib/wan-speed.ts b/src/lib/wan-speed.tsnew file mode 100644index 00000000..c1ca13cc--- /dev/null+++ b/src/lib/wan-speed.ts@@ -0,0 +1,127 @@+// Fast mode for the Wan 14B models (B18, 3.0.9).+//+// lightx2v distilled Wan 2.1 and Wan 2.2 A14B to four sampling steps without+// classifier free guidance and published the difference as rank 64 LoRAs+// (lightx2v/Wan2.2-Distill-Loras, lightx2v/Wan2.1-Distill-Loras, Apache-2.0).+// Loaded on top of the untouched base model they turn a 30 step run at cfg 5,+// which costs two model calls a step, into 4 steps at cfg 1, one call each:+// about fifteen times fewer model calls for the same clip. The model card asks+// for strength 1.0; the sampling values below are the ones its ComfyUI+// workflows run (euler, simple, shift 5, the A14B pair split 2 + 2).+//+// Quality stays one switch away. The quality values are the official+// Comfy-Org templates for the A14B pair (20 steps, cfg 3.5, shift 8) and the+// family defaults for Wan 2.1.++/** Which speed LoRA set a model takes, or null when it has none. */+export type WanSpeedKind = 'a14b-i2v' | 'a14b-t2v' | 'wan21-i2v' | 'wan21-t2v'++export type VideoSpeed = 'fast' | 'quality'++export interface WanSampling {+ steps: number+ cfgScale: number+ sampler: string+ scheduler: string+ /** ModelSamplingSD3 shift. */+ shift: number+}++/** Four steps at cfg 1, as the lightx2v LoRAs are distilled for. */+export const WAN_FAST: WanSampling = { steps: 4, cfgScale: 1, sampler: 'euler', scheduler: 'simple', shift: 5 }++/** The official Comfy-Org A14B templates. */+export const WAN_A14B_QUALITY: WanSampling = { steps: 20, cfgScale: 3.5, sampler: 'euler', scheduler: 'simple', shift: 8 }++/** Wan 2.1 at its family defaults, plus the shift its official templates set+ * (LU ran it without one until 3.0.9). */+export const WAN21_QUALITY: WanSampling = { steps: 30, cfgScale: 6, sampler: 'euler', scheduler: 'normal', shift: 8 }++const isA14B = (lower: string) =>+ /wan[._-]?2[._-]?2/.test(lower) && !lower.includes('ti2v') && !/(^|[^0-9])5b/.test(lower)+ && (/(^|[^0-9])a?14b/.test(lower) || /(high|low)[._-]?noise/.test(lower) || /(^|[^a-z])[it]2v([^a-z]|$)/.test(lower))++/** A merge that already carries a distill (Rapid AIO, Lightning, FusionX,+ * CausVid) runs fast by itself; a second distill on top burns the picture. */+export function isMergedFastModel(name: string): boolean {+ return /rapid|lightning|lightx2v|fusionx|causvid|4step|4-step|distill/i.test(name)+}++/** The speed LoRA set this video model takes, or null. Only the 14B models+ * have one: lightx2v published none for the 1.3B and none for the TI2V-5B. */+export function wanSpeedKind(model: string): WanSpeedKind | null {+ const lower = (model || '').toLowerCase()+ if (!lower || isMergedFastModel(lower)) return null+ const i2v = /(^|[^a-z])i2v([^a-z]|$)/.test(lower) || lower.includes('_i2v') || lower.includes('-i2v')+ if (isA14B(lower)) return i2v ? 'a14b-i2v' : 'a14b-t2v'+ const wan21 = /wan[._-]?2[._-]?1/.test(lower)+ if (wan21 && /(^|[^0-9.])14b/.test(lower) && !lower.includes('vace') && !lower.includes('flf')) {+ return i2v ? 'wan21-i2v' : 'wan21-t2v'+ }+ return null+}++/** True when the model has a fast mode at all. */+export function hasWanFastMode(model: string): boolean {+ return wanSpeedKind(model) !== null+}++/**+ * The installed speed LoRA for one half of the model (`single` for Wan 2.1),+ * from the names ComfyUI's LoRA loader lists, or null.+ *+ * Both spellings are accepted: lightx2v's own+ * (wan2.2_i2v_A14b_high_noise_lora_rank64_lightx2v_4step_1022.safetensors) and+ * the older Comfy-Org repack+ * (wan2.2_i2v_lightx2v_4steps_lora_v1_high_noise.safetensors). When several+ * match, the newest lightx2v release wins (the highest trailing number).+ */+export function findWanSpeedLora(kind: WanSpeedKind, half: 'high' | 'low' | 'single', listed: string[]): string | null {+ const task = kind.endsWith('i2v') ? 'i2v' : 't2v'+ const base = (n: string) => n.replace(/^.*[\\/]/, '').toLowerCase()+ const hits = listed.filter((name) => {+ const b = base(name)+ if (!/lightx2v/.test(b) || !/4[_-]?steps?/.test(b)) return false+ if (!new RegExp(`(^|[^a-z])${task}([^a-z]|$)`).test(b)) return false+ if (kind.startsWith('a14b')) {+ if (!/wan[._-]?2[._-]?2/.test(b)) return false+ return half === 'high' ? /high[._-]?noise/.test(b) : half === 'low' ? /low[._-]?noise/.test(b) : false+ }+ return /wan[._-]?2[._-]?1/.test(b) && half === 'single'+ })+ if (hits.length === 0) return null+ const stamp = (n: string) => Number((/_(\d{3,4})\.safetensors$/i.exec(base(n)) ?? [])[1] ?? 0)+ return [...hits].sort((a, b) => stamp(b) - stamp(a))[0]+}++/** The file names a fast run needs, for the message when one is missing. */+export function wanSpeedLoraNames(kind: WanSpeedKind): string[] {+ switch (kind) {+ case 'a14b-i2v': return [+ 'wan2.2_i2v_A14b_high_noise_lora_rank64_lightx2v_4step_1022.safetensors',+ 'wan2.2_i2v_A14b_low_noise_lora_rank64_lightx2v_4step_1022.safetensors',+ ]+ case 'a14b-t2v': return [+ 'wan2.2_t2v_A14b_high_noise_lora_rank64_lightx2v_4step_1217.safetensors',+ 'wan2.2_t2v_A14b_low_noise_lora_rank64_lightx2v_4step_1217.safetensors',+ ]+ case 'wan21-i2v': return ['wan2.1_i2v_lora_rank64_lightx2v_4step.safetensors']+ case 'wan21-t2v': return ['wan2.1_t2v_14b_lora_rank64_lightx2v_4step.safetensors']+ }+}++/** The sampling a Wan model starts with in the given mode, or null when the+ * model is not one of the 14B models this file speaks for. */+export function wanSamplingFor(model: string, speed: VideoSpeed): WanSampling | null {+ const kind = wanSpeedKind(model)+ if (!kind) return null+ if (speed === 'fast') return WAN_FAST+ return kind.startsWith('a14b') ? WAN_A14B_QUALITY : WAN21_QUALITY+}++/** A run that asks for few steps at cfg 1 is a fast run. The builder reads+ * this off the numbers the run carries, so a user who drags the sliders to+ * 4 and 1 by hand gets the LoRAs too, and one who drags them back gets none. */+export function isFastSampling(steps: number, cfgScale: number): boolean {+ return steps > 0 && steps <= 8 && cfgScale <= 1.5+}diff --git a/src/stores/createStore.ts b/src/stores/createStore.tsindex 30f68ed2..72fd8f83 100644--- a/src/stores/createStore.ts+++ b/src/stores/createStore.ts@@ -1,4 +1,6 @@import { MAX_LOCAL_FRAMES } from '../lib/video-length'+import { wanSamplingFor, type VideoSpeed } from '../lib/wan-speed'+import { MAX_LONG_SECONDS, type LongVideoMode } from '../lib/long-video'import { create } from 'zustand'import { maxTrainImages } from '../lib/train-image-cap'import { MAX_STORED_REFERENCES } from '../lib/edit-references'@@ -42,6 +44,8 @@ const RUNTIME_ONLY_KEYS: readonly string[] = [// 3.0.8 D28: the captions belong to the staged photos, which are runtime// only (blobs); a caption from yesterday has no photo to stand under.'trainCaptions',+ // B18: the clip Extend Video continues is a blob of this session.+ 'extendClip',]import type { ModelType, ClassifiedModel } from '../api/comfyui'import { MAX_SHOTS, MAX_SHOT_CHARS } from '../lib/ltx-multishot'@@ -350,6 +354,17 @@ export interface CreateState {batchSize: numberframes: numberfps: number+ /** Fast (lightx2v 4 steps) or Quality sampling for the Wan 14B models+ * (B18, lib/wan-speed). Other families ignore it. */+ videoSpeed: VideoSpeed+ /** A long local clip in seconds (B18, lib/long-video); 0 is one run at the+ * Frames slider's length. */+ longVideoSeconds: number+ /** Sections (default) or one pass with context windows. */+ longVideoMode: LongVideoMode+ /** The clip Extend Video continues, as picked (runtime only, never+ * persisted: partialize does not list it). */+ extendClip: Blob | null// Review A kleiner Punkt 1 (studio-r2): the cloud video Length control used// to read and write these SAME frames/fps fields, which the local video// lane also owns. Picking a cloud length silently rewrote the local@@ -595,6 +610,10 @@ export interface CreateState {setBatchSize: (batchSize: number) => voidsetFrames: (frames: number) => voidsetFps: (fps: number) => void+ setVideoSpeed: (speed: VideoSpeed) => void+ setLongVideoSeconds: (seconds: number) => void+ setLongVideoMode: (mode: LongVideoMode) => void+ setExtendClip: (clip: Blob | null) => voidsetCloudFrames: (frames: number) => voidsetCloudFps: (fps: number) => voidsetDenoise: (denoise: number) => void@@ -913,7 +932,7 @@ export const MOBILE_CLOUD_VIDEO_FAMILY: ModelType = 'minimaxh3'/** The video model's own sampling values, for picking it and for every tab* that runs it. Lightning/rapid merges are distilled to few steps at cfg 1,* the architecture defaults (30 steps, cfg 5+) render them to mush. */-function videoModelParams(model: string, list: readonly ClassifiedModel[] | null = [], intent = 'video') {+function videoModelParams(model: string, list: readonly ClassifiedModel[] | null = [], intent = 'video', speed: VideoSpeed = 'fast') {// A phone has no local video model, so `model` is empty there and the// family would be 'unknown': 1024 by 1024, a square image size, sent along// with a cloud clip. It takes the family of the cloud's own default video@@ -929,12 +948,17 @@ function videoModelParams(model: string, list: readonly ClassifiedModel[] | null// fps under an LTX (persona walk, 09.10.2026, Fund 19). A ComfyUI entry// carries no `mlxVideo`, and nothing changes for it.const clip = mlxVideoLaneEntry(list, model, intent)?.mlxVideo+ // The Wan 14B models (B18): Fast is lightx2v's 4 steps at cfg 1, Quality+ // the official templates; both at the 81 frames, 832×480 and 16 fps Wan+ // learned. The Mac's MLX entry below still wins on the Mac.+ const wan = clip ? null : wanSamplingFor(model, speed)return {steps: lightning ? 6 : defaults.steps, cfgScale: lightning ? 1.0 : defaults.cfgScale,sampler: defaults.sampler, scheduler: defaults.scheduler,width: defaults.width, height: defaults.height,...(defaults.frames ? { frames: defaults.frames } : {}),...(defaults.fps ? { fps: defaults.fps } : {}),+ ...(wan ? { steps: wan.steps, cfgScale: wan.cfgScale, sampler: wan.sampler, scheduler: wan.scheduler, width: 832, height: 480, frames: 81, fps: 16 } : {}),...(clip ? { frames: clip.frames, fps: clip.fps, width: clip.width, height: clip.height } : {}),// A Wan on the Mac runs its config's steps (50 or 40) unless asked, and// the slider starts there, not at the family's ComfyUI count.@@ -955,7 +979,7 @@ function videoIntentOf(s: Pick<CreateState, 'videoSubMode' | 'cloudOp'>): string*/function restartSampling(s: CreateState): Partial<CreateState> {if (s.cloudOp === 'music') return imageLaneParams(s)- if (s.cloudOp === 'lipsync' || s.cloudOp === 'motion') return videoModelParams(s.videoModel, s.videoModelList, videoIntentOf(s))+ if (s.cloudOp === 'lipsync' || s.cloudOp === 'motion') return videoModelParams(s.videoModel, s.videoModelList, videoIntentOf(s), s.videoSpeed)return {}}@@ -991,6 +1015,10 @@ export const useCreateStore = create<CreateState>()(batchSize: 1,frames: 24,fps: 8,+ videoSpeed: 'fast',+ longVideoSeconds: 0,+ longVideoMode: 'sections',+ extendClip: null,cloudFrames: 24,cloudFps: 8,imageLaneKept: null,@@ -1095,7 +1123,7 @@ export const useCreateStore = create<CreateState>()(// On a phone both lists are empty for good, and the reset must still// happen: the video tab takes the cloud clip size, the way back takes// the image size again.- if (mode === 'video' && (state.videoModel || isMobile())) return { mode, ...videoModelParams(state.videoModel, state.videoModelList, videoIntentOf(state)) }+ if (mode === 'video' && (state.videoModel || isMobile())) return { mode, ...videoModelParams(state.videoModel, state.videoModelList, videoIntentOf(state), state.videoSpeed) }if (mode === 'image' && (state.imageModel || isMobile())) return { mode, ...imageModelParams(state) }return { mode }}),@@ -1106,7 +1134,7 @@ export const useCreateStore = create<CreateState>()(imageModel: model, imageModelType: type,...imageModelParams({ imageModel: model, imageModelType: type }),})),- setVideoModel: (model) => set((s) => ({ videoModel: model, ...videoModelParams(model, s.videoModelList, videoIntentOf(s)) })),+ setVideoModel: (model) => set((s) => ({ videoModel: model, ...videoModelParams(model, s.videoModelList, videoIntentOf(s), s.videoSpeed) })),setSampler: (sampler) => set({ sampler }),setScheduler: (scheduler) => set({ scheduler }),setSteps: (steps) => set({ steps: Math.max(1, Math.min(200, Math.floor(steps))) }),@@ -1128,6 +1156,19 @@ export const useCreateStore = create<CreateState>()(// slider of the picked family keeps a shorter one inside its range.setFrames: (frames) => set({ frames: Math.max(1, Math.min(MAX_LOCAL_FRAMES, Math.floor(frames))) }),setFps: (fps) => set({ fps: Math.max(1, Math.min(60, Math.floor(fps))) }),+ // Switching speed re-reads the sampling values of the picked model; a+ // model without a fast mode keeps what it has.+ setVideoSpeed: (videoSpeed) => set((s) => {+ const wan = wanSamplingFor(s.videoModel, videoSpeed)+ return wan && s.mode === 'video'+ ? { videoSpeed, steps: wan.steps, cfgScale: wan.cfgScale, sampler: wan.sampler, scheduler: wan.scheduler }+ : { videoSpeed }+ }),+ setLongVideoSeconds: (seconds) => set({+ longVideoSeconds: Number.isFinite(seconds) && seconds > 0 ? Math.min(MAX_LONG_SECONDS, Math.round(seconds)) : 0,+ }),+ setLongVideoMode: (longVideoMode) => set({ longVideoMode }),+ setExtendClip: (extendClip) => set({ extendClip }),// Review A kleiner Punkt 1 (studio-r2, 20.09.2026, found by the new// e2e test itself): the local slider's clamp follows the family// (lib/video-length); the cloud track only ever encodes@@ -1206,7 +1247,7 @@ export const useCreateStore = create<CreateState>()(// The local lane continues from the picked clip's last frame —// regular I2V models, regular video defaults.return { ...base, cloudOp: 'extend' as const, mode: 'video' as const, videoSubMode: 't2v' as const, ...dropAll,- ...videoModelParams(s.videoModel, s.videoModelList, 'extend') }+ ...videoModelParams(s.videoModel, s.videoModelList, 'extend', s.videoSpeed) }}case 'motion': {// Keeps the source slot (the character image the video drives).@@ -1234,10 +1275,10 @@ export const useCreateStore = create<CreateState>()(case 'eraser': return { ...base, utilityOp: 'eraser' as const, mode: 'image' as const, imageSubMode: 'img2img' as const }case 'video':return { ...base, mode: 'video' as const, videoSubMode: 't2v' as const, ...dropAll,- ...videoModelParams(s.videoModel, s.videoModelList, 'video') }+ ...videoModelParams(s.videoModel, s.videoModelList, 'video', s.videoSpeed) }case 'animate':return { ...base, mode: 'video' as const, videoSubMode: 'i2v' as const, mask: null,- ...videoModelParams(s.videoModel, s.videoModelList, 'animate') }+ ...videoModelParams(s.videoModel, s.videoModelList, 'animate', s.videoSpeed) }}})()// Leaving the image lane, its values are put aside under the model@@ -1522,7 +1563,7 @@ export const useCreateStore = create<CreateState>()(// The picked model's own values where it has some: a distilled// checkpoint reset to its family's 25 or 30 steps renders to mush.// LU Cloud renders with its own model, there the family stays.- const own = s.backend === 'cloud' ? {} : s.mode === 'video' ? videoModelParams(s.videoModel, s.videoModelList, videoIntentOf(s)) : imageModelParams(s)+ const own = s.backend === 'cloud' ? {} : s.mode === 'video' ? videoModelParams(s.videoModel, s.videoModelList, videoIntentOf(s), s.videoSpeed) : imageModelParams(s)set({sampler: d.sampler,scheduler: d.scheduler,@@ -1751,6 +1792,9 @@ export const useCreateStore = create<CreateState>()(batchSize: state.batchSize,frames: state.frames,fps: state.fps,+ videoSpeed: state.videoSpeed,+ longVideoSeconds: state.longVideoSeconds,+ longVideoMode: state.longVideoMode,...restartSampling(state),denoise: state.denoise,editStrength: state.editStrength,