AI media harness for planning, generating, and editing locally
TypeScript
Merge master into add-worker-support
Bitti4c626cb64e88
diff --cc RELEASE_NOTES.mdindex ecb9945,10b726a..578794b--- a/RELEASE_NOTES.md+++ b/RELEASE_NOTES.md@@@ -4,16 -4,13 +4,14 @@@ This alpha update adds DMAD LoRA suppor## What's new- - Image projects: compose a still image as a hierarchy of objects, text and groups on a canvas, generate it with MiniMax H3, then refine it with sequential edits on an opened or generated image. Generated images and drafts stay in an image bar, and each keeps the settings it was made with.- - Image export as JPG or PNG, at the original size or a size from the project ladder, with adjustable JPG quality. Pick any image to export from the image bar under the preview.- - New scene types: Pose, Character replace, Extend and Bridge, alongside First & last frame and Animate.- - A new interface in the style of Windows 11: a frameless Mica window, a title bar with the project's Save, Undo and Redo, and Fluent controls and icons.- - Project-wide Undo and Redo (Ctrl+Z, Ctrl+Y) for edits made in any view, by the agent, or in project settings.- - Rebuilt Generator, References, Timeline, Export and Settings screens. The Generator is a board of scenes and shot tiles; References has Icons and Details views with multi-select; the Timeline gains zoom, keyboard shortcuts and context menus.- - The agent is a docked, resizable pane that keeps running while hidden.- - LAN workers: unpack the new Slopus worker package on another computer, run `slopus-worker`, and pick it in the new **Settings → Workers** tab to generate there. Slopus finds workers on the local network automatically, or by address. Workers download generator weights from their download links themselves, local-only files are sent from this computer, and finished videos, images and latents are saved in your project as usual.- - The Work queue and Agent buttons show when work is under way, and exports keep running in the background.- - Reference images can be paged through and removed, and effects can be bypassed without removing them.+ - Interrupted weight and LoRA downloads retain their progress and can resume on retry, including after reopening the app.+ - Reference smart chips in image prompts and video shot descriptions, with reference artwork in the picker.+ - Queue still-image generation for individual images. Regenerated and edited images are grouped under their original in the image bar.+ - Generated still images retain their used seed, shown as a read-only field with a copy button in Image generation.+ - Higher image and video generation resolutions, plus standard image and video export sizes.+ - Downloadable DMAD 4-Step LoRA for MiniMax H3, with its re-noising sampling recipe applied automatically. Its fixed four-step schedule overrides step counts and turns off MotionCache.+ - Bundled release notes appear once per app version.++- LAN workers: run the Slopus worker package on another Windows or Linux computer and pick it in the new **Settings → Workers** tab to generate there. Slopus finds workers on the local network automatically, or by address. Workers download generator weights from their download links themselves and use CUDA when available, with a Vulkan fallback; local-only files are sent from this computer, and finished videos, images and latents are saved in your project as usual.## Fixes and improvementsdiff --cc release.cmdindex 2471127,e3df820..3adae0d--- a/release.cmd+++ b/release.cmd@@@ -78,13 -77,15 +78,17 @@@ set "OUTPUT_ZIP=%ARTIFACTS_DIR%\%OUTPUTrem The portable layout is staged straight into the folder the zip is namedrem after, and kept there afterwards so the build is runnable without unpacking.set "OUTPUT_DIR=%ARTIFACTS_DIR%\%OUTPUT_STEM%-portable"+set "WORKER_ZIP=%ARTIFACTS_DIR%\%OUTPUT_STEM%-worker.zip"+set "WORKER_DIR=%ARTIFACTS_DIR%\%OUTPUT_STEM%-worker"echo.- echo [1/5] Installing locked frontend dependencies...+ echo [1/6] Installing locked frontend dependencies...call npm ci || goto :fail+ echo.+ echo [2/6] Running pre-release tests...+ call npm run test:release || goto :fail+rem `npm run tauri build` - NOT `cargo build --release`. Plain cargo compiles therem binary but never runs the Tauri CLI, so the app keeps its dev configuration:rem it points the webview at the dev server on localhost:1420 instead of thediff --cc src-tauri/Cargo.lockindex ee15376,18196e5..0f79019--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@@ -3440,32 -3383,6 +3440,33 @@@ dependencies ="windows-sys 0.59.0",]+[[package]]+name = "slopus-core"- version = "0.2.0"++version = "0.2.1"+dependencies = [+ "getrandom 0.3.4",+ "image",+ "jpeg-encoder",+ "libloading 0.8.9",+ "mdns-sd",+ "reqwest 0.12.28",+ "serde",+ "serde_json",++ "sha2",+ "tempfile",+ "tiny_http",+ "windows",+ "windows-sys 0.59.0",+]++[[package]]+name = "slopus-worker"- version = "0.2.0"++version = "0.2.1"+dependencies = [+ "slopus-core",+ "tauri-winres",+]+[[package]]name = "smallvec"version = "1.15.2"diff --cc src-tauri/Cargo.tomlindex be3883f,6afa9e4..1be59e2--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@@ -1,14 -1,6 +1,14 @@@+# One version for the app and the worker. scripts/updater-manifest.mjs checks+# it against package.json and tauri.conf.json.+[workspace.package]- version = "0.2.0"++version = "0.2.1"++[workspace]+members = ["core", "worker"]+[package]name = "slopus"-version = "0.2.1"+version.workspace = truedescription = "An AI media harness for planning, generating, and editing media locally."authors = ["Slopus"]edition = "2021"diff --cc src-tauri/core/Cargo.tomlindex 8c0c67e,0000000..7d42628mode 100644,000000..100644--- a/src-tauri/core/Cargo.toml+++ b/src-tauri/core/Cargo.toml@@@ -1,30 -1,0 +1,32 @@@+[package]+name = "slopus-core"+version.workspace = true+description = "Slopus generation runtime shared by the desktop app and the LAN worker. No UI framework."+authors = ["Slopus"]+edition = "2021"+rust-version = "1.87"++[lib]+name = "slopus_core"++[dependencies]+serde = { version = "1", features = ["derive"] }+serde_json = "1"+libloading = "0.8"+getrandom = "0.3"+reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] }++# Verifies the downloaded legacy LoRA timestep grid.++sha2 = "0.10"+jpeg-encoder = "0.6"+# Keep image decoding compatible with the package's Rust 1.87 minimum.+image = { version = "=0.25.8", default-features = false, features = ["jpeg", "png"] }+tiny_http = "0.12"+mdns-sd = "0.21"++[target.'cfg(windows)'.dependencies]+# DXGI reads GPU memory for weight selection without a CUDA toolkit.+windows = { version = "0.61", features = ["Win32_Graphics_Dxgi", "Win32_Foundation"] }+windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }++[dev-dependencies]+tempfile = "3"diff --cc src-tauri/core/src/slopfab/tests.rsindex a6f11ff,abf4cc1..626fb8e--- a/src-tauri/core/src/slopfab/tests.rs+++ b/src-tauri/core/src/slopfab/tests.rs@@@ -2,9 -2,49 +2,49 @@@ use super::config::*, events::stage_name, ffi::RequestHandle, h3::*, planning::*, platform::*,references::ReferenceVideos, *,};-use crate::project::{ProviderOption, ProviderSetting};+use crate::settings::{ProviderOption, ProviderSetting};use std::collections::BTreeMap;+ #[test]+ fn dmad_recipe_reaches_preview_and_execution_on_both_backends() {+ let root = tempfile::tempdir().unwrap();+ let adapter = root.path().join("renamed-adapter.safetensors");+ metadata_checkpoint(&adapter, serde_json::json!({}));+ let settings = BTreeMap::from([("slopfab".into(), ProviderSetting {+ enabled: true, model: None,+ options: BTreeMap::from([+ ("samplingPreset".into(), ProviderOption::String("dmad-4step".into())),+ ("motionCache".into(), ProviderOption::Boolean(true)),+ ("stepOverride".into(), ProviderOption::Number(12.0)),+ ("loras".into(), ProviderOption::String(serde_json::json!([+ { "path": adapter, "strength": 1.0 }+ ]).to_string())),+ ]),+ })]);+ let configuration = Configuration::from_settings(&settings);+ assert_eq!(configuration.generation_steps(30).unwrap(), 4);+ let api = ffi::Api::load(&configuration.dll_path).unwrap();+ let request = GenerationRequest {+ prompt: "A polar bear plays the violin in the snow.".into(),+ frames: 124, steps: 30, seed: 42, canvas_width: 1344, canvas_height: 768,+ ..Default::default()+ };+ for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {+ for purpose in [RequestPurpose::Plan, RequestPurpose::Generate] {+ let handle = RequestHandle::new(&api).unwrap();+ configure_request(&api, &handle, &request, &configuration, platform, purpose, &ReferenceVideos::default()).unwrap();+ let plan = api.resolve(&handle).unwrap();+ assert_eq!(plan.num_model_evaluations, 4);+ let description = api.describe(&handle).unwrap();+ assert!(description.contains("renoise"), "{description}");+ assert!(description.contains("shift 12"), "{description}");+ assert!(description.contains("shift 2"), "{description}");+ }+ }+ let ordinary = Configuration::from_settings(&BTreeMap::new());+ assert_ne!(configuration.timing_profile("1.16.0", ComputePlatform::Vulkan), ordinary.timing_profile("1.16.0", ComputePlatform::Vulkan));+ }+#[test]fn image_edit_recipe_disables_motion_cache_and_keeps_source_geometry() {let references = ReferenceVideos::default();diff --cc src-tauri/core/src/weights.rsindex ea58bca,0000000..24b8438mode 100644,000000..100644--- a/src-tauri/core/src/weights.rs+++ b/src-tauri/core/src/weights.rs@@@ -1,374 -1,0 +1,331 @@@+//! Weight downloads, shared by the desktop app and the LAN worker: one+//! downloader, one folder layout and one completion record format.- use reqwest::{blocking::Client, Url};++use reqwest::Url;+use serde::{Deserialize, Serialize};+use std::{+ collections::HashMap,+ fs::{self, OpenOptions},- io::{Read, Write},+ path::{Path, PathBuf},+ sync::atomic::{AtomicBool, Ordering},- time::{Duration, Instant},+};++#[derive(Serialize, Deserialize)]+pub struct CompletedFile { pub url: String, pub bytes: u64 }++pub mod lora;++mod download;++pub use download::{has_partial_download, transfer};++pub fn download_url(value: &str) -> Result<Url, String> {+ let mut url = Url::parse(value.trim()).map_err(|_| "Enter an HTTP or HTTPS download URL.".to_string())?;+ if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() || !url.username().is_empty() || url.password().is_some() {+ return Err("Enter an HTTP or HTTPS download URL without embedded credentials.".into());+ }+ if url.host_str() == Some("huggingface.co") {+ let path = url.path().replacen("/blob/", "/resolve/", 1);+ url.set_path(&path);+ }+ url.set_fragment(None);+ Ok(url)+}++pub fn destination_name(url: &Url) -> String {+ // A stable URL prefix prevents different repositories' model.safetensors+ // files from overwriting each other. Completion metadata also verifies URL identity.+ let hash = url.as_str().bytes().fold(0xcbf29ce484222325u64, |hash, byte| (hash ^ byte as u64).wrapping_mul(0x100000001b3));+ let filename: String = url.path_segments().and_then(|mut parts| parts.next_back()).unwrap_or("weights.bin")+ .chars().take(150).map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') { c } else { '_' }).collect();+ format!("{hash:016x}-{}", if filename.is_empty() { "weights.bin" } else { &filename })+}++pub fn writable_weights(directory: &Path) -> Result<PathBuf, String> {+ fs::create_dir_all(directory).map_err(|error| error.to_string())?;+ let mut random = [0u8; 16];+ getrandom::fill(&mut random).map_err(|error| error.to_string())?;+ let probe = directory.join(format!(".write-check-{:x}", u128::from_le_bytes(random)));+ let file = OpenOptions::new().write(true).create_new(true).open(&probe).map_err(|error| error.to_string())?;+ drop(file);+ fs::remove_file(probe).map_err(|error| error.to_string())?;+ Ok(directory.to_path_buf())+}++pub fn weight_roots(custom: &[PathBuf], primary: PathBuf, fallback: PathBuf) -> Vec<PathBuf> {+ let mut roots = Vec::new();+ for root in custom.iter().cloned().chain([primary, fallback]) {+ if !roots.contains(&root) { roots.push(root); }+ }+ roots+}++pub fn weights_directory(roots: &[PathBuf]) -> Result<PathBuf, String> {+ let mut errors = Vec::new();+ for root in roots {+ match writable_weights(root) {+ Ok(directory) => return Ok(directory),+ Err(error) => errors.push(format!("{}: {error}", root.display())),+ }+ }+ Err(format!("Could not create a writable weights folder: {}", errors.join("; ")))+}++pub fn cached_file(path: &Path, url: &Url) -> bool {+ let metadata = fs::read(path.with_extension("complete.json")).ok()+ .and_then(|bytes| serde_json::from_slice::<CompletedFile>(&bytes).ok());+ metadata.is_some_and(|info| info.url == url.as_str() && info.bytes > 0+ && fs::metadata(path).is_ok_and(|file| file.is_file() && file.len() == info.bytes))+}++pub fn transfer_from_roots(url: &Url, roots: &[PathBuf], cancelled: &AtomicBool, progress: impl FnMut(u64, Option<u64>)) -> Result<String, String> {+ if cancelled.load(Ordering::Relaxed) { return Err("Download cancelled.".into()); }+ // Search every location before choosing a destination, including read-only caches.+ if let Some(path) = find_cached_weight(url, roots) { return Ok(path); }++ // A previous session may have started in a fallback or an older custom folder.++ for root in roots {++ if has_partial_download(url, root) && writable_weights(root).is_ok() {++ return transfer(url, root, cancelled, progress);++ }++ }+ transfer(url, &weights_directory(roots)?, cancelled, progress)+}++pub fn find_cached_weight(url: &Url, roots: &[PathBuf]) -> Option<String> {+ roots.iter().map(|root| root.join(destination_name(url)))+ .find(|path| cached_file(path, url)).map(|path| path.to_string_lossy().into_owned())+}++pub fn find_downloaded(urls: Vec<String>, roots: &[PathBuf]) -> HashMap<String, String> {+ urls.into_iter().filter_map(|original| {+ let url = download_url(&original).ok()?;+ find_cached_weight(&url, roots).map(|path| (original, path))+ }).collect()+}+- /// Weight folders for a process without the desktop settings file: the LAN- /// worker passes its own `--weights` folders and data directory.- pub fn worker_weight_roots(custom: &[PathBuf], data_directory: &Path) -> Result<Vec<PathBuf>, String> {- let executable = std::env::current_exe().map_err(|error| error.to_string())?;- let primary = executable.parent().ok_or("Could not locate the worker executable.")?.join("weights");- Ok(weight_roots(custom, primary, data_directory.join("weights")))- }-- /// A completed download of `url` in any root, without touching the network.- pub fn cached_weight(url: &str, roots: &[PathBuf]) -> Option<PathBuf> {- find_cached_weight(&download_url(url).ok()?, roots).map(PathBuf::from)- }-- /// Finds or downloads one weight URL, as the desktop download command does.- pub fn fetch_weight(url: &str, roots: &[PathBuf], cancelled: &AtomicBool, progress: impl FnMut(u64, Option<u64>)) -> Result<PathBuf, String> {- transfer_from_roots(&download_url(url)?, roots, cancelled, progress).map(PathBuf::from)- }-- /// The URL a complete Slopus download came from. A LAN worker is sent this- /// instead of the file, so it can fetch the weights itself.- pub fn recorded_download_url(path: &Path) -> Option<String> {- let record: CompletedFile = serde_json::from_slice(&fs::read(path.with_extension("complete.json")).ok()?).ok()?;- let url = download_url(&record.url).ok()?;- (path.file_name()?.to_str()? == destination_name(&url) && cached_file(path, &url)).then_some(record.url)- }-- pub fn transfer(url: &Url, directory: &Path, cancelled: &AtomicBool, mut progress: impl FnMut(u64, Option<u64>)) -> Result<String, String> {- let destination = directory.join(destination_name(url));- if cached_file(&destination, url) { return Ok(destination.to_string_lossy().into_owned()); }- let mut random = [0u8; 16];- getrandom::fill(&mut random).map_err(|error| error.to_string())?;- let temporary = directory.join(format!(".download-{:x}.part", u128::from_le_bytes(random)));- let result = (|| {- let client = Client::builder().connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(24 * 60 * 60)).build().map_err(|error| error.to_string())?;- let mut response = client.get(url.clone()).header("Accept-Encoding", "identity").send()- .and_then(|response| response.error_for_status()).map_err(|error| format!("Download failed: {error}"))?;- if response.status() != reqwest::StatusCode::OK { return Err("The server did not return a complete file.".into()); }- if response.headers().get(reqwest::header::CONTENT_TYPE).and_then(|v| v.to_str().ok())- .is_some_and(|value| value.starts_with("text/html")) {- return Err("The URL returned a web page instead of a weight file. Use a direct download link.".into());- }- let total = response.content_length();- let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary).map_err(|error| error.to_string())?;- let mut downloaded = 0u64;- let mut buffer = vec![0u8; 1024 * 1024];- let mut last_progress = Instant::now();- progress(0, total);- loop {- if cancelled.load(Ordering::Relaxed) { return Err("Download cancelled.".into()); }- let count = response.read(&mut buffer).map_err(|error| format!("Download interrupted: {error}"))?;- if count == 0 { break; }- file.write_all(&buffer[..count]).map_err(|error| format!("Could not write weights: {error}"))?;- downloaded += count as u64;- if last_progress.elapsed() >= Duration::from_millis(200) {- progress(downloaded, total);- last_progress = Instant::now();- }- }- if downloaded == 0 || total.is_some_and(|total| downloaded != total) {- return Err("The download is incomplete. Try downloading again.".into());- }- if cancelled.load(Ordering::Relaxed) { return Err("Download cancelled.".into()); }- file.sync_all().map_err(|error| error.to_string())?;- drop(file);- // Only a successful, complete transfer receives the final filename.- if destination.exists() {- if cached_file(&destination, url) { return Ok(destination.to_string_lossy().into_owned()); }- fs::remove_file(&destination).map_err(|error| error.to_string())?;- }- fs::rename(&temporary, &destination).map_err(|error| error.to_string())?;- let record = CompletedFile { url: url.to_string(), bytes: downloaded };- fs::write(destination.with_extension("complete.json"), serde_json::to_vec(&record).map_err(|error| error.to_string())?)- .map_err(|error| error.to_string())?;- progress(downloaded, Some(downloaded));- Ok(destination.to_string_lossy().into_owned())- })();- let _ = fs::remove_file(&temporary);- result- }-+pub fn hardware_devices() -> Vec<crate::slopfab::GpuDevice> {+ #[cfg(windows)]+ {+ use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIFactory1, DXGI_ADAPTER_FLAG_SOFTWARE};+ // DXGI reports dedicated VRAM for NVIDIA, AMD and Intel independently+ // of CUDA installation. COM interface wrappers release their references.+ let mut devices = Vec::new();+ unsafe {+ if let Ok(factory) = CreateDXGIFactory1::<IDXGIFactory1>() {+ let mut index = 0;+ while let Ok(adapter) = factory.EnumAdapters1(index) {+ index += 1;+ if let Ok(description) = adapter.GetDesc1() {+ if description.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { continue; }+ let end = description.Description.iter().position(|value| *value == 0).unwrap_or(description.Description.len());+ devices.push(crate::slopfab::GpuDevice {+ name: String::from_utf16_lossy(&description.Description[..end]),+ memory_bytes: description.DedicatedVideoMemory as u64,+ });+ }+ }+ }+ }+ if !devices.is_empty() { return devices; }+ }+ crate::slopfab::gpu_devices()+}++pub fn validate_removal(path: &Path, roots: &[PathBuf]) -> Result<(), String> {+ if !path.exists() { return Ok(()); }+ let canonical = path.canonicalize().map_err(|error| error.to_string())?;+ let allowed = roots.iter().filter_map(|root| root.canonicalize().ok())+ .any(|root| canonical.parent() == Some(root.as_path()));+ if !allowed { return Err("Only weights downloaded into Slopus's weights folders can be removed.".into()); }+ let record: CompletedFile = serde_json::from_slice(&fs::read(path.with_extension("complete.json"))+ .map_err(|_| "The downloaded weight's completion record is missing.".to_string())?)+ .map_err(|_| "The downloaded weight's completion record is invalid.".to_string())?;+ let url = download_url(&record.url)?;+ if path.file_name().and_then(|name| name.to_str()) != Some(destination_name(&url).as_str()) {+ return Err("The weight file does not match its download record.".into());+ }+ Ok(())+}+++/// Weight folders for a process without the desktop settings file: the LAN++++/// worker passes its own `--weights` folders and data directory.++pub fn worker_weight_roots(custom: &[PathBuf], data_directory: &Path) -> Result<Vec<PathBuf>, String> {++ let executable = std::env::current_exe().map_err(|error| error.to_string())?;++ let primary = executable.parent().ok_or("Could not locate the worker executable.")?.join("weights");++ Ok(weight_roots(custom, primary, data_directory.join("weights")))++}++++/// A completed download of `url` in any root, without touching the network.++pub fn cached_weight(url: &str, roots: &[PathBuf]) -> Option<PathBuf> {++ find_cached_weight(&download_url(url).ok()?, roots).map(PathBuf::from)++}++++/// Finds or downloads one weight URL, as the desktop download command does.++pub fn fetch_weight(url: &str, roots: &[PathBuf], cancelled: &AtomicBool, progress: impl FnMut(u64, Option<u64>)) -> Result<PathBuf, String> {++ transfer_from_roots(&download_url(url)?, roots, cancelled, progress).map(PathBuf::from)++}++++/// The URL a complete Slopus download came from. A LAN worker is sent this++++/// instead of the file, so it can fetch the weights itself.++pub fn recorded_download_url(path: &Path) -> Option<String> {++ let record: CompletedFile = serde_json::from_slice(&fs::read(path.with_extension("complete.json")).ok()?).ok()?;++ let url = download_url(&record.url).ok()?;++ (path.file_name()?.to_str()? == destination_name(&url) && cached_file(path, &url)).then_some(record.url)++}+++#[cfg(test)]+mod tests {+ use super::*;++ use std::io::{Read, Write};+ use std::net::TcpListener;++ #[test]+ fn hardware_probe_reads_device_descriptions_without_a_toolkit() {+ let devices = hardware_devices();+ for device in &devices { assert!(!device.name.trim().is_empty()); }+ println!("Detected weight-selection GPUs: {devices:?}");+ }++ fn server(response: &'static [u8]) -> Url {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let address = listener.local_addr().unwrap();+ std::thread::spawn(move || {+ let (mut connection, _) = listener.accept().unwrap();+ let mut request = [0u8; 8192];+ let _ = connection.read(&mut request);+ let _ = connection.write_all(response);+ });+ Url::parse(&format!("http://{address}/model.safetensors")).unwrap()+ }++ #[test]+ fn converts_hugging_face_pages_and_rejects_non_download_schemes() {+ assert_eq!(download_url("https://huggingface.co/org/repo/blob/main/vae/model.safetensors").unwrap().as_str(), "https://huggingface.co/org/repo/resolve/main/vae/model.safetensors");+ for url in ["file:///C:/secret", "ftp://example.com/model", "https://user:[email protected]/model"] { assert!(download_url(url).is_err()); }+ let url = download_url("https://example.com/../../model?file=../../oops").unwrap();+ assert!(!destination_name(&url).contains('/'));+ }++ #[test]+ fn falls_back_when_the_executable_directory_is_not_writable() {+ let folder = tempfile::tempdir().unwrap();+ let blocked = folder.path().join("blocked");+ fs::write(&blocked, b"file, not a directory").unwrap();+ assert_eq!(weights_directory(&[blocked.join("weights"), folder.path().join("weights")]).unwrap(), folder.path().join("weights"));+ }++ #[test]+ fn custom_folders_are_used_directly_in_order_with_default_fallbacks() {+ let folder = tempfile::tempdir().unwrap();+ let blocked = folder.path().join("blocked");+ fs::write(&blocked, b"not a directory").unwrap();+ let custom = folder.path().join("custom models");+ let primary = folder.path().join("exe/weights");+ let fallback = folder.path().join("logs/weights");+ let roots = weight_roots(&[blocked.clone(), custom.clone(), custom.clone()], primary.clone(), fallback.clone());+ assert_eq!(roots, vec![blocked, custom.clone(), primary.clone(), fallback.clone()]);+ let url = server(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\ndata");+ let downloaded = transfer_from_roots(&url, &roots, &AtomicBool::new(false), |_, _| {}).unwrap();+ assert_eq!(Path::new(&downloaded).parent(), Some(custom.as_path()));+ assert!(!custom.join("weights").exists());+ assert!(!primary.exists());+ assert!(validate_removal(Path::new(&downloaded), &roots).is_ok());+ assert!(validate_removal(Path::new(&downloaded), &[primary.clone(), fallback.clone()]).is_err());+ assert_eq!(weight_roots(&[], primary.clone(), fallback.clone()), vec![primary, fallback]);+ }++ #[test]+ fn searches_all_folders_for_completed_files_before_creating_a_download_destination() {+ let folder = tempfile::tempdir().unwrap();+ let custom = folder.path().join("custom");+ let primary = folder.path().join("exe/weights");+ let fallback = folder.path().join("logs/weights");+ fs::create_dir_all(&fallback).unwrap();+ let roots = weight_roots(&[custom.clone()], primary.clone(), fallback.clone());+ let url = server(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\ndata");+ let downloaded = transfer(&url, &fallback, &AtomicBool::new(false), |_, _| {}).unwrap();+ // The server accepts only one request; reuse must work without network access.+ assert_eq!(transfer_from_roots(&url, &roots, &AtomicBool::new(false), |_, _| {}).unwrap(), downloaded);+ assert!(!custom.exists());+ assert!(!primary.exists());+ fs::create_dir_all(&custom).unwrap();+ let moved = custom.join(destination_name(&url));+ fs::rename(&downloaded, &moved).unwrap();+ fs::rename(Path::new(&downloaded).with_extension("complete.json"), moved.with_extension("complete.json")).unwrap();+ assert_eq!(transfer_from_roots(&url, &roots, &AtomicBool::new(false), |_, _| {}).unwrap(), moved.to_string_lossy());+ assert!(transfer_from_roots(&url, &roots, &AtomicBool::new(true), |_, _| {}).is_err());+ }++ #[test]+ fn discovery_normalizes_urls_and_ignores_missing_incomplete_or_unrecorded_files() {+ let folder = tempfile::tempdir().unwrap();+ let custom = folder.path().join("custom");+ let fallback = folder.path().join("fallback");+ fs::create_dir_all(&custom).unwrap();+ fs::create_dir_all(&fallback).unwrap();+ let blob = "https://huggingface.co/org/repo/blob/main/model.safetensors";+ let url = download_url(blob).unwrap();+ let destination = fallback.join(destination_name(&url));+ fs::write(&destination, b"data").unwrap();+ let roots = [custom.clone(), fallback];+ assert!(find_downloaded(vec![blob.into()], &roots).is_empty());+ let record = CompletedFile { url: url.to_string(), bytes: 4 };+ fs::write(destination.with_extension("complete.json"), serde_json::to_vec(&record).unwrap()).unwrap();+ // A truncated copy in the preferred folder must not hide a complete fallback.+ let incomplete = custom.join(destination_name(&url));+ fs::write(&incomplete, b"bad").unwrap();+ fs::write(incomplete.with_extension("complete.json"), serde_json::to_vec(&record).unwrap()).unwrap();+ let found = find_downloaded(vec![blob.into(), url.to_string(), "https://".into()], &roots);+ assert_eq!(found.len(), 2);+ assert_eq!(found[blob], destination.to_string_lossy());+ assert_eq!(found[url.as_str()], destination.to_string_lossy());+ fs::remove_file(&destination).unwrap();+ assert!(find_downloaded(vec![blob.into()], &roots).is_empty());+ }++ #[test]+ fn publishes_only_complete_files_and_reuses_completed_downloads() {+ let folder = tempfile::tempdir().unwrap();+ let url = server(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\ndata");+ let path = transfer(&url, folder.path(), &AtomicBool::new(false), |_, _| {}).unwrap();+ assert_eq!(fs::read(&path).unwrap(), b"data");+ assert!(cached_file(Path::new(&path), &url));+ assert_eq!(transfer(&url, folder.path(), &AtomicBool::new(false), |_, _| {}).unwrap(), path);+ fs::remove_file(&path).unwrap();+ assert!(!cached_file(Path::new(&path), &url));+ }++ #[test]+ fn rejects_truncated_html_failed_and_cancelled_downloads_without_publishing_files() {+ for (response, cancelled) in [+ (&b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: close\r\n\r\ndata"[..], false),+ (&b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 4\r\nConnection: close\r\n\r\ndata"[..], false),+ (&b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"[..], false),+ (&b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\ndata"[..], true),+ ] {+ let folder = tempfile::tempdir().unwrap();+ let url = server(response);+ assert!(transfer(&url, folder.path(), &AtomicBool::new(cancelled), |_, _| {}).is_err());- assert_eq!(fs::read_dir(folder.path()).unwrap().count(), 0);++ let destination = folder.path().join(destination_name(&url));++ assert!(!destination.exists());++ assert!(!destination.with_extension("complete.json").exists());++ assert!(find_downloaded(vec![url.to_string()], &[folder.path().to_path_buf()]).is_empty());+ }+ }++ #[test]+ fn removal_is_limited_to_files_created_by_the_downloader() {+ let folder = tempfile::tempdir().unwrap();+ let weights = folder.path().join("weights");+ fs::create_dir(&weights).unwrap();+ let external = folder.path().join("personal.safetensors");+ fs::write(&external, b"data").unwrap();+ assert!(validate_removal(&external, &[weights.clone()]).is_err());+ let url = server(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\ndata");+ let downloaded = transfer(&url, &weights, &AtomicBool::new(false), |_, _| {}).unwrap();+ assert!(validate_removal(Path::new(&downloaded), &[weights.clone()]).is_ok());+ let unmanaged = weights.join("personal.safetensors");+ fs::write(&unmanaged, b"data").unwrap();+ assert!(validate_removal(&unmanaged, &[weights]).is_err());+ assert!(external.is_file());+ }+}diff --cc src-tauri/core/src/weights/download.rsindex 0000000,9af6644..3054b9emode 000000,100644..100644--- a/src-tauri/core/src/weights/download.rs+++ b/src-tauri/core/src/weights/download.rs@@@ -1,0 -1,303 +1,303 @@@+ use super::{cached_file, destination_name, CompletedFile};+ use crate::storage::atomic::{atomic_replace, write_atomically};+ use reqwest::{+ blocking::{Client, Response},+ header, StatusCode, Url,+ };+ use serde::{Deserialize, Serialize};+ use std::{+ fs::{self, OpenOptions},+ io::{Read, Seek, SeekFrom, Write},+ path::Path,+ sync::atomic::{AtomicBool, Ordering},+ time::{Duration, Instant},+ };++ #[derive(Serialize, Deserialize)]+ struct PartialFile {+ url: String,+ etag: Option<String>,+ total: Option<u64>,+ // Written only after EOF, size validation and syncing the file. This allows+ // recovery if the app exits between the final rename and completion record.+ #[serde(default)]+ complete: bool,+ }++ fn partial_record(destination: &Path, url: &Url) -> Option<PartialFile> {+ fs::read(destination.with_extension("part.json"))+ .ok()+ .and_then(|bytes| serde_json::from_slice::<PartialFile>(&bytes).ok())+ .filter(|record| record.url == url.as_str())+ }+-pub(super) fn has_partial_download(url: &Url, directory: &Path) -> bool {++pub fn has_partial_download(url: &Url, directory: &Path) -> bool {+ let destination = directory.join(destination_name(url));+ partial_record(&destination, url).is_some_and(|record| {+ destination.with_extension("part").is_file() || (record.complete && destination.is_file())+ })+ }++ fn strong_etag(value: &str) -> bool {+ value.starts_with('"')+ && value.ends_with('"')+ && value.len() >= 2+ && !value[1..value.len() - 1]+ .bytes()+ .any(|byte| byte < 0x21 || byte == b'"' || byte == 0x7f)+ }++ fn response_etag(response: &Response) -> Option<String> {+ response+ .headers()+ .get(header::ETAG)+ .and_then(|value| value.to_str().ok())+ .filter(|value| strong_etag(value))+ .map(str::to_owned)+ }++ fn save_record(destination: &Path, record: &PartialFile) -> Result<(), String> {+ write_atomically(+ &destination.with_extension("part.json"),+ &serde_json::to_vec(record).map_err(|error| error.to_string())?,+ )+ }++ fn publish(destination: &Path, record: &PartialFile) -> Result<String, String> {+ let temporary = destination.with_extension("part");+ if temporary.exists() {+ atomic_replace(&temporary, destination).map_err(|error| error.to_string())?;+ }+ let completed = CompletedFile {+ url: record.url.clone(),+ bytes: record.total.ok_or("Missing completed download size.")?,+ };+ write_atomically(+ &destination.with_extension("complete.json"),+ &serde_json::to_vec(&completed).map_err(|error| error.to_string())?,+ )?;+ let _ = fs::remove_file(destination.with_extension("part.json"));+ Ok(destination.to_string_lossy().into_owned())+ }++ // RFC 9110: never append a different representation or an unexpected byte range.+ // If-Range can omit the ETag in a 206 response; if present it must still match.+ fn resumed_range(response: &Response, offset: u64, record: &PartialFile) -> Option<(u64, u64)> {+ if let Some(etag) = response.headers().get(header::ETAG) {+ if Some(etag.to_str().ok()?) != record.etag.as_deref() {+ return None;+ }+ }+ let range = response+ .headers()+ .get(header::CONTENT_RANGE)?+ .to_str()+ .ok()?+ .strip_prefix("bytes ")?;+ let (range, total) = range.split_once('/')?;+ let (start, end) = range.split_once('-')?;+ let (start, end, total) = (+ start.parse::<u64>().ok()?,+ end.parse::<u64>().ok()?,+ total.parse::<u64>().ok()?,+ );+ if start != offset+ || end < start+ || end >= total+ || record.total.is_some_and(|size| size != total)+ || response+ .content_length()+ .is_some_and(|size| size != end - start + 1)+ {+ return None;+ }+ Some((end + 1, total))+ }+-pub(super) fn transfer(++pub fn transfer(+ url: &Url,+ directory: &Path,+ cancelled: &AtomicBool,+ mut progress: impl FnMut(u64, Option<u64>),+ ) -> Result<String, String> {+ if cancelled.load(Ordering::Relaxed) {+ return Err("Download cancelled.".into());+ }+ let destination = directory.join(destination_name(url));+ if cached_file(&destination, url) {+ return Ok(destination.to_string_lossy().into_owned());+ }+ let temporary = destination.with_extension("part");+ let saved = partial_record(&destination, url);+ if let Some(record) = &saved {+ if record.complete+ && !temporary.exists()+ && record.total.is_some_and(|size| {+ size > 0 && fs::metadata(&destination).is_ok_and(|file| file.len() == size)+ })+ {+ return publish(&destination, record);+ }+ }+ let mut options = OpenOptions::new();+ options.read(true).write(true).create(true).truncate(false);+ #[cfg(windows)]+ {+ use std::os::windows::fs::OpenOptionsExt;+ // Another Slopus process must not append to the same partial file.+ options.share_mode(0);+ }+ let mut file = options+ .open(&temporary)+ .map_err(|error| format!("Could not open partial download (it may be in use): {error}"))?;+ // Read metadata under the file lock; another process may have updated it+ // between the initial recovery check and opening the partial file.+ let saved = partial_record(&destination, url);+ let length = file.metadata().map_err(|error| error.to_string())?.len();+ if let Some(record) = &saved {+ if record.complete && length > 0 && record.total == Some(length) {+ drop(file);+ return publish(&destination, record);+ }+ }+ let resume = saved.as_ref().filter(|record| {+ length > 0+ && !record.complete+ && record.total.is_none_or(|size| length < size)+ && record.etag.as_deref().is_some_and(strong_etag)+ });+ let mut offset = if resume.is_some() { length } else { 0 };+ let client = Client::builder()+ .connect_timeout(Duration::from_secs(30))+ .timeout(Duration::from_secs(24 * 60 * 60))+ .build()+ .map_err(|error| error.to_string())?;+ let request = || {+ client+ .get(url.clone())+ .header(header::ACCEPT_ENCODING, "identity")+ };+ let mut pending = request();+ if let Some(record) = resume {+ pending = pending+ .header(header::RANGE, format!("bytes={offset}-"))+ .header(header::IF_RANGE, record.etag.as_deref().unwrap());+ }+ let mut response = pending+ .send()+ .map_err(|error| format!("Download failed: {error}"))?;+ let mut range = None;+ if let Some(record) = resume {+ if response.status() == StatusCode::PARTIAL_CONTENT {+ range = resumed_range(&response, offset, record);+ }+ if response.status() == StatusCode::RANGE_NOT_SATISFIABLE+ || (response.status() == StatusCode::PARTIAL_CONTENT && range.is_none())+ {+ drop(response);+ if cancelled.load(Ordering::Relaxed) {+ return Err("Download cancelled.".into());+ }+ response = request()+ .send()+ .map_err(|error| format!("Download failed: {error}"))?;+ }+ }+ response+ .error_for_status_ref()+ .map_err(|error| format!("Download failed: {error}"))?;+ if response+ .headers()+ .get(header::CONTENT_TYPE)+ .and_then(|value| value.to_str().ok())+ .is_some_and(|value| value.to_ascii_lowercase().starts_with("text/html"))+ {+ return Err(+ "The URL returned a web page instead of a weight file. Use a direct download link."+ .into(),+ );+ }+ if response+ .headers()+ .get(header::CONTENT_ENCODING)+ .is_some_and(|value| value != "identity")+ {+ return Err("The server returned encoded data instead of the requested file bytes.".into());+ }+ let (end, total, etag) = if response.status() == StatusCode::OK {+ offset = 0;+ (+ response.content_length(),+ response.content_length(),+ response_etag(&response),+ )+ } else if response.status() == StatusCode::PARTIAL_CONTENT && range.is_some() {+ let (end, total) = range.unwrap();+ (Some(end), Some(total), resume.unwrap().etag.clone())+ } else {+ return Err("The server did not return the requested file bytes.".into());+ };+ if cancelled.load(Ordering::Relaxed) {+ return Err("Download cancelled.".into());+ }+ if total == Some(0) {+ return Err("The URL returned an empty weight file.".into());+ }+ if offset == 0 {+ // Truncate before replacing metadata, so a crash cannot pair old bytes+ // with a new ETag. Keep existing data untouched until a valid response.+ file.set_len(0).map_err(|error| error.to_string())?;+ file.sync_all().map_err(|error| error.to_string())?;+ }+ file.seek(SeekFrom::Start(offset))+ .map_err(|error| error.to_string())?;+ let mut record = PartialFile {+ url: url.to_string(),+ etag,+ total,+ complete: false,+ };+ save_record(&destination, &record)?;+ let mut downloaded = offset;+ let mut buffer = vec![0u8; 1024 * 1024];+ let mut last_progress = Instant::now();+ progress(downloaded, total);+ loop {+ if cancelled.load(Ordering::Relaxed) {+ return Err("Download cancelled.".into());+ }+ let count = response+ .read(&mut buffer)+ .map_err(|error| format!("Download interrupted: {error}"))?;+ if count == 0 {+ break;+ }+ if end.is_some_and(|end| count as u64 > end.saturating_sub(downloaded)) {+ return Err("The server sent more bytes than the requested file range.".into());+ }+ file.write_all(&buffer[..count])+ .map_err(|error| format!("Could not write weights: {error}"))?;+ downloaded += count as u64;+ if last_progress.elapsed() >= Duration::from_millis(200) {+ progress(downloaded, total);+ last_progress = Instant::now();+ }+ }+ if downloaded == 0 || total.is_some_and(|total| downloaded != total) {+ return Err("The download is incomplete. Retry to continue downloading.".into());+ }+ if cancelled.load(Ordering::Relaxed) {+ return Err("Download cancelled.".into());+ }+ file.sync_all().map_err(|error| error.to_string())?;+ record.complete = true;+ record.total = Some(downloaded);+ save_record(&destination, &record)?;+ drop(file);+ let path = publish(&destination, &record)?;+ progress(downloaded, Some(downloaded));+ Ok(path)+ }++ #[cfg(test)]+ mod tests;diff --cc src-tauri/core/src/weights/download/tests.rsindex 0000000,0ef66cf..0ef66cfmode 000000,100644..100644--- a/src-tauri/core/src/weights/download/tests.rs+++ b/src-tauri/core/src/weights/download/tests.rsdiff --cc src-tauri/core/src/weights/lora.rsindex 350752e,0000000..c163777mode 100644,000000..100644--- a/src-tauri/core/src/weights/lora.rs+++ b/src-tauri/core/src/weights/lora.rs@@@ -1,102 -1,0 +1,185 @@@+use super::*;++use std::io::Read;++use sha2::{Digest, Sha256};++++const GRID_URL: &str = "https://huggingface.co/deAPI-ai/minimax-h3-33b-int8/resolve/ee696877efb4553214cb8d920d5617fd3309b910/loras/h3_silu_temb_grid.safetensors";++const GRID_SIZE: u64 = 5_510_600;++++fn adapter_header(path: &Path) -> Result<serde_json::Map<String, serde_json::Value>, String> {++ let mut file = fs::File::open(path).map_err(|e| e.to_string())?;++ let mut length = [0u8; 8];++ file.read_exact(&mut length).map_err(|e| e.to_string())?;++ let length = u64::from_le_bytes(length);++ if length == 0 || length > 16 * 1024 * 1024 || length + 8 > file.metadata().map_err(|e| e.to_string())?.len() {++ return Err("Invalid LoRA SafeTensors header length.".into());++ }++ let mut header = vec![0u8; length as usize];++ file.read_exact(&mut header).map_err(|e| e.to_string())?;++ serde_json::from_slice(&header).map_err(|e| format!("Invalid LoRA SafeTensors header: {e}"))++}++++fn download_legacy_grid(directory: &Path) -> Result<(), String> {++ let url = download_url(GRID_URL)?;++ let cached = transfer(&url, directory, &AtomicBool::new(false), |_, _| {})?;++ if fs::metadata(&cached).map_err(|e| e.to_string())?.len() != GRID_SIZE {++ return Err("Downloaded timestep grid has an unexpected size.".into());++ }++ let bytes = fs::read(&cached).map_err(|e| e.to_string())?;++ if format!("{:x}", Sha256::digest(&bytes)) != "30eb3c2cc7fb6b470d9717ff840d359313ac27cd64b705e32da1baa10f72d6a8" {++ return Err("Downloaded timestep grid failed SHA-256 verification.".into());++ }++ // A hard link publishes the verified file without overwriting a local companion.++ fs::hard_link(cached, directory.join("h3_silu_temb_grid.safetensors")).map_err(|e| e.to_string())++}++/// Runs before inference, while no model reader can hold the adapter open.+pub fn prepare(+ path: &Path,+ width: i32,+ allow_download: bool,+ model_access: &std::sync::RwLock<()>,+) -> Result<(), String> {+ let _models = model_access+ .try_write()+ .map_err(|_| "Model files are in use. Prepare the LoRA after generation finishes.")?;+ prepare_exclusive(path, width, allow_download)+}++/// Preparation for a caller that already holds the model write lock. The LAN+/// worker waits for that lock instead of failing while a job is running.+pub fn prepare_exclusive(path: &Path, width: i32, allow_download: bool) -> Result<(), String> {- // Slopfab owns format validation, asset selection and atomic embedding.++ let header = adapter_header(path)?;++ // DMAD only targets attention/MLP projections. The explicit grid API always++ // expects a grid, even for adapters whose inference never needs one.++ if !header.keys().any(|key| key.contains("adaln_proj"))++ && header.keys().any(|key| key.contains(".lora.") || key.contains(".lora_")) {++ return Ok(());++ }++ // Slopfab owns grid validation, asset selection and atomic embedding.+ // Preserve the URL record even on an idempotent retry after a record-write error.+ let record_path = path.with_extension("complete.json");+ let record = fs::read(&record_path)+ .ok()+ .and_then(|bytes| serde_json::from_slice::<CompletedFile>(&bytes).ok())+ .filter(|record| {+ download_url(&record.url).is_ok_and(|url| {+ path.file_name().and_then(|name| name.to_str())+ == Some(destination_name(&url).as_str())+ })+ });- crate::slopfab::prepare_lora_grid(path, width, allow_download)?;++ if let Err(error) = crate::slopfab::prepare_lora_grid(path, width, false) {++ let directory = path.parent().ok_or("LoRA has no parent directory.")?;++ let custom_grid = header.get("__metadata__").and_then(|m| m.get("slopfab.lora_grid")).is_some();++ if !allow_download || width != 2688 || custom_grid++ || directory.join("h3_silu_temb_grid.safetensors").exists()++ || !(error.contains("local companion file:") || error.contains("no matching embedded AdaLN grid")) {++ return Err(error);++ }++ download_legacy_grid(directory)?;++ crate::slopfab::prepare_lora_grid(path, width, false)?;++ }+ if let Some(mut record) = record {+ record.bytes = fs::metadata(path).map_err(|error| error.to_string())?.len();+ fs::write(+ record_path,+ serde_json::to_vec(&record).map_err(|error| error.to_string())?,+ )+ .map_err(|error| {+ format!("LoRA prepared, but its download record could not be updated: {error}")+ })?;+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn fixture(path: &Path, tensor: &str, shape: &[usize]) {+ let bytes = shape.iter().product::<usize>() * 4;+ let header = serde_json::json!({ tensor: { "dtype": "F32", "shape": shape, "data_offsets": [0, bytes] } }).to_string();+ let mut data = (header.len() as u64).to_le_bytes().to_vec();+ data.extend_from_slice(header.as_bytes());+ data.resize(data.len() + bytes, 0);+ fs::write(path, data).unwrap();+ }+++ #[test]++ fn dmad_projections_need_no_companion_or_rewrite() {++ let folder = tempfile::tempdir().unwrap();++ let path = folder.path().join("dmad.safetensors");++ fixture(&path, "transformer_blocks.0.attn.to_q.lora.down.weight", &[2, 2]);++ let original = fs::read(&path).unwrap();++ for allow_download in [false, true] {++ prepare(&path, 2688, allow_download, &std::sync::RwLock::new(())).unwrap();++ assert_eq!(fs::read(&path).unwrap(), original);++ assert_eq!(fs::read_dir(folder.path()).unwrap().count(), 1);++ }++ }++++ #[test]++ fn malformed_adapter_headers_fail_without_allocating_from_untrusted_length() {++ let folder = tempfile::tempdir().unwrap();++ let path = folder.path().join("bad.safetensors");++ fs::write(&path, u64::MAX.to_le_bytes()).unwrap();++ assert!(adapter_header(&path).unwrap_err().contains("header length"));++ }++++ #[test]++ fn cached_grid_must_match_pinned_bytes_before_publication() {++ let folder = tempfile::tempdir().unwrap();++ let url = download_url(GRID_URL).unwrap();++ let cached = folder.path().join(destination_name(&url));++ fs::write(&cached, vec![0u8; GRID_SIZE as usize]).unwrap();++ fs::write(cached.with_extension("complete.json"), serde_json::to_vec(&CompletedFile {++ url: url.to_string(), bytes: GRID_SIZE,++ }).unwrap()).unwrap();++ assert!(download_legacy_grid(folder.path()).unwrap_err().contains("SHA-256"));++ assert!(!folder.path().join("h3_silu_temb_grid.safetensors").exists());++ }+++ #[test]+ fn preparation_preserves_download_discovery_and_is_idempotent() {+ let model_access = std::sync::RwLock::new(());+ let folder = tempfile::tempdir().unwrap();+ let url = download_url("https://example.com/adapter.safetensors").unwrap();+ let path = folder.path().join(destination_name(&url));+ fixture(&path, "weight", &[1]);+ let record = CompletedFile {+ url: url.to_string(),+ bytes: fs::metadata(&path).unwrap().len(),+ };+ fs::write(+ path.with_extension("complete.json"),+ serde_json::to_vec(&record).unwrap(),+ )+ .unwrap();+ let original = fs::read(&path).unwrap();+ assert!(prepare(&path, 2, false, &model_access).is_err());+ assert_eq!(fs::read(&path).unwrap(), original);+ assert!(cached_file(&path, &url));+ let companion = folder.path().join("h3_silu_temb_grid.safetensors");+ fixture(&companion, "silu_t_emb_grid", &[1025, 2]);- prepare(&path, 2, false, &model_access).unwrap();++ prepare(&path, 2, true, &model_access).unwrap();+ let embedded = fs::read(&path).unwrap();+ assert!(embedded.len() > original.len());+ assert!(cached_file(&path, &url));+ assert_eq!(+ find_cached_weight(&url, &[folder.path().to_owned()]),+ Some(path.to_string_lossy().into_owned())+ );+ fs::remove_file(companion).unwrap();+ prepare(&path, 2, false, &model_access).unwrap();+ assert_eq!(fs::read(&path).unwrap(), embedded);+ assert!(validate_removal(&path, &[folder.path().to_owned()]).is_ok());+ }++ #[test]+ fn preparation_rejects_busy_model_files() {+ let model_access = std::sync::RwLock::new(());+ let _models = model_access.read().unwrap();+ assert!(prepare(Path::new("unused"), 2, false, &model_access)+ .unwrap_err()+ .contains("in use"));+ }+}diff --cc src/lib/loras.tsindex 54b0799,3f08ed2..c57058b--- a/src/lib/loras.ts+++ b/src/lib/loras.ts@@@ -90,13 -96,6 +98,13 @@@ export function resolveTemplateLoras(seconst lora = library.find(({ id }) => id === entry.loraId);const strength = entry.strength;if (!isLoraStrength(strength)) throw new Error(`Strength for LoRA ${lora?.name ?? entry.loraId} is outside the supported range.`);+ if (worker) {+ const local = lora?.path.trim() && !/^https?:\/\//i.test(lora.path) && !lora.needsPreparation ? lora.path.trim() : undefined;+ const path = local ?? lora?.url;+ if (!path) throw new Error(lora?.needsPreparation ? `Prepare LoRA ${lora.name} in Settings before using it.`+ : `Locate LoRA ${lora?.name ?? entry.loraId}, or disable it in the generator template.`);- return [{ path, strength, stepOverride: lora?.stepOverride }];++ return [{ path, strength, stepOverride: lora?.stepOverride, samplingPreset: lora?.samplingPreset }];+ }if (lora?.needsPreparation) throw new Error(`Prepare LoRA ${lora.name} in Settings before using it.`);if (!lora?.path.trim() || /^https?:\/\//i.test(lora.path)) {throw new Error(`Download or locate LoRA ${lora?.name ?? entry.loraId}, or disable it in the generator template.`);diff --cc src/lib/workers.test.tsindex bd50881,0000000..14399e5mode 100644,000000..100644--- a/src/lib/workers.test.ts+++ b/src/lib/workers.test.ts@@@ -1,84 -1,0 +1,93 @@@+// @vitest-environment jsdom++import { beforeEach, describe, expect, it, vi } from "vitest";+import { invoke } from "@tauri-apps/api/core";- import { TURBO_LORA } from "./loras";++import { DMAD_LORA, TURBO_LORA } from "./loras";+import { engineProviderSetting, templateNeedsDownload, templateUsable, viggleAnimateTemplate, type GeneratorTemplate } from "./settings";+import { refreshWorkers, remoteWorkerSelected, selectedWorker, selectWorker, WORKERS_EVENT, type WorkerList } from "./workers";++vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));+vi.mock("./persistence", async (original) => ({ ...await original<typeof import("./persistence")>(), isTauri: () => true }));++const worker = (overrides: Partial<WorkerList["workers"][number]> = {}): WorkerList["workers"][number] => ({+ key: "aaaaaaaaaaaaaaaa", id: "aaaaaaaaaaaaaaaa", name: "Studio PC", address: "192.168.1.20:47321", online: true, compatible: true,+ discovered: true, manual: false, selected: false, version: "0.2.0", requiresToken: false, hasToken: false,+ gpus: [{ name: "NVIDIA GeForce RTX 5090", memoryBytes: 32 * 1024 ** 3 }], runtime: null, error: null, ...overrides,+});++function choose(list: WorkerList) {+ vi.mocked(invoke).mockResolvedValue(list);+ return selectWorker(list.selectedId);+}++const downloadable = (): GeneratorTemplate => ({+ id: "remote", name: "Remote", modelType: "minimax-h3", defaultSteps: 8, attention: "sage2",+ paths: { transformer: "", textEncoder: "D:/models/encoder.safetensors", tokenizer: "", videoVae: "https://example.com/vae.safetensors", audioVae: "https://example.com/audio.safetensors" },+ sources: { transformer: [+ { url: "https://example.com/small.safetensors", gpuModel: "", minVramGb: 0 },+ { url: "https://example.com/large.safetensors", gpuModel: "", minVramGb: 24 },+ ] },+ loras: [{ loraId: TURBO_LORA.id, enabled: true, strength: 1 }],+});++describe("LAN generation workers", () => {+ beforeEach(() => { localStorage.clear(); vi.mocked(invoke).mockReset(); });++ it("mirrors the selection Rust reports and announces changes", async () => {+ const changed = vi.fn();+ window.addEventListener(WORKERS_EVENT, changed);+ await choose({ selectedId: "aaaaaaaaaaaaaaaa", workers: [worker({ selected: true })] });+ expect(vi.mocked(invoke)).toHaveBeenCalledWith("select_worker", { id: "aaaaaaaaaaaaaaaa" });+ expect(selectedWorker()).toEqual({ id: "aaaaaaaaaaaaaaaa", name: "Studio PC", gpus: worker().gpus });+ expect(changed).toHaveBeenCalledTimes(1);+ // An offline worker keeps its last known GPUs for weight selection.+ vi.mocked(invoke).mockResolvedValue({ selectedId: "aaaaaaaaaaaaaaaa", workers: [worker({ online: false, gpus: [] })] });+ await refreshWorkers();+ expect(selectedWorker()?.gpus).toEqual(worker().gpus);+ expect(changed).toHaveBeenCalledTimes(1);+ await choose({ selectedId: null, workers: [worker()] });+ expect(remoteWorkerSelected()).toBe(false);+ expect(changed).toHaveBeenCalledTimes(2);+ window.removeEventListener(WORKERS_EVENT, changed);+ });++ it("lets a worker download what this computer has not, and picks weights for the worker's GPU", async () => {+ const template = downloadable();+ expect(templateNeedsDownload(template)).toBe(true);+ expect(templateUsable(template)).toBe(false);+ expect(() => engineProviderSetting(template.paths, undefined, "sage2", template.loras, "prompt", [], false, template.sources)).toThrow(/Download or locate LoRA/);++ await choose({ selectedId: "aaaaaaaaaaaaaaaa", workers: [worker()] });+ expect(templateUsable(template)).toBe(true);+ const options = engineProviderSetting(template.paths, undefined, "sage2", template.loras, "prompt", [], false, template.sources).options;+ expect(options).toMatchObject({+ transformer: "https://example.com/large.safetensors",+ textEncoder: "D:/models/encoder.safetensors",+ videoVae: "https://example.com/vae.safetensors",+ audioVae: "https://example.com/audio.safetensors",+ stepOverride: 4,+ });+ expect(options).not.toHaveProperty("tokenizer");+ expect(JSON.parse(options.loras as string)).toEqual([{ path: TURBO_LORA.url, strength: 1 }]);++ const animate = viggleAnimateTemplate();+ const embedding = engineProviderSetting(animate.paths, undefined, animate.attention, [], "animate", animate.additionalSafetensors, false, animate.sources).options;+ expect(embedding.promptEmbedding).toBe(animate.additionalSafetensors![0].url);+ });+++ it("sends a DMAD download link with its sampling recipe to a worker", async () => {++ await choose({ selectedId: "aaaaaaaaaaaaaaaa", workers: [worker()] });++ const template = { ...downloadable(), loras: [{ loraId: DMAD_LORA.id, enabled: true, strength: 1 }] };++ const options = engineProviderSetting(template.paths, undefined, "sage2", template.loras, "prompt", [], true, template.sources).options;++ expect(JSON.parse(options.loras as string)).toEqual([{ path: DMAD_LORA.url, strength: 1 }]);++ expect(options).toMatchObject({ samplingPreset: "dmad-4step", stepOverride: 4 });++ expect(options).not.toHaveProperty("motionCache");++ });+++ it("still needs a source for every required model on a worker", async () => {+ await choose({ selectedId: "aaaaaaaaaaaaaaaa", workers: [worker()] });+ const template = downloadable();+ template.sources = {};+ expect(templateUsable(template)).toBe(false);+ });+});