AI media harness for planning, generating, and editing locally
TypeScript
Generalize LoRA step overrides and add editor
Bitti052cbf4aec22
diff --git a/docs/generator-weights.md b/docs/generator-weights.mdindex 089255b..f9e9d83 100644--- a/docs/generator-weights.md+++ b/docs/generator-weights.md@@ -8,7 +8,7 @@ It uses the same managed `weights` location, background transfer, progress,cancellation, retry, and Work Queue controls as model weights. Downloads areserialized 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+deletes its managed file; **Add Lora** opens an editor to link a named local file, andremoving that library entry leaves the original file untouched.Open a generator template and use its **LoRAs** section to add available adapters.@@ -18,9 +18,14 @@ are passed to SlopFab in displayed order on both CUDA and Vulkan. SlopFab combinadapter updates by summing them. Negative strengths are supported. An activemissing 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.+Open any LoRA from the library to edit its optional **Override step count**.+Any supported scene step count (a whole number from 2 to 2147483647) is accepted.+The highest override among enabled, nonzero-strength LoRAs replaces the scene's+step count, even when the scene requests more steps. Without an active override,+the scene's steps are used. TaoMate defaults to an editable override of 3;+older TaoMate schedule settings migrate to this value. All adapters now use the+ordinary schedule, whose step count includes the terminal sigma (N steps means+N−1 model evaluations).The library and per-template selections persist on this computer; adapter pathsare injected into runtime requests and are not saved into portable project files.diff --git a/src-tauri/src/slopfab.rs b/src-tauri/src/slopfab.rsindex fa884f9..5487b6e 100644--- a/src-tauri/src/slopfab.rs+++ b/src-tauri/src/slopfab.rs@@ -353,9 +353,11 @@ impl SlopfabRuntime {pub fn enqueue(&self,app: AppHandle,- request: GenerationRequest,+ mut request: GenerationRequest,settings: &BTreeMap<String, ProviderSetting>,) -> Result<(), String> {+ let configuration = Configuration::from_settings(settings);+ request.steps = configuration.generation_steps(request.steps)?;diagnostics::info("slopfab","generation.enqueue_requested",@@ -384,7 +386,6 @@ impl SlopfabRuntime {}flags.insert(request.job_id.clone(), cancel.clone());drop(flags);- let configuration = Configuration::from_settings(settings);let queued_id = request.job_id.clone();if self.sender@@ -466,7 +467,7 @@ struct Configuration {attention: &'static str,models: [(i32, &'static str, Option<PathBuf>); 5],loras: Result<Vec<LoraAdapter>, String>,- taomate_schedule: bool,+ step_override: Result<Option<i32>, String>,}impl Configuration {@@ -510,10 +511,18 @@ impl Configuration {.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"),+ step_override: match slopfab.and_then(|setting| setting.options.get("stepOverride")) {+ None => Ok(None),+ Some(ProviderOption::Number(value)) if value.is_finite() && value.fract() == 0.0 && *value >= 2.0 && *value <= i32::MAX as f64 => Ok(Some(*value as i32)),+ _ => Err("LoRA step override must be a whole number from 2 to 2147483647.".into()),+ },}}+ fn generation_steps(&self, fallback: i32) -> Result<i32, String> {+ self.step_override.clone().map(|steps| steps.unwrap_or(fallback))+ }+fn platform(&self, detected: ComputePlatform) -> ComputePlatform {if self.vulkan {ComputePlatform::Vulkan@@ -539,7 +548,7 @@ impl Configuration {.join(";");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)+ format!("slopfab={version}|platform={}|attention={}|{models}|loras={adapters}|steps={:?}", platform.label(), self.attention, self.step_override)}}@@ -681,7 +690,7 @@ fn configure_request(if request.still_image {api.set_still_image(handle)?;}- api.set_steps(handle, request.steps)?;+ api.set_steps(handle, configuration.generation_steps(request.steps)?)?;api.set_seed(handle, generation_seed(request.seed)?)?;api.set_resolution(handle, request.canvas_width, request.canvas_height)?;api.set_inference_backend(handle, platform.backend())?;@@ -697,7 +706,6 @@ fn configure_request(}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 {@@ -1009,7 +1017,7 @@ pub fn generate_reference_icon_batch(let configuration = Configuration {dll_path: batch.dll_path.clone(),loras: Ok(Vec::new()),- taomate_schedule: false,+ step_override: Ok(None),vulkan: backend == ComputePlatform::Vulkan,attention: "sage2",models: [@@ -1298,7 +1306,6 @@ mod ffi {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>,add_refmod: Option<unsafe extern "C" fn(*mut Request, *const c_char, f32, i32) -> 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,@@ -1399,9 +1406,6 @@ mod ffi {add_refmod: library.get::<unsafe extern "C" fn(*mut Request, *const c_char, f32, i32) -> i32>(b"slopfab_request_add_refmod\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@@ -1568,10 +1572,6 @@ mod ffi {let path = path_cstring(path)?;self.error(unsafe { add(r, path.as_ptr(), strength, copies) })}- 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,@@ -1749,7 +1749,7 @@ mod tests {}#[test]- fn ordered_loras_and_taomate_schedule_reach_cuda_and_vulkan_requests() {+ fn ordered_loras_and_step_override_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(); }@@ -1760,7 +1760,7 @@ mod tests {{ "path": paths[0], "strength": -0.5 },{ "path": paths[1], "strength": 1.0 },]).to_string())),- ("schedule".into(), ProviderOption::String("taomate-3step".into())),+ ("stepOverride".into(), ProviderOption::Number(8.0)),]),})]);let configuration = Configuration::from_settings(&settings);@@ -1776,9 +1776,9 @@ mod tests {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);+ assert_eq!(api.resolve(handle.0).unwrap().num_model_evaluations, 7);let description = api.describe(handle.0).unwrap();- assert!(description.contains("taomate-3step"));+ assert!(!description.contains("taomate-3step"));assert!(description.find("style.safetensors").unwrap() < description.find("TaoMate.safetensors").unwrap());assert!(description.contains("strength -0.5"));}diff --git a/src/components/LoraSettings.tsx b/src/components/LoraSettings.tsxindex 96c802a..975cdf4 100644--- a/src/components/LoraSettings.tsx+++ b/src/components/LoraSettings.tsx@@ -1,7 +1,8 @@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 { highestLoraStepOverride, isLoraStepOverride, loadLoras, 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";@@ -12,13 +13,9 @@ function useLoras() {return loras;}-export function LoraLibrary() {+export function LoraLibrary({ onAdd, onEdit }: { onAdd: () => void; onEdit: (id: string) => void }) {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(() => {@@ -28,50 +25,68 @@ export function LoraLibrary() {const timer = window.setInterval(refresh, 5000);return () => { window.removeEventListener("focus", refresh); window.clearInterval(timer); };}, []);+ 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={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>+ {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>+ {error && <p role="alert">{error}</p>}+ </section>;+}++export function LoraEditor({ loraId, onDone }: { loraId: string; onDone: () => void }) {+ const existing = loadLoras().find(({ id }) => id === loraId);+ const [name, setName] = useState(existing?.name ?? "");+ const [path, setPath] = useState(existing?.path ?? "");+ const [override, setOverride] = useState(existing?.stepOverride !== undefined);+ const [steps, setSteps] = useState(String(existing?.stepOverride ?? 3));+ const [error, setError] = useState<string | null>(null);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")) {+ const save = () => {+ if (!name.trim() || (!path.trim() && !existing?.url)) 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 {- 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);+ const library = loadLoras();+ const entry: Lora = { ...library.find(({ id }) => id === loraId), id: loraId, name: name.trim(), path: path.trim(), stepOverride: override ? Number(steps) : undefined };+ saveLoras(existing ? library.map((lora) => lora.id === loraId ? entry : lora) : [...library, entry]);+ onDone();} 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 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)}%` }} />}- <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>+ 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">+ <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>+ <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="secondary-button" type="button" disabled={!name.trim() || !path.trim()} onClick={add}>Add local LoRA</button>- </div>}- {error && <p role="alert">{error}</p>}- </section>;+ <button className="primary-button" type="button" disabled={!name.trim() || (!path.trim() && !existing?.url) || (override && !isLoraStepOverride(Number(steps)))} onClick={save}>{existing ? "Save Lora" : "Add Lora"}</button>+ {error && <p role="alert">{error}</p>}+ </div>+ </div>;}export function TemplateLorasEditor({ value, onChange }: { value: TemplateLora[]; onChange: (value: TemplateLora[]) => void }) {const library = useLoras();+ const stepOverride = highestLoraStepOverride(value.filter((entry) => entry.enabled && entry.strength !== 0)+ .flatMap((entry) => library.filter(({ id }) => id === entry.loraId)));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) => {@@ -98,6 +113,6 @@ export function TemplateLorasEditor({ value, onChange }: { value: TemplateLora[]<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>}+ {stepOverride !== undefined && <p>Active LoRAs override the scene's step count to {stepOverride}, the highest selected override.</p>}</section>;}diff --git a/src/components/SettingsView.downloads.test.tsx b/src/components/SettingsView.downloads.test.tsxindex 41ee518..f223e45 100644--- a/src/components/SettingsView.downloads.test.tsx+++ b/src/components/SettingsView.downloads.test.tsx@@ -35,11 +35,19 @@ it("downloads TaoMate and persists manual adapters, activation, strength and ordconst 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.click(screen.getByRole("button", { name: "Add Lora" }));+ expect(screen.queryByRole("button", { name: "New generator" })).not.toBeInTheDocument();+ expect(screen.getByRole("heading", { name: "Add Lora" })).toBeInTheDocument();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" }));+ fireEvent.click(screen.getByLabelText("Override step count"));+ fireEvent.change(screen.getByLabelText("LoRA step override"), { target: { value: "8" } });+ fireEvent.click(screen.getByRole("button", { name: "Add Lora" }));const manual = loadLoras().find(({ name }) => name === "My style")!;+ expect(manual.stepOverride).toBe(8);+ fireEvent.click(screen.getByRole("button", { name: "Edit My style LoRA" }));+ expect(screen.getByLabelText("LoRA step override")).toHaveValue(8);+ fireEvent.click(screen.getByRole("button", { name: "Generators" }));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 } });@@ -47,6 +55,7 @@ it("downloads TaoMate and persists manual adapters, activation, strength and ordfireEvent.click(screen.getByRole("button", { name: "Move My style up" }));fireEvent.click(screen.getByLabelText("Enable TaoMate 3-Step"));expect(screen.getByText("1 active")).toBeInTheDocument();+ expect(screen.getByText(/step count to 8/)).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();diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsxindex 7c3d7c1..3fb888b 100644--- a/src/components/SettingsView.tsx+++ b/src/components/SettingsView.tsx@@ -3,7 +3,7 @@ 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 { LoraEditor, 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";@@ -263,6 +263,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onClconst downloadState = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);const downloadPercent = downloadState ? weightDownloadProgress(downloadState) : 0;const [editingTemplateId, setEditingTemplateId] = useState<string | null>(null);+ const [editingLoraId, setEditingLoraId] = useState<string | null>(null);const [showAdvancedOptions, setShowAdvancedOptions] = useState(false);const [status, setStatus] = useState<SlopfabStatus | null>(null);const probeRevision = useRef(0);@@ -422,8 +423,8 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCltablist rather than two buttons that happen to swap the content:the arrow keys move between them, and the panel below is named bythe tab that opened it. */}- {editingTemplateId ? <div className="settings-tabs settings-tabs--editor">- <button type="button" className="generator-editor__back" onClick={() => setEditingTemplateId(null)}><ChevronLeft size={16} /> Generators</button>+ {editingTemplateId || editingLoraId ? <div className="settings-tabs settings-tabs--editor">+ <button type="button" className="generator-editor__back" onClick={() => { setEditingTemplateId(null); setEditingLoraId(null); }}><ChevronLeft size={16} /> Generators</button></div> : <div className="settings-tabs" role="tablist" aria-label="Settings sections">{TABS.map((item, index) => (<button@@ -485,11 +486,11 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl{tab === "engine" && <sectionclassName="settings-section"id="settings-panel-engine"- role={editingTemplateId ? "region" : "tabpanel"}- aria-labelledby={editingTemplateId ? "generator-editor-heading" : "settings-tab-engine"}+ role={editingTemplateId || editingLoraId ? "region" : "tabpanel"}+ aria-labelledby={editingLoraId ? "lora-editor-heading" : editingTemplateId ? "generator-editor-heading" : "settings-tab-engine"}>- {!editingTemplateId && <ReferenceIconSetting />}- {!editingTemplateId ? <>{generatorSections.filter((section) => section.id === "generators" || section.templates.length > 0).map((section) => <section key={section.id} className="generator-templates" aria-labelledby={`${section.id}-heading`}>+ {!editingTemplateId && !editingLoraId && <ReferenceIconSetting />}+ {editingLoraId ? <LoraEditor key={editingLoraId} loraId={editingLoraId} onDone={() => setEditingLoraId(null)} /> : !editingTemplateId ? <>{generatorSections.filter((section) => section.id === "generators" || section.templates.length > 0).map((section) => <section key={section.id} className="generator-templates" aria-labelledby={`${section.id}-heading`}><header><div><h2 id={`${section.id}-heading`}>{section.title}</h2>@@ -525,7 +526,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl</div>))}</div>- </section>)}<LoraLibrary /></> : <div className="generator-editor">+ </section>)}<LoraLibrary onAdd={() => setEditingLoraId(`lora-${crypto.randomUUID()}`)} onEdit={setEditingLoraId} /></> : <div className="generator-editor"><header className="generator-editor__head"><div><h2 id="generator-editor-heading">Edit generator</h2>diff --git a/src/lib/loras.test.ts b/src/lib/loras.test.tsindex de968cb..54b8cc2 100644--- a/src/lib/loras.test.ts+++ b/src/lib/loras.test.ts@@ -1,11 +1,45 @@// @vitest-environment jsdomimport { beforeEach, expect, it } from "vitest";import { loadLoras, saveLoras, TAOMATE_LORA } from "./loras";-import { createGeneratorTemplate, engineProviderSetting, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, withEngineSettings } from "./settings";+import { createGeneratorTemplate, engineProviderSetting, generationStepsWithLoras, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, withEngineSettings } from "./settings";import { createProjectConfig } from "./project";beforeEach(() => localStorage.clear());+it("migrates the old schedule to an editable step override", () => {+ localStorage.setItem("slopus.loras.v1", JSON.stringify([{ id: "legacy", name: "Legacy", path: "D:/legacy.safetensors", schedule: "taomate-3step" }]));+ expect(loadLoras().find(({ id }) => id === "legacy")).toMatchObject({ stepOverride: 3 });+ saveLoras(loadLoras().map((lora) => ({ ...lora, stepOverride: undefined })));+ expect(loadLoras().every((lora) => lora.stepOverride === undefined)).toBe(true);+});++it("uses the highest active override regardless of order, excluding disabled and zero-strength LoRAs", () => {+ saveLoras([+ { id: "low", name: "Low", path: "D:/low.safetensors", stepOverride: 5 },+ { id: "high", name: "High", path: "D:/high.safetensors", stepOverride: 12 },+ { id: "disabled", name: "Disabled", path: "", stepOverride: 40 },+ { id: "zero", name: "Zero", path: "", stepOverride: 50 },+ ]);+ const selection = [+ { loraId: "high", enabled: true, strength: -0.5 },+ { loraId: "low", enabled: true, strength: 1 },+ { loraId: "disabled", enabled: false, strength: 1 },+ { loraId: "zero", enabled: true, strength: 0 },+ ];+ const paths = createGeneratorTemplate().paths;+ const config = createProjectConfig({ name: "Test", prompt: "", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 10 });+ config.providerSettings.slopfab = engineProviderSetting(paths, undefined, "sage2", selection);+ expect(generationStepsWithLoras(30, config)).toBe(12);+ expect(generationStepsWithLoras(3, config)).toBe(12);+ expect(engineProviderSetting(paths, undefined, "sage2", [...selection].reverse()).options.stepOverride).toBe(12);+ config.providerSettings.slopfab = engineProviderSetting(paths, config.providerSettings.slopfab, "sage2", []);+ expect(generationStepsWithLoras(30, config)).toBe(30);+});++it.each([0, 1, -3, 2.5, NaN, Infinity, 2147483648])("rejects invalid step override %s", (stepOverride) => {+ expect(() => saveLoras([{ id: "bad", name: "Bad", path: "D:/bad.safetensors", stepOverride }])).toThrow("Step override must be a whole number");+});+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" }]);@@ -26,11 +60,13 @@ it("round-trips template order, enabled flags and strengths, and sends only actiexpect(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(runtime.providerSettings.slopfab.options.stepOverride).toBe(3);+ expect(runtime.providerSettings.slopfab.options).not.toHaveProperty("schedule");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");+ expect(without.options).not.toHaveProperty("stepOverride");});it("does not silently generate without an active missing adapter", () => {diff --git a/src/lib/loras.ts b/src/lib/loras.tsindex 726f7b8..70bdc4f 100644--- a/src/lib/loras.ts+++ b/src/lib/loras.ts@@ -1,16 +1,18 @@+import { MAX_GENERATION_STEPS } from "./project";+/** Machine-local adapter library; paths never belong in portable projects. */export interface Lora {id: string;name: string;path: string;url?: string;- schedule?: "taomate-3step";+ stepOverride?: number;}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",+ stepOverride: 3,};const KEY = "slopus.loras.v1";const EVENT = "slopus:loras-changed";@@ -24,13 +26,17 @@ export function loadLoras(): Lora[] {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 } : {}) }];+ ...(isLoraStepOverride(entry.stepOverride) ? { stepOverride: entry.stepOverride }+ : entry.stepOverride === undefined && entry.schedule === "taomate-3step" ? { stepOverride: 3 } : {}) }];}) : [];if (!ids.has(TAOMATE_LORA.id)) entries.unshift({ ...TAOMATE_LORA });return entries;} catch { return [{ ...TAOMATE_LORA }]; }}export function saveLoras(loras: Lora[]): void {+ if (loras.some((lora) => lora.stepOverride !== undefined && !isLoraStepOverride(lora.stepOverride))) {+ throw new Error(`Step override must be a whole number from 2 to ${MAX_GENERATION_STEPS}.`);+ }localStorage.setItem(KEY, JSON.stringify(loras));window.dispatchEvent(new Event(EVENT));}@@ -57,6 +63,15 @@ export function resolveTemplateLoras(selection: TemplateLora[] = []) {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 };+ return { path: lora.path.trim(), strength: entry.strength, stepOverride: lora.stepOverride };});}++export function isLoraStepOverride(value: unknown): value is number {+ return typeof value === "number" && Number.isInteger(value) && value >= 2 && value <= MAX_GENERATION_STEPS;+}++export function highestLoraStepOverride(loras: { stepOverride?: number }[]): number | undefined {+ return loras.reduce<number | undefined>((highest, lora) => isLoraStepOverride(lora.stepOverride)+ ? Math.max(highest ?? 0, lora.stepOverride) : highest, undefined);+}diff --git a/src/lib/runtime.ts b/src/lib/runtime.tsindex 34b2c47..0a12db0 100644--- a/src/lib/runtime.ts+++ b/src/lib/runtime.ts@@ -9,7 +9,7 @@ import {} from "./project";import {agentEndpointProviderSettings, endpointProviderSetting, engineProviderSetting,- loadDefaultGenerationSteps, loadEngineSettings, withAgentEndpointSettings,+ generationStepsWithLoras, loadDefaultGenerationSteps, loadEngineSettings, withAgentEndpointSettings,type AttentionMode, type EndpointProviderId, type EndpointProviderSettings, type EnginePathField,} from "./settings";@@ -211,6 +211,7 @@ export async function cancelAgentTurn(requestId: string): Promise<boolean> {}export async function resolveSlopfabPlan(request: SlopfabGenerationRequest, config: ProjectConfig): Promise<ResolvedPlan> {+ request = { ...request, steps: generationStepsWithLoras(request.steps, config) };if (isTauri()) return invoke<ResolvedPlan>("resolve_slopfab_plan", { request, config });const alignedFrames = Math.ceil(Math.max(5, request.frames - 5) / 17) * 17 + 5;return {@@ -227,6 +228,7 @@ export async function resolveSlopfabPlan(request: SlopfabGenerationRequest, conf}export async function enqueueSlopfabGeneration(request: SlopfabGenerationRequest, config: ProjectConfig): Promise<void> {+ request = { ...request, steps: generationStepsWithLoras(request.steps, config) };if (isTauri()) await invoke("enqueue_slopfab_generation", { request, config });}diff --git a/src/lib/settings.ts b/src/lib/settings.tsindex ccf2868..232a25d 100644--- a/src/lib/settings.ts+++ b/src/lib/settings.ts@@ -15,7 +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";+import { highestLoraStepOverride, isLoraStepOverride, 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@@ -349,9 +349,11 @@ export function engineProviderSetting(settings: EngineSettings, base?: ProviderS// Always replace project-carried adapter paths with this machine's selection.delete options.loras;delete options.schedule;+ delete options.stepOverride;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";+ const stepOverride = highestLoraStepOverride(loras);+ if (stepOverride !== undefined) options.stepOverride = stepOverride;for (const field of ENGINE_PATH_FIELDS) {const value = settings[field.id].trim();if (value && !isDownloadUrl(value)) options[field.id] = value;@@ -362,6 +364,11 @@ export function engineProviderSetting(settings: EngineSettings, base?: ProviderS/** A copy of `config` carrying this machine's engine paths. For passing to a* Tauri command only — never store or save the result. */+export function generationStepsWithLoras(steps: number, config: ProjectConfig): number {+ const override = config.providerSettings.slopfab?.options.stepOverride;+ return isLoraStepOverride(override) ? override : steps;+}+export function withEngineSettings(config: ProjectConfig): ProjectConfig {return {...config,diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.tsindex f6f1c6b..443ab7d 100644--- a/src/lib/workQueue.ts+++ b/src/lib/workQueue.ts@@ -7,7 +7,7 @@ import { generationAssetId, GENERATION_FRAME_RATE, projectItemPath, sceneGeneratimport { saveSceneLastFrame } from "./sceneLastFrame";import { ProjectSession, type ProjectWriter } from "./projectSession";import { cancelSlopfabGeneration, enqueueSlopfabGeneration, resolveSlopfabPlan, type SlopfabGenerationRequest } from "./runtime";-import { withEngineSettings } from "./settings";+import { generationStepsWithLoras, withEngineSettings } from "./settings";import { purgeTimelineThumbnails } from "./timelineThumbnails";import { ReferenceIconWork } from "./referenceIconWork";import { prepareReferenceVideos, releaseReferenceVideos } from "./referenceVideo";@@ -167,7 +167,7 @@ export class WorkQueue {const id = `work-${crypto.randomUUID()}`;let finish!: () => void;const done = new Promise<void>((resolve) => { finish = resolve; });- const request = structuredClone({ ...submission.request, jobId: id });+ const request = structuredClone({ ...submission.request, jobId: id, steps: generationStepsWithLoras(submission.request.steps, config) });this.work.set(id, { id, session, sceneId: submission.job.id, request, config, snapshot: submission.snapshot, cancelled: false, submitted: false, done, finish });this.items = [...this.items, {id, projectKey, folderPath: session.record.folderPath, projectName: config.name,