Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Support local upscaler weights

Bitti27b338d7a3a4
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 3fc6732..452fc5f 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -32,6 +32,7 @@ This alpha update adds LAN generation workers, Linux support, expanded color gra
## Fixes and improvements
+- Real-ESRGAN and SeedVR2 weights support local file paths in Other weights settings. SeedVR2 sends selected local files to the worker and downloads any missing components there.
- Scene continuation offers a Lock Overlap toggle for local and worker generation, constraining overlapping video and audio to the source scene.
- Image and video exports share a work queue with progress, cancellation, and retained results. SeedVR2 upscaling runs on the selected CUDA worker, which prepares its own models.
- Upscaler downloads share the generator and LoRA download queue, with progress in Work Queue and cancellation for waiting downloads.
diff --git a/src-tauri/core/src/worker/protocol.rs b/src-tauri/core/src/worker/protocol.rs
index 44d7c99..dd08dc2 100644
--- a/src-tauri/core/src/worker/protocol.rs
+++ b/src-tauri/core/src/worker/protocol.rs
@@ -9,9 +9,10 @@ use std::collections::BTreeMap;
pub const SERVICE_TYPE: &str = "_slopus-worker._tcp.local.";
/// Bumped on any incompatible change to the routes or bodies below.
-// v5 carries overlap locking; older workers would silently ignore it.
+// v6 carries custom upscale weights; older workers would silently ignore them.
+// v5 added overlap locking.
// v4 added SeedVR2 export streams. v3 added inverted image masks.
-pub const PROTOCOL_VERSION: u32 = 5;
+pub const PROTOCOL_VERSION: u32 = 6;
/// Streaming SeedVR2 restoration; model paths are resolved on the worker.
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -22,6 +23,10 @@ pub struct StartUpscale {
pub width: u32,
pub height: u32,
pub segment_frames: u32,
+ #[serde(default)]
+ pub model: Option<FileRef>,
+ #[serde(default)]
+ pub vae: Option<FileRef>,
}
pub const SEEDVR2_MODEL: &str = "https://huggingface.co/Comfy-Org/SeedVR2/resolve/main/diffusion_models/seedvr2_3b_fp16.safetensors";
pub const SEEDVR2_VAE: &str = "https://huggingface.co/Comfy-Org/SeedVR2/resolve/main/vae/seedvr2_ema_vae_fp16.safetensors";
diff --git a/src-tauri/core/src/worker/server.rs b/src-tauri/core/src/worker/server.rs
index 8a90f0a..862d2ad 100644
--- a/src-tauri/core/src/worker/server.rs
+++ b/src-tauri/core/src/worker/server.rs
@@ -403,7 +403,8 @@ impl Worker {
if !sessions.is_empty() { return Err("Another upscale export is running on this worker.".into()); }
let store = self.store.clone();
let session = crate::upscale_stream::Session::start((options.input_width, options.input_height), (options.width, options.height), move |stop, read, write| {
- let files = [FileRef::Url { url: SEEDVR2_MODEL.into(), lora: false }, FileRef::Url { url: SEEDVR2_VAE.into(), lora: false }];
+ let files = [options.model.unwrap_or(FileRef::Url { url: SEEDVR2_MODEL.into(), lora: false }),
+ options.vae.unwrap_or(FileRef::Url { url: SEEDVR2_VAE.into(), lora: false })];
store.prepare(&files, stop, |_| {})?;
let config = slopfab::upscale::UpscaleConfig { method: slopfab::upscale::UpscaleMethod::Seedvr2,
model_path: store.resolve(&files[0])?.to_string_lossy().into_owned(),
diff --git a/src-tauri/src/upscale.rs b/src-tauri/src/upscale.rs
index f0afca0..5c7bb28 100644
--- a/src-tauri/src/upscale.rs
+++ b/src-tauri/src/upscale.rs
@@ -14,7 +14,9 @@ pub(crate) fn run(workers: &Workers, id: &str, config: &UpscaleConfig,
write: &mut (dyn FnMut(Vec<u8>) -> Result<(), String> + Send)) -> Result<u64, String> {
if config.method == UpscaleMethod::Seedvr2 {
let worker = workers.active()?.ok_or("Select a worker in Settings → Workers to use SeedVR2 upscaling.")?;
- worker.upscale(id, &StartUpscale { input_width: input.0, input_height: input.1, width: output.0, height: output.1, segment_frames }, stop, read, write)
+ let [model, vae] = workers.prepare_upscale_files(&worker, id, config, stop)?;
+ worker.upscale(id, &StartUpscale { input_width: input.0, input_height: input.1, width: output.0, height: output.1, segment_frames,
+ model: Some(model), vae: Some(vae) }, stop, read, write)
} else {
upscale::run(config, input, output, segment_frames as i32, stop, read, write)
}
diff --git a/src-tauri/src/worker/client.rs b/src-tauri/src/worker/client.rs
index 77c72a0..5638121 100644
--- a/src-tauri/src/worker/client.rs
+++ b/src-tauri/src/worker/client.rs
@@ -265,6 +265,39 @@ fn probe(address: &str, token: Option<&str>) -> Result<WorkerInfo, String> {
}
impl Workers {
+ /// Reuse the generation upload cache for explicitly selected local upscaler files.
+ pub(crate) fn prepare_upscale_files(&self, connection: &Connection, id: &str,
+ config: &slopfab::upscale::UpscaleConfig, stop: &AtomicBool) -> Result<[FileRef; 2], String> {
+ if !connection.info.runtime.cuda_available { return Err(format!("Worker {} needs CUDA for SeedVR2.", connection.name)); }
+ let mut sources = HashMap::new();
+ let mut source = |path: &str, url: &str| {
+ if path.trim().is_empty() { Ok(FileRef::Url { url: url.into(), lora: false }) }
+ else { file_ref(PathKind::Input, path, &mut sources) }
+ };
+ let files = [source(&config.model_path, SEEDVR2_MODEL)?, source(config.vae_path.as_deref().unwrap_or(""), SEEDVR2_VAE)?];
+ let uploads: Vec<_> = files.iter().filter(|file| matches!(file, FileRef::Upload { .. })).cloned().collect();
+ if stop.load(Ordering::Acquire) { return Err("Export cancelled.".into()); }
+ if !uploads.is_empty() {
+ let job = RemoteJob { request: GenerationRequest { job_id: id.into(), ..Default::default() },
+ settings: BTreeMap::new(), files: uploads, continuation: None, image_edit_source: None };
+ let cancel = Arc::new(AtomicBool::new(false));
+ let finished = AtomicBool::new(false);
+ std::thread::scope(|scope| {
+ scope.spawn(|| {
+ while !finished.load(Ordering::Acquire) {
+ if stop.load(Ordering::Acquire) { cancel.store(true, Ordering::Release); break; }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ });
+ let result = self.send_files(connection, &job, &sources, &cancel);
+ finished.store(true, Ordering::Release);
+ result
+ })?;
+ }
+ if stop.load(Ordering::Acquire) { return Err("Export cancelled.".into()); }
+ Ok(files)
+ }
+
/// Loads the saved selection and starts listening for workers.
pub fn start(&self, app: &AppHandle, data_directory: &Path) {
let _ = APP.set(app.clone());
@@ -944,6 +977,15 @@ mod tests {
fn upscale_stream_sends_and_receives_frames_with_bounded_backpressure() {
let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
let address = server.server_addr().to_ip().unwrap().to_string();
+ let folder = tempfile::tempdir().unwrap();
+ let store = Arc::new(slopus_core::worker::store::FileStore::new(&folder.path().join("worker"), Vec::new()).unwrap());
+ let uploads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let uploaded = uploads.clone();
+ let config = slopfab::upscale::UpscaleConfig { method: slopfab::upscale::UpscaleMethod::Seedvr2,
+ model_path: folder.path().join("model.safetensors").to_string_lossy().into_owned(),
+ vae_path: Some(folder.path().join("vae.safetensors").to_string_lossy().into_owned()) };
+ fs::write(&config.model_path, b"custom model").unwrap();
+ fs::write(config.vae_path.as_ref().unwrap(), b"custom vae").unwrap();
let session = slopus_core::upscale_stream::Session::start((1, 1), (1, 1), |_, read, write| {
// Like SeedVR2, wait for a temporal segment before writing output.
let mut frames = Vec::new();
@@ -955,11 +997,28 @@ mod tests {
let server_thread = std::thread::spawn(move || {
while let Some(mut request) = server.recv_timeout(Duration::from_secs(5)).unwrap() {
let session = session.clone();
+ let store = store.clone();
+ let uploaded = uploaded.clone();
let remove = request.method() == &tiny_http::Method::Delete;
std::thread::spawn(move || {
assert!(request.headers().iter().any(|header| header.field.equiv(TOKEN_HEADER) && header.value.as_str() == "test-token"));
let response = match (request.method().clone(), request.url()) {
- (tiny_http::Method::Post, "/v1/upscales/test") => b"true".to_vec(),
+ (tiny_http::Method::Post, "/v1/uploads/missing") => {
+ let files: Vec<FileRef> = serde_json::from_reader(request.as_reader()).unwrap();
+ serde_json::to_vec(&MissingUploads { missing: store.missing(&files).unwrap() }).unwrap()
+ }
+ (tiny_http::Method::Put, path) if path.starts_with("/v1/uploads/") => {
+ let parts: Vec<_> = path.split('/').map(str::to_owned).collect();
+ store.receive(&parts[3], &parts[4], request.body_length().unwrap() as u64, request.as_reader()).unwrap();
+ uploaded.fetch_add(1, Ordering::Relaxed);
+ b"true".to_vec()
+ }
+ (tiny_http::Method::Post, "/v1/upscales/test") => {
+ let options: StartUpscale = serde_json::from_reader(request.as_reader()).unwrap();
+ assert_eq!(fs::read(store.resolve(options.model.as_ref().unwrap()).unwrap()).unwrap(), b"custom model");
+ assert_eq!(fs::read(store.resolve(options.vae.as_ref().unwrap()).unwrap()).unwrap(), b"custom vae");
+ b"true".to_vec()
+ }
(tiny_http::Method::Post, "/v1/upscales/test/frames") => {
let mut bytes = Vec::new(); request.as_reader().read_to_end(&mut bytes).unwrap();
session.push(bytes).unwrap(); b"true".to_vec()
@@ -978,9 +1037,18 @@ mod tests {
requires_token: true, gpus: Vec::new(), runtime: WorkerRuntime { state: "ready".into(), version: None,
platform: None, cuda_available: true, cuda_device_names: Vec::new(), detail: String::new() } };
let connection = Connection { base: format!("http://{address}"), token: Some("test-token".into()), name: "Stub".into(), address, info, http: http_client(Some(Duration::from_secs(5))) };
+ let workers = Workers::default();
+ let files = workers.prepare_upscale_files(&connection, "test", &config, &AtomicBool::new(false)).unwrap();
+ assert_eq!(workers.prepare_upscale_files(&connection, "test", &config, &AtomicBool::new(false)).unwrap(), files);
+ assert_eq!(uploads.load(Ordering::Relaxed), 2, "unchanged weights are uploaded only once");
+ assert!(workers.prepare_upscale_files(&connection, "test", &config, &AtomicBool::new(true)).is_err());
+ let default_config = slopfab::upscale::UpscaleConfig { model_path: String::new(), vae_path: None, ..config };
+ let defaults = workers.prepare_upscale_files(&connection, "test", &default_config, &AtomicBool::new(false)).unwrap();
+ assert_eq!(defaults, [FileRef::Url { url: SEEDVR2_MODEL.into(), lora: false }, FileRef::Url { url: SEEDVR2_VAE.into(), lora: false }]);
+ let [model, vae] = files;
let mut source = vec![vec![1; 4], vec![2; 4], vec![3; 4], vec![4; 4], vec![5; 4]].into_iter();
let mut frames = Vec::new();
- let count = connection.upscale("test", &StartUpscale { input_width: 1, input_height: 1, width: 1, height: 1, segment_frames: 5 },
+ let count = connection.upscale("test", &StartUpscale { input_width: 1, input_height: 1, width: 1, height: 1, segment_frames: 5, model: Some(model), vae: Some(vae) },
&AtomicBool::new(false), &mut || Ok(source.next()), &mut |frame| { frames.push(frame); Ok(()) }).unwrap();
assert_eq!(count, 5);
assert_eq!(frames, vec![vec![1; 4], vec![2; 4], vec![3; 4], vec![4; 4], vec![5; 4]]);
diff --git a/src/components/OtherWeightsSettings.test.tsx b/src/components/OtherWeightsSettings.test.tsx
index 327a082..3956ee9 100644
--- a/src/components/OtherWeightsSettings.test.tsx
+++ b/src/components/OtherWeightsSettings.test.tsx
@@ -4,10 +4,12 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-li
import { afterEach, expect, it, vi } from "vitest";
import { invoke } from "@tauri-apps/api/core";
import { OtherWeightsSettings } from "./OtherWeightsSettings";
-import { OTHER_WEIGHT_TEMPLATES, otherWeightPaths, upscaleConfig } from "../lib/upscalers";
+import { OTHER_WEIGHT_TEMPLATES, localOtherWeightPaths, otherWeightPaths, refreshOtherWeights, upscaleConfig } from "../lib/upscalers";
+import { chooseEnginePath } from "../lib/runtime";
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn().mockResolvedValue(() => {}) }));
vi.mock("../lib/persistence", () => ({ isTauri: () => true }));
+vi.mock("../lib/runtime", () => ({ chooseEnginePath: vi.fn() }));
afterEach(() => { cleanup(); localStorage.clear(); vi.clearAllMocks(); });
it("downloads the SeedVR2 model and VAE as one template and remembers both paths", async () => {
@@ -28,3 +30,50 @@ it("downloads the SeedVR2 model and VAE as one template and remembers both paths
});
expect(upscaleConfig("none")).toBeUndefined();
});
+
+it.each(OTHER_WEIGHT_TEMPLATES)("saves local $name files and uses them for exports after refreshing downloads", async (template) => {
+ vi.mocked(invoke).mockImplementation(async (name, args) => {
+ if (name === "find_downloaded_weights") return Object.fromEntries(template.files.map((file) => [file.url, `C:/cache/${file.id}.safetensors`])) as never;
+ if (name === "check_weight_files") return Object.fromEntries((args as { paths: string[] }).paths.map((path) => [path, true])) as never;
+ return undefined as never;
+ });
+ localStorage.setItem("slopus.generation-worker.v1", JSON.stringify({ id: "worker" }));
+ render(<OtherWeightsSettings desktop />);
+ fireEvent.click(screen.getByRole("button", { name: `Edit ${template.name} weights` }));
+ for (const file of template.files) {
+ if (file.id === "model") {
+ vi.mocked(chooseEnginePath).mockResolvedValueOnce(`D:/custom/${file.id}.safetensors`);
+ fireEvent.click(screen.getByRole("button", { name: `Browse for ${file.name}` }));
+ await waitFor(() => expect(screen.getByRole("textbox", { name: `${file.name} path` })).toHaveValue(`D:/custom/${file.id}.safetensors`));
+ } else fireEvent.change(screen.getByRole("textbox", { name: `${file.name} path` }), { target: { value: `D:/custom/${file.id}.safetensors` } });
+ }
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ await refreshOtherWeights();
+ expect(upscaleConfig(template.id)).toEqual({ method: template.id, modelPath: "D:/custom/model.safetensors",
+ ...(template.id === "seedvr2" ? { vaePath: "D:/custom/vae.safetensors" } : {}) });
+ fireEvent.click(screen.getByRole("button", { name: `Edit ${template.name} weights` }));
+ for (const file of template.files) {
+ expect(screen.getByRole("textbox", { name: `${file.name} path` })).toHaveValue(`D:/custom/${file.id}.safetensors`);
+ fireEvent.change(screen.getByRole("textbox", { name: `${file.name} path` }), { target: { value: "" } });
+ }
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(localOtherWeightPaths()).toEqual({});
+ expect(otherWeightPaths()[template.files[0].url]).toBe("C:/cache/model.safetensors");
+ if (template.id === "seedvr2") expect(upscaleConfig("seedvr2")).toMatchObject({ modelPath: "", vaePath: undefined });
+});
+
+it("rejects relative paths and missing files without saving them", async () => {
+ vi.mocked(invoke).mockResolvedValue({});
+ render(<OtherWeightsSettings desktop />);
+ fireEvent.click(screen.getByRole("button", { name: "Edit Real-ESRGAN weights" }));
+ const path = screen.getByRole("textbox", { name: "RealESRGAN x4plus path" });
+ fireEvent.change(path, { target: { value: "relative.safetensors" } });
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ expect(screen.getByText("Choose local weight files using their absolute paths.")).toBeInTheDocument();
+ fireEvent.change(path, { target: { value: "C:/missing.safetensors" } });
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(screen.getByText(/Weight file not found/)).toBeInTheDocument());
+ expect(localOtherWeightPaths()).toEqual({});
+});
diff --git a/src/components/OtherWeightsSettings.tsx b/src/components/OtherWeightsSettings.tsx
index 572f0b1..ad6d5ad 100644
--- a/src/components/OtherWeightsSettings.tsx
+++ b/src/components/OtherWeightsSettings.tsx
@@ -1,31 +1,88 @@
import { useEffect, useState, useSyncExternalStore } from "react";
-import { OTHER_WEIGHT_TEMPLATES, otherWeightPaths, refreshOtherWeights, subscribeOtherWeights } from "../lib/upscalers";
+import { invoke } from "@tauri-apps/api/core";
+import { OTHER_WEIGHT_TEMPLATES, localOtherWeightPaths, otherWeightPaths, refreshOtherWeights, saveLocalOtherWeightPaths, subscribeOtherWeights } from "../lib/upscalers";
+import { chooseEnginePath } from "../lib/runtime";
import { cancelQueuedWeightDownload, cancelWeightDownload, downloadOtherWeights, getQueuedWeightDownloads, getWeightDownloadState, subscribeWeightDownloads, weightDownloadProgress } from "../lib/weightDownloads";
-import { InfoBar, ProgressBar, SettingsCard, SettingsGroup } from "./ui";
+import { ContentDialog, InfoBar, ProgressBar, SettingsGroup } from "./ui";
+import { OpenableCard } from "./OpenableCard";
import { Image20 } from "./ui/icons";
+import "../styles/loras.css";
export function OtherWeightsSettings({ desktop }: { desktop: boolean }) {
const [, refresh] = useState(0);
const [error, setError] = useState<string | null>(null);
+ const [editing, setEditing] = useState<string | null>(null);
useEffect(() => subscribeOtherWeights(() => refresh((value) => value + 1)), []);
useEffect(() => { void refreshOtherWeights().catch((reason) => setError(String(reason))); }, []);
const paths = otherWeightPaths();
+ const local = localOtherWeightPaths();
const download = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);
const queued = useSyncExternalStore(subscribeWeightDownloads, getQueuedWeightDownloads);
return <SettingsGroup heading="Other weights">
+ <div className="settings-card-list" role="list" aria-label="Other weights">
{OTHER_WEIGHT_TEMPLATES.map((template) => {
const ready = template.files.every((file) => paths[file.url]);
const active = download?.active && download.otherWeightId === template.id;
const waiting = queued.find((item) => item.otherWeightId === template.id);
- return <SettingsCard key={template.id} icon={<Image20 />} header={template.name}
- description={waiting ? "Queued for download" : active ? `Downloading ${download.currentFile ?? template.name}` : ready ? "Ready for image and video export" : template.files.map((file) => file.name).join(" · ")}>
+ return <OpenableCard key={template.id} icon={<Image20 />} header={template.name}
+ openLabel={`Edit ${template.name} weights`} onOpen={() => setEditing(template.id)}
+ description={waiting ? "Queued for download" : active ? `Downloading ${download.currentFile ?? template.name}` : ready ? "Ready for image and video export" : template.files.map((file) => file.name).join(" · ")}
+ actions={<>
{waiting ? <button type="button" onClick={() => cancelQueuedWeightDownload(waiting.templateId)}>Cancel</button>
: active ? <><ProgressBar value={weightDownloadProgress(download)} aria-label={`Downloading ${template.name} weights`} />
<button type="button" onClick={() => void cancelWeightDownload().catch((reason) => setError(String(reason)))}>Cancel</button></>
: <button type="button" className="secondary-button" disabled={!desktop || ready}
- onClick={() => void downloadOtherWeights(template.id)}>{ready ? "Downloaded" : "Download"}</button>}
- </SettingsCard>;
+ onClick={() => void downloadOtherWeights(template.id)}>{ready ? template.files.some((file) => local[file.url]) ? "Available" : "Downloaded" : "Download"}</button>}
+ </>} />;
})}
+ </div>
{(error || (download?.otherWeightId && download.error)) && <InfoBar severity="error" title="Couldn’t download weights" message={error ?? download!.error!} />}
+ {editing && <OtherWeightEditor key={editing} template={OTHER_WEIGHT_TEMPLATES.find((item) => item.id === editing)!} desktop={desktop}
+ busy={Boolean(download?.active && download.otherWeightId === editing) || queued.some((item) => item.otherWeightId === editing)} onDone={() => setEditing(null)} />}
</SettingsGroup>;
}
+
+function OtherWeightEditor({ template, desktop, busy, onDone }: {
+ template: typeof OTHER_WEIGHT_TEMPLATES[number]; desktop: boolean; busy: boolean; onDone: () => void;
+}) {
+ const [paths, setPaths] = useState(localOtherWeightPaths);
+ const [error, setError] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ const browse = async (file: typeof template.files[number]) => {
+ try {
+ const picked = await chooseEnginePath({ id: "transformer", label: file.name, hint: "", directory: false, extensions: ["safetensors"], required: false });
+ if (picked) setPaths((current) => ({ ...current, [file.url]: picked }));
+ } catch (reason) { setError(String(reason)); }
+ };
+ const save = async () => {
+ const selected = Object.fromEntries(template.files.map((file) => [file.url, (paths[file.url] ?? "").trim()]));
+ const files = Object.values(selected).filter(Boolean);
+ if (files.some((path) => !/^(?:[a-z]:[\\/]|\\\\|\/)/i.test(path) || path.includes("\0"))) {
+ setError("Choose local weight files using their absolute paths."); return;
+ }
+ try {
+ setSaving(true); setError(null);
+ if (desktop && files.length) {
+ const exists = await invoke<Record<string, boolean>>("check_weight_files", { paths: files });
+ const missing = files.find((path) => !exists?.[path]);
+ if (missing) throw new Error(`Weight file not found: ${missing}`);
+ }
+ saveLocalOtherWeightPaths(selected);
+ onDone();
+ } catch (reason) { setError(String(reason)); }
+ finally { setSaving(false); }
+ };
+ return <ContentDialog title={`${template.name} weights`} width={560} primaryText="Save" onPrimary={() => void save()}
+ primaryDisabled={saving || busy} closeText="Cancel" onClose={onDone} defaultButton="primary" disableEscape={saving}>
+ <fieldset className="lora-manual" disabled={saving || busy}>
+ <p>Choose local files, or leave paths empty to use downloaded weights.</p>
+ {template.files.map((file) => <label key={file.id}>{file.name}<span className="lora-manual__path">
+ <input className="text-field" aria-label={`${file.name} path`} value={paths[file.url] ?? ""} spellCheck={false}
+ onChange={(event) => setPaths({ ...paths, [file.url]: event.target.value })} placeholder="Absolute path to a .safetensors file" />
+ <button className="secondary-button" type="button" disabled={!desktop} aria-label={`Browse for ${file.name}`} onClick={() => void browse(file)}>Browse…</button>
+ </span></label>)}
+ {template.id === "seedvr2" && <p>Local files are sent to the selected worker for upscaling. The worker downloads any weights without a local path.</p>}
+ {error && <InfoBar severity="error" message={error} />}
+ </fieldset>
+ </ContentDialog>;
+}
diff --git a/src/lib/upscalers.ts b/src/lib/upscalers.ts
index a070ab1..ece7698 100644
--- a/src/lib/upscalers.ts
+++ b/src/lib/upscalers.ts
@@ -18,18 +18,30 @@ export const OTHER_WEIGHT_TEMPLATES = [
] },
] as const;
const KEY = "slopus.other-weights.v1";
+const LOCAL_KEY = "slopus.other-weights-local.v1";
const EVENT = "slopus:other-weights";
-export function otherWeightPaths(): Record<string, string> {
+function readPaths(key: string): Record<string, string> {
try {
- const value = JSON.parse(localStorage.getItem(KEY) ?? "{}");
+ const value = JSON.parse(localStorage.getItem(key) ?? "{}");
return Object.fromEntries(Object.entries(value).filter(([, path]) => typeof path === "string" && path && !/^https?:/i.test(path))) as Record<string, string>;
} catch { return {}; }
}
+export const localOtherWeightPaths = () => readPaths(LOCAL_KEY);
+export const otherWeightPaths = () => ({ ...readPaths(KEY), ...localOtherWeightPaths() });
+export function saveLocalOtherWeightPaths(paths: Record<string, string>) {
+ const saved = localOtherWeightPaths();
+ for (const [url, path] of Object.entries(paths)) {
+ if (path.trim()) saved[url] = path.trim();
+ else delete saved[url];
+ }
+ localStorage.setItem(LOCAL_KEY, JSON.stringify(saved));
+ window.dispatchEvent(new Event(EVENT));
+}
const savePaths = (paths: Record<string, string>) => {
localStorage.setItem(KEY, JSON.stringify(paths));
window.dispatchEvent(new Event(EVENT));
};
-export const saveOtherWeightPath = (url: string, path: string) => savePaths({ ...otherWeightPaths(), [url]: path });
+export const saveOtherWeightPath = (url: string, path: string) => savePaths({ ...readPaths(KEY), [url]: path });
export function subscribeOtherWeights(listener: () => void) {
window.addEventListener(EVENT, listener);
window.addEventListener("storage", listener);
@@ -40,11 +52,13 @@ export function upscaleConfig(method: Upscaler): UpscaleConfig | undefined {
if (method === "none") return undefined;
if (method === "seedvr2") {
if (!selectedWorker()) throw new Error("Select a worker in Settings → Workers to use SeedVR2 upscaling.");
- return { method, modelPath: "" };
+ const local = localOtherWeightPaths();
+ return { method, modelPath: local[OTHER_WEIGHT_TEMPLATES[1].files[0].url] ?? "",
+ vaePath: local[OTHER_WEIGHT_TEMPLATES[1].files[1].url] };
}
const template = OTHER_WEIGHT_TEMPLATES.find((item) => item.id === method)!;
const paths = otherWeightPaths();
- if (template.files.some((file) => !paths[file.url])) throw new Error(`Download ${template.name} in Settings → Generator → Other weights first.`);
+ if (template.files.some((file) => !paths[file.url])) throw new Error(`Download ${template.name} or choose a local weight file in Settings → Generator → Other weights first.`);
return { method, modelPath: paths[template.files[0].url] };
}
export async function refreshOtherWeights() {
diff --git a/src/lib/weightDownloadQueue.test.ts b/src/lib/weightDownloadQueue.test.ts
index 57d074b..4fecfc4 100644
--- a/src/lib/weightDownloadQueue.test.ts
+++ b/src/lib/weightDownloadQueue.test.ts
@@ -104,3 +104,19 @@ it("retries a failed upscaler through the shared pipeline and reuses its complet
transfers[2].resolve("C:/vae.safetensors"); await retry;
expect(queue.getWeightDownloadState()).toMatchObject({ active: false, completed: 2, error: null });
});
+
+it("keeps a local SeedVR2 model while downloading only its missing VAE", async () => {
+ const queue = await import("./weightDownloads");
+ const { OTHER_WEIGHT_TEMPLATES, saveLocalOtherWeightPaths, refreshOtherWeights, otherWeightPaths } = await import("./upscalers");
+ const [model, vae] = OTHER_WEIGHT_TEMPLATES[1].files;
+ saveLocalOtherWeightPaths({ [model.url]: "D:/custom/seed.safetensors" });
+ const download = queue.downloadOtherWeights("seedvr2");
+ await vi.waitFor(() => expect(transfers).toHaveLength(1));
+ expect(transfers[0].url).toBe(vae.url);
+ transfers[0].resolve("C:/downloaded/vae.safetensors");
+ await download;
+ expect(otherWeightPaths()).toMatchObject({ [model.url]: "D:/custom/seed.safetensors", [vae.url]: "C:/downloaded/vae.safetensors" });
+ saveLocalOtherWeightPaths({ [model.url]: "" });
+ expect(otherWeightPaths()[model.url]).toBeUndefined();
+ await refreshOtherWeights();
+});
diff --git a/src/lib/weightDownloads.ts b/src/lib/weightDownloads.ts
index 15307f9..4beb9fe 100644
--- a/src/lib/weightDownloads.ts
+++ b/src/lib/weightDownloads.ts
@@ -320,9 +320,10 @@ export function downloadOtherWeights(id: string): Promise<void> {
if (cancelled) throw new Error("Download cancelled.");
requestId = crypto.randomUUID();
publish({ ...state!, currentAdditionalId: file.id, currentFile: file.name, downloaded: 0, total: null });
- const path = otherWeightPaths()[file.url] ?? await invoke<string>("download_weight", { requestId, url: file.url });
+ const existing = otherWeightPaths()[file.url];
+ const path = existing ?? await invoke<string>("download_weight", { requestId, url: file.url });
if (!path || isDownloadUrl(path)) throw new Error("The download did not return a local file.");
- saveOtherWeightPath(file.url, path);
+ if (!existing) saveOtherWeightPath(file.url, path);
if (cancelled) throw new Error("Download cancelled.");
publish({ ...state!, completed: state!.completed + 1, currentAdditionalId: undefined, currentFile: undefined, downloaded: 0, total: null });
}