Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Manage downloadable generator templates

Bitti90aec4fb5800
diff --git a/docs/generator-weights.md b/docs/generator-weights.md
new file mode 100644
index 0000000..8c23a59
--- /dev/null
+++ b/docs/generator-weights.md
@@ -0,0 +1,31 @@
+# Generator weights
+
+In Settings → Generator, edit a template and enter local paths or HTTP/HTTPS
+download URLs. Hugging Face `blob` links are converted to direct file downloads.
+The bundled **Minimax H3 Original** template contains the four supplied model URLs.
+
+Open **Download variants** under a weight to add alternative URLs. Each variant
+can specify part of a GPU model name and a minimum VRAM capacity in GB. Selection
+prefers a matching GPU-specific variant, then the highest memory tier that fits;
+ties preserve the listed order. Leave the GPU field blank and VRAM at zero for a
+universal fallback. Windows hardware detection includes NVIDIA, AMD, and Intel.
+Memory tiers account for the small amount of VRAM reserved by the driver.
+
+Click the template's download icon or **Download weights** in its editor to
+download missing weights. Files go into `weights` beside `Slopus.exe`. If that
+location cannot be written, Slopus uses a `weights` subfolder beside its log file.
+Progress and cancellation remain available in Settings if the editor is closed.
+Failed transfers can be retried; completed files are retained, while an interrupted
+file starts again. No full model file is buffered in memory.
+
+After completion, the path fields show local files, while the source URLs remain
+stored. Templates needing downloads cannot be selected as default and are omitted
+from the generation picker. Missing downloaded files are checked at startup, when
+Settings or the generator page opens or regains focus, and periodically while those
+pages are open. A missing file restores its URL for redownload.
+
+For a template with download sources, the remove icon deletes its managed weight
+files and retains the template with its URLs. Manually selected files outside the
+managed download records are not deleted. Templates sharing a removed downloaded
+file also become downloadable again. Removing a template containing only manually
+configured local paths retains the previous behavior of removing the template.
diff --git a/src/components/SettingsView.downloads.test.tsx b/src/components/SettingsView.downloads.test.tsx
new file mode 100644
index 0000000..3bae8e2
--- /dev/null
+++ b/src/components/SettingsView.downloads.test.tsx
@@ -0,0 +1,69 @@
+// @vitest-environment jsdom
+import "@testing-library/jest-dom/vitest";
+import { 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 { SettingsView } from "./SettingsView";
+import { loadGeneratorTemplateSettings } from "../lib/settings";
+
+vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));
+const files = new Set<string>();
+
+beforeEach(() => {
+ localStorage.clear(); files.clear(); vi.clearAllMocks();
+ Object.defineProperty(window, "__TAURI_INTERNALS__", { configurable: true, value: {} });
+ vi.mocked(invoke).mockImplementation(async (command, args) => {
+ if (command === "weight_download_hardware") return [{ name: "RTX 5090", memoryBytes: 32 * 1024 ** 3 }];
+ if (command === "check_weight_files") return Object.fromEntries((args as { paths: string[] }).paths.map((path) => [path, files.has(path)]));
+ if (command === "remove_downloaded_weights") { for (const path of (args as { paths: string[] }).paths) files.delete(path); return; }
+ if (command === "download_weight") {
+ const path = `C:/Slopus/weights/${(args as { url: string }).url.split('/').at(-1)}`;
+ files.add(path); return path;
+ }
+ return { state: "modelsMissing", dllPath: "slopfab.dll", version: "1.4.0", platform: "Vulkan", detail: "Missing models", models: [] };
+ });
+});
+afterEach(() => { cleanup(); delete (window as Window & { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__; });
+
+it("downloads the sample, enables its default choice, and removes only weights to restore the download action", async () => {
+ render(<SettingsView onClose={() => undefined} />);
+ const radio = () => screen.getByRole("radio", { name: "Use Minimax H3 Original as the default generator" });
+ expect(radio()).toBeDisabled();
+ expect(screen.queryByRole("button", { name: "Remove generator Minimax H3 Original" })).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Download generator Minimax H3 Original" }));
+ const remove = await screen.findByRole("button", { name: "Remove downloaded weights for Minimax H3 Original" });
+ expect(radio()).toBeEnabled();
+ fireEvent.click(radio());
+ await waitFor(() => expect(loadGeneratorTemplateSettings().defaultTemplateId).toBe("minimax-h3-original"));
+ fireEvent.click(remove);
+ expect(await screen.findByRole("button", { name: "Download generator Minimax H3 Original" })).toBeEnabled();
+ expect(radio()).toBeDisabled();
+ expect(files.size).toBe(0);
+ expect(loadGeneratorTemplateSettings().templates.find((template) => template.id === "minimax-h3-original")?.paths.transformer).toMatch(/^https:/);
+});
+
+it("restores a deleted downloaded file when Settings regains focus", async () => {
+ render(<SettingsView onClose={() => undefined} />);
+ fireEvent.click(screen.getByRole("button", { name: "Download generator Minimax H3 Original" }));
+ await screen.findByRole("button", { name: "Remove downloaded weights for Minimax H3 Original" });
+ files.clear();
+ fireEvent.focus(window);
+ expect(await screen.findByRole("button", { name: "Download generator Minimax H3 Original" })).toBeEnabled();
+});
+
+it("stores multiple variants and their GPU and VRAM criteria in the editor", async () => {
+ render(<SettingsView onClose={() => undefined} />);
+ fireEvent.click(screen.getByRole("button", { name: "Edit Minimax H3 Original generator" }));
+ const weight = screen.getByLabelText("Transformer weights").closest(".settings-path")!;
+ const details = weight.querySelector("details")!;
+ fireEvent.click(within(weight as HTMLElement).getByText("Download variants (1)"));
+ details.open = true;
+ fireEvent.change(screen.getByLabelText("Add Transformer weights download URL"), { target: { value: "https://example.com/larger.safetensors" } });
+ fireEvent.click(within(weight as HTMLElement).getByRole("button", { name: "Add URL" }));
+ const gpu = screen.getByLabelText("Transformer weights variant 2 GPU model");
+ fireEvent.change(gpu, { target: { value: "RTX 5090" } });
+ fireEvent.blur(gpu);
+ fireEvent.change(screen.getByLabelText("Transformer weights variant 2 minimum VRAM"), { target: { value: "32" } });
+ await waitFor(() => expect(loadGeneratorTemplateSettings().templates.find((template) => template.id === "minimax-h3-original")?.sources?.transformer?.[1]).toMatchObject({ url: "https://example.com/larger.safetensors", gpuModel: "RTX 5090", minVramGb: 32 }));
+});
diff --git a/src/components/SettingsView.test.tsx b/src/components/SettingsView.test.tsx
index 7e51ad0..ea2f6f7 100644
--- a/src/components/SettingsView.test.tsx
+++ b/src/components/SettingsView.test.tsx
@@ -129,7 +129,7 @@ describe("the settings screen", () => {
expect(screen.getByRole("heading", { name: "Generators" })).toBeTruthy();
expect(screen.queryByLabelText(/Transformer weights/)).toBeNull();
editDefaultGenerator();
- expect(screen.getByLabelText(/Transformer weights/)).toBeTruthy();
+ expect(screen.getByLabelText("Transformer weights")).toBeTruthy();
// The other tab's contents are not merely hidden, they are not rendered:
// a settings screen that draws both panels is the tall screen tabs replaced.
expect(screen.queryByLabelText("Appearance")).toBeNull();
@@ -188,7 +188,8 @@ describe("the settings screen", () => {
expect(screen.queryByText("This computer")).toBeNull();
expect(screen.getByRole("heading", { name: "Settings" })).toBeTruthy();
editDefaultGenerator();
- expect(screen.getByText("Reads your prompt so the transformer can act on it.")).toBeTruthy();
+ expect(screen.queryByText("Reads your prompt so the transformer can act on it.")).toBeNull();
+ expect(screen.queryByText("Set its name, generation steps, attention, and model locations on this computer.")).toBeNull();
});
it("puts the optional tokenizer setting last", () => {
@@ -225,12 +226,12 @@ describe("the settings screen", () => {
open();
expect(screen.queryByLabelText(/Transformer weights/)).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "New generator" }));
- expect((screen.getByLabelText("Generator name") as HTMLInputElement).value).toBe("Generator 2");
+ expect((screen.getByLabelText("Generator name") as HTMLInputElement).value).toBe("Generator 3");
expect((screen.getByLabelText("Generator default steps") as HTMLInputElement).value).toBe("20");
fireEvent.change(screen.getByLabelText("Generator name"), { target: { value: "Fast draft" } });
fireEvent.change(screen.getByLabelText("Generator default steps"), { target: { value: "12" } });
- fireEvent.change(screen.getByLabelText(/Transformer weights/), { target: { value: "D:\\Models\\draft.safetensors" } });
+ fireEvent.change(screen.getByLabelText("Transformer weights"), { target: { value: "D:\\Models\\draft.safetensors" } });
fireEvent.click(screen.getByRole("button", { name: "Generators" }));
expect(screen.queryByLabelText(/Transformer weights/)).toBeNull();
fireEvent.click(screen.getByRole("radio", { name: "Use Fast draft as the default generator" }));
diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsx
index bc79f11..c183671 100644
--- a/src/components/SettingsView.tsx
+++ b/src/components/SettingsView.tsx
@@ -1,13 +1,16 @@
-import { AlertCircle, Check, ChevronLeft, FolderOpen, FolderSearch, LoaderCircle, Monitor, Moon, Plus, RefreshCw, RotateCcw, Sun, Trash2, X } from "lucide-react";
+import { AlertCircle, Check, ChevronLeft, Download, FolderOpen, FolderSearch, LoaderCircle, Monitor, Moon, Plus, RefreshCw, RotateCcw, Sun, Trash2, X } from "lucide-react";
import { useCallback, useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
import { revealDiagnosticLog } from "../lib/diagnostics";
import { isTauri } from "../lib/persistence";
+import { WeightSourcesEditor } from "./WeightSourcesEditor";
+import { cancelWeightDownload, downloadTemplateWeights, getWeightDownloadState, refreshDownloadedWeights, removeTemplateWeights, subscribeWeightDownloads, updateWeightPath } from "../lib/weightDownloads";
import { chooseEnginePath, getAgentModels, getEngineStatus, type ModelStatus, type SlopfabStatus } from "../lib/runtime";
import {
EMPTY_ENGINE_SETTINGS, ENGINE_PATH_FIELDS,
createGeneratorTemplate, defaultGeneratorTemplate,
isEndpointProviderConfigured, loadAgentEndpointSettings,
loadGeneratorTemplateSettings, saveAgentEndpointSettings, saveGeneratorTemplateSettings,
+ isDownloadUrl, subscribeGeneratorTemplates, templateNeedsDownload, type WeightSource,
loadDebugOptionsEnabled, saveDebugOptionsEnabled, subscribeDebugOptions,
loadInferenceBackend, saveInferenceBackend, type AttentionMode, type InferenceBackend,
type AgentEndpointSettings, type EndpointProviderId, type EndpointProviderSettings,
@@ -20,10 +23,11 @@ import {
type ResolvedTheme, type ThemeChoice,
} from "../lib/theme";
-type PathState = "unset" | "checking" | "found" | "missing";
+type PathState = "unset" | "checking" | "found" | "missing" | "download";
function pathState(field: EnginePathField, value: string, status: SlopfabStatus | null): PathState {
if (!value.trim()) return "unset";
+ if (isDownloadUrl(value)) return "download";
if (!status) return "checking";
const model: ModelStatus | undefined = status.models.find((item) => item.id === field.id);
if (!model) return "checking";
@@ -38,6 +42,7 @@ const stateLabel: Record<PathState, string> = {
checking: "Checking…",
found: "Found",
missing: "Not found on disk",
+ download: "Download required",
};
/* The system option has to say what the computer is currently set to, or
@@ -253,6 +258,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
ready?" without a click. */
const [tab, setTab] = useState<TabId>(initialTab);
const [templateSettings, setTemplateSettings] = useState<GeneratorTemplateSettings>(() => loadGeneratorTemplateSettings());
+ const downloadState = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);
const [editingTemplateId, setEditingTemplateId] = useState<string | null>(null);
const [status, setStatus] = useState<SlopfabStatus | null>(null);
const probeRevision = useRef(0);
@@ -263,6 +269,16 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
const selectedTemplate = templateSettings.templates.find((template) => template.id === editingTemplateId)
?? defaultTemplate;
const settings = selectedTemplate.paths;
+ const downloading = downloadState?.active && downloadState.templateId === selectedTemplate.id;
+
+ useEffect(() => subscribeGeneratorTemplates(() => setTemplateSettings(loadGeneratorTemplateSettings())), []);
+ useEffect(() => {
+ const refresh = () => { void refreshDownloadedWeights().catch((reason) => setError(String(reason))); };
+ refresh();
+ window.addEventListener("focus", refresh);
+ const timer = window.setInterval(refresh, 5000);
+ return () => { window.removeEventListener("focus", refresh); window.clearInterval(timer); };
+ }, []);
const probe = useCallback((paths?: EngineSettings) => {
const revision = ++probeRevision.current;
@@ -282,7 +298,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
const next = {
...current,
templates: current.templates.map((template) => template.id === selectedTemplate.id
- ? { ...template, paths: { ...template.paths, [id]: value } }
+ ? updateWeightPath(template, id, value)
: template),
};
saveGeneratorTemplateSettings(next);
@@ -290,7 +306,19 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
});
};
- useEffect(() => { probe(settings); }, [probe, editingTemplateId, templateSettings.defaultTemplateId]);
+ useEffect(() => { probe(settings); }, [probe, editingTemplateId, templateSettings.defaultTemplateId, downloadState?.completed]);
+
+ const updateSources = (id: EnginePathId, sources: WeightSource[]) => {
+ const current = loadGeneratorTemplateSettings();
+ const next = { ...current, templates: current.templates.map((template) => {
+ if (template.id !== selectedTemplate.id) return template;
+ const path = template.paths[id];
+ const nextPath = !path || isDownloadUrl(path) ? (sources.find((source) => source.url === path)?.url ?? sources[0]?.url ?? "") : path;
+ return { ...template, paths: { ...template.paths, [id]: nextPath }, sources: { ...template.sources, [id]: sources } };
+ }) };
+ saveGeneratorTemplateSettings(next);
+ setTemplateSettings(next);
+ };
useEffect(() => {
const close = (event: KeyboardEvent) => { if (event.key === "Escape") onClose(); };
@@ -315,7 +343,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
const next = {
...current,
templates: current.templates.map((template) => template.id === selectedTemplate.id
- ? { ...template, paths: { ...EMPTY_ENGINE_SETTINGS } }
+ ? { ...template, paths: { ...EMPTY_ENGINE_SETTINGS }, sources: {} }
: template),
};
saveGeneratorTemplateSettings(next);
@@ -346,9 +374,15 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
};
const removeTemplate = (id: string) => {
+ const template = templateSettings.templates.find((template) => template.id === id);
+ if (template && Object.values(template.sources ?? {}).some((sources) => sources.length > 0)) {
+ void removeTemplateWeights(id).catch((reason) => setError(String(reason)));
+ return;
+ }
if (templateSettings.templates.length <= 1) return;
const remaining = templateSettings.templates.filter((template) => template.id !== id);
const next: GeneratorTemplateSettings = {
+ ...templateSettings,
templates: remaining,
defaultTemplateId: id === templateSettings.defaultTemplateId ? remaining[0].id : templateSettings.defaultTemplateId,
};
@@ -358,6 +392,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
};
const makeDefault = (id: string) => {
+ if (templateSettings.templates.some((template) => template.id === id && templateNeedsDownload(template))) return;
const next = { ...templateSettings, defaultTemplateId: id };
setTemplateSettings(next);
saveGeneratorTemplateSettings(next);
@@ -456,12 +491,16 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
{templateSettings.templates.map((template) => (
<div className={`generator-template-item${template.id === templateSettings.defaultTemplateId ? " generator-template-item--selected" : ""}`} role="listitem" key={template.id}>
<label className="generator-template-item__default" title="Use this generator for generation by default">
- <input type="radio" name="default-generator-template" checked={template.id === templateSettings.defaultTemplateId} onChange={() => makeDefault(template.id)} aria-label={`Use ${template.name} as the default generator`} />
+ <input type="radio" name="default-generator-template" checked={template.id === templateSettings.defaultTemplateId && !templateNeedsDownload(template)} disabled={templateNeedsDownload(template)} onChange={() => makeDefault(template.id)} aria-label={`Use ${template.name} as the default generator`} />
</label>
<button type="button" className="generator-template-item__open" onClick={() => setEditingTemplateId(template.id)} aria-label={`Edit ${template.name} generator`}>
<b>{template.name}</b><small>{template.defaultSteps} steps</small>
</button>
- <button type="button" className="icon-button" disabled={templateSettings.templates.length === 1} onClick={() => removeTemplate(template.id)} aria-label={`Remove generator ${template.name}`} title={templateSettings.templates.length === 1 ? "At least one generator is required" : `Remove ${template.name}`}><Trash2 size={15} /></button>
+ {templateNeedsDownload(template)
+ ? <button type="button" className="icon-button" disabled={!desktop || downloadState?.active} onClick={() => void downloadTemplateWeights(template.id)} aria-label={`Download generator ${template.name}`} title={`Download ${template.name} weights`}>
+ {downloadState?.active && downloadState.templateId === template.id ? <LoaderCircle size={15} className="spin" /> : <Download size={15} />}
+ </button>
+ : <button type="button" className="icon-button" disabled={Boolean(downloadState?.active) || (Object.values(template.sources ?? {}).some((sources) => sources.length) ? !desktop : templateSettings.templates.length === 1)} onClick={() => removeTemplate(template.id)} aria-label={Object.values(template.sources ?? {}).some((sources) => sources.length) ? `Remove downloaded weights for ${template.name}` : `Remove generator ${template.name}`} title={Object.values(template.sources ?? {}).some((sources) => sources.length) ? `Remove ${template.name} weights and keep the template` : `Remove ${template.name}`}><Trash2 size={15} /></button>}
</div>
))}
</div>
@@ -469,7 +508,6 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
<header className="generator-editor__head">
<div>
<h2 id="generator-editor-heading">Edit generator</h2>
- <p>Set its name, generation steps, attention, and model locations on this computer.</p>
</div>
</header>
<div className="generator-template-fields">
@@ -505,14 +543,14 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
<div className={`settings-path settings-path--${state}`} key={field.id}>
<label htmlFor={`engine-${field.id}`}>
<b>{field.label}{!field.required && <em>Optional</em>}</b>
- <small>{field.hint}</small>
</label>
<div className="settings-path__row">
<input
id={`engine-${field.id}`}
value={value}
spellCheck={false}
- placeholder={field.directory ? "Folder on this computer" : "File on this computer"}
+ placeholder={field.directory ? "Folder on this computer or download URL" : "Local path or download URL"}
+ disabled={Boolean(downloading)}
onChange={(event) => update(field.id, event.target.value)}
onBlur={() => probe(settings)}
/>
@@ -520,7 +558,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
type="button"
className="secondary-button"
onClick={() => void browse(field)}
- disabled={!desktop}
+ disabled={!desktop || Boolean(downloading)}
title={desktop ? `Browse for ${field.label}` : "Browsing for files is available in the desktop app"}
>
<FolderSearch size={16} /> Browse
@@ -530,6 +568,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
{stateLabel[state]}
</span>
</div>
+ <WeightSourcesEditor label={field.label} sources={selectedTemplate.sources?.[field.id] ?? []} disabled={Boolean(downloading)} onChange={(sources) => updateSources(field.id, sources)} />
</div>
);
})}
@@ -537,14 +576,18 @@ export function SettingsView({ onClose, updates, initialTab = "engine" }: { onCl
</section>}
</div>
- {(tab === "diagnostics" || (tab === "engine" && editingTemplateId)) && <footer className="settings-view__foot">
+ {tab === "engine" && downloadState && <div className="weight-download-status" role="status">
+ <span>{templateSettings.templates.find((template) => template.id === downloadState.templateId)?.name}: {downloadState.error ?? (downloadState.active ? `${downloadState.completed}/${downloadState.files} files · ${(downloadState.downloaded / 1024 ** 3).toFixed(2)} GB${downloadState.total ? ` / ${(downloadState.total / 1024 ** 3).toFixed(2)} GB` : ""}` : "Download complete")}</span>
+ {downloadState.active && <><progress aria-label="Weight download progress" value={downloadState.total ? downloadState.downloaded : undefined} max={downloadState.total ?? 1} /><button type="button" className="secondary-button" onClick={() => void cancelWeightDownload().catch((reason) => setError(String(reason)))}>Cancel download</button></>}
+ </div>}
+ {tab === "engine" && editingTemplateId && <footer className="settings-view__foot">
{/* Clearing the paths is an engine action, so it is only offered
beside them. */}
- {tab === "engine" && editingTemplateId && <button className="secondary-button" onClick={clearAll}><RotateCcw size={16} /> Clear generator paths</button>}
- {tab === "diagnostics" && <span>Logs stay on this computer.</span>}
+ <button className="secondary-button" disabled={Boolean(downloading)} onClick={clearAll}><RotateCcw size={16} /> Clear generator paths</button>
+ {templateNeedsDownload(selectedTemplate) && <button type="button" className="primary-button" disabled={!desktop || downloadState?.active} onClick={() => void downloadTemplateWeights(selectedTemplate.id)}><Download size={16} /> Download weights</button>}
</footer>}
- {error && <div className="toast" role="alert"><strong>Couldn’t open the file picker</strong><span>{error}</span><button onClick={() => setError(null)}>Dismiss</button></div>}
+ {error && <div className="toast" role="alert"><strong>Couldn’t update generator settings</strong><span>{error}</span><button onClick={() => setError(null)}>Dismiss</button></div>}
</div>
</div>
);
diff --git a/src/components/WeightSourcesEditor.tsx b/src/components/WeightSourcesEditor.tsx
new file mode 100644
index 0000000..91d5f34
--- /dev/null
+++ b/src/components/WeightSourcesEditor.tsx
@@ -0,0 +1,33 @@
+import { useState } from "react";
+import { Plus, Trash2 } from "lucide-react";
+import { isDownloadUrl, type WeightSource } from "../lib/settings";
+
+export function WeightSourcesEditor({ label, sources, disabled, onChange }: {
+ label: string; sources: WeightSource[]; disabled: boolean; onChange: (sources: WeightSource[]) => void;
+}) {
+ const [url, setUrl] = useState("");
+ const [error, setError] = useState<string | null>(null);
+ const update = (index: number, patch: Partial<WeightSource>) => onChange(sources.map((source, i) => i === index ? { ...source, ...patch } : source));
+ return <details className="weight-sources">
+ <summary>Download variants{sources.length > 0 ? ` (${sources.length})` : ""}</summary>
+ <p>GPU model matches part of the device name, such as “RTX 5090”. Leave it blank for any GPU. Among matches, the highest minimum VRAM that fits is selected.</p>
+ {sources.map((source, index) => <div className="weight-source" key={`${index}-${source.url}`}>
+ <label>Download URL<input aria-label={`${label} variant ${index + 1} URL`} defaultValue={source.url} disabled={disabled} onBlur={(event) => {
+ const value = event.target.value.trim();
+ if (!isDownloadUrl(value)) { setError("Enter an HTTP or HTTPS download URL."); return; }
+ setError(null);
+ if (value !== source.url) update(index, { url: value, downloadedPath: undefined });
+ }} /></label>
+ <label>GPU model<input aria-label={`${label} variant ${index + 1} GPU model`} defaultValue={source.gpuModel} placeholder="Any GPU" disabled={disabled} onBlur={(event) => update(index, { gpuModel: event.target.value })} /></label>
+ <label>Minimum VRAM (GB)<input aria-label={`${label} variant ${index + 1} minimum VRAM`} type="number" min={0} step={1} value={source.minVramGb} disabled={disabled} onChange={(event) => update(index, { minVramGb: Math.max(0, Number(event.target.value) || 0) })} /></label>
+ <button type="button" className="icon-button" disabled={disabled} onClick={() => onChange(sources.filter((_, i) => i !== index))} aria-label={`Remove ${label} variant ${index + 1}`}><Trash2 size={15} /></button>
+ </div>)}
+ <div className="weight-source-add">
+ <input aria-label={`Add ${label} download URL`} value={url} disabled={disabled} placeholder="https://…" onChange={(event) => setUrl(event.target.value)} />
+ <button type="button" className="secondary-button" disabled={disabled || !isDownloadUrl(url) || sources.some((source) => source.url === url.trim())} onClick={() => {
+ onChange([...sources, { url: url.trim(), gpuModel: "", minVramGb: 0 }]); setUrl("");
+ }}><Plus size={15} /> Add URL</button>
+ </div>
+ {error && <p role="alert">{error}</p>}
+ </details>;
+}
diff --git a/src/components/workspace/GeneratorView.test.tsx b/src/components/workspace/GeneratorView.test.tsx
index 1298a4e..424f11f 100644
--- a/src/components/workspace/GeneratorView.test.tsx
+++ b/src/components/workspace/GeneratorView.test.tsx
@@ -7,7 +7,7 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vite
import { createDraftGenerationJob, createProjectConfig, parseProjectConfig, sceneShots, type ProjectConfig } from "../../lib/project";
import { cancelSlopfabGeneration, getEngineStatus, type SlopfabStatus } from "../../lib/runtime";
import { GeneratorView } from "./GeneratorView";
-import { saveDebugOptionsEnabled } from "../../lib/settings";
+import { minimaxOriginalTemplate, saveDebugOptionsEnabled } from "../../lib/settings";
vi.mock("../../lib/runtime", async (importOriginal) => ({
...await importOriginal<typeof import("../../lib/runtime")>(),
@@ -22,6 +22,19 @@ beforeEach(() => {
});
afterEach(cleanup);
+it("hides unfinished templates from the generator picker", () => {
+ setup();
+ fireEvent.click(screen.getByRole("combobox", { name: /Video generator template/ }));
+ expect(screen.getByRole("option", { name: "Default" })).toBeInTheDocument();
+ expect(screen.queryByRole("option", { name: "Minimax H3 Original" })).toBeNull();
+});
+
+it("has no selected generator when all templates still need downloads", () => {
+ localStorage.setItem("slopus.generator-templates.v1", JSON.stringify({ templates: [minimaxOriginalTemplate()], defaultTemplateId: "minimax-h3-original", catalogVersion: 1 }));
+ setup();
+ expect(screen.getByRole("combobox", { name: "Video generator template: No downloaded generators" })).toBeDisabled();
+});
+
const readyRuntime: SlopfabStatus = {
state: "ready",
dllPath: "test",
diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsx
index bb9b275..4d148b8 100644
--- a/src/components/workspace/GeneratorView.tsx
+++ b/src/components/workspace/GeneratorView.tsx
@@ -11,7 +11,8 @@ import { SceneInspector, ShotInspector, STEP_SECONDS, writeShots } from "./Scene
import { statusIcon } from "./sceneStatus";
import { forgetShotPosters } from "./ShotThumbnail";
import { purgeTimelineThumbnails } from "../../lib/timelineThumbnails";
-import { defaultGeneratorTemplate, loadDebugOptionsEnabled, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, subscribeDebugOptions, type GeneratorTemplate } from "../../lib/settings";
+import { defaultGeneratorTemplate, loadDebugOptionsEnabled, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, subscribeDebugOptions, subscribeGeneratorTemplates, templateNeedsDownload, type GeneratorTemplate } from "../../lib/settings";
+import { refreshDownloadedWeights } from "../../lib/weightDownloads";
import { DebugPromptDialog } from "./DebugPromptDialog";
interface GeneratorViewProps {
@@ -51,6 +52,8 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo
const [generatorRuntime, setGeneratorRuntime] = useState<SlopfabStatus | null>(runtime);
const [runtimeError, setRuntimeError] = useState<string | null>(null);
const runtimeProbe = useRef(0);
+ const templateKey = JSON.stringify([selectedTemplate.id, selectedTemplate.paths, selectedTemplate.attention]);
+ const probedTemplate = useRef(templateKey);
const configRef = useRef(config);
configRef.current = config;
/* A scene is always what is named; the shot inside it is what a card opens.
@@ -73,17 +76,31 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo
}, [runtime]);
useEffect(() => () => { runtimeProbe.current += 1; }, []);
+ useEffect(() => subscribeGeneratorTemplates(() => setTemplateSettings(loadGeneratorTemplateSettings())), []);
+ useEffect(() => {
+ const refresh = () => { void refreshDownloadedWeights().catch((reason) => setRuntimeError(String(reason))); };
+ refresh();
+ window.addEventListener("focus", refresh);
+ const timer = window.setInterval(refresh, 5000);
+ return () => { window.removeEventListener("focus", refresh); window.clearInterval(timer); };
+ }, []);
const chooseGeneratorTemplate = (templateId: string) => {
const template = templateSettings.templates.find((candidate) => candidate.id === templateId);
- if (!template || template.id === templateSettings.defaultTemplateId) return;
+ if (!template || templateNeedsDownload(template) || template.id === templateSettings.defaultTemplateId) return;
const next = { ...templateSettings, defaultTemplateId: template.id };
saveGeneratorTemplateSettings(next);
setTemplateSettings(next);
+ };
+
+ useEffect(() => {
+ if (probedTemplate.current === templateKey) return;
+ probedTemplate.current = templateKey;
setGeneratorRuntime(null);
setRuntimeError(null);
const probe = ++runtimeProbe.current;
- void getEngineStatus(template.paths).then((status) => {
+ if (!selectedTemplate.id) return;
+ void getEngineStatus(selectedTemplate.paths).then((status) => {
if (probe !== runtimeProbe.current) return;
setGeneratorRuntime(status);
onRuntimeChange?.(status);
@@ -91,7 +108,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo
if (probe !== runtimeProbe.current) return;
setRuntimeError(reason instanceof Error ? reason.message : String(reason));
});
- };
+ }, [templateKey]);
useEffect(() => { if (selectedJobId) setSelection({ jobId: selectedJobId, shotId: null }); }, [selectedJobId]);
@@ -106,7 +123,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo
const queued = jobs.filter((job) => job.status === "queued");
const cancellable = jobs.filter((job) => job.status === "queued" || job.status === "generating");
const boundRefs = useMemo(() => selected ? sceneGenerationReferences(selected, config.references) : [], [config.references, selected]);
- const runtimeReady = generatorRuntime?.state === "ready";
+ const runtimeReady = Boolean(selectedTemplate.id) && generatorRuntime?.state === "ready";
const updateJob = (id: string, updates: Partial<GenerationJob>) => {
const current = configRef.current;
@@ -386,7 +403,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo
>
<i role="img" aria-label={runtimeError ? "Video generator unavailable" : runtimeHeadline(generatorRuntime)} />
<span className="generator-runtime__label">Generator:</span>
- <GeneratorTemplateCombobox templates={templateSettings.templates} selected={selectedTemplate} onChange={chooseGeneratorTemplate} />
+ <GeneratorTemplateCombobox templates={templateSettings.templates.filter((template) => !templateNeedsDownload(template))} selected={selectedTemplate} onChange={chooseGeneratorTemplate} />
{(runtimeError || (generatorRuntime?.state !== "ready" && generatorRuntime?.state !== "modelsMissing")) && <span className="generator-runtime__status" aria-hidden="true">{runtimeError ? "Unavailable" : runtimeHeadline(generatorRuntime)}</span>}
</div>
<button
@@ -672,6 +689,7 @@ function GeneratorTemplateCombobox({ templates, selected, onChange }: {
type="button"
className="generator-runtime__trigger"
role="combobox"
+ disabled={templates.length === 0}
aria-label={`Video generator template: ${selected.name}`}
aria-expanded={open}
aria-haspopup="listbox"
diff --git a/src/lib/runtime.ts b/src/lib/runtime.ts
index 84e0eed..e59ad55 100644
--- a/src/lib/runtime.ts
+++ b/src/lib/runtime.ts
@@ -1,5 +1,6 @@
import { invoke } from "@tauri-apps/api/core";
import { isTauri } from "./persistence";
+import { refreshDownloadedWeights } from "./weightDownloads";
import {
actionReferenceIds, createDraftGenerationJob, GENERATION_FRAME_RATE, parseProjectConfig,
sceneBriefText, type AgentMessage, type GenerationJob, type ProjectAsset, type ProjectConfig,
@@ -120,6 +121,7 @@ const DEMO_STATUS: RuntimeStatus = {
* startup and every project shares the answer. */
export async function getRuntimeStatus(): Promise<RuntimeStatus> {
if (!isTauri()) return DEMO_STATUS;
+ await refreshDownloadedWeights();
return invoke<RuntimeStatus>("runtime_status", {
settings: { slopfab: engineProviderSetting(loadEngineSettings()), ...agentEndpointProviderSettings() },
});
diff --git a/src/lib/settings.test.ts b/src/lib/settings.test.ts
index 8cf605c..6328e11 100644
--- a/src/lib/settings.test.ts
+++ b/src/lib/settings.test.ts
@@ -22,7 +22,8 @@ describe("generator templates", () => {
localStorage.setItem("slopus.engine-paths.v1", JSON.stringify({ transformer: "D:\\Models\\main.safetensors" }));
const settings = loadGeneratorTemplateSettings();
expect(settings.defaultTemplateId).toBe("default");
- expect(settings.templates).toHaveLength(1);
+ expect(settings.templates).toHaveLength(2);
+ expect(settings.templates[1].name).toBe("Minimax H3 Original");
expect(settings.templates[0]).toMatchObject({
id: "default",
name: "Default",
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index 0f96108..c057b46 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -72,6 +72,32 @@ export interface GeneratorTemplate {
defaultSteps: number;
attention: AttentionMode;
paths: EngineSettings;
+ sources?: Partial<Record<EnginePathId, WeightSource[]>>;
+}
+
+export interface WeightSource {
+ url: string;
+ gpuModel: string;
+ minVramGb: number;
+ downloadedPath?: string;
+}
+
+export const isDownloadUrl = (value: string): boolean => /^https?:\/\//i.test(value.trim());
+
+export function templateNeedsDownload(template: GeneratorTemplate): boolean {
+ return ENGINE_PATH_FIELDS.some(({ id }) => isDownloadUrl(template.paths[id])
+ || (!template.paths[id].trim() && (template.sources?.[id]?.length ?? 0) > 0));
+}
+
+const GENERATOR_TEMPLATES_EVENT = "slopus:generator-templates-changed";
+export function subscribeGeneratorTemplates(listener: () => void) {
+ const storage = (event: StorageEvent) => { if (event.key === GENERATOR_TEMPLATES_KEY || event.key === null) listener(); };
+ window.addEventListener(GENERATOR_TEMPLATES_EVENT, listener);
+ window.addEventListener("storage", storage);
+ return () => {
+ window.removeEventListener(GENERATOR_TEMPLATES_EVENT, listener);
+ window.removeEventListener("storage", storage);
+ };
}
export type AttentionMode = "exact" | "flash2" | "sage2";
@@ -97,6 +123,7 @@ export function saveInferenceBackend(backend: InferenceBackend): void {
export interface GeneratorTemplateSettings {
templates: GeneratorTemplate[];
defaultTemplateId: string;
+ catalogVersion?: number;
}
const copyPaths = (paths: EngineSettings): EngineSettings => ({ ...paths });
@@ -122,14 +149,27 @@ export function createGeneratorTemplate(name = "New template"): GeneratorTemplat
};
}
+export function minimaxOriginalTemplate(): GeneratorTemplate {
+ const root = "https://huggingface.co/Comfy-Org/MiniMax-H3/blob/main/";
+ const paths = {
+ transformer: `${root}diffusion_models/minimax_h3_fl2va_pruned_int8_convrot.safetensors`,
+ textEncoder: `${root}text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors`,
+ videoVae: `${root}vae/minimax_h3_video_vae_fp16.safetensors`,
+ audioVae: `${root}vae/minimax_h3_audio_vae_fp32.safetensors`, tokenizer: "",
+ };
+ return { id: "minimax-h3-original", name: "Minimax H3 Original", defaultSteps: 20, attention: "sage2", paths,
+ sources: Object.fromEntries(ENGINE_PATH_FIELDS.filter(({ id }) => paths[id]).map(({ id }) => [id, [{ url: paths[id], gpuModel: "", minVramGb: 0 }]])) };
+}
+
const initialTemplateSettings = (paths = EMPTY_ENGINE_SETTINGS): GeneratorTemplateSettings => ({
- templates: [{ id: "default", name: "Default", defaultSteps: DEFAULT_GENERATION_STEPS, attention: "sage2", paths: copyPaths(paths) }],
+ templates: [{ id: "default", name: "Default", defaultSteps: DEFAULT_GENERATION_STEPS, attention: "sage2", paths: copyPaths(paths) }, minimaxOriginalTemplate()],
defaultTemplateId: "default",
+ catalogVersion: 1,
});
const normalizeTemplateSettings = (value: unknown): GeneratorTemplateSettings | null => {
if (!value || typeof value !== "object") return null;
- const record = value as { templates?: unknown; defaultTemplateId?: unknown };
+ const record = value as { templates?: unknown; defaultTemplateId?: unknown; catalogVersion?: unknown };
if (!Array.isArray(record.templates)) return null;
const ids = new Set<string>();
const templates = record.templates.flatMap((item): GeneratorTemplate[] => {
@@ -146,13 +186,30 @@ const normalizeTemplateSettings = (value: unknown): GeneratorTemplateSettings |
? candidate.defaultSteps
: DEFAULT_GENERATION_STEPS;
const attention = candidate.attention === "exact" || candidate.attention === "flash2" ? candidate.attention : "sage2";
- return [{ id, name, defaultSteps, attention, paths: pathsFrom(candidate.paths) }];
+ const paths = pathsFrom(candidate.paths);
+ const sources: GeneratorTemplate["sources"] = {};
+ for (const field of ENGINE_PATH_FIELDS) {
+ const raw = (candidate.sources as Record<string, unknown> | undefined)?.[field.id];
+ const entries: WeightSource[] = Array.isArray(raw) ? raw.flatMap((source) => {
+ if (!source || typeof source.url !== "string" || !isDownloadUrl(source.url)) return [];
+ return [{ url: source.url.trim(), gpuModel: typeof source.gpuModel === "string" ? source.gpuModel : "",
+ minVramGb: typeof source.minVramGb === "number" && Number.isFinite(source.minVramGb) ? Math.max(0, source.minVramGb) : 0,
+ ...(typeof source.downloadedPath === "string" ? { downloadedPath: source.downloadedPath } : {}) }];
+ }) : [];
+ if (isDownloadUrl(paths[field.id]) && !entries.some((source) => source.url === paths[field.id].trim())) {
+ entries.unshift({ url: paths[field.id].trim(), gpuModel: "", minVramGb: 0 });
+ }
+ if (entries.length) sources[field.id] = entries;
+ }
+ return [{ id, name, defaultSteps, attention, paths, sources }];
});
if (templates.length === 0) return null;
const requestedDefault = typeof record.defaultTemplateId === "string" ? record.defaultTemplateId : "";
return {
templates,
- defaultTemplateId: templates.some((template) => template.id === requestedDefault) ? requestedDefault : templates[0].id,
+ defaultTemplateId: templates.find((template) => template.id === requestedDefault && !templateNeedsDownload(template))?.id
+ ?? templates.find((template) => !templateNeedsDownload(template))?.id ?? "",
+ catalogVersion: record.catalogVersion === 1 ? 1 : 0,
};
};
@@ -164,7 +221,14 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {
const stored = migratedStorageItem(GENERATOR_TEMPLATES_KEY, LEGACY_GENERATOR_TEMPLATES_KEY);
if (stored) {
const normalized = normalizeTemplateSettings(JSON.parse(stored));
- if (normalized) return normalized;
+ if (normalized) {
+ if (!normalized.catalogVersion) {
+ if (!normalized.templates.some((template) => template.id === "minimax-h3-original")) normalized.templates.push(minimaxOriginalTemplate());
+ normalized.catalogVersion = 1;
+ localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
+ }
+ return normalized;
+ }
}
const legacy = migratedStorageItem(ENGINE_KEY, LEGACY_ENGINE_KEY);
return initialTemplateSettings(legacy ? pathsFrom(JSON.parse(legacy)) : EMPTY_ENGINE_SETTINGS);
@@ -180,10 +244,13 @@ export function saveGeneratorTemplateSettings(settings: GeneratorTemplateSetting
} catch {
/* The current React state remains usable for this session. */
}
+ queueMicrotask(() => window.dispatchEvent(new Event(GENERATOR_TEMPLATES_EVENT)));
}
export function defaultGeneratorTemplate(settings = loadGeneratorTemplateSettings()): GeneratorTemplate {
- return settings.templates.find((template) => template.id === settings.defaultTemplateId) ?? settings.templates[0];
+ return settings.templates.find((template) => template.id === settings.defaultTemplateId && !templateNeedsDownload(template))
+ ?? settings.templates.find((template) => !templateNeedsDownload(template))
+ ?? { id: "", name: "No downloaded generators", defaultSteps: DEFAULT_GENERATION_STEPS, attention: "sage2", paths: copyPaths(EMPTY_ENGINE_SETTINGS) };
}
export function loadDefaultGenerationSteps(): number {
@@ -213,7 +280,8 @@ export function engineProviderSetting(settings: EngineSettings, base?: ProviderS
const options: ProviderSetting["options"] = { ...(base?.options ?? {}), attention, inferenceBackend: loadInferenceBackend() };
for (const field of ENGINE_PATH_FIELDS) {
const value = settings[field.id].trim();
- if (value) options[field.id] = value;
+ if (value && !isDownloadUrl(value)) options[field.id] = value;
+ else if (isDownloadUrl(value)) delete options[field.id];
}
return { enabled: base?.enabled ?? true, model: base?.model ?? null, options };
}
diff --git a/src/lib/weightDownloads.test.ts b/src/lib/weightDownloads.test.ts
new file mode 100644
index 0000000..c827cb8
--- /dev/null
+++ b/src/lib/weightDownloads.test.ts
@@ -0,0 +1,135 @@
+// @vitest-environment jsdom
+import { invoke } from "@tauri-apps/api/core";
+import { beforeEach, expect, it, vi } from "vitest";
+import { chooseWeightSource, downloadTemplateWeights, getWeightDownloadState, refreshDownloadedWeights, removeTemplateWeights, updateWeightPath } from "./weightDownloads";
+import { createGeneratorTemplate, defaultGeneratorTemplate, isDownloadUrl, loadGeneratorTemplateSettings, minimaxOriginalTemplate, saveGeneratorTemplateSettings, templateNeedsDownload, type WeightSource } from "./settings";
+
+vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));
+vi.mock("./persistence", () => ({ isTauri: () => true }));
+const files = new Set<string>();
+const source = (url: string, gpuModel = "", minVramGb = 0): WeightSource => ({ url, gpuModel, minVramGb });
+const saved = () => loadGeneratorTemplateSettings().templates.find((template) => template.id === "minimax-h3-original")!;
+
+beforeEach(() => {
+ localStorage.clear(); files.clear(); vi.clearAllMocks();
+ vi.mocked(invoke).mockImplementation(async (command, args) => {
+ if (command === "weight_download_hardware") return [{ name: "NVIDIA GeForce RTX 5090", memoryBytes: 32 * 1024 ** 3 }];
+ if (command === "check_weight_files") return Object.fromEntries((args as { paths: string[] }).paths.map((path) => [path, files.has(path)]));
+ if (command === "remove_downloaded_weights") { for (const path of (args as { paths: string[] }).paths) files.delete(path); return; }
+ if (command === "download_weight") {
+ const path = `C:/Slopus/weights/${(args as { url: string }).url.split('/').at(-1)}`;
+ files.add(path); return path;
+ }
+ });
+});
+
+it("chooses a matching GPU variant and the largest VRAM tier that fits", () => {
+ const generic = source("https://example.com/small"), large = source("https://example.com/large", "", 24);
+ const specific = source("https://example.com/5090", "RTX 5090", 32);
+ const oversized = source("https://example.com/huge", "RTX 5090", 48);
+ const variants = [generic, large, specific, oversized];
+ expect(chooseWeightSource(variants, [{ name: "NVIDIA GeForce RTX 5090", memoryBytes: 32 * 1024 ** 3 }])).toBe(specific);
+ expect(chooseWeightSource(variants, [{ name: "NVIDIA GeForce RTX 5090", memoryBytes: 33753661440 }])).toBe(specific);
+ expect(chooseWeightSource(variants, [{ name: "NVIDIA GeForce RTX 4090", memoryBytes: 24 * 1024 ** 3 }])).toBe(large);
+ expect(chooseWeightSource(variants, [{ name: "AMD Radeon RX 7600", memoryBytes: 8 * 1024 ** 3 }])).toBe(generic);
+ expect(chooseWeightSource(variants, [])).toBe(generic);
+ expect(chooseWeightSource([specific], [{ name: "RTX 3090", memoryBytes: 24 * 1024 ** 3 }])).toBeNull();
+});
+
+it("preserves the sample links and prevents an unfinished template from being the default", () => {
+ const sample = minimaxOriginalTemplate();
+ saveGeneratorTemplateSettings({ templates: [sample], defaultTemplateId: sample.id, catalogVersion: 1 });
+ expect(templateNeedsDownload(saved())).toBe(true);
+ expect(loadGeneratorTemplateSettings().defaultTemplateId).toBe("");
+ expect(defaultGeneratorTemplate().id).toBe("");
+ expect(Object.values(saved().sources ?? {}).flat()).toHaveLength(4);
+});
+
+it("replaces a URL being typed instead of accumulating partial download sources", () => {
+ let template = createGeneratorTemplate();
+ for (const value of ["https://", "https://e", "https://example.com/model"]) template = updateWeightPath(template, "transformer", value);
+ expect(template.sources?.transformer).toEqual([source("https://example.com/model")]);
+});
+
+it("downloads all sample weights, saves local paths, and restores a deleted weight's URL", async () => {
+ await downloadTemplateWeights("minimax-h3-original");
+ const template = saved();
+ expect(templateNeedsDownload(template)).toBe(false);
+ expect(getWeightDownloadState()).toMatchObject({ active: false, completed: 4, files: 4, error: null });
+ const url = template.sources!.transformer![0].url;
+ expect(template.paths.transformer).toMatch(/^C:\/Slopus\/weights\//);
+ saveGeneratorTemplateSettings({ ...loadGeneratorTemplateSettings(), defaultTemplateId: template.id });
+ files.delete(template.paths.transformer);
+ await refreshDownloadedWeights();
+ expect(saved().paths.transformer).toBe(url);
+ expect(saved().sources!.transformer![0].downloadedPath).toBeUndefined();
+ expect(loadGeneratorTemplateSettings().defaultTemplateId).toBe("default");
+ vi.mocked(invoke).mockClear();
+ await downloadTemplateWeights(template.id);
+ expect(vi.mocked(invoke).mock.calls.filter(([command]) => command === "download_weight")).toHaveLength(1);
+ expect(templateNeedsDownload(saved())).toBe(false);
+});
+
+it("removes downloaded files while retaining the template and original URLs", async () => {
+ await downloadTemplateWeights("minimax-h3-original");
+ await removeTemplateWeights("minimax-h3-original");
+ expect(files.size).toBe(0);
+ expect(saved().paths).toEqual(minimaxOriginalTemplate().paths);
+ expect(Object.values(saved().sources ?? {}).flat().every((source) => !source.downloadedPath)).toBe(true);
+ expect(templateNeedsDownload(saved())).toBe(true);
+ await downloadTemplateWeights("minimax-h3-original");
+ expect(templateNeedsDownload(saved())).toBe(false);
+});
+
+it("never sends a manually selected local file to the removal command", async () => {
+ const template = minimaxOriginalTemplate();
+ template.paths.transformer = "D:/MyModels/personal.safetensors";
+ saveGeneratorTemplateSettings({ templates: [template], defaultTemplateId: "", catalogVersion: 1 });
+ await removeTemplateWeights(template.id);
+ expect(invoke).toHaveBeenCalledWith("remove_downloaded_weights", { paths: [] });
+ expect(saved().paths.transformer).toBe(minimaxOriginalTemplate().paths.transformer);
+});
+
+it("retains successful files when a later download fails and retries only unfinished weights", async () => {
+ const original = vi.mocked(invoke).getMockImplementation()!;
+ let attempts = 0;
+ vi.mocked(invoke).mockImplementation(async (command, args) => {
+ if (command === "download_weight" && ++attempts === 2) throw new Error("Network lost");
+ return original(command, args);
+ });
+ await downloadTemplateWeights("minimax-h3-original");
+ expect(isDownloadUrl(saved().paths.transformer)).toBe(false);
+ expect(isDownloadUrl(saved().paths.textEncoder)).toBe(true);
+ expect(getWeightDownloadState()).toMatchObject({ active: false, completed: 1, error: "Network lost" });
+ vi.mocked(invoke).mockImplementation(original);
+ vi.mocked(invoke).mockClear();
+ await downloadTemplateWeights("minimax-h3-original");
+ expect(vi.mocked(invoke).mock.calls.filter(([command]) => command === "download_weight")).toHaveLength(3);
+});
+
+it("preserves edits made while a download is running", async () => {
+ const original = vi.mocked(invoke).getMockImplementation()!;
+ vi.mocked(invoke).mockImplementation(async (command, args) => {
+ if (command === "download_weight") {
+ const settings = loadGeneratorTemplateSettings();
+ const template = settings.templates.find((template) => template.id === "minimax-h3-original")!;
+ template.paths.transformer = "D:/MyModels/replacement.safetensors";
+ saveGeneratorTemplateSettings(settings);
+ }
+ return original(command, args);
+ });
+ await downloadTemplateWeights("minimax-h3-original");
+ expect(saved().paths.transformer).toBe("D:/MyModels/replacement.safetensors");
+});
+
+it("restores all templates sharing a downloaded weight when one removes it", async () => {
+ await downloadTemplateWeights("minimax-h3-original");
+ const settings = loadGeneratorTemplateSettings();
+ settings.templates.push({ ...saved(), id: "copy", name: "Shared copy" });
+ saveGeneratorTemplateSettings(settings);
+ await removeTemplateWeights("minimax-h3-original");
+ const copy = loadGeneratorTemplateSettings().templates.find((template) => template.id === "copy")!;
+ expect(templateNeedsDownload(copy)).toBe(true);
+ expect(copy.paths).toEqual(minimaxOriginalTemplate().paths);
+});
diff --git a/src/lib/weightDownloads.ts b/src/lib/weightDownloads.ts
new file mode 100644
index 0000000..2ab6905
--- /dev/null
+++ b/src/lib/weightDownloads.ts
@@ -0,0 +1,165 @@
+import { invoke } from "@tauri-apps/api/core";
+import { listen } from "@tauri-apps/api/event";
+import { isTauri } from "./persistence";
+import { ENGINE_PATH_FIELDS, isDownloadUrl, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, templateNeedsDownload,
+ type EnginePathId, type GeneratorTemplate, type WeightSource } from "./settings";
+
+export interface WeightGpu { name: string; memoryBytes: number }
+export interface DownloadState {
+ templateId: string;
+ field: EnginePathId | null;
+ downloaded: number;
+ total: number | null;
+ completed: number;
+ files: number;
+ error: string | null;
+ active: boolean;
+}
+let state: DownloadState | null = null;
+let requestId: string | null = null;
+let cancelled = false;
+const subscribers = new Set<() => void>();
+export const getWeightDownloadState = () => state;
+export const subscribeWeightDownloads = (listener: () => void) => { subscribers.add(listener); return () => { subscribers.delete(listener); }; };
+const publish = (next: DownloadState | null) => { state = next; subscribers.forEach((listener) => listener()); };
+
+export function chooseWeightSource(sources: WeightSource[], devices: WeightGpu[]): WeightSource | null {
+ // Prefer an explicit GPU match, then the highest memory tier that fits.
+ // Equal-ranked alternatives keep the author's order. Unknown hardware only
+ // qualifies for universal variants with no minimum memory requirement.
+ const matches = sources.filter((source) => !source.gpuModel.trim() && source.minVramGb === 0
+ || devices.some((gpu) => gpu.name.toLowerCase().includes(source.gpuModel.trim().toLowerCase())
+ // Drivers reserve part of VRAM (a 32 GB card may report 31.4 GiB).
+ && Math.ceil(gpu.memoryBytes / 1024 ** 3) >= source.minVramGb));
+ return matches.sort((a, b) => Number(Boolean(b.gpuModel.trim())) - Number(Boolean(a.gpuModel.trim())) || b.minVramGb - a.minVramGb)[0] ?? null;
+}
+
+export function updateWeightPath(template: GeneratorTemplate, field: EnginePathId, value: string): GeneratorTemplate {
+ const sources = { ...template.sources };
+ if (isDownloadUrl(value)) {
+ const existing = sources[field] ?? [];
+ const previous = template.paths[field].trim();
+ if (isDownloadUrl(previous) && existing.some((source) => source.url === previous)) {
+ sources[field] = existing.map((source) => source.url === previous ? { ...source, url: value.trim(), downloadedPath: undefined } : source);
+ } else if (!existing.some((source) => source.url === value.trim())) sources[field] = [{ url: value.trim(), gpuModel: "", minVramGb: 0 }, ...existing];
+ }
+ return { ...template, paths: { ...template.paths, [field]: value }, sources };
+}
+
+let refreshPending: Promise<void> | null = null;
+export function refreshDownloadedWeights(): Promise<void> {
+ if (!isTauri()) return Promise.resolve();
+ if (refreshPending) return refreshPending;
+ refreshPending = (async () => {
+ const before = loadGeneratorTemplateSettings();
+ const paths = [...new Set(before.templates.flatMap((template) => Object.values(template.sources ?? {}).flatMap((sources) => sources.flatMap((source) => source.downloadedPath ? [source.downloadedPath] : []))))];
+ if (!paths.length) return;
+ const exists = await invoke<Record<string, boolean>>("check_weight_files", { paths });
+ const current = loadGeneratorTemplateSettings();
+ let changed = false;
+ const templates = current.templates.map((template) => {
+ const restored = { ...template, paths: { ...template.paths }, sources: { ...template.sources } };
+ for (const { id } of ENGINE_PATH_FIELDS) {
+ const sources = template.sources?.[id];
+ if (!sources) continue;
+ restored.sources[id] = sources.map((source) => {
+ if (!source.downloadedPath || exists?.[source.downloadedPath] !== false) return source;
+ changed = true;
+ if (restored.paths[id] === source.downloadedPath) restored.paths[id] = source.url;
+ const { downloadedPath: _removed, ...remaining } = source;
+ return remaining;
+ });
+ }
+ return restored;
+ });
+ if (changed) {
+ saveGeneratorTemplateSettings({ ...current, templates });
+ if (state && !state.active && templates.some((template) => template.id === state?.templateId && templateNeedsDownload(template))) publish(null);
+ }
+ })().finally(() => { refreshPending = null; });
+ return refreshPending;
+}
+
+export async function downloadTemplateWeights(templateId: string): Promise<void> {
+ if (!isTauri() || state?.active) return;
+ cancelled = false;
+ publish({ templateId, field: null, downloaded: 0, total: null, completed: 0, files: 0, error: null, active: true });
+ let unlisten: (() => void) | undefined;
+ try {
+ await refreshDownloadedWeights();
+ const template = loadGeneratorTemplateSettings().templates.find((template) => template.id === templateId);
+ if (!template) throw new Error("This generator was removed.");
+ const devices = await invoke<WeightGpu[]>("weight_download_hardware");
+ const downloads = ENGINE_PATH_FIELDS.flatMap(({ id }) => {
+ if (template.paths[id].trim() && !isDownloadUrl(template.paths[id])) return [];
+ const sources = template.sources?.[id] ?? [];
+ if (!sources.length) return [];
+ const source = chooseWeightSource(sources, devices ?? []);
+ if (!source) throw new Error(`No ${ENGINE_PATH_FIELDS.find((field) => field.id === id)?.label} download matches this GPU and its memory.`);
+ return [{ field: id, source, originalPath: template.paths[id] }];
+ });
+ publish({ ...state!, files: downloads.length });
+ unlisten = await listen<{ requestId: string; downloaded: number; total: number | null }>("weight-download-progress", ({ payload }) => {
+ if (payload.requestId === requestId && state?.active) publish({ ...state, downloaded: payload.downloaded, total: payload.total });
+ });
+ for (const { field, source, originalPath } of downloads) {
+ if (cancelled) throw new Error("Download cancelled.");
+ requestId = crypto.randomUUID();
+ publish({ ...state!, field, downloaded: 0, total: null });
+ const path = source.downloadedPath ?? await invoke<string>("download_weight", { requestId, url: source.url });
+ if (!path || isDownloadUrl(path)) throw new Error("The download did not return a local file.");
+ const current = loadGeneratorTemplateSettings();
+ const templates = current.templates.map((template) => {
+ if (template.id !== templateId) return template;
+ // A download finishing must not overwrite edits made while it ran.
+ const sources = template.sources?.[field];
+ if (!sources?.some((entry) => entry.url === source.url)) return template;
+ return { ...template,
+ paths: template.paths[field] === originalPath ? { ...template.paths, [field]: path } : template.paths,
+ sources: { ...template.sources, [field]: sources.map((entry) => entry.url === source.url ? { ...entry, downloadedPath: path } : entry) },
+ };
+ });
+ saveGeneratorTemplateSettings({ ...current, templates });
+ publish({ ...state!, completed: state!.completed + 1 });
+ }
+ publish({ ...state!, active: false });
+ } catch (reason) {
+ publish({ ...state!, active: false, error: reason instanceof Error ? reason.message : String(reason) });
+ } finally {
+ requestId = null;
+ unlisten?.();
+ }
+}
+
+export async function cancelWeightDownload() {
+ cancelled = true;
+ if (requestId) await invoke("cancel_weight_download", { requestId });
+}
+
+export async function removeTemplateWeights(templateId: string): Promise<void> {
+ if (!isTauri() || state?.active) return;
+ const template = loadGeneratorTemplateSettings().templates.find((template) => template.id === templateId);
+ if (!template) return;
+ const paths = [...new Set(Object.values(template.sources ?? {}).flatMap((sources) => sources.flatMap((source) => source.downloadedPath ? [source.downloadedPath] : [])))];
+ try {
+ await invoke("remove_downloaded_weights", { paths });
+ const current = loadGeneratorTemplateSettings();
+ const templates = current.templates.map((template) => {
+ if (template.id !== templateId) return template;
+ const restored = { ...template, paths: { ...template.paths }, sources: { ...template.sources } };
+ for (const { id } of ENGINE_PATH_FIELDS) {
+ const sources = template.sources?.[id];
+ if (!sources?.length) continue;
+ restored.paths[id] = (sources.find((source) => source.downloadedPath === template.paths[id]) ?? sources[0]).url;
+ restored.sources[id] = sources.map(({ downloadedPath: _removed, ...source }) => source);
+ }
+ return restored;
+ });
+ saveGeneratorTemplateSettings({ ...current, templates });
+ if (state?.templateId === templateId) publish(null);
+ } finally {
+ // Shared weights removed from one template become downloadable in every
+ // template that referred to that same file, including after a partial failure.
+ await refreshDownloadedWeights();
+ }
+}
diff --git a/src/styles/shell.css b/src/styles/shell.css
index ada1764..b0bc8e7 100644
--- a/src/styles/shell.css
+++ b/src/styles/shell.css
@@ -348,12 +348,6 @@
font-size: var(--text-lg);
}
-.generator-editor__head p {
- margin: var(--space-1) 0 0;
- color: var(--text-muted);
- font-size: var(--text-sm);
-}
-
.generator-editor__back {
padding-inline: var(--space-2);
}
@@ -680,14 +674,12 @@
line-height: var(--leading-normal);
}
-/* Five of these, and stacked (name, hint, field, state) each one was four
- rows tall — the reason this screen needed scrolling at all. Side by side the
- same five fit in a window without losing a word of what they say. */
+/* Keep the path on a full-width row so long filenames and URLs remain readable. */
.settings-path {
display: grid;
- grid-template-columns: minmax(0, 5fr) minmax(0, 7fr);
+ grid-template-columns: minmax(0, 1fr);
align-items: start;
- gap: var(--space-4);
+ gap: var(--space-2);
padding: var(--space-3) 0;
border-top: 1px solid var(--line);
}
@@ -719,14 +711,6 @@
text-transform: uppercase;
}
-.settings-path label small {
- display: block;
- margin-top: var(--space-1);
- color: var(--text-muted);
- font-size: var(--text-sm);
- line-height: var(--leading-normal);
-}
-
.settings-path__row {
display: flex;
flex-wrap: wrap;
@@ -746,6 +730,18 @@
font: var(--weight-regular) var(--text-sm) / 1 var(--font-mono);
}
+.weight-sources { min-width: 0; font-size: var(--text-sm); color: var(--text-muted); }
+.weight-sources summary { cursor: pointer; }
+.weight-sources p { margin: var(--space-2) 0; }
+.weight-source { display: grid; grid-template-columns: minmax(0, 1fr) 135px 125px auto; gap: var(--space-2); align-items: end; margin: var(--space-3) 0; }
+.weight-source label { min-width: 0; font-size: var(--text-xs); }
+.weight-source input, .weight-source-add input { width: 100%; min-width: 0; height: var(--field-height); padding: 0 var(--space-2); color: var(--text-primary); background: var(--field-bg); border: 1px solid var(--line-strong); border-radius: var(--radius-sm); }
+.weight-source-add { display: flex; gap: var(--space-2); margin-top: var(--space-2); }
+.weight-source-add input { flex: 1; }
+.weight-download-status { display: flex; align-items: center; flex-wrap: wrap; gap: var(--space-2); padding: var(--space-3) 0; color: var(--text-secondary); font-size: var(--text-sm); }
+.weight-download-status span { flex: 1 1 100%; }
+.weight-download-status progress { flex: 1; accent-color: var(--accent-bright); }
+
.settings-path__row .secondary-button {
flex: 0 0 auto;
}