AI media harness for planning, generating, and editing locally
TypeScript
Add portable slop generator bundles
Bittie54a784850c0
diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rsindex 8a8bd84..00815ed 100644--- a/src-tauri/src/app.rs+++ b/src-tauri/src/app.rs@@ -249,6 +249,8 @@ pub fn run() {native_shell::show_text_context_menu,native_shell::reveal_in_explorer,native_shell::pick_file,+ crate::slop::import_slop_file,+ crate::slop::export_slop_file,commands::artifacts::write_generated_video,commands::artifacts::write_scene_last_frame,commands::artifacts::write_reference_frame,diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 802a6dd..6439998 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -13,6 +13,7 @@ mod linux_webview;mod media;mod native_shell;mod project;+mod slop;mod weights;mod window;mod worker;diff --git a/src-tauri/src/slop.rs b/src-tauri/src/slop.rsnew file mode 100644index 0000000..ff51963--- /dev/null+++ b/src-tauri/src/slop.rs@@ -0,0 +1,87 @@+//! File transport for portable, versioned Slopus bundles. Payload schemas live+//! with their importers; these commands only access user-selected .slop files.+use std::{fs::File, io::Read, path::Path};+use tauri::AppHandle;+use tauri_plugin_dialog::DialogExt;++const MAX_SLOP_BYTES: usize = 4 * 1024 * 1024;++fn validate_contents(contents: &str) -> Result<(), String> {+ if contents.len() > MAX_SLOP_BYTES {+ return Err("The .slop file exceeds 4 MB.".into());+ }+ let value: serde_json::Value = serde_json::from_str(contents.trim_start_matches('\u{feff}'))+ .map_err(|_| "This .slop file is not valid JSON.")?;+ if value.get("format").and_then(|v| v.as_str()) != Some("slop") {+ return Err("This is not a Slopus .slop bundle.".into());+ }+ Ok(())+}++fn read_slop(path: &Path) -> Result<String, String> {+ if !path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("slop")) {+ return Err("Choose a .slop file.".into());+ }+ let file = File::open(path).map_err(|error| format!("Could not open .slop file: {error}"))?;+ if !file.metadata().map_err(|error| error.to_string())?.is_file() {+ return Err("Choose a regular .slop file.".into());+ }+ let mut contents = String::new();+ file.take((MAX_SLOP_BYTES + 1) as u64).read_to_string(&mut contents)+ .map_err(|error| format!("Could not read .slop file as UTF-8: {error}"))?;+ validate_contents(&contents)?;+ Ok(contents)+}++#[tauri::command]+pub(crate) async fn import_slop_file(app: AppHandle) -> Result<Option<String>, String> {+ tauri::async_runtime::spawn_blocking(move || {+ let Some(file) = app.dialog().file().set_title("Import generator templates")+ .add_filter("Slopus bundle", &["slop"]).blocking_pick_file() else { return Ok(None); };+ let path = file.into_path().map_err(|_| "Choose a local .slop file.")?;+ read_slop(&path).map(Some)+ }).await.map_err(|error| error.to_string())?+}++#[tauri::command]+pub(crate) async fn export_slop_file(app: AppHandle, contents: String, filename: String) -> Result<bool, String> {+ validate_contents(&contents)?;+ // This is a suggested basename, never a path supplied by the webview.+ let filename = if filename.ends_with(".slop") && !filename.contains(['/', '\\', ':']) {+ filename+ } else { "generators.slop".into() };+ tauri::async_runtime::spawn_blocking(move || {+ let Some(file) = app.dialog().file().set_title("Export generator templates")+ .add_filter("Slopus bundle", &["slop"]).set_file_name(&filename).blocking_save_file() else { return Ok(false); };+ let path = file.into_path().map_err(|_| "Choose a local .slop destination.")?;+ let destination = path.with_extension("slop");+ if path != destination && destination.exists() {+ return Err("That .slop file already exists. Select it in the Save dialog to confirm replacement.".into());+ }+ crate::storage::atomic::write_atomically(&destination, contents.as_bytes())?;+ Ok(true)+ }).await.map_err(|error| error.to_string())?+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_utf8_bundles_and_rejects_invalid_files() {+ let directory = tempfile::tempdir().unwrap();+ let file = directory.path().join("templates.SLOP");+ let contents = "\u{feff}{\"format\":\"slop\",\"version\":1,\"items\":[]}";+ std::fs::write(&file, contents).unwrap();+ assert_eq!(read_slop(&file).unwrap(), contents);+ std::fs::write(&file, "not JSON").unwrap();+ assert!(read_slop(&file).unwrap_err().contains("JSON"));+ std::fs::write(&file, "{\"format\":\"other\"}").unwrap();+ assert!(read_slop(&file).is_err());+ std::fs::write(&file, [0xff, 0xfe]).unwrap();+ assert!(read_slop(&file).unwrap_err().contains("UTF-8"));+ std::fs::write(&file, " ".repeat(MAX_SLOP_BYTES + 1)).unwrap();+ assert!(read_slop(&file).unwrap_err().contains("4 MB"));+ assert!(read_slop(&directory.path().join("templates.json")).unwrap_err().contains("Choose a .slop"));+ }+}diff --git a/src/components/GeneratorSharing.test.tsx b/src/components/GeneratorSharing.test.tsxnew file mode 100644index 0000000..8a9e684--- /dev/null+++ b/src/components/GeneratorSharing.test.tsx@@ -0,0 +1,102 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { invoke } from "@tauri-apps/api/core";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { GeneratorSharing } from "./GeneratorSharing";+import { SettingsView } from "./SettingsView";+import { createGeneratorTemplate, loadGeneratorTemplateSettings, minimaxOriginalTemplate, saveGeneratorTemplateSettings } from "../lib/settings";+import { parseGeneratorSlop, serializeGeneratorSlop } from "../lib/slop";++vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));+beforeEach(() => {+ localStorage.clear(); vi.clearAllMocks();+ Object.assign(window, { __TAURI_INTERNALS__: {} });+ vi.mocked(invoke).mockImplementation(async () => null as never);+});+afterEach(() => { cleanup(); delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__; });++it("exports only chosen URL templates through the native save dialog", async () => {+ const template = minimaxOriginalTemplate();+ render(<GeneratorSharing templates={[createGeneratorTemplate("Local setup"), template, { ...template, id: "other", name: "Other" }]} />);+ fireEvent.click(screen.getByRole("button", { name: "Export", exact: true }));+ const dialog = within(screen.getByRole("dialog", { name: "Export generator templates" }));+ expect((dialog.getByRole("checkbox", { name: "Export Local setup" }) as HTMLInputElement).disabled).toBe(true);+ expect(dialog.getByText(/Transformer weights needs a download URL/)).toBeTruthy();+ fireEvent.click(dialog.getByRole("checkbox", { name: "Export Other" }));+ vi.mocked(invoke).mockResolvedValue(true);+ fireEvent.click(dialog.getByRole("button", { name: "Export", exact: true }));+ await screen.findByText("Exported 1 generator template.");+ const [command, args] = vi.mocked(invoke).mock.calls[0];+ expect(command).toBe("export_slop_file");+ expect(args).toMatchObject({ filename: "First-Last Frame.slop" });+ expect(parseGeneratorSlop((args as { contents: string }).contents).items.map(({ data }) => data.name)).toEqual([template.name]);+ expect(screen.queryByRole("dialog")).toBeNull();+});++it("imports from the Generators page and updates its list without downloading or replacing defaults", async () => {+ const shared = { ...minimaxOriginalTemplate(), name: "Shared generator" };+ vi.mocked(invoke).mockImplementation(async (command) => command === "import_slop_file" ? serializeGeneratorSlop([shared]) : null as never);+ const previous = loadGeneratorTemplateSettings();+ render(<SettingsView onClose={() => undefined} />);+ fireEvent.click(screen.getByRole("button", { name: "Import", exact: true }));+ await screen.findByText("Added 1 generator template.");+ expect(screen.getByRole("button", { name: "Edit Shared generator generator" })).toBeTruthy();+ expect(loadGeneratorTemplateSettings().templates).toHaveLength(previous.templates.length + 1);+ expect(loadGeneratorTemplateSettings().defaultTemplateId).toBe(previous.defaultTemplateId);+ expect(vi.mocked(invoke).mock.calls.some(([command]) => command === "download_weight")).toBe(false);+});++it("does not mutate on cancellation or malformed files, and reports native read errors", async () => {+ const before = loadGeneratorTemplateSettings();+ render(<GeneratorSharing templates={before.templates} />);+ fireEvent.click(screen.getByRole("button", { name: "Import", exact: true }));+ await waitFor(() => expect((screen.getByRole("button", { name: "Import" }) as HTMLButtonElement).disabled).toBe(false));+ expect(screen.queryByText(/Added/)).toBeNull();+ expect(loadGeneratorTemplateSettings()).toEqual(before);+ vi.mocked(invoke).mockResolvedValue("bad JSON");+ fireEvent.click(screen.getByRole("button", { name: "Import" }));+ await screen.findByText("This .slop file is not valid JSON.");+ expect(loadGeneratorTemplateSettings()).toEqual(before);+ vi.mocked(invoke).mockRejectedValue(new Error("File unreadable"));+ fireEvent.click(screen.getByRole("button", { name: "Import" }));+ await screen.findByText("File unreadable");+});++it("keeps concurrent edits when a native import completes and prevents duplicate dialogs", async () => {+ let resolve: (value: string) => void = () => undefined;+ vi.mocked(invoke).mockImplementation(() => new Promise((done) => { resolve = done; }));+ render(<GeneratorSharing templates={loadGeneratorTemplateSettings().templates} />);+ fireEvent.click(screen.getByRole("button", { name: "Import" }));+ fireEvent.click(screen.getByRole("button", { name: "Import" }));+ expect(invoke).toHaveBeenCalledTimes(1);+ const latest = loadGeneratorTemplateSettings();+ const edited = { ...latest.templates[0], name: "Changed while dialog open" };+ saveGeneratorTemplateSettings({ ...latest, templates: [edited, ...latest.templates.slice(1)] });+ await act(async () => resolve(serializeGeneratorSlop([minimaxOriginalTemplate()])));+ await screen.findByText("Added 1 generator template.");+ expect(loadGeneratorTemplateSettings().templates[0].name).toBe(edited.name);+});++it("keeps the export selection after save cancellation and reports write failures", async () => {+ render(<GeneratorSharing templates={[minimaxOriginalTemplate()]} />);+ fireEvent.click(screen.getByRole("button", { name: "Export" }));+ const dialog = within(screen.getByRole("dialog"));+ vi.mocked(invoke).mockResolvedValue(false);+ fireEvent.click(dialog.getByRole("button", { name: "Export" }));+ await waitFor(() => expect((dialog.getByRole("button", { name: "Export" }) as HTMLButtonElement).disabled).toBe(false));+ expect(screen.getByRole("dialog")).toBeTruthy();+ expect(screen.queryByText(/Exported/)).toBeNull();+ vi.mocked(invoke).mockRejectedValue(new Error("Disk full"));+ fireEvent.click(dialog.getByRole("button", { name: "Export" }));+ await screen.findByText("Disk full");+});++it("accepts browser-selected .slop files", async () => {+ delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;+ render(<GeneratorSharing templates={loadGeneratorTemplateSettings().templates} />);+ const file = new File([""], "shared.slop", { type: "application/json" });+ Object.defineProperty(file, "text", { value: async () => serializeGeneratorSlop([minimaxOriginalTemplate()]) });+ fireEvent.change(screen.getByLabelText("Import .slop file"), { target: { files: [file] } });+ await screen.findByText("Added 1 generator template.");+ expect(invoke).not.toHaveBeenCalled();+});diff --git a/src/components/GeneratorSharing.tsx b/src/components/GeneratorSharing.tsxnew file mode 100644index 0000000..6b80f07--- /dev/null+++ b/src/components/GeneratorSharing.tsx@@ -0,0 +1,76 @@+import { useEffect, useRef, useState } from "react";+import { Checkbox, ContentDialog, InfoBar, SettingsCard } from "./ui";+import { Video20 } from "./ui/icons";+import { inTauri } from "../lib/nativeShell";+import { importGeneratorSlop, portableGenerator, serializeGeneratorSlop } from "../lib/slop";+import { openSlopFile, readBrowserSlopFile, saveSlopFile } from "../lib/slopFiles";+import type { GeneratorTemplate } from "../lib/settings";++export function GeneratorSharing({ templates }: { templates: GeneratorTemplate[] }) {+ const [choosing, setChoosing] = useState(false);+ const [selected, setSelected] = useState<string[]>([]);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [message, setMessage] = useState<string | null>(null);+ const input = useRef<HTMLInputElement>(null);+ const pending = useRef(false);+ const mounted = useRef(true);+ useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);+ const choices = templates.map((template) => {+ try { portableGenerator(template); return { template, reason: null }; }+ catch (reason) { return { template, reason: reason instanceof Error ? reason.message : String(reason) }; }+ });+ const begin = () => {+ if (pending.current) return false;+ pending.current = true; setBusy(true); setError(null); setMessage(null); return true;+ };+ const finish = () => { pending.current = false; if (mounted.current) setBusy(false); };+ const fail = (reason: unknown) => { if (mounted.current) setError(reason instanceof Error ? reason.message : String(reason)); };+ const accept = (contents: string) => {+ if (!mounted.current) return;+ const imported = importGeneratorSlop(contents);+ setMessage(`Added ${imported.length} generator ${imported.length === 1 ? "template" : "templates"}.`);+ };+ const importFile = async () => {+ if (!inTauri()) { input.current?.click(); return; }+ if (!begin()) return;+ try { const contents = await openSlopFile(); if (contents !== null) accept(contents); }+ catch (reason) { fail(reason); } finally { finish(); }+ };+ const exportFile = async () => {+ if (!begin()) return;+ try {+ const chosen = templates.filter((template) => selected.includes(template.id));+ const contents = serializeGeneratorSlop(chosen);+ if (await saveSlopFile(contents, chosen.length === 1 ? chosen[0].name : "generators") && mounted.current) {+ setChoosing(false); setMessage(`Exported ${chosen.length} generator ${chosen.length === 1 ? "template" : "templates"}.`);+ }+ } catch (reason) { fail(reason); } finally { finish(); }+ };+ return <>+ <SettingsCard icon={<Video20 />} header="Share generator templates" description="Share download URLs and generator settings in a .slop file.">+ <button type="button" className="secondary-button" disabled={busy} onClick={() => void importFile()}>Import</button>+ <button type="button" className="secondary-button" disabled={busy} onClick={() => {+ setError(null); setMessage(null); setSelected(choices.filter((choice) => !choice.reason).slice(0, 100).map(({ template }) => template.id)); setChoosing(true);+ }}>Export</button>+ </SettingsCard>+ <input ref={input} type="file" accept=".slop,application/json" hidden aria-label="Import .slop file" disabled={busy} onChange={(event) => {+ const file = event.target.files?.[0]; event.target.value = "";+ if (!file || !begin()) return;+ void readBrowserSlopFile(file).then(accept).catch(fail).finally(finish);+ }} />+ {error && !choosing && <InfoBar severity="error" title="Couldn’t share generator templates" message={error} onClose={() => setError(null)} />}+ {message && <InfoBar severity="success" title={message} onClose={() => setMessage(null)} />}+ {choosing && <ContentDialog title="Export generator templates" primaryText={busy ? "Exporting…" : "Export"} primaryDisabled={busy || selected.length === 0 || selected.length > 100}+ onPrimary={() => void exportFile()} closeText="Cancel" closeDisabled={busy} disableEscape={busy} onClose={() => { setChoosing(false); setError(null); }}>+ <p>Choose up to 100 templates to share. Each model file and LoRA needs a download URL.</p>+ <div className="generator-sharing__choices">+ {choices.map(({ template, reason }) => <div className="generator-sharing__choice" key={template.id}>+ <Checkbox label={template.name} description={reason ?? undefined} aria-label={`Export ${template.name}`} checked={selected.includes(template.id)} disabled={busy || Boolean(reason)}+ onChange={(checked) => setSelected((current) => checked ? [...current, template.id] : current.filter((id) => id !== template.id))} />+ </div>)}+ </div>+ {error && <InfoBar severity="error" title="Couldn’t export templates" message={error} />}+ </ContentDialog>}+ </>;+}diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsxindex 2203885..b2ed816 100644--- a/src/components/SettingsView.tsx+++ b/src/components/SettingsView.tsx@@ -1,4 +1,5 @@import { AdditionalSafetensorsEditor } from "./AdditionalSafetensorsEditor";+import { GeneratorSharing } from "./GeneratorSharing";import {Add20, Agent16, Agent16Filled, Agent20, Back16, Check14, Check16, Check20, ChevronRight20, Delete16, Diagnostics16,Diagnostics16Filled, Download16, Download20, Error16, Error20, Flash20, Folder20, Gauge20, Gpu20, Image20, ModelFile20, More16,@@ -575,6 +576,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine", titleBarconst generatorList = <>{downloadStatus}+ <GeneratorSharing templates={templateSettings.templates} /><ReferenceIconSetting templates={templateSettings} />{generatorSections.filter((section) => section.id === "generators" || section.templates.length > 0).map((section) => <SettingsGroup key={section.id} heading={section.title}>{section.id === "generators" && <SettingsCard icon={<Add20 />} header="Add a generator" description="Choose the generator used by default, or open one to edit its model setup">diff --git a/src/lib/settings.ts b/src/lib/settings.tsindex 1b1a3ff..7c8fc65 100644--- a/src/lib/settings.ts+++ b/src/lib/settings.ts@@ -466,11 +466,12 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {}}-export function saveGeneratorTemplateSettings(settings: GeneratorTemplateSettings): void {+export function saveGeneratorTemplateSettings(settings: GeneratorTemplateSettings, options: { strict?: boolean } = {}): void {const normalized = normalizeTemplateSettings(settings) ?? initialTemplateSettings();try {localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));- } catch {+ } catch (error) {+ if (options.strict) throw error;/* The current React state remains usable for this session. */}queueMicrotask(() => window.dispatchEvent(new Event(GENERATOR_TEMPLATES_EVENT)));diff --git a/src/lib/slop.test.ts b/src/lib/slop.test.tsnew file mode 100644index 0000000..ca1b70e--- /dev/null+++ b/src/lib/slop.test.ts@@ -0,0 +1,108 @@+// @vitest-environment jsdom+import { beforeEach, describe, expect, it, vi } from "vitest";+import { importGeneratorSlop, MAX_SLOP_BYTES, mergeGeneratorSlop, parseGeneratorSlop, portableGenerator, serializeGeneratorSlop } from "./slop";+import { createGeneratorTemplate, loadGeneratorTemplateSettings, minimaxOriginalTemplate, minimaxSingularityTemplate, saveGeneratorTemplateSettings, viggleAnimateTemplate } from "./settings";+import { loadLoras, saveLoras, TURBO_LORA } from "./loras";++beforeEach(() => { localStorage.clear(); vi.restoreAllMocks(); });++describe("portable generator bundles", () => {+ it("exports downloaded weights as URL variants, keeping metadata and dropping all machine state", () => {+ const template = minimaxOriginalTemplate();+ template.paths.transformer = "C:/private/person/model.safetensors";+ template.sources!.transformer![0].downloadedPath = template.paths.transformer;+ template.additionalSafetensors = [{ id: "local-extra", name: "Extra", url: "https://example.com/extra.safetensors", downloadedPath: "C:/private/extra.safetensors" }];+ template.loras = [{ loraId: "private-lora-id", enabled: true, strength: .75 }];+ const text = serializeGeneratorSlop([template], [{ id: "private-lora-id", name: "Custom", path: "C:/private/lora.safetensors", url: "https://example.com/lora.safetensors", stepOverride: 6, needsPreparation: true }]);+ expect(text).not.toMatch(/C:\/private|downloadedPath|needsPreparation|private-lora-id|local-extra|"paths"/);+ const data = parseGeneratorSlop(text).items[0].data;+ expect(data.sources.transformer).toEqual(template.sources!.transformer!.map(({ downloadedPath: _path, ...source }) => source));+ expect(data.loras).toEqual([{ name: "Custom", url: "https://example.com/lora.safetensors", enabled: true, strength: .75, stepOverride: 6 }]);+ expect(data.additionalSafetensors).toEqual([{ name: "Extra", url: "https://example.com/extra.safetensors" }]);+ });+ it("round trips prompt, accelerated and Animate templates including LoRA recipes and conditioning", () => {+ const templates = [minimaxOriginalTemplate(), minimaxSingularityTemplate(), viggleAnimateTemplate()];+ templates[0].motionCache = true;+ const bundle = parseGeneratorSlop(serializeGeneratorSlop(templates));+ const current = { templates: [createGeneratorTemplate("Existing")], defaultTemplateId: "existing", catalogVersion: 9 };+ const merged = mergeGeneratorSlop(bundle, current, loadLoras());+ expect(merged.settings.defaultTemplateId).toBe("existing");+ expect(merged.settings.templates[0]).toBe(current.templates[0]);+ expect(merged.imported.map((item) => portableGenerator(item, merged.loras))).toEqual(bundle.items.map(({ data }) => data));+ expect(merged.imported[2].additionalSafetensors![0].role).toBe("promptEmbedding");+ expect(merged.imported[1].loras![0].loraId).toBe(TURBO_LORA.id);+ });+ it("does not silently share missing local files or unresolvable LoRAs", () => {+ const local = minimaxOriginalTemplate(); local.paths.tokenizer = "C:/private/tokenizer";+ expect(() => portableGenerator(local)).toThrow(/Tokenizer/);+ const missing = createGeneratorTemplate("Empty");+ expect(() => portableGenerator(missing)).toThrow(/download URL/);+ const lora = minimaxOriginalTemplate(); lora.loras = [{ loraId: "unknown", enabled: false, strength: 0 }];+ expect(() => portableGenerator(lora, [])).toThrow(/unknown/);+ });+ it("adds fresh template IDs and conflict-free names, reusing matching LoRAs without changing them", () => {+ const template = minimaxSingularityTemplate();+ const existingLora = { ...TURBO_LORA, path: "D:/downloaded.safetensors" };+ const current = { templates: [template, { ...template, id: "other", name: `${template.name} (2)` }], defaultTemplateId: template.id, catalogVersion: 9 };+ const result = mergeGeneratorSlop(parseGeneratorSlop(serializeGeneratorSlop([template, template], [existingLora])), current, [existingLora]);+ expect(result.imported.map((t) => t.name)).toEqual([`${template.name} (3)`, `${template.name} (4)`]);+ expect(new Set(result.settings.templates.map((t) => t.id)).size).toBe(4);+ expect(result.loras).toEqual([existingLora]);+ expect(result.settings.defaultTemplateId).toBe(template.id);+ });+ it("imports custom LoRAs with distinct recipes and preserves unrelated settings", () => {+ const template = minimaxOriginalTemplate(); template.loras = [{ loraId: "custom", enabled: true, strength: 1.25 }];+ const lora = { id: "custom", name: "My adapter", path: "", url: "https://example.com/lora", samplingPreset: "dmad-4step" as const };+ const text = serializeGeneratorSlop([template], [lora]);+ saveLoras([{ ...lora, samplingPreset: undefined, path: "D:/different-recipe.safetensors" }]);+ localStorage.setItem("slopus.test-secret", "private");+ const before = loadGeneratorTemplateSettings();+ const [imported] = importGeneratorSlop(text);+ const reopened = loadGeneratorTemplateSettings();+ expect(reopened.templates).toHaveLength(before.templates.length + 1);+ expect(reopened.defaultTemplateId).toBe(before.defaultTemplateId);+ expect(localStorage.getItem("slopus.test-secret")).toBe("private");+ expect(loadLoras().find((entry) => entry.id === imported.loras![0].loraId)).toMatchObject({ url: lora.url, path: "", samplingPreset: "dmad-4step" });+ expect(imported.loras![0].loraId).not.toBe("custom");+ });+ it("reports storage errors and rolls back newly added LoRAs", () => {+ const template = minimaxOriginalTemplate(); template.loras = [{ loraId: "new", enabled: true, strength: 1 }];+ const text = serializeGeneratorSlop([template], [{ id: "new", name: "New", path: "", url: "https://example.com/new" }]);+ saveGeneratorTemplateSettings(loadGeneratorTemplateSettings());+ const before = loadGeneratorTemplateSettings();+ const loras = loadLoras(); const setItem = Storage.prototype.setItem;+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(function (this: Storage, key, value) {+ if (key === "slopus.generator-templates.v1") throw new Error("Storage full");+ setItem.call(this, key, value);+ });+ expect(() => importGeneratorSlop(text)).toThrow("Storage full");+ expect(loadLoras()).toEqual(loras);+ expect(loadGeneratorTemplateSettings()).toEqual(before);+ });+});++describe("slop validation", () => {+ const valid = () => JSON.parse(serializeGeneratorSlop([minimaxOriginalTemplate()]));+ it("supports a UTF-8 BOM and rejects invalid, empty and oversized documents", () => {+ expect(parseGeneratorSlop("\uFEFF" + JSON.stringify(valid())).items).toHaveLength(1);+ for (const text of ["{", "null", "[]", "{}", '{"format":"slop","version":1,"items":[]}']) expect(() => parseGeneratorSlop(text)).toThrow();+ expect(() => parseGeneratorSlop(" ".repeat(MAX_SLOP_BYTES + 1))).toThrow(/4 MB/);+ expect(() => serializeGeneratorSlop([])).toThrow(/Choose/);+ });+ it.each([+ (bundle: ReturnType<typeof valid>) => { bundle.version = 2; },+ (bundle: ReturnType<typeof valid>) => { bundle.items[0].version = 2; },+ (bundle: ReturnType<typeof valid>) => { bundle.items.push({ type: "project-template", version: 1, data: {} }); },+ (bundle: ReturnType<typeof valid>) => { bundle.items[0].data.sources.transformer[0].url = "file:///C:/private/model"; },+ (bundle: ReturnType<typeof valid>) => { bundle.items[0].data.sources.transformer[0].url = "https://user:[email protected]/model"; },+ (bundle: ReturnType<typeof valid>) => { bundle.items[0].data.sources.transformer[0].downloadedPath = "C:/private/model"; },+ (bundle: ReturnType<typeof valid>) => { bundle.items[0].data.defaultSteps = 0; },+ (bundle: ReturnType<typeof valid>) => { delete bundle.items[0].data.sources.audioVae; },+ (bundle: ReturnType<typeof valid>) => { bundle.items[0].data.mode = "animate"; },+ ])("refuses the entire import without changing settings", (invalidate) => {+ const bundle = valid(); invalidate(bundle);+ const settings = loadGeneratorTemplateSettings(), loras = loadLoras();+ expect(() => importGeneratorSlop(JSON.stringify(bundle))).toThrow();+ expect(loadGeneratorTemplateSettings()).toEqual(settings); expect(loadLoras()).toEqual(loras);+ });+});diff --git a/src/lib/slop.ts b/src/lib/slop.tsnew file mode 100644index 0000000..9d5d630--- /dev/null+++ b/src/lib/slop.ts@@ -0,0 +1,153 @@+import { z } from "zod";+import { MAX_GENERATION_STEPS } from "./project";+import { loadLoras, MAX_LORA_STRENGTH, saveLoras, type Lora } from "./loras";+import {+ createGeneratorTemplate, EMPTY_ENGINE_SETTINGS, ENGINE_PATH_FIELDS, generatorPathFields,+ isDownloadUrl, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings,+ type GeneratorTemplate, type GeneratorTemplateSettings,+} from "./settings";++export const MAX_SLOP_BYTES = 4 * 1024 * 1024;+const name = z.string().trim().min(1).max(256);+const url = z.string().trim().max(8192).url().refine((value) => {+ try { const parsed = new URL(value); return ["http:", "https:"].includes(parsed.protocol) && !parsed.username && !parsed.password; }+ catch { return false; }+}, "Use an HTTP or HTTPS download URL without embedded credentials.");+const steps = z.number().int().min(2).max(MAX_GENERATION_STEPS);+const sourceSchema = z.object({ url, gpuModel: z.string().max(256).default(""), minVramGb: z.number().finite().min(0).max(1048576).default(0) }).strict();+const sourcesSchema = z.object({+ transformer: z.array(sourceSchema).min(1).max(64).optional(),+ textEncoder: z.array(sourceSchema).min(1).max(64).optional(),+ tokenizer: z.array(sourceSchema).min(1).max(64).optional(),+ videoVae: z.array(sourceSchema).min(1).max(64).optional(),+ audioVae: z.array(sourceSchema).min(1).max(64).optional(),+}).strict();+const portableLoraSchema = z.object({+ name, url, enabled: z.boolean(), strength: z.number().finite().min(-MAX_LORA_STRENGTH).max(MAX_LORA_STRENGTH),+ stepOverride: steps.optional(), samplingPreset: z.literal("dmad-4step").optional(),+}).strict();+export const portableGeneratorSchema = z.object({+ name, modelType: name, defaultSteps: steps, attention: z.enum(["exact", "flash2", "sage2"]),+ mode: z.enum(["prompt", "animate"]).default("prompt"), motionCache: z.boolean().default(false),+ sources: sourcesSchema,+ loras: z.array(portableLoraSchema).max(128).default([]),+ additionalSafetensors: z.array(z.object({ name, url, role: z.literal("promptEmbedding").optional() }).strict()).max(128).default([]),+}).strict().superRefine((template, context) => {+ for (const field of generatorPathFields(template)) {+ if (field.required && !template.sources[field.id]?.length) context.addIssue({ code: "custom", path: ["sources", field.id], message: `${field.label} needs a download URL.` });+ }+ if (template.mode === "animate" && !template.additionalSafetensors.some((file) => file.role === "promptEmbedding")) {+ context.addIssue({ code: "custom", path: ["additionalSafetensors"], message: "Animate templates need a prompt embedding download URL." });+ }+});+export type PortableGenerator = z.infer<typeof portableGeneratorSchema>;++/** Each entry has its own type and version; future payloads do not require+ * changing the envelope or pretending to be generator settings. */+const envelopeSchema = z.object({+ format: z.literal("slop"), version: z.literal(1),+ items: z.array(z.object({ type: name, version: z.number().int().positive(), data: z.unknown() }).strict()).min(1).max(100),+}).strict();+export interface GeneratorSlop {+ format: "slop"; version: 1;+ items: { type: "generator-template"; version: 1; data: PortableGenerator }[];+}++function validatedGenerator(value: unknown, label: string): PortableGenerator {+ const result = portableGeneratorSchema.safeParse(value);+ if (!result.success) {+ const issue = result.error.issues[0];+ throw new Error(`${label}: ${issue.path.join(".") || "template"}: ${issue.message}`);+ }+ return result.data;+}++/** Explicit projection is deliberate: machine paths, IDs, credentials and+ * download/preparation state are never serialized into a shared template. */+export function portableGenerator(template: GeneratorTemplate, library = loadLoras()): PortableGenerator {+ const sources: PortableGenerator["sources"] = {};+ for (const field of ENGINE_PATH_FIELDS) {+ const entries = (template.sources?.[field.id] ?? []).map((source) => ({ url: source.url, gpuModel: source.gpuModel, minVramGb: source.minVramGb }));+ const path = template.paths[field.id].trim();+ if (isDownloadUrl(path) && !entries.some((source) => source.url === path)) entries.unshift({ url: path, gpuModel: "", minVramGb: 0 });+ if (path && !isDownloadUrl(path) && !entries.length) throw new Error(`${template.name}: add a download URL for ${field.label} before sharing.`);+ if (entries.length) sources[field.id] = entries;+ }+ const loras = (template.loras ?? []).map((selection) => {+ const lora = library.find(({ id }) => id === selection.loraId);+ if (!lora?.url) throw new Error(`${template.name}: add a download URL for LoRA ${lora?.name ?? selection.loraId} before sharing.`);+ return { name: lora.name, url: lora.url, enabled: selection.enabled, strength: selection.strength,+ ...(lora.stepOverride !== undefined ? { stepOverride: lora.stepOverride } : {}),+ ...(lora.samplingPreset ? { samplingPreset: lora.samplingPreset } : {}) };+ });+ return validatedGenerator({+ name: template.name, modelType: template.modelType, defaultSteps: template.defaultSteps, attention: template.attention,+ mode: template.mode ?? "prompt", motionCache: template.motionCache ?? false, sources, loras,+ additionalSafetensors: (template.additionalSafetensors ?? []).map((file) => ({ name: file.name, url: file.url, ...(file.role ? { role: file.role } : {}) })),+ }, template.name);+}++export function serializeGeneratorSlop(templates: GeneratorTemplate[], library = loadLoras()): string {+ if (!templates.length || templates.length > 100) throw new Error("Choose between 1 and 100 generator templates to export.");+ const document: GeneratorSlop = { format: "slop", version: 1, items: templates.map((template) => ({ type: "generator-template", version: 1, data: portableGenerator(template, library) })) };+ const text = JSON.stringify(document, null, 2) + "\n";+ if (new TextEncoder().encode(text).byteLength > MAX_SLOP_BYTES) throw new Error("The .slop file exceeds 4 MB. Export fewer templates.");+ return text;+}++export function parseGeneratorSlop(text: string): GeneratorSlop {+ if (new TextEncoder().encode(text).byteLength > MAX_SLOP_BYTES) throw new Error("The .slop file exceeds 4 MB.");+ let raw: unknown;+ try { raw = JSON.parse(text.replace(/^\uFEFF/, "")); } catch { throw new Error("This .slop file is not valid JSON."); }+ if (raw && typeof raw === "object" && "format" in raw && raw.format === "slop" && "version" in raw && raw.version !== 1) throw new Error("This .slop format version is not supported. Update Slopus to open it.");+ const result = envelopeSchema.safeParse(raw);+ if (!result.success) throw new Error("This is not a valid .slop bundle. Expected format, version and a nonempty items array.");+ return { format: "slop", version: 1, items: result.data.items.map((item, index) => {+ if (item.type !== "generator-template" || item.version !== 1) throw new Error(`Entry ${index + 1}: ${item.type} version ${item.version} is not supported here. No templates were imported.`);+ return { type: "generator-template", version: 1, data: validatedGenerator(item.data, `Entry ${index + 1}`) };+ }) };+}++export function mergeGeneratorSlop(document: GeneratorSlop, current: GeneratorTemplateSettings, library: Lora[]) {+ const loras = [...library];+ const names = new Set(current.templates.map((template) => template.name.toLowerCase()));+ const imported = document.items.map(({ data }) => {+ let title = data.name, suffix = 2;+ while (names.has(title.toLowerCase())) {+ const ending = ` (${suffix++})`;+ title = `${data.name.slice(0, 256 - ending.length)}${ending}`;+ }+ names.add(title.toLowerCase());+ const template = createGeneratorTemplate(title, data.modelType);+ const paths = { ...EMPTY_ENGINE_SETTINGS };+ for (const field of ENGINE_PATH_FIELDS) paths[field.id] = data.sources[field.id]?.[0]?.url ?? "";+ return { ...template, defaultSteps: data.defaultSteps, attention: data.attention, mode: data.mode, motionCache: data.motionCache,+ paths, sources: structuredClone(data.sources),+ additionalSafetensors: data.additionalSafetensors.map((file) => ({ ...file, id: `additional-${crypto.randomUUID()}` })),+ loras: data.loras.map((entry) => {+ let lora = loras.find((existing) => existing.url === entry.url && existing.stepOverride === entry.stepOverride && existing.samplingPreset === entry.samplingPreset);+ if (!lora) {+ lora = { id: `lora-${crypto.randomUUID()}`, name: entry.name, path: "", url: entry.url,+ ...(entry.stepOverride !== undefined ? { stepOverride: entry.stepOverride } : {}),+ ...(entry.samplingPreset ? { samplingPreset: entry.samplingPreset } : {}) };+ loras.push(lora);+ }+ return { loraId: lora.id, enabled: entry.enabled, strength: entry.strength };+ }),+ } satisfies GeneratorTemplate;+ });+ return { settings: { ...current, templates: [...current.templates, ...imported] }, loras, imported };+}++export function importGeneratorSlop(text: string): GeneratorTemplate[] {+ // Validate the entire bundle before touching either settings store, and read+ // fresh settings after the file dialog so concurrent edits/downloads survive.+ const document = parseGeneratorSlop(text);+ const previousLoras = loadLoras();+ const next = mergeGeneratorSlop(document, loadGeneratorTemplateSettings(), previousLoras);+ const addedLoras = next.loras.length !== previousLoras.length;+ if (addedLoras) saveLoras(next.loras);+ try { saveGeneratorTemplateSettings(next.settings, { strict: true }); }+ catch (error) { if (addedLoras) saveLoras(previousLoras); throw error; }+ return next.imported;+}diff --git a/src/lib/slopFiles.ts b/src/lib/slopFiles.tsnew file mode 100644index 0000000..b4a547a--- /dev/null+++ b/src/lib/slopFiles.ts@@ -0,0 +1,23 @@+import { invoke } from "@tauri-apps/api/core";+import { inTauri } from "./nativeShell";+import { MAX_SLOP_BYTES } from "./slop";++export async function openSlopFile(): Promise<string | null> {+ return invoke<string | null>("import_slop_file");+}++export async function readBrowserSlopFile(file: File): Promise<string> {+ if (!file.name.toLowerCase().endsWith(".slop")) throw new Error("Choose a .slop file.");+ if (file.size > MAX_SLOP_BYTES) throw new Error("The .slop file exceeds 4 MB.");+ return file.text();+}++export async function saveSlopFile(contents: string, name: string): Promise<boolean> {+ const filename = `${name.replace(/[<>:"/\\|?*\x00-\x1f]/g, "-").trim().replace(/[. ]+$/, "").slice(0, 120) || "generators"}.slop`;+ if (inTauri()) return invoke<boolean>("export_slop_file", { contents, filename });+ const url = URL.createObjectURL(new Blob([contents], { type: "application/json" }));+ const link = document.createElement("a");+ link.href = url; link.download = filename; document.body.append(link); link.click(); link.remove();+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);+ return true;+}diff --git a/src/styles/settings.css b/src/styles/settings.cssindex 467af5f..c44ce84 100644--- a/src/styles/settings.css+++ b/src/styles/settings.css@@ -15,6 +15,25 @@/* --- Page frame ----------------------------------------------------------- */+.generator-sharing__choices {+ display: grid;+ gap: var(--space-3);+ max-height: 360px;+ overflow-y: auto;+ margin-top: var(--space-3);+}++.generator-sharing__choice {+ display: grid;+ gap: var(--space-1);+}++.generator-sharing__choice > label {+ display: flex;+ align-items: center;+ gap: var(--space-2);+}+.settings-view {flex: 1;width: 100%;