AI media harness for planning, generating, and editing locally
TypeScript
Enable SlopFab Animate recipe
Bitti0b5184ac32f9
diff --git a/docs/video-references.md b/docs/video-references.mdindex 3471473..8c11825 100644--- a/docs/video-references.md+++ b/docs/video-references.md@@ -3,11 +3,22 @@## AnimateDownload **Animate** in Settings → Generators, then select it in the Generator.-Choose a **Reference video** in the scene inspector. Animate requires a video-and sends Viggle's bundled [fixed prompt](https://huggingface.co/Viggle/Viggle-Animate/raw/main/assets/fixed_prompt.txt);-shot descriptions, look, sound and music prompts are not used. The prompt is-embedded in the app, so generation does not need to fetch it. Video trim and-soundtrack settings still come from References.+Choose one **Reference video** and one **Repainted scene frame** in the scene+inspector. The image should be a frame of the driving scene with the character+repainted, preserving pose, framing, background and lighting. A standalone+portrait is not an equivalent input. Continuation and refmods are unsupported.++Slopus enables SlopFab C API 1.10's Animate recipe and supplies the downloaded+362-token embedding and modality tags. Qwen and the tokenizer are neither+downloaded nor passed to Animate. The bundled fixed prompt remains descriptive+text; the DLL uses the frozen embedding instead of encoding it. Shot descriptions,+look, sound and music prompts are not used. Older DLLs report an update error.++Video trim and soundtrack settings come from References. When a soundtrack is+included and decoded, Slopus pins it in the output audio latents. This preserves+it through an audio-VAE round trip, not a sample-identical copy. Without attached+audio, the model generates audio. References are ordered video first and image+second, resized using the target canvas, and video flow shift is 3.The template uses `Viggle-Animate-pruned_rank8_int8_convrot.safetensors` and`viggle_animate_distillation_bf16.safetensors` from DeepBeepMeep/MiniMax-H3.@@ -15,11 +26,18 @@ The enabled distillation LoRA has a **4-step override**, which takes precedenceover the scene's step count. Existing installations receive the template oncewithout replacing their default generator or local model paths.-This uses the DLL's generic H3 reference-generation API with the Viggle-checkpoint. Its shared text encoder and video/audio VAEs are still required.-It does not reproduce upstream Viggle's frozen-embedding character-replacement-pipeline. Planning is tested on both CUDA and Vulkan; rendered animation quality-requires a run with the downloaded weights and a compatible GPU.+The video/audio VAEs are still required. Animate also downloads its frozen+conditioning as an **Additional safetensor** into the weights folder. Existing+Animate templates receive this download entry once. In a custom Animate template,+set the conditioning file's **Use** to **Animate conditioning**. Slopus converts+the downloaded BF16 file losslessly to SlopFab's F32 layout and caches the result+beside it. Neither file is included in the installer or portable package.+See [embedding provenance](../src-tauri/assets/README.md).++**Known runtime limitation:** SlopFab's 2026-09-16 comparison with the new recipe+still produced a flat brown texture. Its VAE reference reconstruction succeeded+and pinned audio latents remained unchanged. This integration enables the recipe;+it does not resolve or validate the remaining conditioning/transformer failure.## Adding video referencesdiff --git a/lib/slopfab/slopfab.dll b/lib/slopfab/slopfab.dllindex 480bc42..f42d4be 100644--- a/lib/slopfab/slopfab.dll+++ b/lib/slopfab/slopfab.dll@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:9a95e75291aa91387f33ac232ef484e7bf78be8a902471b845d0e5506d850ed6-size 15671296+oid sha256:7a6e36a262446195a0e450f02896827bc09224ad097a5709ee975d028318cd3b+size 15914496diff --git a/package.cmd b/package.cmdindex 4f931e3..9dd31ed 100644--- a/package.cmd+++ b/package.cmd@@ -135,7 +135,7 @@ exit /b 0>>"%~1" echo Microsoft Edge WebView2. Use the setup installer if it is missing.>>"%~1" echo.>>"%~1" echo VIDEO GENERATION->>"%~1" echo The runtime is included. Keep slopfab.dll beside Slopus.exe.+>>"%~1" echo The runtime is included. Keep slopfab.dll beside Slopus.exe. Download generator weights in Settings.>>"%~1" echo Model weights are not included. Set their paths in Settings.exit /b 0diff --git a/release.cmd b/release.cmdindex 9d5becc..53d8729 100644--- a/release.cmd+++ b/release.cmd@@ -204,7 +204,7 @@ exit /b 1>>"%~1" echo Microsoft Edge WebView2. Use the setup installer if it is missing.>>"%~1" echo.>>"%~1" echo VIDEO GENERATION->>"%~1" echo The runtime is included. Keep slopfab.dll beside Slopus.exe.+>>"%~1" echo The runtime is included. Keep slopfab.dll beside Slopus.exe. Download generator weights in Settings.>>"%~1" echo Model weights are not included. Set their paths in Settings.exit /b 0diff --git a/src-tauri/assets/README.md b/src-tauri/assets/README.mdnew file mode 100644index 0000000..b1a31c3--- /dev/null+++ b/src-tauri/assets/README.md@@ -0,0 +1,25 @@+# Animate conditioning++Animate downloads [fixed_embed_fwd_anyframe.safetensors](https://huggingface.co/drbaph/Viggle-Animate-ComfyUI/resolve/main/text_cond/fixed_embed_fwd_anyframe.safetensors)+as an additional safetensor in its generator template, into the configured+weights folder. No conditioning binary is bundled with Slopus.++The download contains Viggle's frozen `prompt_embeds` BF16 `[1,362,5120]` and+`text_token_tags` I64 `[362]`. When Animate is used, Slopus losslessly expands+BF16 to F32, renames the embedding to `prompt_embedding` `[362,5120]`, and+writes I32 tags for SlopFab. This derived `.slopfab.safetensors` file stays+beside the download and is reused while its contents match. Missing or damaged+copies are rebuilt. Removing downloaded generator weights also removes it.+SlopFab-compatible F32 files can be used directly without conversion.++The downloaded tensor values were verified against the previous bundled+conditioning (SHA-256 `54858d948cb547267495246c7d02b87973ce2b2df7d9af59ff8efe70530b2493`):+both the embedding and modality tags match exactly.++`viggle-animate-fixed-prompt.txt` is the upstream descriptive prompt. Animate+uses the frozen embedding rather than recomputing conditioning from this text.+Qwen is not needed at runtime.++These model assets originate from [Viggle/Viggle-Animate](https://huggingface.co/Viggle/Viggle-Animate)+and are covered by the upstream MiniMax-H3 Community License; see the upstream+[modification notice](https://huggingface.co/Viggle/Viggle-Animate/blob/main/MODIFICATIONS.md).diff --git a/src-tauri/src/conditioning.rs b/src-tauri/src/conditioning.rsnew file mode 100644index 0000000..120fc2f--- /dev/null+++ b/src-tauri/src/conditioning.rs@@ -0,0 +1,145 @@+//! Adapt downloaded ComfyUI conditioning to SlopFab's F32 input contract.+use serde_json::{json, Value};+use std::{fs, io::{Read, Write}, path::{Path, PathBuf}, sync::Mutex};++static CONVERSION: Mutex<()> = Mutex::new(());+const TOKENS: usize = 362;+const VALUES: usize = TOKENS * 5120;++pub fn cached_path(source: &Path) -> PathBuf {+ source.with_extension("slopfab.safetensors")+}++fn tensor<'a>(header: &Value, data: &'a [u8], name: &str, dtype: &str, shape: &[usize], bytes: usize) -> Result<&'a [u8], String> {+ let entry = &header[name];+ if entry["dtype"] != dtype || entry["shape"] != json!(shape) {+ return Err(format!("Animate conditioning requires {name} {dtype} {shape:?}."));+ }+ let offsets = entry["data_offsets"].as_array().filter(|values| values.len() == 2)+ .ok_or("Invalid conditioning tensor offsets.")?;+ let start = offsets[0].as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("Invalid tensor offset.")?;+ let end = offsets[1].as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("Invalid tensor offset.")?;+ if end.checked_sub(start) != Some(bytes) { return Err("Invalid conditioning tensor size.".into()); }+ data.get(start..end).ok_or_else(|| "Truncated conditioning tensor.".into())+}++fn convert(bytes: &[u8]) -> Result<Option<Vec<u8>>, String> {+ let size = u64::from_le_bytes(bytes.get(..8).ok_or("Missing safetensors header.")?.try_into().unwrap());+ let end = usize::try_from(size).ok().and_then(|n| n.checked_add(8)).filter(|n| *n <= bytes.len())+ .ok_or("Invalid safetensors header length.")?;+ let header: Value = serde_json::from_slice(&bytes[8..end]).map_err(|e| format!("Invalid conditioning header: {e}"))?;+ let data = &bytes[end..];+ let native = header.get("prompt_embedding").is_some();+ let embedding = if native {+ tensor(&header, data, "prompt_embedding", "F32", &[TOKENS, 5120], VALUES * 4)?+ } else {+ tensor(&header, data, "prompt_embeds", "BF16", &[1, TOKENS, 5120], VALUES * 2)?+ };+ let tag_width = match header["text_token_tags"]["dtype"].as_str() {+ Some("I32") => 4, Some("I64") => 8,+ _ => return Err("Animate conditioning requires integer text_token_tags.".into()),+ };+ let tags = tensor(&header, data, "text_token_tags", if tag_width == 4 { "I32" } else { "I64" }, &[TOKENS], TOKENS * tag_width)?;+ let mut tag_bytes = Vec::with_capacity(TOKENS * 4);+ for tag in tags.chunks_exact(tag_width) {+ let value = if tag_width == 4 { i32::from_le_bytes(tag.try_into().unwrap()) as i64 } else { i64::from_le_bytes(tag.try_into().unwrap()) };+ if !(0..=2).contains(&value) { return Err("Invalid conditioning modality tag.".into()); }+ tag_bytes.extend_from_slice(&(value as i32).to_le_bytes());+ }+ let mut values = Vec::with_capacity(VALUES * 4);+ for value in embedding.chunks_exact(if native { 4 } else { 2 }) {+ let bits = if native { u32::from_le_bytes(value.try_into().unwrap()) } else { (u16::from_le_bytes(value.try_into().unwrap()) as u32) << 16 };+ if !f32::from_bits(bits).is_finite() { return Err("Non-finite conditioning value.".into()); }+ if !native { values.extend_from_slice(&bits.to_le_bytes()); }+ }+ if native { return Ok(None); }+ let mut header = serde_json::to_vec(&json!({+ "prompt_embedding": { "dtype": "F32", "shape": [TOKENS, 5120], "data_offsets": [0, VALUES * 4] },+ "text_token_tags": { "dtype": "I32", "shape": [TOKENS], "data_offsets": [VALUES * 4, VALUES * 4 + TOKENS * 4] },+ })).map_err(|e| e.to_string())?;+ header.resize((header.len() + 7) / 8 * 8, b' ');+ let mut output = (header.len() as u64).to_le_bytes().to_vec();+ output.extend(header);+ output.extend(values);+ output.extend(tag_bytes);+ Ok(Some(output))+}++pub fn prepare(source: &Path) -> Result<PathBuf, String> {+ let _guard = CONVERSION.lock().map_err(|_| "Conditioning conversion lock failed.")?;+ // Bound allocations even when a template points to the wrong model file.+ let mut bytes = Vec::new();+ fs::File::open(source).and_then(|file| file.take(8_000_001).read_to_end(&mut bytes))+ .map_err(|e| format!("Cannot read Animate conditioning {}: {e}. Download Animate in Settings.", source.display()))?;+ if bytes.len() > 8_000_000 { return Err("Animate conditioning file is too large.".into()); }+ let Some(converted) = convert(&bytes)? else { return Ok(source.to_path_buf()); };+ let destination = cached_path(source);+ // Compare contents so a replaced source or damaged cache is repaired. No+ // timestamp assumptions, and repeat requests do not rewrite the cache.+ let mut existing = Vec::new();+ if let Ok(file) = fs::File::open(&destination) {+ let _ = file.take(converted.len() as u64 + 1).read_to_end(&mut existing);+ }+ if existing != converted {+ let temporary = source.with_extension("slopfab.part");+ fs::File::create(&temporary).and_then(|mut file| { file.write_all(&converted)?; file.sync_all() })+ .and_then(|_| fs::rename(&temporary, &destination)).map_err(|e| format!("Cannot cache Animate conditioning: {e}"))?;+ }+ Ok(destination)+}++#[cfg(test)]+pub(crate) fn fixture(path: &Path) {+ let header = serde_json::to_vec(&json!({+ "prompt_embeds": { "dtype": "BF16", "shape": [1, TOKENS, 5120], "data_offsets": [0, VALUES * 2] },+ "text_token_tags": { "dtype": "I64", "shape": [TOKENS], "data_offsets": [VALUES * 2, VALUES * 2 + TOKENS * 8] },+ })).unwrap();+ let mut bytes = (header.len() as u64).to_le_bytes().to_vec();+ bytes.extend(header);+ for _ in 0..VALUES { bytes.extend_from_slice(&0x3fc0u16.to_le_bytes()); }+ for i in 0..TOKENS { bytes.extend_from_slice(&(i as i64 % 3).to_le_bytes()); }+ fs::write(path, bytes).unwrap();+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn converts_exactly_reuses_and_repairs_cache() {+ let root = tempfile::tempdir().unwrap();+ let source = root.path().join("conditioning.safetensors");+ fixture(&source);+ let result = prepare(&source).unwrap();+ let bytes = fs::read(&result).unwrap();+ let end = u64::from_le_bytes(bytes[..8].try_into().unwrap()) as usize + 8;+ assert_eq!(f32::from_le_bytes(bytes[end..end + 4].try_into().unwrap()), 1.5);+ assert_eq!(i32::from_le_bytes(bytes[end + VALUES * 4 + 8..end + VALUES * 4 + 12].try_into().unwrap()), 2);+ let modified = fs::metadata(&result).unwrap().modified().unwrap();+ assert_eq!(prepare(&source).unwrap(), result);+ assert_eq!(fs::metadata(&result).unwrap().modified().unwrap(), modified);+ assert_eq!(prepare(&result).unwrap(), result);+ fs::write(&result, b"broken").unwrap();+ prepare(&source).unwrap();+ assert_eq!(fs::read(&result).unwrap(), bytes);+ fs::write(&source, b"truncated").unwrap();+ assert!(prepare(&source).is_err());+ }++ #[test]+ fn rejects_invalid_values_tags_and_offsets() {+ let root = tempfile::tempdir().unwrap();+ let source = root.path().join("conditioning.safetensors");+ fixture(&source);+ let bytes = fs::read(source).unwrap();+ let end = u64::from_le_bytes(bytes[..8].try_into().unwrap()) as usize + 8;+ let mut invalid = bytes.clone();+ invalid[end..end + 2].copy_from_slice(&0x7fc0u16.to_le_bytes());+ assert!(convert(&invalid).unwrap_err().contains("Non-finite"));+ let mut invalid = bytes.clone();+ invalid[end + VALUES * 2..end + VALUES * 2 + 8].copy_from_slice(&3i64.to_le_bytes());+ assert!(convert(&invalid).unwrap_err().contains("modality"));+ assert!(convert(&bytes[..bytes.len() - 1]).is_err());+ assert!(convert(&u64::MAX.to_le_bytes()).is_err());+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex fd3a555..4f8c3ea 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -13,6 +13,7 @@ mod agent_commands;mod app_paths;mod app_settings;mod cuda_support;+mod conditioning;mod diagnostics;mod export;mod reference_icons;diff --git a/src-tauri/src/slopfab.rs b/src-tauri/src/slopfab.rsindex 33e94ae..001e75d 100644--- a/src-tauri/src/slopfab.rs+++ b/src-tauri/src/slopfab.rs@@ -476,6 +476,7 @@ struct Configuration {vulkan: bool,attention: &'static str,animate: bool,+ prompt_embedding: Option<PathBuf>,models: [(i32, &'static str, Option<PathBuf>); 5],loras: Result<Vec<LoraAdapter>, String>,step_override: Result<Option<i32>, String>,@@ -505,6 +506,7 @@ impl Configuration {dll_path: option("dllPath").unwrap_or_else(default_dll_path),vulkan: string_option("inferenceBackend") == Some("vulkan"),animate: string_option("generationMode") == Some("animate"),+ prompt_embedding: option("promptEmbedding"),attention: match string_option("attention") {Some("exact") => "exact",Some("flash2") => "flash2",@@ -536,8 +538,14 @@ impl Configuration {if request.still_image {return Err("Animate requires video generation.".into());}- if request.reference_video_ids.is_empty() {- return Err("Animate requires a reference video.".into());+ if request.reference_video_ids.len() != 1 {+ return Err("Animate requires exactly one reference video.".into());+ }+ if request.reference_paths.len() != 1 {+ return Err("Animate requires exactly one repainted frame of the driving scene.".into());+ }+ if request.continuation_path.is_some() || !request.refmods.is_empty() {+ return Err("Animate does not support scene continuation or refmods.".into());}} else if request.prompt.trim().is_empty() {return Err("Generation prompt cannot be empty.".into());@@ -580,9 +588,10 @@ impl Configuration {pub fn status(settings: &BTreeMap<String, ProviderSetting>) -> SlopfabStatus {let configuration = Configuration::from_settings(settings);- let models = configuration+ let mut models = configuration.models.iter()+ .filter(|(id, _, _)| !configuration.animate || (*id != 1 && *id != 2)).map(|(_, id, path)| ModelStatus {id,configured: path.is_some(),@@ -592,6 +601,13 @@ pub fn status(settings: &BTreeMap<String, ProviderSetting>) -> SlopfabStatus {.map(|value| value.to_string_lossy().into_owned()),}).collect::<Vec<_>>();+ if configuration.animate {+ models.push(ModelStatus {+ id: "promptEmbedding", configured: configuration.prompt_embedding.is_some(),+ available: configuration.prompt_embedding.as_deref().is_some_and(Path::is_file),+ path: configuration.prompt_embedding.as_ref().map(|path| path.to_string_lossy().into_owned()),+ });+ }let dll_path = configuration.dll_path.to_string_lossy().into_owned();match ffi::Api::load(&configuration.dll_path) {Ok(api) => match api.version() {@@ -713,6 +729,17 @@ fn configure_request(include_models: bool,) -> Result<(), String> {configuration.validate_inputs(request)?;+ if configuration.animate {+ let videos = REFERENCE_VIDEOS.lock().map_err(|_| "Reference video lock failed.")?;+ let video = videos.get(&request.reference_video_ids[0])+ .ok_or("The prepared reference video no longer exists. Please retry generation.")?;+ // The setter selects Euler and four boundaries; explicit step settings follow.+ api.set_animate(handle, video.has_audio())?;+ let source = configuration.prompt_embedding.as_deref()+ .ok_or("Animate conditioning is missing. Download Animate in Settings and select its conditioning additional safetensor.")?;+ let embedding = crate::conditioning::prepare(source)?;+ api.set_prompt_embedding(handle, &embedding)?;+ }api.set_prompt(handle, if configuration.animate { ANIMATE_PROMPT } else { &request.prompt })?;api.set_frames(handle, request.frames)?;if request.still_image {@@ -745,6 +772,7 @@ fn configure_request(if include_models {api.set_reuse_models(handle, true)?;for (id, _, path) in &configuration.models {+ if configuration.animate && (*id == 1 || *id == 2) { continue; }if request.still_image && *id == 4 {continue;}@@ -1082,6 +1110,7 @@ pub fn generate_reference_icon_batch(vulkan: backend == ComputePlatform::Vulkan,attention: "sage2",animate: false,+ prompt_embedding: None,models: [(0, "transformer", Some(batch.transformer.clone())),(1, "textEncoder", Some(batch.text_encoder.clone())),@@ -1206,6 +1235,7 @@ mod ffi {attach_video: VideoAttach,dll_path: std::path::PathBuf,frames: usize,+ has_audio: bool,}// The registry mutex serializes access. The DLL handle and all copied input@@ -1224,7 +1254,7 @@ mod ffi {let mut handle = std::ptr::null_mut();api.error(create(duration, &mut handle))?;if handle.is_null() { return Err("slopfab returned an empty reference video handle.".into()); }- Ok(Self { api, handle, destroy, append_rgba, audio, attach_video, dll_path, frames: 0 })+ Ok(Self { api, handle, destroy, append_rgba, audio, attach_video, dll_path, frames: 0, has_audio: false })}}pub fn append(&mut self, bytes: &[u8], width: i32, height: i32, timestamp: f64) -> Result<(), String> {@@ -1236,8 +1266,11 @@ mod ffi {Ok(())}pub fn set_audio(&mut self, samples: &[f32], channels: i32, sample_rate: i32) -> Result<(), String> {- self.api.error(unsafe { (self.audio)(self.handle, samples.as_ptr(), samples.len(), channels, sample_rate, 0.0) })+ self.api.error(unsafe { (self.audio)(self.handle, samples.as_ptr(), samples.len(), channels, sample_rate, 0.0) })?;+ self.has_audio = !samples.is_empty();+ Ok(())}+ pub fn has_audio(&self) -> bool { self.has_audio }pub fn attach(&self, request: *mut Request, dll_path: &Path) -> Result<(), String> {if dll_path != self.dll_path { return Err("Reference video and generation must use the same slopfab runtime.".into()); }self.api.error(unsafe { (self.attach_video)(request, self.handle) })@@ -1360,6 +1393,8 @@ mod ffi {request_create: unsafe extern "C" fn() -> *mut Request,request_destroy: unsafe extern "C" fn(*mut Request),set_prompt: unsafe extern "C" fn(*mut Request, *const c_char) -> i32,+ set_animate: Option<unsafe extern "C" fn(*mut Request, i32, i32) -> i32>,+ set_prompt_embedding: Option<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>,set_resolution: unsafe extern "C" fn(*mut Request, i32, i32) -> i32,set_frames: unsafe extern "C" fn(*mut Request, i32) -> i32,set_still_image: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,@@ -1437,6 +1472,12 @@ mod ffi {"slopfab_request_set_prompt",unsafe extern "C" fn(*mut Request, *const c_char) -> i32),+ set_animate: library+ .get::<unsafe extern "C" fn(*mut Request, i32, i32) -> i32>(b"slopfab_request_set_animate\0")+ .ok().map(|symbol| *symbol),+ set_prompt_embedding: library+ .get::<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>(b"slopfab_request_set_prompt_embedding_path\0")+ .ok().map(|symbol| *symbol),set_resolution: symbol!("slopfab_request_set_resolution",unsafe extern "C" fn(*mut Request, i32, i32) -> i32@@ -1591,6 +1632,17 @@ mod ffi {let v = CString::new(v).map_err(|_| "Prompt contains a null byte.".to_string())?;self.error(unsafe { (self.set_prompt)(r, v.as_ptr()) })}+ #[cfg(test)]+ pub fn disable_animate_for_test(&mut self) { self.set_animate = None; }+ pub fn set_animate(&self, r: *mut Request, preserve_audio: bool) -> Result<(), String> {+ let set = self.set_animate.ok_or("Animate requires slopfab.dll API 1.10 or later. Update the runtime.")?;+ self.error(unsafe { set(r, 1, preserve_audio as i32) })+ }+ pub fn set_prompt_embedding(&self, r: *mut Request, path: &Path) -> Result<(), String> {+ let set = self.set_prompt_embedding.ok_or("This slopfab.dll does not support frozen conditioning. Update the runtime.")?;+ let path = path_cstring(path)?;+ self.error(unsafe { set(r, path.as_ptr()) })+ }pub fn set_resolution(&self, r: *mut Request, w: i32, h: i32) -> Result<(), String> {self.error(unsafe { (self.set_resolution)(r, w, h) })}@@ -1797,11 +1849,15 @@ mod tests {}#[test]- fn animate_fixed_prompt_and_four_steps_reach_bundled_dll() {+ fn animate_recipe_and_audio_selection_reach_bundled_dll() {+ let root = tempfile::tempdir().unwrap();+ let embedding = root.path().join("conditioning.safetensors");+ crate::conditioning::fixture(&embedding);let settings = BTreeMap::from([("slopfab".into(), ProviderSetting {enabled: true, model: None,options: BTreeMap::from([("generationMode".into(), ProviderOption::String("animate".into())),+ ("promptEmbedding".into(), ProviderOption::String(embedding.to_string_lossy().into_owned())),("stepOverride".into(), ProviderOption::Number(4.0)),]),})]);@@ -1810,22 +1866,29 @@ mod tests {let id = create_reference_video(2.0, &settings).unwrap();let result = (|| -> Result<(), String> {append_reference_video(&id, &vec![127; 64 * 64 * 4], 64, 64, 0.0)?;- let mut request = GenerationRequest {+ let request = GenerationRequest {job_id: "animate-test".into(), frames: 48, steps: 20, seed: 1,+ prompt: "This scene prompt must be ignored by Animate.".into(),canvas_width: 736, canvas_height: 416, reference_video_ids: vec![id.clone()],+ reference_paths: vec!["repainted.png".into()],..Default::default()};- for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {- for include_models in [false, true] {- let handle = RequestHandle::new(&api)?;- configure_request(&api, handle.0, &request, &configuration, platform, include_models)?;- assert_eq!(api.resolve(handle.0)?.num_model_evaluations, 3);- assert!(api.describe(handle.0)?.contains(&format!("prompt {} characters", ANIMATE_PROMPT.len())));- request.prompt = "This scene prompt must be ignored by Animate.".into();- let handle = RequestHandle::new(&api)?;- configure_request(&api, handle.0, &request, &configuration, platform, include_models)?;- assert!(api.describe(handle.0)?.contains(&format!("prompt {} characters", ANIMATE_PROMPT.len())));- request.prompt.clear();+ for preserve_audio in [false, true] {+ if preserve_audio {+ set_reference_video_audio(&id, &vec![0; 32_000 * 2 * 4], 1, 32_000)?;+ }+ for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {+ for include_models in [false, true] {+ let handle = RequestHandle::new(&api)?;+ configure_request(&api, handle.0, &request, &configuration, platform, include_models)?;+ assert_eq!(api.resolve(handle.0)?.num_model_evaluations, 3);+ let description = api.describe(handle.0)?;+ assert!(description.contains("fixed 362-token embedding; video then repainted image"));+ assert!(description.contains("reference short edge 416"));+ assert!(description.contains("video 1.000000 .. 0.600000 (shift 3.0)"));+ assert!(description.contains(if preserve_audio { "pinned driving soundtrack" } else { "generated; driving reference soundtrack omitted" }));+ assert!(description.contains(&format!("prompt {} characters", ANIMATE_PROMPT.len())));+ }}}Ok(())@@ -1834,6 +1897,14 @@ mod tests {result.unwrap();}+ #[test]+ fn animate_reports_missing_runtime_api() {+ let mut api = ffi::Api::load(&default_dll_path()).unwrap();+ api.disable_animate_for_test();+ let handle = RequestHandle::new(&api).unwrap();+ assert!(api.set_animate(handle.0, true).unwrap_err().contains("1.10"));+ }+#[test]fn continuation_uses_22_frames_and_plans_only_the_new_scene() {// An independent 39-frame, 64x32 archive exercises the real DLL withoutdiff --git a/src-tauri/src/weights.rs b/src-tauri/src/weights.rsindex 71c6b15..182f2f3 100644--- a/src-tauri/src/weights.rs+++ b/src-tauri/src/weights.rs@@ -265,6 +265,7 @@ pub async fn remove_downloaded_weights(app: AppHandle, paths: Vec<String>) -> Reif path.exists() {fs::remove_file(&path).map_err(|error| format!("Could not remove {}: {error}", path.display()))?;let _ = fs::remove_file(path.with_extension("complete.json"));+ let _ = fs::remove_file(crate::conditioning::cached_path(&path));}}Ok(())diff --git a/src/components/AdditionalSafetensorsEditor.tsx b/src/components/AdditionalSafetensorsEditor.tsxnew file mode 100644index 0000000..756a526--- /dev/null+++ b/src/components/AdditionalSafetensorsEditor.tsx@@ -0,0 +1,42 @@+import { useState } from "react";+import { Plus, Trash2 } from "lucide-react";+import { isDownloadUrl, type AdditionalSafetensor } from "../lib/settings";++export function AdditionalSafetensorsEditor({ value, disabled, animate, onChange }: {+ value: AdditionalSafetensor[]; disabled: boolean; animate: boolean; onChange: (files: AdditionalSafetensor[]) => void;+}) {+ const [url, setUrl] = useState("");+ const [error, setError] = useState<string | null>(null);+ const update = (id: string, patch: Partial<AdditionalSafetensor>) => onChange(value.map((file) => file.id === id ? { ...file, ...patch } : file));+ return <details className="weight-sources" open={animate || undefined}>+ <summary>Additional safetensors ({value.length})</summary>+ <p>These files download with this generator into your weights folder.</p>+ {value.map((file, index) => <div className="weight-source" key={`${file.id}-${file.url}`}>+ <label>Name<input aria-label={`Additional safetensor ${index + 1} name`} value={file.name} disabled={disabled}+ onChange={(event) => update(file.id, { name: event.target.value })} /></label>+ <label>Download URL<input aria-label={`Additional safetensor ${index + 1} URL`} defaultValue={file.url} disabled={disabled} onBlur={(event) => {+ const url = event.target.value.trim();+ if (!isDownloadUrl(url)) { setError("Enter an HTTP or HTTPS download URL."); return; }+ setError(null);+ if (url !== file.url) update(file.id, { url, downloadedPath: undefined });+ }} /></label>+ {animate && <label>Use<select aria-label={`Additional safetensor ${index + 1} use`} value={file.role ?? ""} disabled={disabled} onChange={(event) => {+ const role = event.target.value === "promptEmbedding" ? "promptEmbedding" : undefined;+ onChange(value.map((entry) => entry.id === file.id ? { ...entry, role } : role ? { ...entry, role: undefined } : entry));+ }}><option value="">Additional file</option><option value="promptEmbedding">Animate conditioning</option></select></label>}+ <span title={file.downloadedPath}>{file.downloadedPath ? "Downloaded" : "Download required"}</span>+ <button type="button" className="icon-button" disabled={disabled} aria-label={`Remove additional safetensor ${index + 1}`}+ onClick={() => onChange(value.filter((entry) => entry.id !== file.id))}><Trash2 size={15} /></button>+ </div>)}+ <div className="weight-source-add">+ <input aria-label="Add additional safetensor URL" value={url} disabled={disabled} placeholder="https://…"+ onChange={(event) => setUrl(event.target.value)} />+ <button type="button" className="secondary-button" disabled={disabled || !isDownloadUrl(url) || value.some((file) => file.url === url.trim())} onClick={() => {+ onChange([...value, { id: crypto.randomUUID(), name: url.trim().split("/").pop()?.split("?")[0] || "Additional safetensor", url: url.trim(),+ ...(animate && !value.some((file) => file.role === "promptEmbedding") ? { role: "promptEmbedding" } : {}) }]);+ setUrl("");+ }}><Plus size={15} /> Add file</button>+ </div>+ {error && <p role="alert">{error}</p>}+ </details>;+}diff --git a/src/components/SettingsView.downloads.test.tsx b/src/components/SettingsView.downloads.test.tsxindex e1868e2..54c9d77 100644--- a/src/components/SettingsView.downloads.test.tsx+++ b/src/components/SettingsView.downloads.test.tsx@@ -32,6 +32,22 @@ beforeEach(() => {});afterEach(() => { cleanup(); delete (window as Window & { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__; });+it("adds and downloads an additional safetensor from a generator's settings", async () => {+ render(<SettingsView onClose={() => undefined} />);+ fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));+ fireEvent.change(screen.getByLabelText("Add additional safetensor URL"), { target: { value: "https://example.com/extra.safetensors" } });+ fireEvent.click(screen.getByRole("button", { name: "Add file" }));+ expect(screen.getByLabelText("Additional safetensor 1 URL")).toHaveValue("https://example.com/extra.safetensors");+ fireEvent.click(screen.getByRole("button", { name: "Download weights" }));+ await waitFor(() => expect(getWeightDownloadState()).toMatchObject({ templateId: "default", active: false, completed: 1, error: null }));+ expect(loadGeneratorTemplateSettings().templates[0].additionalSafetensors![0].downloadedPath).toBe("C:/Slopus/weights/extra.safetensors");+ fireEvent.change(screen.getByLabelText("Generator mode"), { target: { value: "animate" } });+ fireEvent.change(screen.getByLabelText("Additional safetensor 1 use"), { target: { value: "promptEmbedding" } });+ await waitFor(() => expect(invoke).toHaveBeenCalledWith("slopfab_status", expect.objectContaining({ settings: {+ slopfab: expect.objectContaining({ options: expect.objectContaining({ generationMode: "animate", promptEmbedding: "C:/Slopus/weights/extra.safetensors" }) }),+ } })));+});+it("discovers Singularity's existing weights on opening Settings and downloads only missing Turbo", async () => {const normal = vi.mocked(invoke).getMockImplementation()!;const cached = Object.fromEntries(Object.values(minimaxSingularityTemplate().paths).filter(Boolean)diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsxindex 4472212..3314057 100644--- a/src/components/SettingsView.tsx+++ b/src/components/SettingsView.tsx@@ -1,3 +1,4 @@+import { AdditionalSafetensorsEditor } from "./AdditionalSafetensorsEditor";import { AlertCircle, Check, ChevronLeft, Download, FolderOpen, FolderSearch, LoaderCircle, Monitor, Moon, Plus, RefreshCw, RotateCcw, Sun, Trash2, Video, X } from "lucide-react";import { useCallback, useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";import { revealDiagnosticLog } from "../lib/diagnostics";@@ -9,7 +10,7 @@ import { retryWeightDownload } from "../lib/weightDownloads";import { cancelWeightDownload, downloadTemplateWeights, getWeightDownloadState, refreshDownloadedWeights, removeTemplateWeights, subscribeWeightDownloads, updateWeightPath, weightDownloadProgress } from "../lib/weightDownloads";import { chooseEnginePath, getAgentModels, getEngineStatus, type ModelStatus, type SlopfabStatus } from "../lib/runtime";import {- EMPTY_ENGINE_SETTINGS, ENGINE_PATH_FIELDS,+ EMPTY_ENGINE_SETTINGS, generatorPathFields,createGeneratorTemplate, defaultGeneratorTemplate,isEndpointProviderConfigured, loadAgentEndpointSettings,loadGeneratorTemplateSettings, saveAgentEndpointSettings, saveGeneratorTemplateSettings,@@ -50,7 +51,7 @@ const stateLabel: Record<PathState, string> = {function templateSummary(template: GeneratorTemplate): string {const loras = downloadableTemplateLoras(template.loras);- const pendingModels = ENGINE_PATH_FIELDS.some(({ id }) => isDownloadUrl(template.paths[id])+ const pendingModels = generatorPathFields(template).some(({ id }) => isDownloadUrl(template.paths[id])|| (!template.paths[id].trim() && (template.sources?.[id]?.length ?? 0) > 0));return `${template.defaultSteps} steps${loras.length && !pendingModels ? ` · Needs ${loras.map(({ name }) => name).join(", ")} LoRA${loras.length > 1 ? "s" : ""}` : ""}`;}@@ -302,12 +303,12 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onClconst probe = useCallback((paths?: EngineSettings) => {const revision = ++probeRevision.current;- void getEngineStatus(paths, selectedTemplate.attention, selectedTemplate.loras ?? [], selectedTemplate.mode ?? "prompt").then((next) => {+ void getEngineStatus(paths, selectedTemplate.attention, selectedTemplate.loras ?? [], selectedTemplate.mode ?? "prompt", selectedTemplate.additionalSafetensors ?? []).then((next) => {if (revision === probeRevision.current) setStatus(next);}).catch(() => {if (revision === probeRevision.current) setStatus(null);});- }, [selectedTemplate.attention, selectedTemplate.loras, selectedTemplate.mode]);+ }, [selectedTemplate.attention, selectedTemplate.loras, selectedTemplate.mode, selectedTemplate.additionalSafetensors]);/* Saved on every keystroke — there is no Save button here, so a half-typedpath must never be the reason generation is still broken after a restart.@@ -372,7 +373,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onClprobe({ ...EMPTY_ENGINE_SETTINGS });};- const updateTemplate = (updates: Partial<Pick<typeof selectedTemplate, "name" | "defaultSteps" | "attention" | "loras" | "mode">>) => {+ const updateTemplate = (updates: Partial<Pick<typeof selectedTemplate, "name" | "defaultSteps" | "attention" | "loras" | "mode" | "additionalSafetensors">>) => {setTemplateSettings((current) => {const next = {...current,@@ -395,7 +396,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onClconst removeTemplate = (id: string) => {const template = templateSettings.templates.find((template) => template.id === id);- if (template && Object.values(template.sources ?? {}).some((sources) => sources.length > 0)) {+ if (template && (Object.values(template.sources ?? {}).some((sources) => sources.length > 0) || Boolean(template.additionalSafetensors?.length))) {void removeTemplateWeights(id).catch((reason) => setError(String(reason)));return;}@@ -418,7 +419,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onClsaveGeneratorTemplateSettings(next);};- const missing = ENGINE_PATH_FIELDS.filter((field) => field.required && pathState(field, settings[field.id], status) !== "found");+ const missing = generatorPathFields(selectedTemplate).filter((field) => field.required && pathState(field, settings[field.id], status) !== "found");return (<div className="settings-overlay" role="dialog" aria-modal="true" aria-labelledby="settings-heading">@@ -531,7 +532,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl? <button type="button" className="icon-button" disabled={!desktop || downloadState?.active} onClick={() => void downloadTemplateWeights(template.id)} aria-label={`Download generator ${template.name}`} title={`Download ${template.name} weights`}>{downloadState?.active && downloadState.templateId === template.id ? <LoaderCircle size={15} className="spin" /> : <Download size={15} />}</button>- : <button type="button" className="icon-button" disabled={Boolean(downloadState?.active) || (Object.values(template.sources ?? {}).some((sources) => sources.length) ? !desktop : templateSettings.templates.length === 1)} onClick={() => removeTemplate(template.id)} aria-label={Object.values(template.sources ?? {}).some((sources) => sources.length) ? `Remove downloaded weights for ${template.name}` : `Remove generator ${template.name}`} title={Object.values(template.sources ?? {}).some((sources) => sources.length) ? `Remove ${template.name} weights and keep the template` : `Remove ${template.name}`}><Trash2 size={15} /></button>}+ : <button type="button" className="icon-button" disabled={Boolean(downloadState?.active) || ((Object.values(template.sources ?? {}).some((sources) => sources.length) || Boolean(template.additionalSafetensors?.length)) ? !desktop : templateSettings.templates.length === 1)} onClick={() => removeTemplate(template.id)} aria-label={(Object.values(template.sources ?? {}).some((sources) => sources.length) || Boolean(template.additionalSafetensors?.length)) ? `Remove downloaded weights for ${template.name}` : `Remove generator ${template.name}`} title={(Object.values(template.sources ?? {}).some((sources) => sources.length) || Boolean(template.additionalSafetensors?.length)) ? `Remove ${template.name} weights and keep the template` : `Remove ${template.name}`}><Trash2 size={15} /></button>}</div>))}</div>@@ -575,7 +576,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl<p>{engineDetail(status, desktop, missing.length)}</p>{status?.platform && <small className="settings-status__platform"><b>Platform</b>{status.platform}</small>}</div>- {ENGINE_PATH_FIELDS.map((field) => {+ {generatorPathFields(selectedTemplate).map((field) => {const value = settings[field.id];const state = pathState(field, value, status);return (@@ -611,6 +612,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl</div>);})}+ <AdditionalSafetensorsEditor key={selectedTemplate.id} value={selectedTemplate.additionalSafetensors ?? []} disabled={Boolean(downloading)} animate={selectedTemplate.mode === "animate"} onChange={(additionalSafetensors) => updateTemplate({ additionalSafetensors })} /><TemplateLorasEditor value={selectedTemplate.loras ?? []} onChange={(loras) => updateTemplate({ loras })} /><label className="generator-editor__advanced"><input type="checkbox" checked={showAdvancedOptions} onChange={(event) => setShowAdvancedOptions(event.target.checked)} />diff --git a/src/components/workspace/GeneratorView.test.tsx b/src/components/workspace/GeneratorView.test.tsxindex b8ff2e8..3d266c3 100644--- a/src/components/workspace/GeneratorView.test.tsx+++ b/src/components/workspace/GeneratorView.test.tsx@@ -35,8 +35,9 @@ it("has no selected generator when all templates still need downloads", () => {expect(screen.getByRole("combobox", { name: "Video generator template: No downloaded generators" })).toBeDisabled();});-it("animates a blank scene only after selecting a video and submits an empty prompt", () => {+it("animates a blank scene only with a video and repainted frame", () => {const template = viggleAnimateTemplate();+ template.additionalSafetensors![0].downloadedPath = "conditioning.safetensors";template.paths = { transformer: "viggle.safetensors", textEncoder: "encoder", videoVae: "video", audioVae: "audio", tokenizer: "" };localStorage.setItem("slopus.loras.v1", JSON.stringify([{ id: template.loras![0].loraId, name: "Viggle", path: "distillation.safetensors", stepOverride: 4 }]));localStorage.setItem("slopus.generator-templates.v1", JSON.stringify({ templates: [template], defaultTemplateId: template.id, catalogVersion: 7 }));@@ -44,7 +45,9 @@ it("animates a blank scene only after selecting a video and submits an empty proinitial.generationJobs = [createDraftGenerationJob("", { id: "blank", title: "Blank scene" })];initial.references = [{ id: "motion", kind: "video", name: "Motion", description: "", intendedUse: [],sourcePath: "C:/motion.mp4", createdAt: "2026-09-15T00:00:00.000Z",- video: { startSeconds: 1, durationSeconds: 3, includeAudio: false } }];+ video: { startSeconds: 1, durationSeconds: 3, includeAudio: false } },+ { id: "repainted", kind: "image", name: "Repainted frame", description: "", intendedUse: [],+ relativePath: "references/repainted.png", createdAt: "2026-09-15T00:00:00.000Z" }];const submitted = vi.fn();function Harness() {const [config, setConfig] = useState(initial);@@ -58,11 +61,18 @@ it("animates a blank scene only after selecting a video and submits an empty proexpect(submitted.mock.calls.flatMap(([items]) => items)).toHaveLength(0);expect(screen.queryByLabelText("The sound of this scene")).toBeNull();fireEvent.change(screen.getByLabelText("Reference video for this scene"), { target: { value: "motion" } });+ expect(generate).toBeDisabled();+ fireEvent.change(screen.getByLabelText("Start frame for this scene"), { target: { value: "repainted" } });expect(generate).toBeEnabled();fireEvent.click(generate);expect(submitted).toHaveBeenLastCalledWith([expect.objectContaining({ request: expect.objectContaining({prompt: "", referenceVideos: [{ name: "Motion", sourcePath: "C:/motion.mp4", startSeconds: 1, durationSeconds: 3, includeAudio: false }],+ referencePaths: ["C:/project/references/repainted.png"],}) })]);+ fireEvent.change(screen.getByLabelText("Start frame for this scene"), { target: { value: "" } });+ expect(generate).toBeDisabled();+ fireEvent.change(screen.getByLabelText("Start frame for this scene"), { target: { value: "repainted" } });+ expect(generate).toBeEnabled();fireEvent.change(screen.getByLabelText("Reference video for this scene"), { target: { value: "" } });expect(generate).toBeDisabled();});@@ -468,7 +478,7 @@ describe("Generator scene controls", () => {fireEvent.click(screen.getByRole("option", { name: "Fast draft" }));await waitFor(() => expect(document.querySelector(".generator-runtime--modelsMissing > i")).not.toBeNull());- expect(getEngineStatus).toHaveBeenCalledWith(expect.objectContaining({ transformer: "draft.safetensors" }), "sage2", [], "prompt");+ expect(getEngineStatus).toHaveBeenCalledWith(expect.objectContaining({ transformer: "draft.safetensors" }), "sage2", [], "prompt", []);expect(JSON.parse(localStorage.getItem("slopus.generator-templates.v1")!).defaultTemplateId).toBe("draft");expect(screen.queryByText("Video model files missing")).not.toBeInTheDocument();expect(template.closest(".generator-runtime--modelsMissing")).not.toBeNull();diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsxindex d9675aa..e139bdc 100644--- a/src/components/workspace/GeneratorView.tsx+++ b/src/components/workspace/GeneratorView.tsx@@ -6,7 +6,7 @@ import { referenceRefmodInputs } from "../../lib/project";import { ChevronDown, Plus, Square, Trash2, WandSparkles } from "lucide-react";import { invoke } from "@tauri-apps/api/core";import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";-import { actionReferenceIds, compileGenerationJobPrompt, compileGenerationJobSegments, createDraftGenerationJob, danglingReferenceTokens, GENERATION_FRAME_RATE, RANDOM_GENERATION_SEED, sceneDurationSeconds, sceneFrameInputs, sceneGenerationSeed, sceneGenerationSnapshot, sceneGenerationSteps, sceneShots, SCENE_MAX_SECONDS, SCENE_MIN_SECONDS, projectItemPath, usableReferenceImages, type GenerationJob, type ProjectConfig, type ProjectReference, type SceneShot } from "../../lib/project";+import { actionReferenceIds, compileGenerationJobPrompt, compileGenerationJobSegments, createDraftGenerationJob, danglingReferenceTokens, GENERATION_FRAME_RATE, RANDOM_GENERATION_SEED, sceneDurationSeconds, sceneFrameInputs, sceneGenerationReferences, sceneGenerationSeed, sceneGenerationSnapshot, sceneGenerationSteps, sceneShots, SCENE_MAX_SECONDS, SCENE_MIN_SECONDS, projectItemPath, usableReferenceImages, type GenerationJob, type ProjectConfig, type ProjectReference, type SceneShot } from "../../lib/project";import { generationDimensions } from "../../lib/export";import { isTauri } from "../../lib/persistence";import { getEngineStatus, type SlopfabGenerationRequest, type SlopfabStatus } from "../../lib/runtime";@@ -59,7 +59,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst runtimeProbe = useRef(0);const [loraLibrary, setLoraLibrary] = useState(loadLoras);useEffect(() => subscribeLoras(() => setLoraLibrary(loadLoras())), []);- const templateKey = JSON.stringify([selectedTemplate.id, selectedTemplate.mode, selectedTemplate.paths, selectedTemplate.attention, selectedTemplate.loras, loraLibrary]);+ const templateKey = JSON.stringify([selectedTemplate.id, selectedTemplate.mode, selectedTemplate.paths, selectedTemplate.attention, selectedTemplate.loras, selectedTemplate.additionalSafetensors, loraLibrary]);const probedTemplate = useRef(templateKey);const configRef = useRef(config);configRef.current = config;@@ -107,7 +107,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCosetRuntimeError(null);const probe = ++runtimeProbe.current;if (!selectedTemplate.id) return;- void getEngineStatus(selectedTemplate.paths, selectedTemplate.attention, selectedTemplate.loras ?? [], selectedTemplate.mode ?? "prompt").then((status) => {+ void getEngineStatus(selectedTemplate.paths, selectedTemplate.attention, selectedTemplate.loras ?? [], selectedTemplate.mode ?? "prompt", selectedTemplate.additionalSafetensors ?? []).then((status) => {if (probe !== runtimeProbe.current) return;setGeneratorRuntime(status);onRuntimeChange?.(status);@@ -615,8 +615,13 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo/** Validate the inputs required by the selected generator before submission. */function sendBlocker(job: GenerationJob, references: ProjectReference[], animate = false): string | null {const shots = sceneShots(job);- if (animate && !usableVideoReferences(references.filter((reference) => job.referenceIds.includes(reference.id))).length) {- return "Select a reference video for this scene before animating.";+ if (animate) {+ const bound = sceneGenerationReferences(job, references);+ if (usableVideoReferences(bound).length !== 1) return "Select exactly one reference video for this scene before animating.";+ if (usableReferenceImages(bound).length !== 1) return "Select exactly one repainted frame of the driving scene before animating.";+ if (job.usePreviousSceneLastFrame || bound.some((reference) => reference.refmods?.some((refmod) => refmod.strength > 0))) {+ return "Animate does not support scene continuation or refmods.";+ }}if (!animate && shots.every((shot) => shot.action.trim().length === 0 && !(shot.speech ?? "").trim())) {return "Describe what happens or add speech in at least one shot before this scene can be generated.";diff --git a/src/components/workspace/SceneEditor.tsx b/src/components/workspace/SceneEditor.tsxindex 8e410d2..641ed99 100644--- a/src/components/workspace/SceneEditor.tsx+++ b/src/components/workspace/SceneEditor.tsx@@ -305,7 +305,7 @@ export function SceneInspector({ job, shots, references, previousScene, defaultS<option value="">Select a video</option>{usableVideoReferences(references).map((reference) => <option key={reference.id} value={reference.id}>{reference.name}</option>)}</select>- <small>Animate requires a reference video. Add videos under References. No text prompt is needed.</small>+ <small>Choose one driving video and one repainted frame of its scene. Enable the video's soundtrack under References to preserve it. No text prompt is needed.</small></label>}{!animate && <label className="scene-settings__field"><span>Look</span>@@ -328,19 +328,25 @@ export function SceneInspector({ job, shots, references, previousScene, defaultS</select></label>}<div className="scene-settings__field">- <span>Start frame</span>+ <span>{animate ? "Repainted scene frame" : "Start frame"}</span><div className="scene-settings__start-frame"><select- value={job.usePreviousSceneLastFrame ? "previous-scene" : job.startFrameReferenceId ?? ""}+ value={animate+ ? job.startFrameReferenceId ?? imageReferences.find((reference) => job.referenceIds.includes(reference.id))?.id ?? ""+ : job.usePreviousSceneLastFrame ? "previous-scene" : job.startFrameReferenceId ?? ""}disabled={disabled}aria-label="Start frame for this scene"onChange={(event) => onChange({usePreviousSceneLastFrame: event.target.value === "previous-scene" || undefined,startFrameReferenceId: event.target.value === "previous-scene" ? undefined : event.target.value || undefined,+ ...(animate ? {+ endFrameReferenceId: undefined,+ referenceIds: job.referenceIds.filter((id) => !imageReferences.some((reference) => reference.id === id)),+ } : {}),})}><option value="">None</option>- <option value="previous-scene" disabled={!previousScene}>Previous scene's last frame</option>+ {!animate && <option value="previous-scene" disabled={!previousScene}>Previous scene's last frame</option>}{imageReferences.map((reference) => <option key={reference.id} value={reference.id}>{reference.name}</option>)}</select><button@@ -351,11 +357,11 @@ export function SceneInspector({ job, shots, references, previousScene, defaultSonClick={onAddStartFrame}><ImagePlus size={15} /> Add image</button></div>- <small>{job.usePreviousSceneLastFrame+ <small>{animate ? "Use a frame of the driving video with the character repainted. Keep its pose, framing, background and lighting." : job.usePreviousSceneLastFrame? previousScene ? `Continues “${previousScene.title}” using its saved latents with 22 overlapping frames. Generate that scene first, or use Generate All.` : "Move this scene after another scene to continue it.": "The selected image anchors the opening frame."}</small></div>- <div className="scene-settings__field">+ {!animate && <div className="scene-settings__field"><span>Last frame</span><div className="scene-settings__start-frame"><select value={job.endFrameReferenceId ?? ""} disabled={disabled} aria-label="Last frame for this scene"@@ -368,7 +374,7 @@ export function SceneInspector({ job, shots, references, previousScene, defaultSonClick={onAddEndFrame}><ImagePlus size={15} /> Add image</button></div><small>The selected image anchors the closing frame.</small>- </div>+ </div>}{importError && <small className="scene-settings__error" role="alert">{importError}</small>}{!animate && <><label className="scene-settings__field"><span>Sound</span>diff --git a/src/lib/runtime.ts b/src/lib/runtime.tsindex b159f63..eddac6e 100644--- a/src/lib/runtime.ts+++ b/src/lib/runtime.ts@@ -144,16 +144,16 @@ export const CHECKING_PROVIDERS: ProviderStatus[] = [/** Probes the engine paths on their own, with no project in hand — what the* settings screen shows. */-export async function getEngineStatus(settings = loadEngineSettings(), attention?: AttentionMode, loras?: TemplateLora[], mode?: GeneratorTemplate["mode"]): Promise<SlopfabStatus> {+export async function getEngineStatus(settings = loadEngineSettings(), attention?: AttentionMode, loras?: TemplateLora[], mode?: GeneratorTemplate["mode"], additionalSafetensors?: GeneratorTemplate["additionalSafetensors"]): Promise<SlopfabStatus> {if (!isTauri()) return DEMO_STATUS.slopfab;let slopfab;let adapterError: string | undefined;try {- slopfab = engineProviderSetting(settings, undefined, attention, loras, mode);+ slopfab = engineProviderSetting(settings, undefined, attention, loras, mode, additionalSafetensors);} catch (reason) {// A missing adapter must not prevent checking the individual model files.adapterError = reason instanceof Error ? reason.message : String(reason);- slopfab = engineProviderSetting(settings, undefined, attention, [], mode);+ slopfab = engineProviderSetting(settings, undefined, attention, [], mode, additionalSafetensors);}const status = await invoke<SlopfabStatus>("slopfab_status", { settings: { slopfab } });return adapterError ? { ...status, state: status.state === "ready" ? "modelsMissing" : status.state,diff --git a/src/lib/settings.test.ts b/src/lib/settings.test.tsindex fcc321a..53105f7 100644--- a/src/lib/settings.test.ts+++ b/src/lib/settings.test.ts@@ -49,6 +49,20 @@ describe("generator templates", () => {}});+ it("adds conditioning to installed Animate templates once without replacing custom files", () => {+ const animate = viggleAnimateTemplate();+ animate.paths.transformer = "D:/models/viggle.safetensors";+ delete animate.additionalSafetensors;+ localStorage.setItem("slopus.generator-templates.v1", JSON.stringify({ templates: [animate], defaultTemplateId: "", catalogVersion: 7 }));+ const migrated = loadGeneratorTemplateSettings();+ expect(migrated.templates[0].paths.transformer).toBe(animate.paths.transformer);+ expect(migrated.templates[0].additionalSafetensors).toEqual(viggleAnimateTemplate().additionalSafetensors);+ expect(loadGeneratorTemplateSettings()).toEqual(migrated);+ migrated.templates[0].additionalSafetensors![0].url = "https://example.com/custom.safetensors";+ saveGeneratorTemplateSettings(migrated);+ expect(loadGeneratorTemplateSettings().templates[0].additionalSafetensors![0].url).toBe("https://example.com/custom.safetensors");+ });+it("migrates Animate once and preserves its mode, local weights and four-step adapter", () => {const custom = createGeneratorTemplate("Existing");saveGeneratorTemplateSettings({ templates: [custom], defaultTemplateId: custom.id, catalogVersion: 6 });@@ -59,15 +73,19 @@ describe("generator templates", () => {expect(loadGeneratorTemplateSettings()).toEqual(settings);expect(template.paths.transformer).toBe("https://huggingface.co/DeepBeepMeep/MiniMax-H3/resolve/main/Viggle-Animate-pruned_rank8_int8_convrot.safetensors");expect(templateNeedsDownload(template)).toBe(true);+ template.additionalSafetensors![0].downloadedPath = "D:/weights/conditioning.safetensors";template.name = "My animation";template.paths = { transformer: "local", textEncoder: "encoder", videoVae: "video", audioVae: "audio", tokenizer: "" };saveLoras(loadLoras().map((lora) => lora.id === VIGGLE_ANIMATE_LORA.id ? { ...lora, path: "adapter" } : lora));saveGeneratorTemplateSettings({ ...settings, defaultTemplateId: template.id });expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === template.id)).toEqual(template);const options = engineProviderSetting(loadEngineSettings()).options;- expect(options).toMatchObject({ generationMode: "animate", stepOverride: 4 });+ expect(options).toMatchObject({ generationMode: "animate", stepOverride: 4, promptEmbedding: "D:/weights/conditioning.safetensors" });+ expect(options).not.toHaveProperty("textEncoder");+ expect(options).not.toHaveProperty("tokenizer");expect(JSON.parse(options.loras as string)).toEqual([{ path: "adapter", strength: 1 }]);expect(engineProviderSetting(custom.paths, { enabled: true, model: null, options }, "sage2", [], "prompt").options).not.toHaveProperty("generationMode");+ expect(engineProviderSetting(custom.paths, { enabled: true, model: null, options }, "sage2", [], "prompt").options).not.toHaveProperty("promptEmbedding");});it("adds References with the same settings and VRAM variants except for the main transformer URL", () => {@@ -96,7 +114,7 @@ describe("generator templates", () => {expect(settings.templates[2]).toEqual(minimaxFastTemplate());expect(settings.templates[3]).toEqual(minimaxSingularityTemplate());expect(settings.defaultTemplateId).toBe(template.id);- expect(settings.catalogVersion).toBe(7);+ expect(settings.catalogVersion).toBe(8);expect(loadGeneratorTemplateSettings()).toEqual(settings);saveGeneratorTemplateSettings({ ...settings, templates: [settings.templates[0]] });expect(loadGeneratorTemplateSettings().templates).toHaveLength(1);@@ -117,7 +135,7 @@ describe("generator templates", () => {const settings = loadGeneratorTemplateSettings();expect(settings.templates).toEqual([expect.objectContaining(custom), minimaxSingularityTemplate(), viggleAnimateTemplate()]);expect(settings.defaultTemplateId).toBe(custom.id);- expect(settings.catalogVersion).toBe(7);+ expect(settings.catalogVersion).toBe(8);expect(loadGeneratorTemplateSettings()).toEqual(settings);saveGeneratorTemplateSettings({ ...settings, templates: [custom] });expect(loadGeneratorTemplateSettings().templates).toEqual([expect.objectContaining(custom)]);@@ -171,7 +189,7 @@ describe("generator templates", () => {template.paths[field] = downloadedPath;localStorage.setItem("slopus.generator-templates.v1", JSON.stringify({ templates: [template], catalogVersion: 1 }));const settings = loadGeneratorTemplateSettings();- expect(settings.catalogVersion).toBe(7);+ expect(settings.catalogVersion).toBe(8);expect(settings.templates[0].paths[field]).toBe(downloadedPath);expect(settings.templates[0].sources![field]).toEqual(minimaxOriginalTemplate().sources![field]!.map((source, index) =>index === 0 ? { ...source, downloadedPath } : source));@@ -206,7 +224,7 @@ describe("generator templates", () => {localStorage.setItem("slopus.generator-templates.v1", JSON.stringify({ templates: [template], defaultTemplateId: template.id, catalogVersion: 2 }));const settings = loadGeneratorTemplateSettings();const migrated = settings.templates[0];- expect(settings.catalogVersion).toBe(7);+ expect(settings.catalogVersion).toBe(8);expect(migrated.sources!.textEncoder).toEqual([{ url: originalUrl, gpuModel: "", minVramGb: 0, ...(selection === "cached original" ? { downloadedPath: cachedOriginal } : {}) },custom,diff --git a/src/lib/settings.ts b/src/lib/settings.tsindex 5b84641..b90b028 100644--- a/src/lib/settings.ts+++ b/src/lib/settings.ts@@ -76,8 +76,19 @@ export interface GeneratorTemplate {paths: EngineSettings;sources?: Partial<Record<EnginePathId, WeightSource[]>>;loras?: TemplateLora[];+ additionalSafetensors?: AdditionalSafetensor[];}+export interface AdditionalSafetensor {+ id: string;+ name: string;+ url: string;+ role?: "promptEmbedding";+ downloadedPath?: string;+}++export const ANIMATE_CONDITIONING_URL = "https://huggingface.co/drbaph/Viggle-Animate-ComfyUI/resolve/main/text_cond/fixed_embed_fwd_anyframe.safetensors";+export interface WeightSource {url: string;gpuModel: string;@@ -85,12 +96,19 @@ export interface WeightSource {downloadedPath?: string;}+export function generatorPathFields(template: Pick<GeneratorTemplate, "mode">): EnginePathField[] {+ return template.mode === "animate"+ ? ENGINE_PATH_FIELDS.filter(({ id }) => id !== "textEncoder" && id !== "tokenizer")+ : ENGINE_PATH_FIELDS;+}+export const isDownloadUrl = (value: string): boolean => /^https?:\/\//i.test(value.trim());export function templateNeedsDownload(template: GeneratorTemplate): boolean {- return ENGINE_PATH_FIELDS.some(({ id }) => isDownloadUrl(template.paths[id])+ return generatorPathFields(template).some(({ id }) => isDownloadUrl(template.paths[id])|| (!template.paths[id].trim() && (template.sources?.[id]?.length ?? 0) > 0))- || downloadableTemplateLoras(template.loras).length > 0;+ || downloadableTemplateLoras(template.loras).length > 0+ || (template.additionalSafetensors ?? []).some((file) => !file.downloadedPath || isDownloadUrl(file.downloadedPath));}const GENERATOR_TEMPLATES_EVENT = "slopus:generator-templates-changed";@@ -204,6 +222,7 @@ export function viggleAnimateTemplate(): GeneratorTemplate {const template = minimaxOriginalTemplate();const transformer = "https://huggingface.co/DeepBeepMeep/MiniMax-H3/resolve/main/Viggle-Animate-pruned_rank8_int8_convrot.safetensors";return { ...template, id: "viggle-animate", name: "Animate", mode: "animate", defaultSteps: 4,+ additionalSafetensors: [{ id: "animate-conditioning", name: "Animate conditioning", url: ANIMATE_CONDITIONING_URL, role: "promptEmbedding" }],loras: [{ loraId: VIGGLE_ANIMATE_LORA.id, enabled: true, strength: 1 }],paths: { ...template.paths, transformer },sources: { ...template.sources, transformer: [{ url: transformer, gpuModel: "", minVramGb: 0 }] },@@ -213,7 +232,7 @@ export function viggleAnimateTemplate(): GeneratorTemplate {const initialTemplateSettings = (paths = EMPTY_ENGINE_SETTINGS): GeneratorTemplateSettings => ({templates: [{ id: "default", name: "Default", defaultSteps: DEFAULT_GENERATION_STEPS, attention: "sage2", paths: copyPaths(paths) }, minimaxOriginalTemplate(), minimaxReferencesTemplate(), minimaxFastTemplate(), minimaxSingularityTemplate(), viggleAnimateTemplate()],defaultTemplateId: "default",- catalogVersion: 7,+ catalogVersion: 8,});const normalizeTemplateSettings = (value: unknown): GeneratorTemplateSettings | null => {@@ -250,7 +269,18 @@ const normalizeTemplateSettings = (value: unknown): GeneratorTemplateSettings |}if (entries.length) sources[field.id] = entries;}+ const additionalIds = new Set<string>();+ const additionalSafetensors: AdditionalSafetensor[] = Array.isArray(candidate.additionalSafetensors)+ ? candidate.additionalSafetensors.flatMap((file) => {+ if (!file || typeof file.id !== "string" || !file.id.trim() || additionalIds.has(file.id)+ || typeof file.url !== "string" || !isDownloadUrl(file.url)) return [];+ additionalIds.add(file.id);+ return [{ id: file.id, name: typeof file.name === "string" && file.name.trim() ? file.name.trim() : "Additional safetensor",+ url: file.url.trim(), ...(file.role === "promptEmbedding" ? { role: "promptEmbedding" as const } : {}),+ ...(typeof file.downloadedPath === "string" && file.downloadedPath.trim() && !isDownloadUrl(file.downloadedPath) ? { downloadedPath: file.downloadedPath } : {}) }];+ }) : [];return [{ id, name, defaultSteps, attention, paths, sources,+ ...(candidate.additionalSafetensors !== undefined ? { additionalSafetensors } : {}),...(candidate.mode === "animate" || candidate.mode === "prompt" ? { mode: candidate.mode } : {}),...(candidate.loras !== undefined ? { loras: normalizeTemplateLoras(candidate.loras) } : {}) }];});@@ -260,7 +290,7 @@ const normalizeTemplateSettings = (value: unknown): GeneratorTemplateSettings |templates,defaultTemplateId: templates.find((template) => template.id === requestedDefault && !templateNeedsDownload(template))?.id?? templates.find((template) => !templateNeedsDownload(template))?.id ?? "",- catalogVersion: typeof record.catalogVersion === "number" && [1, 2, 3, 4, 5, 6, 7].includes(record.catalogVersion) ? record.catalogVersion : 0,+ catalogVersion: typeof record.catalogVersion === "number" && [1, 2, 3, 4, 5, 6, 7, 8].includes(record.catalogVersion) ? record.catalogVersion : 0,};};@@ -338,6 +368,14 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 7 })!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}+ if ((normalized.catalogVersion ?? 0) < 8) {+ const animate = normalized.templates.find(({ id }) => id === "viggle-animate");+ if (animate && !animate.additionalSafetensors?.some((file) => file.role === "promptEmbedding")) {+ animate.additionalSafetensors = [...(animate.additionalSafetensors ?? []), ...viggleAnimateTemplate().additionalSafetensors!];+ }+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 8 })!;+ localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));+ }return normalized;}}@@ -387,19 +425,28 @@ export function saveEngineSettings(settings: EngineSettings): void {/** The `slopfab` provider setting these paths describe, with blanks dropped so* an unset field falls through to whatever the project (or the Rust default)* already had rather than overwriting it with "". */-export function engineProviderSetting(settings: EngineSettings, base?: ProviderSetting, attention = defaultGeneratorTemplate().attention, selection = defaultGeneratorTemplate().loras, mode = defaultGeneratorTemplate().mode): ProviderSetting {+export function engineProviderSetting(settings: EngineSettings, base?: ProviderSetting, attention = defaultGeneratorTemplate().attention, selection = defaultGeneratorTemplate().loras, mode = defaultGeneratorTemplate().mode, additionalSafetensors = defaultGeneratorTemplate().additionalSafetensors): ProviderSetting {const options: ProviderSetting["options"] = { ...(base?.options ?? {}), attention, inferenceBackend: loadInferenceBackend() };// Always replace project-carried adapter paths with this machine's selection.delete options.loras;delete options.schedule;delete options.stepOverride;delete options.generationMode;+ delete options.promptEmbedding;if (mode === "animate") options.generationMode = "animate";+ if (mode === "animate") {+ const path = additionalSafetensors?.find((file) => file.role === "promptEmbedding")?.downloadedPath;+ if (path && !isDownloadUrl(path)) options.promptEmbedding = path;+ }const loras = resolveTemplateLoras(selection);if (loras.length) options.loras = JSON.stringify(loras.map(({ path, strength }) => ({ path, strength })));const stepOverride = highestLoraStepOverride(loras);if (stepOverride !== undefined) options.stepOverride = stepOverride;for (const field of ENGINE_PATH_FIELDS) {+ if (mode === "animate" && (field.id === "textEncoder" || field.id === "tokenizer")) {+ delete options[field.id];+ continue;+ }const value = settings[field.id].trim();if (value && !isDownloadUrl(value)) options[field.id] = value;else if (isDownloadUrl(value)) delete options[field.id];diff --git a/src/lib/weightDownloads.test.ts b/src/lib/weightDownloads.test.tsindex a6fef08..f1bf76c 100644--- a/src/lib/weightDownloads.test.ts+++ b/src/lib/weightDownloads.test.ts@@ -4,7 +4,7 @@ import { cancelWeightDownload, downloadLora, removeLora, refreshDownloadedLoras,import { loadLoras, saveLoras, TAOMATE_LORA, TURBO_LORA, VIGGLE_ANIMATE_LORA } from "./loras";import { beforeEach, expect, it, vi } from "vitest";import { chooseWeightSource, downloadTemplateWeights, getWeightDownloadState, refreshDownloadedWeights, removeTemplateWeights, updateWeightPath, weightDownloadProgress, type DownloadState } from "./weightDownloads";-import { createGeneratorTemplate, defaultGeneratorTemplate, isDownloadUrl, loadGeneratorTemplateSettings, minimaxOriginalTemplate, minimaxSingularityTemplate, saveGeneratorTemplateSettings, templateNeedsDownload, type WeightSource } from "./settings";+import { ANIMATE_CONDITIONING_URL, engineProviderSetting, createGeneratorTemplate, defaultGeneratorTemplate, isDownloadUrl, loadGeneratorTemplateSettings, minimaxOriginalTemplate, minimaxSingularityTemplate, saveGeneratorTemplateSettings, templateNeedsDownload, type WeightSource } from "./settings";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));@@ -17,13 +17,75 @@ it("downloads Animate with its transformer and four-step distillation adapter",await downloadTemplateWeights("viggle-animate");const template = loadGeneratorTemplateSettings().templates.find(({ id }) => id === "viggle-animate")!;expect(templateNeedsDownload(template)).toBe(false);+ expect(vi.mocked(invoke).mock.calls.filter(([command]) => command === "download_weight")+ .some(([, args]) => String((args as { url?: string }).url).includes("qwen"))).toBe(false);expect(template.paths.transformer).toBe("C:/Slopus/weights/Viggle-Animate-pruned_rank8_int8_convrot.safetensors");+ expect(invoke).toHaveBeenCalledWith("download_weight", expect.objectContaining({ url: ANIMATE_CONDITIONING_URL }));+ expect(template.additionalSafetensors![0].downloadedPath).toBe("C:/Slopus/weights/fixed_embed_fwd_anyframe.safetensors");+ expect(engineProviderSetting(template.paths, undefined, template.attention, template.loras, template.mode, template.additionalSafetensors).options.promptEmbedding)+ .toBe("C:/Slopus/weights/fixed_embed_fwd_anyframe.safetensors");+ expect(getWeightDownloadState()).toMatchObject({ completed: 5, files: 5, active: false, error: null });expect(invoke).toHaveBeenCalledWith("download_weight", expect.objectContaining({ url: VIGGLE_ANIMATE_LORA.url }));expect(loadLoras().find(({ id }) => id === VIGGLE_ANIMATE_LORA.id)).toMatchObject({path: "C:/Slopus/weights/viggle_animate_distillation_bf16.safetensors", stepOverride: 4,});});+it("discovers moved additional safetensors and makes missing files downloadable again", async () => {+ await downloadTemplateWeights("viggle-animate");+ const animate = () => loadGeneratorTemplateSettings().templates.find(({ id }) => id === "viggle-animate")!;+ const oldPath = animate().additionalSafetensors![0].downloadedPath!;+ files.delete(oldPath);+ const normal = vi.mocked(invoke).getMockImplementation()!;+ const moved = "D:/weights/conditioning.safetensors";+ files.add(moved);+ vi.mocked(invoke).mockImplementation(async (command, args) => command === "find_downloaded_weights"+ ? { [ANIMATE_CONDITIONING_URL]: moved } : normal(command, args));+ await refreshDownloadedWeights();+ expect(animate().additionalSafetensors![0].downloadedPath).toBe(moved);+ expect(templateNeedsDownload(animate())).toBe(false);+ vi.mocked(invoke).mockImplementation(normal);+ files.delete(moved);+ await refreshDownloadedWeights();+ expect(animate().additionalSafetensors![0].downloadedPath).toBeUndefined();+ expect(templateNeedsDownload(animate())).toBe(true);+ await downloadTemplateWeights("viggle-animate");+ expect(getWeightDownloadState()).toMatchObject({ files: 1, completed: 1, error: null });+ await removeTemplateWeights("viggle-animate");+ expect(invoke).toHaveBeenCalledWith("remove_downloaded_weights", { paths: expect.arrayContaining([oldPath]) });+ expect(animate().additionalSafetensors![0]).toMatchObject({ url: ANIMATE_CONDITIONING_URL, role: "promptEmbedding" });+ expect(animate().additionalSafetensors![0].downloadedPath).toBeUndefined();+});++it("preserves additional file edits while a download is in flight and retries failures", async () => {+ const template = createGeneratorTemplate("Extra files");+ template.additionalSafetensors = [{ id: "extra", name: "Extra", url: "https://example.com/extra.safetensors" }];+ saveGeneratorTemplateSettings({ templates: [template], defaultTemplateId: "", catalogVersion: 8 });+ const normal = vi.mocked(invoke).getMockImplementation()!;+ vi.mocked(invoke).mockImplementation(async (command, args) => {+ if (command === "download_weight") throw new Error("Network lost");+ return normal(command, args);+ });+ await downloadTemplateWeights(template.id);+ expect(getWeightDownloadState()).toMatchObject({ active: false, completed: 0, error: "Network lost" });+ expect(templateNeedsDownload(loadGeneratorTemplateSettings().templates[0])).toBe(true);+ vi.mocked(invoke).mockImplementation(async (command, args) => {+ if (command === "download_weight") {+ const current = loadGeneratorTemplateSettings();+ current.templates[0].additionalSafetensors![0].url = "https://example.com/replacement.safetensors";+ saveGeneratorTemplateSettings(current);+ }+ return normal(command, args);+ });+ await retryWeightDownload();+ const extra = loadGeneratorTemplateSettings().templates[0].additionalSafetensors![0];+ expect(extra.url).toBe("https://example.com/replacement.safetensors");+ expect(extra.downloadedPath).toBeUndefined();+ vi.mocked(invoke).mockImplementation(normal);+ await retryWeightDownload();+ expect(getWeightDownloadState()).toMatchObject({ active: false, completed: 1, error: null });+});+it.each([TAOMATE_LORA, TURBO_LORA, VIGGLE_ANIMATE_LORA])("downloads $name through the weight transfer and restores missing downloads", async (lora) => {const savedLora = () => loadLoras().find(({ id }) => id === lora.id)!;await downloadLora(lora.id);diff --git a/src/lib/weightDownloads.ts b/src/lib/weightDownloads.tsindex c7a4cab..47beaf5 100644--- a/src/lib/weightDownloads.ts+++ b/src/lib/weightDownloads.ts@@ -2,7 +2,7 @@ import { invoke } from "@tauri-apps/api/core";import { listen } from "@tauri-apps/api/event";import { isTauri } from "./persistence";import { downloadableTemplateLoras, loadLoras, saveLoras, type Lora } from "./loras";-import { ENGINE_PATH_FIELDS, isDownloadUrl, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, templateNeedsDownload,+import { ENGINE_PATH_FIELDS, generatorPathFields, isDownloadUrl, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, templateNeedsDownload,type EnginePathId, type GeneratorTemplate, type WeightSource } from "./settings";export interface WeightGpu { name: string; memoryBytes: number }@@ -10,6 +10,7 @@ export interface DownloadState {templateId: string;loraId?: string;currentLoraId?: string;+ currentAdditionalId?: string;name?: string;field: EnginePathId | null;downloaded: number;@@ -31,7 +32,7 @@ const publish = (next: DownloadState | null) => { state = next; subscribers.forEexport function weightDownloadProgress(download: DownloadState): number {if (!download.files) return 0;- const current = (download.field || download.loraId || download.currentLoraId) && download.total && download.total > 0+ const current = (download.field || download.loraId || download.currentLoraId || download.currentAdditionalId) && download.total && download.total > 0? Math.min(1, Math.max(0, download.downloaded / download.total)) : 0;return Math.min(download.active ? 99 : 100, 100 * (download.completed + current) / download.files);}@@ -66,8 +67,14 @@ export function refreshDownloadedWeights(): Promise<void> {refreshPending = (async () => {await refreshDownloadedLoras();const before = loadGeneratorTemplateSettings();- const paths = [...new Set(before.templates.flatMap((template) => Object.values(template.sources ?? {}).flatMap((sources) => sources.flatMap((source) => source.downloadedPath ? [source.downloadedPath] : []))))];- const urls = [...new Set(before.templates.flatMap((template) => Object.values(template.sources ?? {}).flatMap((sources) => sources.map((source) => source.url))))];+ const paths = [...new Set(before.templates.flatMap((template) => [+ ...generatorPathFields(template).flatMap(({ id }) => (template.sources?.[id] ?? []).flatMap((source) => source.downloadedPath ? [source.downloadedPath] : [])),+ ...(template.additionalSafetensors ?? []).flatMap((file) => file.downloadedPath ? [file.downloadedPath] : []),+ ]))];+ const urls = [...new Set(before.templates.flatMap((template) => [+ ...Object.values(template.sources ?? {}).flatMap((sources) => sources.map((source) => source.url)),+ ...(template.additionalSafetensors ?? []).map((file) => file.url),+ ]))];if (!paths.length && !urls.length) return;const [exists, found, devices] = await Promise.all([paths.length ? invoke<Record<string, boolean>>("check_weight_files", { paths }) : Promise.resolve({} as Record<string, boolean>),@@ -78,7 +85,7 @@ export function refreshDownloadedWeights(): Promise<void> {let changed = false;const templates = current.templates.map((template) => {const restored = { ...template, paths: { ...template.paths }, sources: { ...template.sources } };- for (const { id } of ENGINE_PATH_FIELDS) {+ for (const { id } of generatorPathFields(template)) {const sources = template.sources?.[id];if (!sources) continue;restored.sources[id] = sources.map((source) => {@@ -96,6 +103,13 @@ export function refreshDownloadedWeights(): Promise<void> {if (selected?.downloadedPath) { restored.paths[id] = selected.downloadedPath; changed = true; }}}+ restored.additionalSafetensors = template.additionalSafetensors?.map((file) => {+ if (!before.templates.find(({ id }) => id === template.id)?.additionalSafetensors?.some((old) => old.id === file.id && old.url === file.url && old.downloadedPath === file.downloadedPath)) return file;+ const downloadedPath = file.downloadedPath && exists?.[file.downloadedPath] !== false ? file.downloadedPath : found?.[file.url];+ if (downloadedPath === file.downloadedPath) return file;+ changed = true;+ return { ...file, downloadedPath };+ });return restored;});if (changed) {@@ -116,7 +130,7 @@ export async function downloadTemplateWeights(templateId: string): Promise<void>const template = loadGeneratorTemplateSettings().templates.find((template) => template.id === templateId);if (!template) throw new Error("This generator was removed.");const devices = await invoke<WeightGpu[]>("weight_download_hardware");- const downloads = ENGINE_PATH_FIELDS.flatMap(({ id }) => {+ const downloads = generatorPathFields(template).flatMap(({ id }) => {if (template.paths[id].trim() && !isDownloadUrl(template.paths[id])) return [];const sources = template.sources?.[id] ?? [];if (!sources.length) return [];@@ -125,7 +139,8 @@ export async function downloadTemplateWeights(templateId: string): Promise<void>return [{ field: id, source, originalPath: template.paths[id] }];});const loraDownloads = downloadableTemplateLoras(template.loras);- publish({ ...state!, files: downloads.length + loraDownloads.length });+ const additionalDownloads = (template.additionalSafetensors ?? []).filter((file) => !file.downloadedPath);+ publish({ ...state!, files: downloads.length + loraDownloads.length + additionalDownloads.length });unlisten = await listen<{ requestId: string; downloaded: number; total: number | null }>("weight-download-progress", ({ payload }) => {if (payload.requestId === requestId && state?.active) publish({ ...state, downloaded: payload.downloaded, total: payload.total });});@@ -149,6 +164,19 @@ export async function downloadTemplateWeights(templateId: string): Promise<void>saveGeneratorTemplateSettings({ ...current, templates });publish({ ...state!, completed: state!.completed + 1, field: null, downloaded: 0, total: null });}+ for (const file of additionalDownloads) {+ if (cancelled) throw new Error("Download cancelled.");+ requestId = crypto.randomUUID();+ publish({ ...state!, currentAdditionalId: file.id, downloaded: 0, total: null });+ const path = await invoke<string>("download_weight", { requestId, url: file.url });+ if (!path || isDownloadUrl(path)) throw new Error("The download did not return a local file.");+ const current = loadGeneratorTemplateSettings();+ saveGeneratorTemplateSettings({ ...current, templates: current.templates.map((template) => template.id !== templateId ? template : {+ ...template, additionalSafetensors: template.additionalSafetensors?.map((entry) =>+ entry.id === file.id && entry.url === file.url && entry.downloadedPath === file.downloadedPath ? { ...entry, downloadedPath: path } : entry),+ }) });+ publish({ ...state!, completed: state!.completed + 1, currentAdditionalId: undefined, downloaded: 0, total: null });+ }for (const lora of loraDownloads) {if (cancelled) throw new Error("Download cancelled.");publish({ ...state!, currentLoraId: lora.id, downloaded: 0, total: null });@@ -246,14 +274,18 @@ export async function removeTemplateWeights(templateId: string): Promise<void> {if (!isTauri() || state?.active) return;const template = loadGeneratorTemplateSettings().templates.find((template) => template.id === templateId);if (!template) return;- const paths = [...new Set(Object.values(template.sources ?? {}).flatMap((sources) => sources.flatMap((source) => source.downloadedPath ? [source.downloadedPath] : [])))];+ const paths = [...new Set([+ ...generatorPathFields(template).flatMap(({ id }) => (template.sources?.[id] ?? []).flatMap((source) => source.downloadedPath ? [source.downloadedPath] : [])),+ ...(template.additionalSafetensors ?? []).flatMap((file) => file.downloadedPath ? [file.downloadedPath] : []),+ ])];try {await invoke("remove_downloaded_weights", { paths });const current = loadGeneratorTemplateSettings();const templates = current.templates.map((template) => {if (template.id !== templateId) return template;const restored = { ...template, paths: { ...template.paths }, sources: { ...template.sources } };- for (const { id } of ENGINE_PATH_FIELDS) {+ restored.additionalSafetensors = template.additionalSafetensors?.map((file) => paths.includes(file.downloadedPath ?? "") ? { ...file, downloadedPath: undefined } : file);+ for (const { id } of generatorPathFields(template)) {const sources = template.sources?.[id];if (!sources?.length) continue;restored.paths[id] = (sources.find((source) => source.downloadedPath === template.paths[id]) ?? sources[0]).url;