AI media harness for planning, generating, and editing locally
TypeScript
Prepare LoRA grids through Slopfab API
Bitti04f2491996e8
diff --git a/docs/slopfab-compatibility.md b/docs/slopfab-compatibility.mdindex 35a6470..268f0aa 100644--- a/docs/slopfab-compatibility.md+++ b/docs/slopfab-compatibility.md@@ -1,7 +1,7 @@-# Slopfab 1.12 compatibility+# Slopfab 1.13 compatibility-Reviewed on 2026-09-20 against Slopfab commit `50ca721` and the local-`lib/slopfab/slopfab.dll`, which reports C API `1.12.0`.+Reviewed on 2026-09-20 against Slopfab commit `9b61787` and the local+`lib/slopfab/slopfab.dll`, which reports C API `1.13.0`.## ABI and runtime@@ -43,8 +43,24 @@ during planning instead of being deferred until generation.Inference no longer downloads a missing AdaLN timestep grid or rewrites theadapter to embed it. This affects adapters that need rebasing onto an H3 table-model and do not already have an embedded grid. Slopus's current LoRA download-flow downloads the adapter itself; it does not prepare this companion asset.+model and do not already have an embedded grid. Slopus calls C API 1.13's+`slopfab_prepare_lora_grid` after downloading a LoRA+and before saving a newly imported local adapter. The LoRA library's **Prepare**+action handles existing files. Current H3 profiles use grid width 2688.++Downloaded and repaired adapters permit the pinned legacy grid download. Local+imports have a **Download missing timestep grid** checkbox; disabling it uses+local assets only. Preparation may embed the grid in the selected file, using+Slopfab's atomic replacement. Slopus updates its download completion record+with the resulting file size and keeps failed preparations unavailable until+retried successfully. Existing adapters without a preparation status remain+usable and can be prepared explicitly when needed.++The native operation runs on a blocking worker and excludes model readers,+generation and removal while replacing the file. The UI shows a preparation+state instead of a fabricated byte percentage. The synchronous API cannot be+cancelled, so the cancel action is unavailable during preparation. An older DLL+can still load, but attempting preparation reports that API 1.13 is required.For legacy H3 adapters, place `h3_silu_temb_grid.safetensors` beside the adapter,or use Slopfab's explicit preparation command before selecting it in Slopus:@@ -57,12 +73,14 @@ That command explicitly downloads the pinned legacy grid and embeds it in theadapter. Omit `--download` to use local assets only. Custom `slopfab.lora_grid`metadata requires its declared local asset and matching identity/width; thelegacy downloader cannot supply arbitrary grids. Already embedded adapters-need no migration. Automatic asset preparation in Slopus would be a separate-download-workflow enhancement, not a C ABI binding change.+need no migration. The CLI is an alternative for manual/offline setup; normal+Slopus downloads and imports use the DLL directly.## Validation limits-All 26 Slopus Slopfab integration tests passed with the updated DLL, including+Slopus Slopfab integration tests cover the updated DLL, includingplanning for both backends, Animate, MotionCache, video reference ownership,-continuation and still images. These tests do not run a full model inference;+continuation and still images. Preparation tests use small local fixtures to+check embedding, idempotence, missing assets, busy model files, older DLLs and+download-record updates. These tests do not run a full model inference;CUDA/Vulkan numerical output and render performance were not revalidated here.diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rsindex 67bf57e..4400eaf 100644--- a/src-tauri/src/app.rs+++ b/src-tauri/src/app.rs@@ -86,6 +86,7 @@ pub fn run() {.invoke_handler(tauri::generate_handler![app_updater_enabled,weights::download_weight,+ weights::lora::prepare_lora,weights::cancel_weight_download,weights::check_weight_files,weights::find_downloaded_weights,diff --git a/src-tauri/src/slopfab/ffi/mod.rs b/src-tauri/src/slopfab/ffi/mod.rsindex b8737c2..47123be 100644--- a/src-tauri/src/slopfab/ffi/mod.rs+++ b/src-tauri/src/slopfab/ffi/mod.rs@@ -36,6 +36,20 @@ impl Api {pub fn clear_reused_models(&self) -> Result<(), String> {self.inner.clear_reused_models()}+ pub fn prepare_lora_grid(+ &self,+ path: &Path,+ width: i32,+ allow_download: bool,+ ) -> Result<(), String> {+ self.inner.prepare_lora_grid(path, width, allow_download)+ }+ #[cfg(test)]+ pub fn disable_lora_preparation_for_test(&mut self) {+ Arc::get_mut(&mut self.inner)+ .expect("configure API before creating handles")+ .disable_lora_preparation_for_test();+ }#[cfg(test)]pub fn disable_animate_for_test(&mut self) {Arc::get_mut(&mut self.inner)diff --git a/src-tauri/src/slopfab/ffi/raw/mod.rs b/src-tauri/src/slopfab/ffi/raw/mod.rsindex d829605..8459805 100644--- a/src-tauri/src/slopfab/ffi/raw/mod.rs+++ b/src-tauri/src/slopfab/ffi/raw/mod.rs@@ -83,6 +83,7 @@ pub struct Api {set_seed: unsafe extern "C" fn(*mut Request, u64) -> i32,set_model: unsafe extern "C" fn(*mut Request, i32, *const c_char) -> i32,add_lora: Option<unsafe extern "C" fn(*mut Request, *const c_char, f32) -> i32>,+ prepare_lora_grid: Option<unsafe extern "C" fn(*const c_char, i32, i32) -> i32>,add_refmod: Option<unsafe extern "C" fn(*mut Request, *const c_char, f32, i32) -> i32>,add_reference: unsafe extern "C" fn(*mut Request, *const c_char) -> i32,set_attention: unsafe extern "C" fn(*mut Request, *const c_char) -> i32,@@ -140,6 +141,12 @@ impl Api {"slopfab_request_create",unsafe extern "C" fn() -> *mut Request),+ prepare_lora_grid: library+ .get::<unsafe extern "C" fn(*const c_char, i32, i32) -> i32>(+ b"slopfab_prepare_lora_grid\0",+ )+ .ok()+ .map(|symbol| *symbol),request_destroy: symbol!("slopfab_request_destroy",unsafe extern "C" fn(*mut Request)@@ -429,6 +436,22 @@ impl Api {let path = path_cstring(path)?;self.error(unsafe { add(r, path.as_ptr(), strength) })}+ pub fn prepare_lora_grid(+ &self,+ path: &Path,+ width: i32,+ allow_download: bool,+ ) -> Result<(), String> {+ let prepare = self.prepare_lora_grid.ok_or(+ "LoRA preparation requires slopfab.dll API 1.13 or later. Update the runtime.",+ )?;+ let path = path_cstring(path)?;+ self.error(unsafe { prepare(path.as_ptr(), width, allow_download as i32) })+ }+ #[cfg(test)]+ pub fn disable_lora_preparation_for_test(&mut self) {+ self.prepare_lora_grid = None;+ }pub fn add_refmod(&self,r: *mut Request,diff --git a/src-tauri/src/slopfab/ffi/tests.rs b/src-tauri/src/slopfab/ffi/tests.rsindex dbe36c2..425ec9d 100644--- a/src-tauri/src/slopfab/ffi/tests.rs+++ b/src-tauri/src/slopfab/ffi/tests.rs@@ -1,5 +1,18 @@use super::*;+#[test]+fn older_runtimes_report_missing_lora_preparation_without_breaking_planning() {+ let mut api = Api::load(&crate::slopfab::default_dll_path()).unwrap();+ api.disable_lora_preparation_for_test();+ assert!(api+ .prepare_lora_grid(Path::new("adapter.safetensors"), 2688, false)+ .unwrap_err()+ .contains("API 1.13"));+ let request = RequestHandle::new(&api).unwrap();+ api.set_frames(&request, 48).unwrap();+ assert!(api.resolve(&request).is_ok());+}+#[test]fn requests_retain_the_library_and_reject_cross_instance_calls() {let path = crate::slopfab::default_dll_path();diff --git a/src-tauri/src/slopfab/generation.rs b/src-tauri/src/slopfab/generation.rsindex f06e06f..16e95a5 100644--- a/src-tauri/src/slopfab/generation.rs+++ b/src-tauri/src/slopfab/generation.rs@@ -26,6 +26,9 @@ impl rendered::FrameSource for FrameSource {pub(super) fn run_generation(item: &QueueItem,) -> Result<(OutputMetadata, rendered::RenderedVideo), String> {+ let _models = super::MODEL_ACCESS+ .read()+ .map_err(|_| "Model access lock failed.")?;if item.cancel.load(Ordering::Acquire) {return Err("Generation was cancelled before it started.".into());}diff --git a/src-tauri/src/slopfab/icons.rs b/src-tauri/src/slopfab/icons.rsindex c167a1c..dcb2553 100644--- a/src-tauri/src/slopfab/icons.rs+++ b/src-tauri/src/slopfab/icons.rs@@ -34,6 +34,9 @@ pub(super) fn write_reference_icon(platform: ComputePlatform,spec: &ReferenceIconSpec,) -> Result<(), String> {+ let _models = super::MODEL_ACCESS+ .read()+ .map_err(|_| "Model access lock failed.")?;let request = GenerationRequest {job_id: spec.id.clone(),prompt: spec.prompt.clone(),diff --git a/src-tauri/src/slopfab/mod.rs b/src-tauri/src/slopfab/mod.rsindex 1d974c4..04bd21c 100644--- a/src-tauri/src/slopfab/mod.rs+++ b/src-tauri/src/slopfab/mod.rs@@ -1,5 +1,15 @@//! Native runtime adapter. Raw ABI and resource ownership are confined to ffi.use std::path::{Path, PathBuf};+// Preparation atomically replaces adapters; model readers must be closed first.+pub(crate) static MODEL_ACCESS: std::sync::RwLock<()> = std::sync::RwLock::new(());++pub(crate) fn prepare_lora_grid(+ path: &Path,+ width: i32,+ allow_download: bool,+) -> Result<(), String> {+ ffi::Api::load(&default_dll_path())?.prepare_lora_grid(path, width, allow_download)+}mod config;mod events;mod ffi;diff --git a/src-tauri/src/slopfab/planning.rs b/src-tauri/src/slopfab/planning.rsindex 850e5eb..6dd0725 100644--- a/src-tauri/src/slopfab/planning.rs+++ b/src-tauri/src/slopfab/planning.rs@@ -20,6 +20,9 @@ pub fn resolve_plan(settings: &BTreeMap<String, ProviderSetting>,references: &ReferenceVideos,) -> Result<ResolvedPlan, String> {+ let _models = super::MODEL_ACCESS.try_read().map_err(|_| {+ "Model files are in use. Retry planning after generation or LoRA preparation finishes."+ })?;validate_generation_controls(request)?;let configuration = Configuration::from_settings(settings);let api = ffi::Api::load(&configuration.dll_path)?;diff --git a/src-tauri/src/weights.rs b/src-tauri/src/weights.rsindex 182f2f3..96db79a 100644--- a/src-tauri/src/weights.rs+++ b/src-tauri/src/weights.rs@@ -21,6 +21,8 @@ struct Progress { request_id: String, downloaded: u64, total: Option<u64> }#[derive(Serialize, Deserialize)]struct CompletedFile { url: String, bytes: u64 }+pub(crate) mod lora;+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() {@@ -182,6 +184,8 @@ pub async fn download_weight(app: AppHandle, downloads: State<'_, WeightDownload}let event_id = request_id.clone();let result = tauri::async_runtime::spawn_blocking(move || {+ let _models = crate::slopfab::MODEL_ACCESS.try_read()+ .map_err(|_| "Wait for LoRA preparation to finish before downloading weights.")?;let roots = configured_weight_roots(&app)?;transfer_from_roots(&url, &roots, &cancelled, |downloaded, total| {let _ = app.emit("weight-download-progress", Progress { request_id: event_id.clone(), downloaded, total });@@ -258,6 +262,8 @@ fn validate_removal(path: &Path, roots: &[PathBuf]) -> Result<(), String> {#[tauri::command]pub async fn remove_downloaded_weights(app: AppHandle, paths: Vec<String>) -> Result<(), String> {tauri::async_runtime::spawn_blocking(move || {+ let _models = crate::slopfab::MODEL_ACCESS.try_write()+ .map_err(|_| "Model files are in use. Wait for generation, downloads or preparation to finish.")?;let roots = configured_weight_roots(&app)?;let paths: Vec<PathBuf> = paths.into_iter().map(PathBuf::from).collect();for path in &paths { validate_removal(path, &roots)?; }diff --git a/src-tauri/src/weights/lora.rs b/src-tauri/src/weights/lora.rsnew file mode 100644index 0000000..687a985--- /dev/null+++ b/src-tauri/src/weights/lora.rs@@ -0,0 +1,110 @@+use super::*;++/// Runs before inference, while no model reader can hold the adapter open.+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.")?;+ // Slopfab owns format 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 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(())+}++#[tauri::command]+pub async fn prepare_lora(path: String, allow_download: bool) -> Result<(), String> {+ let path = PathBuf::from(path);+ if !path.is_absolute() || !path.is_file() {+ return Err("Choose an existing local LoRA file using its absolute path.".into());+ }+ // All current Slopus generator profiles use the H3 2688-wide adapter grid.+ tauri::async_runtime::spawn_blocking(move || {+ prepare(&path, 2688, allow_download, &crate::slopfab::MODEL_ACCESS)+ })+ .await+ .map_err(|error| error.to_string())?+}++#[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 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();+ 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 --git a/src/components/LoraSettings.tsx b/src/components/LoraSettings.tsxindex 1d16720..e91de2f 100644--- a/src/components/LoraSettings.tsx+++ b/src/components/LoraSettings.tsx@@ -1,11 +1,11 @@-import { ArrowDown, ArrowUp, Download, FolderSearch, Layers, Plus, Trash2 } from "lucide-react";+import { ArrowDown, ArrowUp, Download, FolderSearch, Layers, LoaderCircle, Plus, Trash2, Wrench } from "lucide-react";import "../styles/loras.css";-import { useEffect, useState, useSyncExternalStore } from "react";+import { useEffect, useRef, useState, useSyncExternalStore } from "react";import { effectiveLoraStrength, highestLoraStepOverride, isLoraMultiplier, isLoraStepOverride, loadLoras, MAX_LORA_MULTIPLIER, saveLoras, subscribeLoras, type Lora, type TemplateLora } from "../lib/loras";import { MAX_GENERATION_STEPS } from "../lib/project";import { isTauri } from "../lib/persistence";import { chooseEnginePath } from "../lib/runtime";-import { downloadLora, getWeightDownloadState, refreshDownloadedLoras, removeLora, subscribeWeightDownloads, weightDownloadProgress } from "../lib/weightDownloads";+import { downloadLora, getWeightDownloadState, prepareLora, refreshDownloadedLoras, removeLora, subscribeWeightDownloads, weightDownloadProgress } from "../lib/weightDownloads";function useLoras() {const [loras, setLoras] = useState(loadLoras);@@ -30,8 +30,9 @@ export function LoraLibrary({ onAdd, onEdit }: { onAdd: () => void; onEdit: (id:<button className="secondary-button" type="button" onClick={onAdd}><Plus size={16} /> Add Lora</button></header><div className="generator-template-list" role="list" aria-label="LoRAs">{loras.map((lora) => <div className="generator-template-item lora-library-item" role="listitem" key={lora.id}>- {download?.active && download.loraId === lora.id && <span className="generator-template-item__progress" role="progressbar" aria-label={`Downloading ${lora.name}`} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.floor(weightDownloadProgress(download))} style={{ width: `${weightDownloadProgress(download)}%` }} />}- <button type="button" className="generator-template-item__open" aria-label={`Edit ${lora.name} LoRA`} onClick={() => onEdit(lora.id)}><Layers size={16} /><b>{lora.name}</b><small title={lora.path}>{download?.active && download.loraId === lora.id ? `Downloading · ${Math.floor(weightDownloadProgress(download))}%` : lora.path ? "Available" : "Not downloaded"}</small></button>+ {download?.active && download.loraId === lora.id && download.phase !== "preparing" && <span className="generator-template-item__progress" role="progressbar" aria-label={`Downloading ${lora.name}`} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.floor(weightDownloadProgress(download))} style={{ width: `${weightDownloadProgress(download)}%` }} />}+ <button type="button" className="generator-template-item__open" aria-label={`Edit ${lora.name} LoRA`} onClick={() => onEdit(lora.id)}><Layers size={16} /><b>{lora.name}</b><small title={lora.path}>{download?.active && download.loraId === lora.id ? download.phase === "preparing" ? "Preparing…" : `Downloading · ${Math.floor(weightDownloadProgress(download))}%` : lora.needsPreparation ? "Needs preparation" : lora.path ? "Available" : "Not downloaded"}</small></button>+ {lora.path ? <button className="icon-button" type="button" disabled={!desktop || download?.active} aria-label={`Prepare LoRA ${lora.name}`} title="Prepare missing timestep grid" onClick={() => { setError(null); void prepareLora(lora).catch((reason) => setError(String(reason))); }}>{download?.active && download.loraId === lora.id && download.phase === "preparing" ? <LoaderCircle size={15} className="spin" /> : <Wrench size={15} />}</button> : <span />}{lora.url && !lora.path ? <button className="icon-button" type="button" disabled={!desktop || download?.active} aria-label={`Download LoRA ${lora.name}`} onClick={() => void downloadLora(lora.id)}><Download size={15} /></button>: <button className="icon-button" type="button" disabled={Boolean(download?.active)} aria-label={`Remove LoRA ${lora.name}`} onClick={() => void removeLora(lora.id).catch((reason) => setError(String(reason)))}><Trash2 size={15} /></button>}</div>)}@@ -49,6 +50,11 @@ export function LoraEditor({ loraId, onDone }: { loraId: string; onDone: () => vconst [override, setOverride] = useState(existing?.stepOverride !== undefined);const [steps, setSteps] = useState(String(existing?.stepOverride ?? 3));const [error, setError] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);+ const [allowDownload, setAllowDownload] = useState(true);+ const download = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);+ const mounted = useRef(true);+ useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);const browse = async () => {try {const picked = await chooseEnginePath({ id: "transformer", label: "LoRA", hint: "", directory: false, extensions: ["safetensors"], required: false });@@ -57,21 +63,27 @@ export function LoraEditor({ loraId, onDone }: { loraId: string; onDone: () => vif (!name.trim()) setName(picked.split(/[\\/]/).pop()!.replace(/\.safetensors$/i, ""));} catch (reason) { setError(String(reason)); }};- const save = () => {+ const save = async () => {if (!name.trim() || (!path.trim() && !existing?.url) || !validMultiplier) return;if (path.trim() && (!/^(?:[a-z]:[\\/]|\\\\|\/)/i.test(path.trim()) || path.includes("\0"))) {setError("Choose a local LoRA file using its absolute path."); return;}try {+ setSaving(true); setError(null);+ if (path.trim() && path.trim() !== existing?.path && isTauri()) {+ await prepareLora({ id: loraId, name: name.trim(), path: path.trim() }, allowDownload);+ }const library = loadLoras();- const entry: Lora = { ...library.find(({ id }) => id === loraId), id: loraId, name: name.trim(), path: path.trim(), multiplier: Number(multiplier), stepOverride: override ? Number(steps) : undefined };+ const entry: Lora = { ...library.find(({ id }) => id === loraId), id: loraId, name: name.trim(), path: path.trim(), multiplier: Number(multiplier), stepOverride: override ? Number(steps) : undefined,+ ...(path.trim() !== existing?.path ? { needsPreparation: undefined } : {}) };saveLoras(existing ? library.map((lora) => lora.id === loraId ? entry : lora) : [...library, entry]);- onDone();+ if (mounted.current) onDone();} catch (reason) { setError(String(reason)); }+ finally { setSaving(false); }};return <div className="generator-editor"><header className="generator-editor__head"><h2 id="lora-editor-heading">{existing ? "Edit Lora" : "Add Lora"}</h2></header>- <div className="lora-manual">+ <fieldset className="lora-manual" disabled={saving}><label>Name<input aria-label="LoRA name" autoFocus value={name} onChange={(event) => setName(event.target.value)} /></label><label>Local file<div className="settings-path__row"><input aria-label="LoRA path" value={path} onChange={(event) => setPath(event.target.value)} placeholder="Absolute path to a .safetensors file" /><button className="secondary-button" type="button" disabled={!isTauri()} onClick={() => void browse()}><FolderSearch size={16} /> Browse</button></div></label>@@ -80,10 +92,11 @@ export function LoraEditor({ loraId, onDone }: { loraId: string; onDone: () => v<label className="lora-toggle"><input type="checkbox" checked={override} onChange={(event) => setOverride(event.target.checked)} /> Override step count</label>{override && <label>Step count<input aria-label="LoRA step override" type="number" min={2} max={MAX_GENERATION_STEPS} step={1} value={steps} onChange={(event) => setSteps(event.target.value)} /></label>}<p>The highest override among active LoRAs replaces the scene's step count. Without an override, the scene's steps are used.</p>- <p>The file stays in its current location.</p>- <button className="primary-button" type="button" disabled={!name.trim() || (!path.trim() && !existing?.url) || !validMultiplier || (override && !isLoraStepOverride(Number(steps)))} onClick={save}>{existing ? "Save Lora" : "Add Lora"}</button>+ <label className="lora-toggle"><input type="checkbox" checked={allowDownload} onChange={(event) => setAllowDownload(event.target.checked)} /> Download missing timestep grid</label>+ <p>Newly selected files are prepared in place before use. Preparation may embed a timestep grid in the adapter.</p>+ <button className="primary-button" type="button" disabled={Boolean(download?.active) || !name.trim() || (!path.trim() && !existing?.url) || !validMultiplier || (override && !isLoraStepOverride(Number(steps)))} onClick={() => void save()}>{saving ? "Preparing LoRA…" : existing ? "Save Lora" : "Add Lora"}</button>{error && <p role="alert">{error}</p>}- </div>+ </fieldset></div>;}diff --git a/src/components/SettingsView.downloads.test.tsx b/src/components/SettingsView.downloads.test.tsxindex 1f2fade..74ddec3 100644--- a/src/components/SettingsView.downloads.test.tsx+++ b/src/components/SettingsView.downloads.test.tsx@@ -9,12 +9,52 @@ import { loadGeneratorTemplateSettings, minimaxSingularityTemplate } from "../liimport { getWeightDownloadState } from "../lib/weightDownloads";import { WorkQueuePanel } from "./WorkQueuePanel";import { WorkQueue } from "../lib/workQueue";-import { loadLoras, TAOMATE_LORA, TURBO_LORA } from "../lib/loras";+import { loadLoras, saveLoras, TAOMATE_LORA, TURBO_LORA } from "../lib/loras";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));const files = new Set<string>();+it("keeps a failed local import editable and supports local-only preparation", async () => {+ const normal = vi.mocked(invoke).getMockImplementation()!;+ vi.mocked(invoke).mockImplementation(async (command, args) => {+ if (command === "prepare_lora") throw new Error("Local companion grid missing");+ return normal(command, args);+ });+ render(<SettingsView onClose={() => undefined} />);+ fireEvent.click(screen.getByRole("button", { name: "Add Lora" }));+ fireEvent.change(screen.getByLabelText("LoRA name"), { target: { value: "Offline style" } });+ fireEvent.change(screen.getByLabelText("LoRA path"), { target: { value: "D:/style.safetensors" } });+ fireEvent.click(screen.getByLabelText("Download missing timestep grid"));+ fireEvent.click(screen.getByRole("button", { name: "Add Lora" }));+ expect(await screen.findByRole("alert")).toHaveTextContent("Local companion grid missing");+ expect(loadLoras().find(({ name }) => name === "Offline style")).toBeUndefined();+ expect(invoke).toHaveBeenCalledWith("prepare_lora", { path: "D:/style.safetensors", allowDownload: false });+ expect(screen.getByLabelText("LoRA name")).toHaveValue("Offline style");+ vi.mocked(invoke).mockImplementation(normal);+ fireEvent.click(screen.getByRole("button", { name: "Add Lora" }));+ await screen.findByRole("button", { name: "Prepare LoRA Offline style" });+ expect(loadLoras().find(({ name }) => name === "Offline style")?.path).toBe("D:/style.safetensors");+});++it("prepares an existing adapter with a busy state and no unsupported cancel action", async () => {+ const lora = { id: "local", name: "Existing style", path: "D:/style.safetensors" };+ saveLoras([lora]);+ const normal = vi.mocked(invoke).getMockImplementation()!;+ let finish!: () => void;+ vi.mocked(invoke).mockImplementation(async (command, args) => command === "prepare_lora"+ ? new Promise<void>((resolve) => { finish = resolve; }) : normal(command, args));+ render(<SettingsView onClose={() => undefined} />);+ fireEvent.click(screen.getByRole("button", { name: "Prepare LoRA Existing style" }));+ expect(screen.getByRole("button", { name: "Prepare LoRA Existing style" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Remove LoRA Existing style" })).toBeDisabled();+ expect(screen.queryByRole("button", { name: "Cancel download" })).not.toBeInTheDocument();+ expect(screen.getByRole("status")).toHaveTextContent(/Preparing LoRA/);+ await act(async () => finish());+ expect(screen.getByRole("status")).toHaveTextContent("LoRA prepared");+ expect(loadLoras().find(({ id }) => id === lora.id)?.needsPreparation).toBeUndefined();+});+beforeEach(() => {localStorage.clear(); files.clear(); vi.clearAllMocks();Object.defineProperty(window, "__TAURI_INTERNALS__", { configurable: true, value: {} });@@ -123,6 +163,8 @@ it("downloads TaoMate and persists manual adapters, activation, strength and ordfireEvent.click(screen.getByLabelText("Override step count"));fireEvent.change(screen.getByLabelText("LoRA step override"), { target: { value: "8" } });fireEvent.click(screen.getByRole("button", { name: "Add Lora" }));+ await waitFor(() => expect(loadLoras().find(({ name }) => name === "My style")).toBeDefined());+ expect(invoke).toHaveBeenCalledWith("prepare_lora", { path: "D:/models/style.safetensors", allowDownload: true });const manual = loadLoras().find(({ name }) => name === "My style")!;expect(manual.stepOverride).toBe(8);expect(manual.multiplier).toBe(0.75);diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsxindex 02c08f7..a858295 100644--- a/src/components/SettingsView.tsx+++ b/src/components/SettingsView.tsx@@ -525,9 +525,9 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl</label></div>;const downloadStatus = downloadState && <div className="weight-download-status" role="status">- <span>{downloadState.name ?? templateSettings.templates.find((template) => template.id === downloadState.templateId)?.name}: {downloadState.error ?? (downloadState.active ? `${downloadState.completed}/${downloadState.files} files · ${(downloadState.downloaded / 1024 ** 3).toFixed(2)} GB${downloadState.total ? ` / ${(downloadState.total / 1024 ** 3).toFixed(2)} GB` : ""}` : "Download complete")}</span>- {downloadState.active && <button type="button" className="secondary-button" onClick={() => void cancelWeightDownload().catch((reason) => setError(String(reason)))}>Cancel download</button>}- {downloadState.error && <button type="button" className="secondary-button" onClick={() => void retryWeightDownload()}>Retry download</button>}+ <span>{downloadState.name ?? templateSettings.templates.find((template) => template.id === downloadState.templateId)?.name}: {downloadState.error ?? (downloadState.active ? downloadState.phase === "preparing" ? "Preparing LoRA…" : `${downloadState.completed}/${downloadState.files} files · ${(downloadState.downloaded / 1024 ** 3).toFixed(2)} GB${downloadState.total ? ` / ${(downloadState.total / 1024 ** 3).toFixed(2)} GB` : ""}` : downloadState.preparePath ? "LoRA prepared" : "Download complete")}</span>+ {downloadState.active && downloadState.phase !== "preparing" && <button type="button" className="secondary-button" onClick={() => void cancelWeightDownload().catch((reason) => setError(String(reason)))}>Cancel download</button>}+ {downloadState.error && <button type="button" className="secondary-button" onClick={() => void retryWeightDownload()}>{downloadState.phase === "preparing" ? "Retry preparation" : "Retry download"}</button>}</div>;const generatorFooter = <>{downloadStatus}<footer className="settings-view__foot">{/* Clearing the paths is an engine action, so it is only offered@@ -630,7 +630,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl<div className="generator-template-list" role="list" aria-label={section.title}>{section.templates.map((template) => (<div className={`generator-template-item${templateNeedsDownload(template) ? " generator-template-item--download" : template.id === templateSettings.defaultTemplateId ? " generator-template-item--selected" : ""}`} role="listitem" key={template.id}>- {downloadState?.active && downloadState.templateId === template.id && <span+ {downloadState?.active && downloadState.templateId === template.id && downloadState.phase !== "preparing" && <spanclassName="generator-template-item__progress"role="progressbar"aria-label={`Downloading ${template.name} weights`}@@ -645,7 +645,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl</label>}<button type="button" className="generator-template-item__open" onClick={() => setEditingTemplateId(template.id)} aria-label={`Edit ${template.name} generator`}><Video size={16} aria-hidden="true" />- <b>{template.name}</b><small>{downloadState?.active && downloadState.templateId === template.id ? `Downloading · ${Math.floor(downloadPercent)}%` : templateSummary(template)}</small>+ <b>{template.name}</b><small>{downloadState?.active && downloadState.templateId === template.id ? downloadState.phase === "preparing" ? "Preparing LoRA…" : `Downloading · ${Math.floor(downloadPercent)}%` : templateSummary(template)}</small></button>{templateNeedsDownload(template)? <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`}>diff --git a/src/lib/loras.ts b/src/lib/loras.tsindex 755d871..1c29944 100644--- a/src/lib/loras.ts+++ b/src/lib/loras.ts@@ -8,6 +8,7 @@ export interface Lora {url?: string;stepOverride?: number;multiplier?: number;+ needsPreparation?: boolean;}export interface TemplateLora { loraId: string; enabled: boolean; strength: number }export const TAOMATE_LORA: Lora = {@@ -42,6 +43,7 @@ export function loadLoras(): Lora[] {|| typeof entry.name !== "string" || !entry.name.trim() || typeof entry.path !== "string") return [];ids.add(entry.id);return [{ id: entry.id, name: entry.name, path: entry.path,+ ...(entry.needsPreparation === true ? { needsPreparation: true } : {}),...(typeof entry.url === "string" && /^https?:\/\//i.test(entry.url) ? { url: entry.url } : {}),...(isLoraMultiplier(entry.multiplier) ? { multiplier: entry.multiplier } : {}),...(isLoraStepOverride(entry.stepOverride) ? { stepOverride: entry.stepOverride }@@ -83,7 +85,7 @@ export function normalizeTemplateLoras(value: unknown): TemplateLora[] {export function downloadableTemplateLoras(selection: TemplateLora[] = []): Lora[] {const active = new Set(selection.filter((entry) => entry.enabled && entry.strength !== 0).map((entry) => entry.loraId));return loadLoras().filter((lora) => active.has(lora.id) && lora.multiplier !== 0 && lora.url- && (!lora.path.trim() || /^https?:\/\//i.test(lora.path)));+ && (lora.needsPreparation || !lora.path.trim() || /^https?:\/\//i.test(lora.path)));}export function resolveTemplateLoras(selection: TemplateLora[] = []) {@@ -93,6 +95,7 @@ export function resolveTemplateLoras(selection: TemplateLora[] = []) {const strength = effectiveLoraStrength(entry, lora);if (!isLoraMultiplier(strength)) throw new Error(`Combined multiplier for LoRA ${lora?.name ?? entry.loraId} is outside the supported range.`);if (strength === 0) return [];+ 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 --git a/src/lib/weightDownloads.test.ts b/src/lib/weightDownloads.test.tsindex 377603e..e489388 100644--- a/src/lib/weightDownloads.test.ts+++ b/src/lib/weightDownloads.test.ts@@ -1,6 +1,6 @@// @vitest-environment jsdomimport { invoke } from "@tauri-apps/api/core";-import { cancelWeightDownload, downloadLora, removeLora, refreshDownloadedLoras, retryWeightDownload } from "./weightDownloads";+import { cancelWeightDownload, downloadLora, prepareLora, removeLora, refreshDownloadedLoras, retryWeightDownload } from "./weightDownloads";import { LIGHTX2V_TURBO_LORA, 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";@@ -13,6 +13,54 @@ const files = new Set<string>();const source = (url: string, gpuModel = "", minVramGb = 0): WeightSource => ({ url, gpuModel, minVramGb });const saved = () => loadGeneratorTemplateSettings().templates.find((template) => template.id === "minimax-h3-original")!;+it("prepares downloaded adapters before publishing them and does not offer fake cancellation", async () => {+ const normal = vi.mocked(invoke).getMockImplementation()!;+ let finish!: () => void;+ vi.mocked(invoke).mockImplementation(async (command, args) => command === "prepare_lora"+ ? new Promise<void>((resolve) => { finish = resolve; }) : normal(command, args));+ const pending = downloadLora(TURBO_LORA.id);+ await vi.waitFor(() => expect(getWeightDownloadState()?.phase).toBe("preparing"));+ expect(loadLoras().find(({ id }) => id === TURBO_LORA.id)).toMatchObject({ path: "", needsPreparation: true });+ await cancelWeightDownload();+ expect(invoke).not.toHaveBeenCalledWith("cancel_weight_download", expect.anything());+ expect(invoke).toHaveBeenCalledWith("prepare_lora", { path: expect.stringContaining(".safetensors"), allowDownload: true });+ expect(getWeightDownloadState()?.active).toBe(true);+ finish(); await pending;+ expect(loadLoras().find(({ id }) => id === TURBO_LORA.id)?.needsPreparation).toBeUndefined();+ expect(getWeightDownloadState()).toMatchObject({ active: false, completed: 1, error: null });+});++it("keeps failed preparation unavailable across discovery and retries it", async () => {+ const normal = vi.mocked(invoke).getMockImplementation()!;+ vi.mocked(invoke).mockImplementation(async (command, args) => {+ if (command === "prepare_lora") throw new Error("Grid missing");+ if (command === "find_downloaded_weights") return { [TURBO_LORA.url!]: "C:/raw-adapter.safetensors" };+ return normal(command, args);+ });+ await downloadLora(TURBO_LORA.id);+ await refreshDownloadedLoras();+ expect(loadLoras().find(({ id }) => id === TURBO_LORA.id)).toMatchObject({ path: "", needsPreparation: true });+ expect(getWeightDownloadState()).toMatchObject({ active: false, phase: "preparing", error: "Grid missing" });+ expect(() => engineProviderSetting(createGeneratorTemplate().paths, undefined, "sage2", [{ loraId: TURBO_LORA.id, enabled: true, strength: 1 }])).toThrow(/Prepare LoRA/);+ vi.mocked(invoke).mockImplementation(normal);+ await retryWeightDownload();+ expect(getWeightDownloadState()).toMatchObject({ active: false, completed: 1, error: null });+ expect(loadLoras().find(({ id }) => id === TURBO_LORA.id)?.path).not.toBe("");+});++it("repairs local adapters with local-only assets and preserves that choice on retry", async () => {+ const lora = { id: "local", name: "Style", path: "D:/style.safetensors" };+ saveLoras([lora]);+ vi.mocked(invoke).mockRejectedValueOnce(new Error("Companion missing"));+ await expect(prepareLora(lora, false)).rejects.toThrow("Companion missing");+ expect(loadLoras().find(({ id }) => id === lora.id)?.needsPreparation).toBe(true);+ await retryWeightDownload();+ expect(invoke).toHaveBeenLastCalledWith("prepare_lora", { path: lora.path, allowDownload: false });+ expect(loadLoras().find(({ id }) => id === lora.id)).toMatchObject(lora);+ expect(loadLoras().find(({ id }) => id === lora.id)?.needsPreparation).toBeUndefined();+ expect(invoke).not.toHaveBeenCalledWith("download_weight", expect.anything());+});+it("downloads Animate with its transformer and four-step distillation adapter", async () => {await downloadTemplateWeights("viggle-animate");const template = loadGeneratorTemplateSettings().templates.find(({ id }) => id === "viggle-animate")!;diff --git a/src/lib/weightDownloads.ts b/src/lib/weightDownloads.tsindex 47beaf5..bb2e6eb 100644--- a/src/lib/weightDownloads.ts+++ b/src/lib/weightDownloads.ts@@ -19,6 +19,9 @@ export interface DownloadState {files: number;error: string | null;active: boolean;+ phase?: "preparing";+ preparePath?: string;+ allowDownload?: boolean;}let state: DownloadState | null = null;let requestId: string | null = null;@@ -193,6 +196,8 @@ export async function downloadTemplateWeights(templateId: string): Promise<void>}export async function cancelWeightDownload() {+ // The DLL preparation call is synchronous and has no cancellation API.+ if (state?.active && state.phase === "preparing") return;cancelled = true;if (requestId) await invoke("cancel_weight_download", { requestId });}@@ -201,7 +206,35 @@ async function transferLora(lora: Lora): Promise<void> {requestId = crypto.randomUUID();const path = await invoke<string>("download_weight", { requestId, url: lora.url });if (!path || isDownloadUrl(path)) throw new Error("The download did not return a local file.");- saveLoras(loadLoras().map((entry) => entry.id === lora.id && entry.url === lora.url && entry.path === lora.path ? { ...entry, path } : entry));+ if (cancelled) throw new Error("Download cancelled.");+ saveLoras(loadLoras().map((entry) => entry.id === lora.id && entry.path === lora.path ? { ...entry, needsPreparation: true } : entry));+ await prepareLoraFile(path, true);+ saveLoras(loadLoras().map((entry) => entry.id === lora.id && entry.url === lora.url && entry.path === lora.path ? { ...entry, path, needsPreparation: undefined } : entry));+ publish({ ...state!, phase: undefined });+}++async function prepareLoraFile(path: string, allowDownload: boolean): Promise<void> {+ requestId = null;+ publish({ ...state!, phase: "preparing", downloaded: 0, total: null });+ await invoke("prepare_lora", { path, allowDownload });+}++/** Explicit setup for a local or previously downloaded adapter. */+export async function prepareLora(lora: Pick<Lora, "id" | "name" | "path">, allowDownload = true): Promise<void> {+ if (!isTauri()) throw new Error("LoRA preparation is available in the desktop app.");+ if (state?.active) throw new Error("Wait for the current download or preparation to finish.");+ publish({ templateId: `lora:${lora.id}`, loraId: lora.id, name: lora.name, field: null,+ downloaded: 0, total: null, completed: 0, files: 1, error: null, active: true,+ preparePath: lora.path, allowDownload, phase: "preparing" });+ try {+ saveLoras(loadLoras().map((entry) => entry.id === lora.id && entry.path === lora.path ? { ...entry, needsPreparation: true } : entry));+ await prepareLoraFile(lora.path, allowDownload);+ saveLoras(loadLoras().map((entry) => entry.id === lora.id && entry.path === lora.path ? { ...entry, needsPreparation: undefined } : entry));+ publish({ ...state!, active: false, completed: 1 });+ } catch (reason) {+ publish({ ...state!, active: false, error: reason instanceof Error ? reason.message : String(reason) });+ throw reason;+ }}/** Uses the same native transfer, storage, cancellation and app-wide lock as weights. */@@ -226,12 +259,15 @@ export async function downloadLora(loraId: string): Promise<void> {}export function retryWeightDownload(): Promise<void> {+ if (state?.preparePath && state.loraId) return prepareLora({ id: state.loraId, name: state.name ?? "LoRA", path: state.preparePath }, state.allowDownload)+ .catch(() => undefined); // The shared status retains the error for another retry.return state?.loraId ? downloadLora(state.loraId) : state ? downloadTemplateWeights(state.templateId) : Promise.resolve();}let loraRefreshPending: Promise<void> | null = null;export function refreshDownloadedLoras(): Promise<void> {if (!isTauri()) return Promise.resolve();+ if (state?.active) return Promise.resolve();if (loraRefreshPending) return loraRefreshPending;loraRefreshPending = (async () => {const before = loadLoras().filter((entry) => entry.url);@@ -244,6 +280,7 @@ export function refreshDownloadedLoras(): Promise<void> {]);let changed = false;const loras = loadLoras().map((entry) => {+ if (entry.needsPreparation) return entry;if (!entry.url || !before.some((old) => old.id === entry.id && old.url === entry.url && old.path === entry.path)) return entry;if (entry.path.trim() && !isDownloadUrl(entry.path) && exists?.[entry.path] !== false) return entry;const path = found?.[entry.url] || "";diff --git a/src/styles/loras.css b/src/styles/loras.cssindex 82a5cc4..8ce9968 100644--- a/src/styles/loras.css+++ b/src/styles/loras.css@@ -1,4 +1,5 @@-.generator-template-item.lora-library-item { grid-template-columns: minmax(0, 1fr) var(--control-sm); }+.generator-template-item.lora-library-item { grid-template-columns: minmax(0, 1fr) var(--control-sm) var(--control-sm); }+.lora-manual { min-width: 0; padding: 0; border: 0; }.lora-manual, .template-loras { display: grid; gap: var(--space-3); margin-top: var(--space-4); }.lora-manual > label { display: grid; gap: var(--space-2); }.lora-manual input:not([type="checkbox"]), .template-loras select, .template-loras input[type="number"] {