AI media harness for planning, generating, and editing locally
TypeScript
Add LoRA library and ordered template adapters
Bittib0d094fecd8a
diff --git a/docs/generator-weights.md b/docs/generator-weights.mdindex e2af00e..089255b 100644--- a/docs/generator-weights.md+++ b/docs/generator-weights.md@@ -1,5 +1,31 @@# Generator weights+## LoRAs++Settings → Generators includes a separate **LoRAs** library. **TaoMate 3-Step**+downloads [TaoMate-H3-3step-ComfyUI.safetensors](https://huggingface.co/CZMartin22/TaoMate-H3-3step-ComfyUI/resolve/main/TaoMate-H3-3step-ComfyUI.safetensors).+It uses the same managed `weights` location, background transfer, progress,+cancellation, retry, and Work Queue controls as model weights. Downloads are+serialized with weight downloads, and video generation can continue while downloading.+Missing managed files become downloadable again. Removing a downloaded LoRA+deletes its managed file; **Add LoRA manually** links a named local file, and+removing that library entry leaves the original file untouched.++Open a generator template and use its **LoRAs** section to add available adapters.+Enable any number, adjust their strengths, and move them up or down. Disabled+adapters and strength-zero entries are omitted; the remaining paths and strengths+are passed to SlopFab in displayed order on both CUDA and Vulkan. SlopFab combines+adapter updates by summing them. Negative strengths are supported. An active+missing adapter causes an error rather than silently changing the generation.++TaoMate 3-Step automatically selects the DLL's dedicated three-evaluation schedule,+overriding the ordinary scene step count. Manually added TaoMate files can select+the same schedule. Other LoRAs use the template's ordinary generation settings.+The library and per-template selections persist on this computer; adapter paths+are injected into runtime requests and are not saved into portable project files.++## Model weights+In Settings → Generator, edit a template and enter local paths or HTTP/HTTPSdownload URLs. Hugging Face `blob` links are converted to direct file downloads.The bundled **First/Last Frame** (formerly **Minimax H3 Original**),diff --git a/src-tauri/src/slopfab.rs b/src-tauri/src/slopfab.rsindex 19b0504..506dd57 100644--- a/src-tauri/src/slopfab.rs+++ b/src-tauri/src/slopfab.rs@@ -444,12 +444,20 @@ struct QueueItem {cancel: Arc<AtomicBool>,}+#[derive(Debug, Clone, Deserialize)]+struct LoraAdapter {+ path: String,+ strength: f32,+}+#[derive(Clone)]struct Configuration {dll_path: PathBuf,vulkan: bool,attention: &'static str,models: [(i32, &'static str, Option<PathBuf>); 5],+ loras: Result<Vec<LoraAdapter>, String>,+ taomate_schedule: bool,}impl Configuration {@@ -487,6 +495,13 @@ impl Configuration {(3, "videoVae", option("videoVae")),(4, "audioVae", option("audioVae")),],+ loras: match slopfab.and_then(|setting| setting.options.get("loras")) {+ None => Ok(Vec::new()),+ Some(ProviderOption::String(value)) => serde_json::from_str::<Vec<LoraAdapter>>(value)+ .map_err(|error| format!("Invalid LoRA settings: {error}")),+ _ => Err("LoRA settings must be a JSON array of paths and strengths.".into()),+ },+ taomate_schedule: string_option("schedule") == Some("taomate-3step"),}}@@ -513,7 +528,9 @@ impl Configuration {}).collect::<Vec<_>>().join(";");- format!("slopfab={version}|platform={}|attention={}|{models}", platform.label(), self.attention)+ let adapters = self.loras.as_ref().map(|loras| loras.iter()+ .map(|lora| format!("{}@{}", lora.path, lora.strength)).collect::<Vec<_>>().join(";")).unwrap_or_default();+ format!("slopfab={version}|platform={}|attention={}|{models}|loras={adapters}|taomate={}", platform.label(), self.attention, self.taomate_schedule)}}@@ -661,6 +678,17 @@ fn configure_request(api.set_inference_backend(handle, platform.backend())?;api.set_attention(handle, configuration.attention)?;api.set_verbose(handle, false)?;+ for lora in configuration.loras.as_ref().map_err(Clone::clone)? {+ if lora.path.trim().is_empty() || !lora.strength.is_finite() {+ return Err("LoRA paths must be nonempty and strengths finite.".into());+ }+ if lora.strength == 0.0 { continue; }+ if include_models && !Path::new(&lora.path).is_file() {+ return Err(format!("LoRA file is missing: {}", lora.path));+ }+ api.add_lora(handle, Path::new(&lora.path), lora.strength)?;+ }+ if configuration.taomate_schedule { api.set_taomate_schedule(handle)?; }if include_models {api.set_reuse_models(handle, true)?;for (id, _, path) in &configuration.models {@@ -962,6 +990,8 @@ pub fn generate_reference_icon_batch(};let configuration = Configuration {dll_path: batch.dll_path.clone(),+ loras: Ok(Vec::new()),+ taomate_schedule: false,vulkan: backend == ComputePlatform::Vulkan,attention: "sage2",models: [@@ -1248,6 +1278,8 @@ mod ffi {set_steps: unsafe extern "C" fn(*mut Request, i32) -> i32,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>,+ set_schedule: Option<unsafe extern "C" fn(*mut Request, 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,set_inference_backend: unsafe extern "C" fn(*mut Request, i32) -> i32,@@ -1342,6 +1374,12 @@ mod ffi {"slopfab_request_add_reference_image",unsafe extern "C" fn(*mut Request, *const c_char) -> i32),+ add_lora: library+ .get::<unsafe extern "C" fn(*mut Request, *const c_char, f32) -> i32>(b"slopfab_request_add_lora\0")+ .ok().map(|symbol| *symbol),+ set_schedule: library+ .get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(b"slopfab_request_set_schedule\0")+ .ok().map(|symbol| *symbol),set_attention: symbol!("slopfab_request_set_attention",unsafe extern "C" fn(*mut Request, *const c_char) -> i32@@ -1498,6 +1536,15 @@ mod ffi {let v = path_cstring(path)?;self.error(unsafe { (self.add_reference)(r, v.as_ptr()) })}+ pub fn add_lora(&self, r: *mut Request, path: &Path, strength: f32) -> Result<(), String> {+ let add = self.add_lora.ok_or("This slopfab.dll does not support LoRAs. Update the DLL or disable the selected LoRAs.")?;+ let path = path_cstring(path)?;+ self.error(unsafe { add(r, path.as_ptr(), strength) })+ }+ pub fn set_taomate_schedule(&self, r: *mut Request) -> Result<(), String> {+ let set = self.set_schedule.ok_or("This slopfab.dll does not support the TaoMate three-step schedule.")?;+ self.error(unsafe { set(r, 1) })+ }pub fn resolve(&self, request: *mut Request) -> Result<Plan, String> {let mut value = Plan {canvas_width: 0,@@ -1626,6 +1673,50 @@ mod ffi {#[cfg(test)]mod tests {use super::*;+ #[test]+ fn ordered_loras_and_taomate_schedule_reach_cuda_and_vulkan_requests() {+ let root = tempfile::tempdir().unwrap();+ let paths = [root.path().join("style.safetensors"), root.path().join("TaoMate.safetensors")];+ for path in &paths { std::fs::write(path, b"planning does not load weights").unwrap(); }+ let settings = BTreeMap::from([("slopfab".into(), ProviderSetting {+ enabled: true, model: None,+ options: BTreeMap::from([+ ("loras".into(), ProviderOption::String(serde_json::json!([+ { "path": paths[0], "strength": -0.5 },+ { "path": paths[1], "strength": 1.0 },+ ]).to_string())),+ ("schedule".into(), ProviderOption::String("taomate-3step".into())),+ ]),+ })]);+ let configuration = Configuration::from_settings(&settings);+ let api = ffi::Api::load(&configuration.dll_path).unwrap();+ let request = GenerationRequest {+ job_id: "lora-test".into(), prompt: "A quiet harbour.".into(),+ frames: 120, still_image: false, steps: 20, seed: 1,+ canvas_width: 736, canvas_height: 416,+ reference_paths: Vec::new(), reference_video_ids: Vec::new(),+ };+ for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {+ for include_models in [false, true] {+ let handle = RequestHandle::new(&api).unwrap();+ configure_request(&api, handle.0, &request, &configuration, platform, include_models).unwrap();+ assert_eq!(api.resolve(handle.0).unwrap().num_model_evaluations, 3);+ let description = api.describe(handle.0).unwrap();+ assert!(description.contains("taomate-3step"));+ assert!(description.find("style.safetensors").unwrap() < description.find("TaoMate.safetensors").unwrap());+ assert!(description.contains("strength -0.5"));+ }+ }+ let invalid = BTreeMap::from([("slopfab".into(), ProviderSetting {+ enabled: true, model: None,+ options: BTreeMap::from([("loras".into(), ProviderOption::String("invalid JSON".into()))]),+ })]);+ assert!(Configuration::from_settings(&invalid).loras.is_err());+ std::fs::remove_file(&paths[0]).unwrap();+ let handle = RequestHandle::new(&api).unwrap();+ assert!(configure_request(&api, handle.0, &request, &configuration, ComputePlatform::Vulkan, true).unwrap_err().contains("LoRA file is missing"));+ }+#[test]fn vulkan_video_references_prepare_and_attach_for_planning_and_generation() {let settings = BTreeMap::from([("slopfab".into(), ProviderSetting {diff --git a/src/components/LoraSettings.tsx b/src/components/LoraSettings.tsxnew file mode 100644index 0000000..8cf2404--- /dev/null+++ b/src/components/LoraSettings.tsx@@ -0,0 +1,103 @@+import { ArrowDown, ArrowUp, Download, FolderSearch, Layers, Plus, Trash2 } from "lucide-react";+import "../styles/loras.css";+import { useEffect, useState, useSyncExternalStore } from "react";+import { loadLoras, saveLoras, subscribeLoras, type TemplateLora } from "../lib/loras";+import { isTauri } from "../lib/persistence";+import { chooseEnginePath } from "../lib/runtime";+import { downloadLora, getWeightDownloadState, refreshDownloadedLoras, removeLora, subscribeWeightDownloads, weightDownloadProgress } from "../lib/weightDownloads";++function useLoras() {+ const [loras, setLoras] = useState(loadLoras);+ useEffect(() => subscribeLoras(() => setLoras(loadLoras())), []);+ return loras;+}++export function LoraLibrary() {+ const loras = useLoras();+ const download = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);+ const [adding, setAdding] = useState(false);+ const [name, setName] = useState("");+ const [path, setPath] = useState("");+ const [taomate, setTaomate] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const desktop = isTauri();+ useEffect(() => {+ const refresh = () => { void refreshDownloadedLoras().catch((reason) => setError(String(reason))); };+ refresh();+ window.addEventListener("focus", refresh);+ const timer = window.setInterval(refresh, 5000);+ return () => { window.removeEventListener("focus", refresh); window.clearInterval(timer); };+ }, []);+ const browse = async () => {+ try {+ const picked = await chooseEnginePath({ id: "transformer", label: "LoRA", hint: "", directory: false, extensions: ["safetensors"], required: false });+ if (!picked) return;+ setPath(picked);+ if (!name.trim()) setName(picked.split(/[\\/]/).pop()!.replace(/\.safetensors$/i, ""));+ setTaomate(/taomate/i.test(picked));+ } catch (reason) { setError(String(reason)); }+ };+ const add = () => {+ if (!name.trim() || !path.trim()) return;+ if (!/^(?:[a-z]:[\\/]|\\\\|\/)/i.test(path.trim()) || path.includes("\0")) {+ setError("Choose a local LoRA file using its absolute path."); return;+ }+ try {+ saveLoras([...loadLoras(), { id: `lora-${crypto.randomUUID()}`, name: name.trim(), path: path.trim(), ...(taomate ? { schedule: "taomate-3step" as const } : {}) }]);+ setAdding(false); setName(""); setPath(""); setTaomate(false); setError(null);+ } catch (reason) { setError(String(reason)); }+ };+ return <section className="generator-templates" aria-labelledby="loras-heading">+ <header><div><h2 id="loras-heading">LoRAs</h2><p>Download adapters or add local files, then activate them in a generator template.</p></div>+ <button className="secondary-button" type="button" onClick={() => setAdding(!adding)}><Plus size={16} /> Add LoRA manually</button></header>+ <div className="generator-template-list" role="list" aria-label="LoRAs">+ {loras.map((lora) => <div className="generator-template-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)}%` }} />}+ <div className="generator-template-item__open"><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></div>+ {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>)}+ </div>+ {adding && <div className="lora-manual">+ <label>Name<input aria-label="LoRA name" 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); setTaomate(/taomate/i.test(event.target.value)); }} placeholder="Absolute path to a .safetensors file" />+ <button className="secondary-button" type="button" disabled={!desktop} onClick={() => void browse()}><FolderSearch size={16} /> Browse</button></div></label>+ <label className="lora-toggle"><input type="checkbox" checked={taomate} onChange={(event) => setTaomate(event.target.checked)} /> Use TaoMate three-step schedule</label>+ <p>The file stays in its current location.</p>+ <button className="secondary-button" type="button" disabled={!name.trim() || !path.trim()} onClick={add}>Add local LoRA</button>+ </div>}+ {error && <p role="alert">{error}</p>}+ </section>;+}++export function TemplateLorasEditor({ value, onChange }: { value: TemplateLora[]; onChange: (value: TemplateLora[]) => void }) {+ const library = useLoras();+ const available = library.filter((entry) => entry.path && !value.some(({ loraId }) => loraId === entry.id));+ const update = (index: number, patch: Partial<TemplateLora>) => onChange(value.map((entry, i) => i === index ? { ...entry, ...patch } : entry));+ const move = (index: number, delta: number) => {+ const next = [...value];+ [next[index], next[index + delta]] = [next[index + delta], next[index]];+ onChange(next);+ };+ return <section className="template-loras" aria-labelledby="template-loras-heading">+ <h3 id="template-loras-heading">LoRAs <small>{value.filter((entry) => entry.enabled && entry.strength !== 0).length} active</small></h3>+ <p>Enable any number of adapters and arrange their order. Strength 0 disables an adapter.</p>+ {value.map((entry, index) => {+ const lora = library.find(({ id }) => id === entry.loraId);+ const name = lora?.name ?? "Missing LoRA";+ return <div className="template-lora-row" key={entry.loraId}>+ <span>{index + 1}.</span>+ <label className="lora-toggle"><input type="checkbox" checked={entry.enabled} aria-label={`Enable ${name}`} onChange={(event) => update(index, { enabled: event.target.checked })} /> {name}{!lora?.path && " (file unavailable)"}</label>+ <label>Strength<input type="number" step="0.1" aria-label={`${name} strength`} value={entry.strength} onChange={(event) => { const strength = Number(event.target.value); if (event.target.value && Number.isFinite(strength)) update(index, { strength }); }} /></label>+ <button className="icon-button" type="button" aria-label={`Move ${name} up`} disabled={index === 0} onClick={() => move(index, -1)}><ArrowUp size={15} /></button>+ <button className="icon-button" type="button" aria-label={`Move ${name} down`} disabled={index === value.length - 1} onClick={() => move(index, 1)}><ArrowDown size={15} /></button>+ <button className="icon-button" type="button" aria-label={`Deactivate and remove ${name}`} onClick={() => onChange(value.filter((_, i) => i !== index))}><Trash2 size={15} /></button>+ </div>;+ })}+ <select aria-label="Add LoRA to generator" value="" disabled={!available.length} onChange={(event) => { if (event.target.value) onChange([...value, { loraId: event.target.value, enabled: true, strength: 1 }]); }}>+ <option value="">{available.length ? "Add an available LoRA…" : "Download or add a LoRA in Generators settings"}</option>+ {available.map((lora) => <option value={lora.id} key={lora.id}>{lora.name}</option>)}+ </select>+ {value.some((entry) => entry.enabled && entry.strength !== 0 && library.find(({ id }) => id === entry.loraId)?.schedule === "taomate-3step") && <p>TaoMate uses its three-step schedule, overriding the scene's step count.</p>}+ </section>;+}diff --git a/src/components/SettingsView.downloads.test.tsx b/src/components/SettingsView.downloads.test.tsxindex e24100e..41ee518 100644--- a/src/components/SettingsView.downloads.test.tsx+++ b/src/components/SettingsView.downloads.test.tsx@@ -9,6 +9,7 @@ import { loadGeneratorTemplateSettings } from "../lib/settings";import { getWeightDownloadState } from "../lib/weightDownloads";import { WorkQueuePanel } from "./WorkQueuePanel";import { WorkQueue } from "../lib/workQueue";+import { loadLoras, TAOMATE_LORA } from "../lib/loras";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));@@ -30,6 +31,60 @@ beforeEach(() => {});afterEach(() => { cleanup(); delete (window as Window & { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__; });+it("downloads TaoMate and persists manual adapters, activation, strength and order per template", async () => {+ const settings = render(<SettingsView onClose={() => undefined} />);+ fireEvent.click(screen.getByRole("button", { name: "Download LoRA TaoMate 3-Step" }));+ await waitFor(() => expect(loadLoras()[0].path).not.toBe(""));+ fireEvent.click(screen.getByRole("button", { name: "Add LoRA manually" }));+ fireEvent.change(screen.getByLabelText("LoRA name"), { target: { value: "My style" } });+ fireEvent.change(screen.getByLabelText("LoRA path"), { target: { value: "D:/models/style.safetensors" } });+ fireEvent.click(screen.getByRole("button", { name: "Add local LoRA" }));+ const manual = loadLoras().find(({ name }) => name === "My style")!;+ fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));+ fireEvent.change(screen.getByLabelText("Add LoRA to generator"), { target: { value: TAOMATE_LORA.id } });+ fireEvent.change(screen.getByLabelText("Add LoRA to generator"), { target: { value: manual.id } });+ fireEvent.change(screen.getByLabelText("My style strength"), { target: { value: "-0.5" } });+ fireEvent.click(screen.getByRole("button", { name: "Move My style up" }));+ fireEvent.click(screen.getByLabelText("Enable TaoMate 3-Step"));+ expect(screen.getByText("1 active")).toBeInTheDocument();+ const expected = [{ loraId: manual.id, enabled: true, strength: -0.5 }, { loraId: TAOMATE_LORA.id, enabled: false, strength: 1 }];+ expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "default")!.loras).toEqual(expected);+ settings.unmount();+ render(<SettingsView onClose={() => undefined} />);+ fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));+ expect(screen.getByLabelText("My style strength")).toHaveValue(-0.5);+ expect(screen.getByLabelText("Enable TaoMate 3-Step")).not.toBeChecked();+ expect(screen.getByRole("button", { name: "Move My style up" })).toBeDisabled();+});++it("keeps a LoRA download alive outside Settings, shows progress and cancels through Work Queue", async () => {+ let progress: (event: { payload: { requestId: string; downloaded: number; total: number | null } }) => void = () => undefined;+ vi.mocked(listen).mockImplementation((async (_name, callback) => { progress = callback as typeof progress; return () => undefined; }) as typeof listen);+ const normal = vi.mocked(invoke).getMockImplementation()!;+ let requestId = "";+ let rejectDownload: (reason: Error) => void = () => undefined;+ vi.mocked(invoke).mockImplementation(async (command, args) => {+ if (command === "download_weight") {+ requestId = (args as { requestId: string }).requestId;+ return new Promise((_resolve, reject) => { rejectDownload = reject; });+ }+ if (command === "cancel_weight_download") { rejectDownload(new Error("Download cancelled.")); return; }+ return normal(command, args);+ });+ const settings = render(<SettingsView onClose={() => undefined} />);+ fireEvent.click(screen.getByRole("button", { name: "Download LoRA TaoMate 3-Step" }));+ await waitFor(() => expect(requestId).not.toBe(""));+ expect(screen.getByRole("button", { name: "Download generator First/Last Frame" })).toBeDisabled();+ settings.unmount();+ render(<WorkQueuePanel queue={new WorkQueue()} items={[]} onClose={() => undefined} />);+ act(() => progress({ payload: { requestId, downloaded: 50, total: 100 } }));+ expect(screen.getByRole("progressbar", { name: "TaoMate 3-Step download progress" })).toHaveAttribute("value", "50");+ fireEvent.click(screen.getByRole("button", { name: "Cancel TaoMate 3-Step download" }));+ await waitFor(() => expect(getWeightDownloadState()).toMatchObject({ active: false, error: "Download cancelled." }));+ expect(loadLoras()[0].path).toBe("");+ expect(screen.getByRole("button", { name: "Retry download" })).toBeInTheDocument();+});+it("keeps downloading with Settings closed and restores progress in the template row and Work Queue", async () => {let progress: (event: { payload: { requestId: string; downloaded: number; total: number | null } }) => void = () => undefined;vi.mocked(listen).mockImplementation((async (_name, callback) => { progress = callback as typeof progress; return () => undefined; }) as typeof listen);diff --git a/src/components/SettingsView.test.tsx b/src/components/SettingsView.test.tsxindex 830013e..f6f0d13 100644--- a/src/components/SettingsView.test.tsx+++ b/src/components/SettingsView.test.tsx@@ -5,6 +5,7 @@ import { invoke } from "@tauri-apps/api/core";import { readFileSync } from "node:fs";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { SettingsView } from "./SettingsView";+import { loadGeneratorTemplateSettings } from "../lib/settings";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));@@ -225,7 +226,7 @@ describe("the settings screen", () => {it("creates a generator with 20 steps, edits it on its own page, and can make it the default", () => {open();expect(screen.queryByLabelText(/Transformer weights/)).toBeNull();- const nextGeneratorName = `Generator ${screen.getAllByRole("listitem").length + 1}`;+ const nextGeneratorName = `Generator ${loadGeneratorTemplateSettings().templates.length + 1}`;fireEvent.click(screen.getByRole("button", { name: "New generator" }));expect((screen.getByLabelText("Generator name") as HTMLInputElement).value).toBe(nextGeneratorName);expect((screen.getByLabelText("Generator default steps") as HTMLInputElement).value).toBe("20");diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsxindex 8e77159..7c3d7c1 100644--- a/src/components/SettingsView.tsx+++ b/src/components/SettingsView.tsx@@ -3,6 +3,8 @@ import { useCallback, useEffect, useRef, useState, useSyncExternalStore, type Reimport { revealDiagnosticLog } from "../lib/diagnostics";import { isTauri } from "../lib/persistence";import { WeightSourcesEditor } from "./WeightSourcesEditor";+import { LoraLibrary, TemplateLorasEditor } from "./LoraSettings";+import { retryWeightDownload } from "../lib/weightDownloads";import { cancelWeightDownload, downloadTemplateWeights, getWeightDownloadState, refreshDownloadedWeights, removeTemplateWeights, subscribeWeightDownloads, updateWeightPath, weightDownloadProgress } from "../lib/weightDownloads";import { chooseEnginePath, getAgentModels, getEngineStatus, type ModelStatus, type SlopfabStatus } from "../lib/runtime";import {@@ -290,12 +292,12 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onClconst probe = useCallback((paths?: EngineSettings) => {const revision = ++probeRevision.current;- void getEngineStatus(paths, selectedTemplate.attention).then((next) => {+ void getEngineStatus(paths, selectedTemplate.attention, selectedTemplate.loras ?? []).then((next) => {if (revision === probeRevision.current) setStatus(next);}).catch(() => {if (revision === probeRevision.current) setStatus(null);});- }, [selectedTemplate.attention]);+ }, [selectedTemplate.attention, selectedTemplate.loras]);/* Saved on every keystroke — there is no Save button here, so a half-typedpath must never be the reason generation is still broken after a restart.@@ -360,7 +362,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onClprobe({ ...EMPTY_ENGINE_SETTINGS });};- const updateTemplate = (updates: Partial<Pick<typeof selectedTemplate, "name" | "defaultSteps" | "attention">>) => {+ const updateTemplate = (updates: Partial<Pick<typeof selectedTemplate, "name" | "defaultSteps" | "attention" | "loras">>) => {setTemplateSettings((current) => {const next = {...current,@@ -523,7 +525,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl</div>))}</div>- </section>)}</> : <div className="generator-editor">+ </section>)}<LoraLibrary /></> : <div className="generator-editor"><header className="generator-editor__head"><div><h2 id="generator-editor-heading">Edit generator</h2>@@ -591,6 +593,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl</div>);})}+ <TemplateLorasEditor value={selectedTemplate.loras ?? []} onChange={(loras) => updateTemplate({ loras })} /><label className="generator-editor__advanced"><input type="checkbox" checked={showAdvancedOptions} onChange={(event) => setShowAdvancedOptions(event.target.checked)} /><span>Show advanced options</span>@@ -600,8 +603,9 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl</div>{tab === "engine" && downloadState && <div className="weight-download-status" role="status">- <span>{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>+ <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>}</div>}{tab === "engine" && editingTemplateId && <footer className="settings-view__foot">{/* Clearing the paths is an engine action, so it is only offereddiff --git a/src/components/WorkQueuePanel.tsx b/src/components/WorkQueuePanel.tsxindex 3d4f82e..495010b 100644--- a/src/components/WorkQueuePanel.tsx+++ b/src/components/WorkQueuePanel.tsx@@ -4,13 +4,13 @@ import { createPortal } from "react-dom";import { GENERATION_FRAME_RATE } from "../lib/project";import { isWorkActive, type WorkItem, type WorkQueue } from "../lib/workQueue";import { loadGeneratorTemplateSettings } from "../lib/settings";-import { cancelWeightDownload, downloadTemplateWeights, getWeightDownloadState, subscribeWeightDownloads, weightDownloadProgress } from "../lib/weightDownloads";+import { cancelWeightDownload, retryWeightDownload, getWeightDownloadState, subscribeWeightDownloads, weightDownloadProgress } from "../lib/weightDownloads";export function WorkQueuePanel({ queue, items, onClose }: { queue: WorkQueue; items: readonly WorkItem[]; onClose: () => void }) {// Downloads are observed here, never enqueued in the GPU generation scheduler.const download = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);const [downloadError, setDownloadError] = useState<string | null>(null);- const downloadName = download ? loadGeneratorTemplateSettings().templates.find((template) => template.id === download.templateId)?.name ?? "Generator weights" : "";+ const downloadName = download ? download.name ?? loadGeneratorTemplateSettings().templates.find((template) => template.id === download.templateId)?.name ?? "Generator weights" : "";const panel = useRef<HTMLElement>(null);const close = useRef<HTMLButtonElement>(null);useEffect(() => {@@ -62,7 +62,7 @@ export function WorkQueuePanel({ queue, items, onClose }: { queue: WorkQueue; it<span className={`work-queue__state work-queue__state--${download.active ? "preparing" : download.error ? "failed" : "completed"}`} aria-hidden="true">{download.active ? <Download size={17} /> : download.error ? <TriangleAlert size={17} /> : <Check size={17} />}</span>- <div><strong>{downloadName}</strong><span>Weight download</span></div>+ <div><strong>{downloadName}</strong><span>{download.loraId ? "LoRA download" : "Weight download"}</span></div>{download.active && <button type="button" className="icon-button" aria-label={`Cancel ${downloadName} download`} onClick={() => {setDownloadError(null);void cancelWeightDownload().catch((reason) => setDownloadError(String(reason)));@@ -73,7 +73,7 @@ export function WorkQueuePanel({ queue, items, onClose }: { queue: WorkQueue; it</div>{download.active && <progress max={100} value={weightDownloadProgress(download)} aria-label={`${downloadName} download progress`} />}{download.active && <p className="work-queue__settings">Generations can continue during this download.</p>}- {download.error && <button type="button" className="secondary-button" onClick={() => { setDownloadError(null); void downloadTemplateWeights(download.templateId); }}>Retry download</button>}+ {download.error && <button type="button" className="secondary-button" onClick={() => { setDownloadError(null); void retryWeightDownload(); }}>Retry download</button>}{downloadError && <p className="work-queue__error" role="alert">{downloadError}</p>}</li></ul></section>}{upcoming.length > 0 && <section aria-label="Upcoming work"><h3>Up next <span>{upcoming.length}</span></h3><ul>{upcoming.map(row)}</ul></section>}diff --git a/src/components/workspace/GeneratorView.test.tsx b/src/components/workspace/GeneratorView.test.tsxindex 3655e9d..3bdac3e 100644--- a/src/components/workspace/GeneratorView.test.tsx+++ b/src/components/workspace/GeneratorView.test.tsx@@ -424,7 +424,7 @@ describe("Generator scene controls", () => {fireEvent.click(screen.getByRole("option", { name: "Fast draft" }));await waitFor(() => expect(document.querySelector(".generator-runtime--modelsMissing > i")).not.toBeNull());- expect(getEngineStatus).toHaveBeenCalledWith(expect.objectContaining({ transformer: "draft.safetensors" }));+ expect(getEngineStatus).toHaveBeenCalledWith(expect.objectContaining({ transformer: "draft.safetensors" }), "sage2", []);expect(JSON.parse(localStorage.getItem("slopus.generator-templates.v1")!).defaultTemplateId).toBe("draft");expect(screen.queryByText("Video model files missing")).not.toBeInTheDocument();expect(template.closest(".generator-runtime--modelsMissing")).not.toBeNull();diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsxindex 7136ef6..9269f3a 100644--- a/src/components/workspace/GeneratorView.tsx+++ b/src/components/workspace/GeneratorView.tsx@@ -1,4 +1,6 @@import type { GenerationSubmission } from "../../lib/workQueue";+import { loadLoras, subscribeLoras } from "../../lib/loras";+import { refreshDownloadedLoras } from "../../lib/weightDownloads";import { usableVideoReferences } from "../../lib/project";import { ChevronDown, Plus, Square, Trash2, WandSparkles } from "lucide-react";import { invoke } from "@tauri-apps/api/core";@@ -53,7 +55,9 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst [generatorRuntime, setGeneratorRuntime] = useState<SlopfabStatus | null>(runtime);const [runtimeError, setRuntimeError] = useState<string | null>(null);const runtimeProbe = useRef(0);- const templateKey = JSON.stringify([selectedTemplate.id, selectedTemplate.paths, selectedTemplate.attention]);+ const [loraLibrary, setLoraLibrary] = useState(loadLoras);+ useEffect(() => subscribeLoras(() => setLoraLibrary(loadLoras())), []);+ const templateKey = JSON.stringify([selectedTemplate.id, selectedTemplate.paths, selectedTemplate.attention, selectedTemplate.loras, loraLibrary]);const probedTemplate = useRef(templateKey);const configRef = useRef(config);configRef.current = config;@@ -79,7 +83,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCouseEffect(() => () => { runtimeProbe.current += 1; }, []);useEffect(() => subscribeGeneratorTemplates(() => setTemplateSettings(loadGeneratorTemplateSettings())), []);useEffect(() => {- const refresh = () => { void refreshDownloadedWeights().catch((reason) => setRuntimeError(String(reason))); };+ const refresh = () => { void Promise.all([refreshDownloadedWeights(), refreshDownloadedLoras()]).catch((reason) => setRuntimeError(String(reason))); };refresh();window.addEventListener("focus", refresh);const timer = window.setInterval(refresh, 5000);@@ -101,7 +105,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCosetRuntimeError(null);const probe = ++runtimeProbe.current;if (!selectedTemplate.id) return;- void getEngineStatus(selectedTemplate.paths).then((status) => {+ void getEngineStatus(selectedTemplate.paths, selectedTemplate.attention, selectedTemplate.loras ?? []).then((status) => {if (probe !== runtimeProbe.current) return;setGeneratorRuntime(status);onRuntimeChange?.(status);@@ -330,7 +334,8 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst request = requestFor(job);return { job, request, snapshot: snapshotFor(job, request) };});- onGenerate?.(submissions);+ try { onGenerate?.(submissions); }+ catch (reason) { setRuntimeError(reason instanceof Error ? reason.message : String(reason)); }};/* A scene now starts EMPTY. There is no box that turns a sentence into adiff --git a/src/lib/loras.test.ts b/src/lib/loras.test.tsnew file mode 100644index 0000000..de968cb--- /dev/null+++ b/src/lib/loras.test.ts@@ -0,0 +1,40 @@+// @vitest-environment jsdom+import { beforeEach, expect, it } from "vitest";+import { loadLoras, saveLoras, TAOMATE_LORA } from "./loras";+import { createGeneratorTemplate, engineProviderSetting, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, withEngineSettings } from "./settings";+import { createProjectConfig } from "./project";++beforeEach(() => localStorage.clear());++it("starts with only TaoMate and preserves the local library", () => {+ expect(loadLoras()).toEqual([TAOMATE_LORA]);+ saveLoras([{ ...TAOMATE_LORA, path: "C:/weights/TaoMate.safetensors" }, { id: "style", name: "Style", path: "D:/style.safetensors" }]);+ expect(loadLoras().map(({ name }) => name)).toEqual(["TaoMate 3-Step", "Style"]);+});++it("round-trips template order, enabled flags and strengths, and sends only active adapters", () => {+ saveLoras([{ ...TAOMATE_LORA, path: "C:/weights/TaoMate.safetensors" }, { id: "style", name: "Style", path: "D:/style.safetensors" }, { id: "off", name: "Off", path: "" }]);+ const template = { ...createGeneratorTemplate(), loras: [+ { loraId: "style", enabled: true, strength: -0.5 },+ { loraId: "off", enabled: false, strength: 1 },+ { loraId: TAOMATE_LORA.id, enabled: true, strength: 1 },+ ] };+ saveGeneratorTemplateSettings({ templates: [template], defaultTemplateId: template.id, catalogVersion: 4 });+ expect(loadGeneratorTemplateSettings().templates[0].loras).toEqual(template.loras);+ const config = createProjectConfig({ name: "Test", prompt: "", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 10 });+ const runtime = withEngineSettings(config);+ expect(JSON.parse(runtime.providerSettings.slopfab.options.loras as string)).toEqual([+ { path: "D:/style.safetensors", strength: -0.5 }, { path: "C:/weights/TaoMate.safetensors", strength: 1 },+ ]);+ expect(runtime.providerSettings.slopfab.options.schedule).toBe("taomate-3step");+ expect(config.providerSettings).toEqual({});+ const without = engineProviderSetting(template.paths, runtime.providerSettings.slopfab, "sage2", []);+ expect(without.options).not.toHaveProperty("loras");+ expect(without.options).not.toHaveProperty("schedule");+});++it("does not silently generate without an active missing adapter", () => {+ const template = createGeneratorTemplate();+ expect(() => engineProviderSetting(template.paths, undefined, "sage2", [{ loraId: TAOMATE_LORA.id, enabled: true, strength: 1 }])).toThrow("Download or locate LoRA TaoMate 3-Step");+ expect(engineProviderSetting(template.paths, undefined, "sage2", [{ loraId: TAOMATE_LORA.id, enabled: true, strength: 0 }]).options).not.toHaveProperty("loras");+});diff --git a/src/lib/loras.ts b/src/lib/loras.tsnew file mode 100644index 0000000..726f7b8--- /dev/null+++ b/src/lib/loras.ts@@ -0,0 +1,62 @@+/** Machine-local adapter library; paths never belong in portable projects. */+export interface Lora {+ id: string;+ name: string;+ path: string;+ url?: string;+ schedule?: "taomate-3step";+}+export interface TemplateLora { loraId: string; enabled: boolean; strength: number }+export const TAOMATE_LORA: Lora = {+ id: "taomate-3step", name: "TaoMate 3-Step", path: "",+ url: "https://huggingface.co/CZMartin22/TaoMate-H3-3step-ComfyUI/resolve/main/TaoMate-H3-3step-ComfyUI.safetensors",+ schedule: "taomate-3step",+};+const KEY = "slopus.loras.v1";+const EVENT = "slopus:loras-changed";+export function loadLoras(): Lora[] {+ try {+ const raw: unknown = JSON.parse(localStorage.getItem(KEY) ?? "[]");+ const ids = new Set<string>();+ const entries: Lora[] = Array.isArray(raw) ? raw.flatMap((entry) => {+ if (!entry || typeof entry.id !== "string" || !entry.id || ids.has(entry.id)+ || 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,+ ...(typeof entry.url === "string" && /^https?:\/\//i.test(entry.url) ? { url: entry.url } : {}),+ ...(entry.schedule === "taomate-3step" ? { schedule: "taomate-3step" as const } : {}) }];+ }) : [];+ if (!ids.has(TAOMATE_LORA.id)) entries.unshift({ ...TAOMATE_LORA });+ return entries;+ } catch { return [{ ...TAOMATE_LORA }]; }+}+export function saveLoras(loras: Lora[]): void {+ localStorage.setItem(KEY, JSON.stringify(loras));+ window.dispatchEvent(new Event(EVENT));+}+export function subscribeLoras(listener: () => void) {+ const storage = (event: StorageEvent) => { if (event.key === KEY || event.key === null) listener(); };+ window.addEventListener(EVENT, listener);+ window.addEventListener("storage", storage);+ return () => { window.removeEventListener(EVENT, listener); window.removeEventListener("storage", storage); };+}+export function normalizeTemplateLoras(value: unknown): TemplateLora[] {+ const ids = new Set<string>();+ return Array.isArray(value) ? value.flatMap((entry) => {+ if (!entry || typeof entry.loraId !== "string" || !entry.loraId || ids.has(entry.loraId)) return [];+ ids.add(entry.loraId);+ return [{ loraId: entry.loraId, enabled: entry.enabled !== false,+ strength: typeof entry.strength === "number" && Number.isFinite(entry.strength) && Math.abs(entry.strength) <= 3.4028234663852886e38 ? entry.strength : 1 }];+ }) : [];+}++export function resolveTemplateLoras(selection: TemplateLora[] = []) {+ const library = loadLoras();+ return selection.filter((entry) => entry.enabled && entry.strength !== 0).map((entry) => {+ const lora = library.find(({ id }) => id === entry.loraId);+ 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.`);+ }+ return { path: lora.path.trim(), strength: entry.strength, schedule: lora.schedule };+ });+}diff --git a/src/lib/runtime.ts b/src/lib/runtime.tsindex 96546f7..4e9214a 100644--- a/src/lib/runtime.ts+++ b/src/lib/runtime.ts@@ -1,6 +1,7 @@import { invoke } from "@tauri-apps/api/core";import { isTauri } from "./persistence";-import { refreshDownloadedWeights } from "./weightDownloads";+import type { TemplateLora } from "./loras";+import { refreshDownloadedLoras, refreshDownloadedWeights } from "./weightDownloads";import {actionReferenceIds, createDraftGenerationJob, GENERATION_FRAME_RATE, parseProjectConfig,sceneBriefText, type AgentMessage, type GenerationJob, type ProjectAsset, type ProjectConfig,@@ -127,6 +128,7 @@ const DEMO_STATUS: RuntimeStatus = {export async function getRuntimeStatus(): Promise<RuntimeStatus> {if (!isTauri()) return DEMO_STATUS;await refreshDownloadedWeights();+ await refreshDownloadedLoras();return invoke<RuntimeStatus>("runtime_status", {settings: { slopfab: engineProviderSetting(loadEngineSettings()), ...agentEndpointProviderSettings() },});@@ -140,9 +142,9 @@ export const CHECKING_PROVIDERS: ProviderStatus[] = [/** Probes the engine paths on their own, with no project in hand — what the* settings screen shows. */-export async function getEngineStatus(settings = loadEngineSettings(), attention?: AttentionMode): Promise<SlopfabStatus> {+export async function getEngineStatus(settings = loadEngineSettings(), attention?: AttentionMode, loras?: TemplateLora[]): Promise<SlopfabStatus> {if (!isTauri()) return DEMO_STATUS.slopfab;- return invoke<SlopfabStatus>("slopfab_status", { settings: { slopfab: engineProviderSetting(settings, undefined, attention) } });+ return invoke<SlopfabStatus>("slopfab_status", { settings: { slopfab: engineProviderSetting(settings, undefined, attention, loras) } });}/** Opens the OS picker for one engine path. Returns null when the user cancels. */diff --git a/src/lib/settings.ts b/src/lib/settings.tsindex 35eb481..ccf2868 100644--- a/src/lib/settings.ts+++ b/src/lib/settings.ts@@ -15,6 +15,7 @@import { DEFAULT_GENERATION_STEPS, MAX_GENERATION_STEPS, type ProjectConfig, type ProviderSetting } from "./project";// Type-only: erased at build time, so this does not close a cycle with runtime.ts.import type { ProviderId } from "./runtime";+import { normalizeTemplateLoras, resolveTemplateLoras, type TemplateLora } from "./loras";/* Light/dark appearance is machine-level for the same reason and lives in* ./theme.ts, which is separate only because index.html has to read the same@@ -73,6 +74,7 @@ export interface GeneratorTemplate {attention: AttentionMode;paths: EngineSettings;sources?: Partial<Record<EnginePathId, WeightSource[]>>;+ loras?: TemplateLora[];}export interface WeightSource {@@ -224,7 +226,8 @@ const normalizeTemplateSettings = (value: unknown): GeneratorTemplateSettings |}if (entries.length) sources[field.id] = entries;}- return [{ id, name, defaultSteps, attention, paths, sources }];+ return [{ id, name, defaultSteps, attention, paths, sources,+ ...(candidate.loras !== undefined ? { loras: normalizeTemplateLoras(candidate.loras) } : {}) }];});if (templates.length === 0) return null;const requestedDefault = typeof record.defaultTemplateId === "string" ? record.defaultTemplateId : "";@@ -341,8 +344,14 @@ export function saveEngineSettings(settings: EngineSettings): void {/** The `slopfab` provider setting these paths describe, with blanks dropped so* an unset field falls through to whatever the project (or the Rust default)* already had rather than overwriting it with "". */-export function engineProviderSetting(settings: EngineSettings, base?: ProviderSetting, attention = defaultGeneratorTemplate().attention): ProviderSetting {+export function engineProviderSetting(settings: EngineSettings, base?: ProviderSetting, attention = defaultGeneratorTemplate().attention, selection = defaultGeneratorTemplate().loras): ProviderSetting {const options: ProviderSetting["options"] = { ...(base?.options ?? {}), attention, inferenceBackend: loadInferenceBackend() };+ // Always replace project-carried adapter paths with this machine's selection.+ delete options.loras;+ delete options.schedule;+ const loras = resolveTemplateLoras(selection);+ if (loras.length) options.loras = JSON.stringify(loras.map(({ path, strength }) => ({ path, strength })));+ if (loras.some(({ schedule }) => schedule === "taomate-3step")) options.schedule = "taomate-3step";for (const field of ENGINE_PATH_FIELDS) {const value = settings[field.id].trim();if (value && !isDownloadUrl(value)) options[field.id] = value;diff --git a/src/lib/weightDownloads.test.ts b/src/lib/weightDownloads.test.tsindex 98d20e8..34e3e72 100644--- a/src/lib/weightDownloads.test.ts+++ b/src/lib/weightDownloads.test.ts@@ -1,5 +1,7 @@// @vitest-environment jsdomimport { invoke } from "@tauri-apps/api/core";+import { downloadLora, removeLora, refreshDownloadedLoras, retryWeightDownload } from "./weightDownloads";+import { loadLoras, saveLoras, TAOMATE_LORA } from "./loras";import { beforeEach, expect, it, vi } from "vitest";import { chooseWeightSource, downloadTemplateWeights, getWeightDownloadState, refreshDownloadedWeights, removeTemplateWeights, updateWeightPath, weightDownloadProgress, type DownloadState } from "./weightDownloads";import { createGeneratorTemplate, defaultGeneratorTemplate, isDownloadUrl, loadGeneratorTemplateSettings, minimaxOriginalTemplate, saveGeneratorTemplateSettings, templateNeedsDownload, type WeightSource } from "./settings";@@ -11,6 +13,38 @@ 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("downloads LoRAs through the weight transfer and restores missing downloads", async () => {+ await downloadLora(TAOMATE_LORA.id);+ expect(invoke).toHaveBeenCalledWith("download_weight", { requestId: expect.any(String), url: TAOMATE_LORA.url });+ expect(loadLoras()[0].path).toContain("TaoMate-H3-3step-ComfyUI.safetensors");+ expect(getWeightDownloadState()).toMatchObject({ loraId: TAOMATE_LORA.id, active: false, completed: 1, error: null });+ files.clear();+ await refreshDownloadedLoras();+ expect(loadLoras()[0].path).toBe("");+ await downloadLora(TAOMATE_LORA.id);+ await removeLora(TAOMATE_LORA.id);+ expect(invoke).toHaveBeenCalledWith("remove_downloaded_weights", { paths: [expect.stringContaining("TaoMate")] });+ expect(loadLoras()[0].path).toBe("");+});++it("removes manually added adapters without deleting the user's file", async () => {+ saveLoras([{ id: "manual", name: "Manual", path: "D:/personal.safetensors" }]);+ await removeLora("manual");+ expect(loadLoras().some(({ id }) => id === "manual")).toBe(false);+ expect(invoke).not.toHaveBeenCalledWith("remove_downloaded_weights", expect.anything());+});++it("retries a failed LoRA download without leaving the shared transfer locked", async () => {+ const normal = vi.mocked(invoke).getMockImplementation()!;+ vi.mocked(invoke).mockRejectedValueOnce(new Error("Network lost"));+ await downloadLora(TAOMATE_LORA.id);+ expect(getWeightDownloadState()).toMatchObject({ active: false, error: "Network lost" });+ expect(loadLoras()[0].path).toBe("");+ vi.mocked(invoke).mockImplementation(normal);+ await retryWeightDownload();+ expect(getWeightDownloadState()).toMatchObject({ active: false, completed: 1, error: null });+});+it("keeps overall progress continuous across files and below 100 until completion", () => {const download: DownloadState = { templateId: "sample", field: "transformer", downloaded: 100, total: 100, completed: 0, files: 4, active: true, error: null };expect(weightDownloadProgress(download)).toBe(25);diff --git a/src/lib/weightDownloads.ts b/src/lib/weightDownloads.tsindex 2283eb7..47b0752 100644--- a/src/lib/weightDownloads.ts+++ b/src/lib/weightDownloads.ts@@ -1,12 +1,15 @@import { invoke } from "@tauri-apps/api/core";import { listen } from "@tauri-apps/api/event";import { isTauri } from "./persistence";+import { loadLoras, saveLoras } from "./loras";import { ENGINE_PATH_FIELDS, isDownloadUrl, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, templateNeedsDownload,type EnginePathId, type GeneratorTemplate, type WeightSource } from "./settings";export interface WeightGpu { name: string; memoryBytes: number }export interface DownloadState {templateId: string;+ loraId?: string;+ name?: string;field: EnginePathId | null;downloaded: number;total: number | null;@@ -27,7 +30,7 @@ const publish = (next: DownloadState | null) => { state = next; subscribers.forEexport function weightDownloadProgress(download: DownloadState): number {if (!download.files) return 0;- const current = download.field && download.total && download.total > 0+ const current = (download.field || download.loraId) && download.total && download.total > 0? Math.min(1, Math.max(0, download.downloaded / download.total)) : 0;return Math.min(download.active ? 99 : 100, 100 * (download.completed + current) / download.files);}@@ -145,6 +148,62 @@ export async function cancelWeightDownload() {if (requestId) await invoke("cancel_weight_download", { requestId });}+/** Uses the same native transfer, storage, cancellation and app-wide lock as weights. */+export async function downloadLora(loraId: string): Promise<void> {+ if (!isTauri() || state?.active) return;+ const lora = loadLoras().find(({ id }) => id === loraId);+ if (!lora?.url) return;+ cancelled = false;+ publish({ templateId: `lora:${loraId}`, loraId, name: lora.name, field: null,+ downloaded: 0, total: null, completed: 0, files: 1, error: null, active: true });+ let unlisten: (() => void) | undefined;+ try {+ unlisten = await listen<{ requestId: string; downloaded: number; total: number | null }>("weight-download-progress", ({ payload }) => {+ if (payload.requestId === requestId && state?.active) publish({ ...state, downloaded: payload.downloaded, total: payload.total });+ });+ if (cancelled) throw new Error("Download cancelled.");+ 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 === loraId && entry.url === lora.url && entry.path === lora.path ? { ...entry, path } : entry));+ publish({ ...state!, completed: 1, active: false });+ } catch (reason) {+ publish({ ...state!, active: false, error: reason instanceof Error ? reason.message : String(reason) });+ } finally { requestId = null; unlisten?.(); }+}++export function retryWeightDownload(): Promise<void> {+ return state?.loraId ? downloadLora(state.loraId) : state ? downloadTemplateWeights(state.templateId) : Promise.resolve();+}++export async function refreshDownloadedLoras(): Promise<void> {+ if (!isTauri()) return;+ const paths = loadLoras().filter((entry) => entry.url && entry.path).map(({ path }) => path);+ if (!paths.length) return;+ const exists = await invoke<Record<string, boolean>>("check_weight_files", { paths });+ let changed = false;+ const loras = loadLoras().map((entry) => {+ if (!entry.url || !paths.includes(entry.path) || exists?.[entry.path] !== false) return entry;+ changed = true;+ return { ...entry, path: "" };+ });+ if (changed) saveLoras(loras);+}++export async function removeLora(loraId: string): Promise<void> {+ if (state?.active) return;+ const lora = loadLoras().find(({ id }) => id === loraId);+ if (!lora) return;+ // Manual imports are links to the user's file; removing them never deletes it.+ if (lora.url && lora.path) {+ if (!isTauri()) return;+ await invoke("remove_downloaded_weights", { paths: [lora.path] });+ }+ saveLoras(loadLoras().flatMap((entry) => entry.id !== loraId ? [entry] : entry.url ? [{ ...entry, path: "" }] : []));+ if (state?.loraId === loraId) publish(null);+ await refreshDownloadedLoras();+}+export async function removeTemplateWeights(templateId: string): Promise<void> {if (!isTauri() || state?.active) return;const template = loadGeneratorTemplateSettings().templates.find((template) => template.id === templateId);diff --git a/src/styles/loras.css b/src/styles/loras.cssnew file mode 100644index 0000000..48f002f--- /dev/null+++ b/src/styles/loras.css@@ -0,0 +1,14 @@+.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"] {+ min-width: 0; min-height: var(--field-height); padding: var(--space-2) var(--space-3); border: 1px solid var(--line); border-radius: var(--radius-sm);+ color: inherit; background: var(--panel); font: inherit;+}+.lora-manual .lora-toggle, .lora-toggle { display: flex; align-items: center; gap: var(--space-2); }+.lora-manual p, .template-loras p { margin: 0; color: var(--text-muted); font-size: var(--text-sm); }+.template-loras h3 { margin: 0; }+.template-loras h3 small { margin-left: var(--space-2); font-weight: normal; font-size: var(--text-sm); }+.template-lora-row { display: flex; align-items: center; gap: var(--space-2); flex-wrap: wrap; }+.template-lora-row .lora-toggle { flex: 1; min-width: 140px; }+.template-lora-row > label:not(.lora-toggle) { display: grid; gap: var(--space-1); font-size: var(--text-2xs); }+.template-lora-row input[type="number"] { width: 78px; }