AI media harness for planning, generating, and editing locally
TypeScript
Add shared H3 VAEs and text encoders
Bitti21f45d19f7c7
diff --git a/src/components/H3ComponentSettings.tsx b/src/components/H3ComponentSettings.tsxnew file mode 100644index 0000000..f0d25a5--- /dev/null+++ b/src/components/H3ComponentSettings.tsx@@ -0,0 +1,98 @@+import { useState, useSyncExternalStore } from "react";+import { type H3ComponentTemplate, type H3ComponentType } from "../lib/h3Components";+import { isDownloadUrl, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, type GeneratorTemplateSettings } from "../lib/settings";+import { chooseEnginePath } from "../lib/runtime";+import { downloadH3Component, getQueuedWeightDownloads, getWeightDownloadState, subscribeWeightDownloads } from "../lib/weightDownloads";+import { ComboBox, ContentDialog, InfoBar, SettingsCard, SettingsGroup } from "./ui";+import { Add20, Delete16, Download16, ModelFile20, TextFile20 } from "./ui/icons";+import { OpenableCard } from "./OpenableCard";+import { WeightSourcesEditor } from "./WeightSourcesEditor";++export function H3ComponentSettings({ settings, desktop }: { settings: GeneratorTemplateSettings; desktop: boolean }) {+ const [editing, setEditing] = useState<H3ComponentTemplate | null>(null);+ const library = settings.h3Components!;+ const download = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);+ const queued = useSyncExternalStore(subscribeWeightDownloads, getQueuedWeightDownloads);+ const add = (type: H3ComponentType) => setEditing({ id: `h3-component-${crypto.randomUUID()}`, name: "", type, path: "", sources: [] });+ const used = (entry: H3ComponentTemplate) => entry.id === library.defaultTextEncoderId || settings.templates.some((template) =>+ template.modelType === "minimax-h3" && (template.videoVaeId === entry.id || template.audioVaeId === entry.id));+ const remove = (id: string) => {+ const current = loadGeneratorTemplateSettings();+ saveGeneratorTemplateSettings({ ...current, h3Components: { ...current.h3Components!, templates: current.h3Components!.templates.filter((entry) => entry.id !== id) } });+ };+ return <>+ {([false, true] as const).map((encoders) => <SettingsGroup key={String(encoders)} heading={encoders ? "Text Encoders" : "VAEs"}>+ <SettingsCard icon={<Add20 />} header={encoders ? "Add a text encoder" : "Add a VAE"}+ description={encoders ? "The default text encoder is used whenever MiniMax H3 needs one. Missing files download with generators." : "Name video and audio VAEs, then select them in your generators."}>+ <button type="button" className="secondary-button" onClick={() => add(encoders ? "textEncoder" : "video")}>{encoders ? "New text encoder" : "New VAE"}</button>+ </SettingsCard>+ {encoders && <SettingsCard icon={<TextFile20 />} header="Default Text Encoder">+ <ComboBox aria-label="Default Text Encoder" value={library.defaultTextEncoderId} options={library.templates.filter((entry) => entry.type === "textEncoder").map((entry) => ({ value: entry.id, label: entry.name }))}+ onChange={(defaultTextEncoderId) => {+ const current = loadGeneratorTemplateSettings();+ saveGeneratorTemplateSettings({ ...current, h3Components: { ...current.h3Components!, defaultTextEncoderId } });+ }} />+ </SettingsCard>}+ <div className="settings-card-list" role="list" aria-label={encoders ? "Text Encoders" : "VAEs"}>+ {library.templates.filter((entry) => (entry.type === "textEncoder") === encoders).map((entry) => {+ const active = download?.active && download.h3ComponentId === entry.id;+ const waiting = queued.some((item) => item.h3ComponentId === entry.id);+ const ready = entry.path && !isDownloadUrl(entry.path) && !isDownloadUrl(entry.tokenizer ?? "");+ return <OpenableCard key={entry.id} icon={encoders ? <TextFile20 /> : <ModelFile20 />} header={entry.name}+ openLabel={`Edit ${entry.name} ${encoders ? "text encoder" : "VAE"}`} onOpen={() => setEditing(entry)}+ description={waiting ? "Queued for download" : active ? "Downloading…" : `${encoders ? entry.id === library.defaultTextEncoderId ? "Used by default" : "Text encoder" : entry.type === "video" ? "Video" : "Audio"} · ${ready ? "Available" : "Download required"}`}+ actions={<>+ {!ready && <button type="button" className="icon-button" aria-label={`Download ${entry.name}`} disabled={!desktop || active || waiting || !entry.sources.length} onClick={() => void downloadH3Component(entry.id)}><Download16 /></button>}+ <button type="button" className="icon-button" aria-label={`Remove ${entry.name} template`} data-tooltip={used(entry) ? "This template is in use" : "Remove template"}+ disabled={used(entry) || Boolean(download?.active) || waiting} onClick={() => remove(entry.id)}><Delete16 /></button>+ </>} />;+ })}+ </div>+ </SettingsGroup>)}+ {editing && <ComponentEditor key={editing.id} initial={editing} desktop={desktop} onDone={() => setEditing(null)} />}+ </>;+}++function ComponentEditor({ initial, desktop, onDone }: { initial: H3ComponentTemplate; desktop: boolean; onDone: () => void }) {+ const [entry, setEntry] = useState(() => structuredClone(initial));+ const [error, setError] = useState<string | null>(null);+ const encoder = entry.type === "textEncoder";+ const updatePath = (path: string) => setEntry((current) => ({ ...current, path,+ sources: isDownloadUrl(path) ? [{ url: path.trim(), gpuModel: "", minVramGb: 0 }, ...current.sources.filter((source) => source.url !== current.path && source.url !== path.trim())] : current.sources }));+ const browse = async (tokenizer = false) => {+ try {+ const path = await chooseEnginePath({ id: tokenizer ? "tokenizer" : encoder ? "textEncoder" : entry.type === "video" ? "videoVae" : "audioVae",+ label: tokenizer ? "Tokenizer" : encoder ? "Text encoder weights" : "VAE weights", hint: "", directory: tokenizer, extensions: tokenizer ? [] : ["safetensors", "gguf", "bin"], required: !tokenizer });+ if (path) { if (tokenizer) setEntry((current) => ({ ...current, tokenizer: path })); else updatePath(path); }+ } catch (reason) { setError(String(reason)); }+ };+ const save = () => {+ const current = loadGeneratorTemplateSettings();+ const library = current.h3Components!;+ if (!entry.name.trim() || (!entry.path.trim() && !entry.sources.length)) { setError("Enter a name and a weight path or download URL."); return; }+ if (entry.type !== initial.type && current.templates.some((template) => template.videoVaeId === entry.id || template.audioVaeId === entry.id)) {+ setError("Select another VAE in generators using this template before changing its type."); return;+ }+ const saved = { ...entry, name: entry.name.trim(), path: entry.path.trim() || entry.sources[0]?.url || "" };+ // Preserve downloads completed while this dialog was open if their source was not edited.+ const latest = library.templates.find((item) => item.id === entry.id);+ saved.sources = saved.sources.map((source) => ({ ...source, downloadedPath: latest?.sources.find((item) => item.url === source.url)?.downloadedPath ?? source.downloadedPath }));+ if (latest && saved.path === initial.path) saved.path = latest.path;+ saveGeneratorTemplateSettings({ ...current, h3Components: { ...library,+ templates: latest ? library.templates.map((item) => item.id === entry.id ? saved : item) : [...library.templates, saved] } });+ onDone();+ };+ return <ContentDialog title={encoder ? "Text encoder template" : "VAE template"} width={640} primaryText="Save" onPrimary={save} closeText="Cancel" onClose={onDone} defaultButton="primary">+ <div className="lora-manual">+ <label>Name<input className="text-field" aria-label={encoder ? "Text encoder name" : "VAE name"} value={entry.name} onChange={(event) => setEntry({ ...entry, name: event.target.value })} /></label>+ {!encoder && <label>Type<ComboBox aria-label="VAE type" value={entry.type} options={[{ value: "video", label: "Video" }, { value: "audio", label: "Audio" }]} onChange={(type) => setEntry({ ...entry, type: type as "video" | "audio" })} /></label>}+ <label>Weight path or URL<span className="lora-manual__path"><input className="text-field" aria-label="Weight path or URL" value={entry.path} spellCheck={false} onChange={(event) => updatePath(event.target.value)} />+ <button type="button" className="secondary-button" disabled={!desktop} onClick={() => void browse()}>Browse…</button></span></label>+ {encoder && <label>Tokenizer (optional)<span className="lora-manual__path"><input className="text-field" aria-label="Text encoder tokenizer" value={entry.tokenizer ?? ""} onChange={(event) => setEntry({ ...entry, tokenizer: event.target.value })} />+ <button type="button" className="secondary-button" disabled={!desktop} onClick={() => void browse(true)}>Browse…</button></span></label>}+ <WeightSourcesEditor label={encoder ? "Text encoder" : "VAE"} sources={entry.sources} disabled={false} onChange={(sources) => setEntry({ ...entry, sources,+ path: !entry.path || isDownloadUrl(entry.path) ? sources.find((source) => source.url === entry.path)?.url ?? sources[0]?.url ?? "" : entry.path })} />+ {error && <InfoBar severity="error" message={error} />}+ </div>+ </ContentDialog>;+}diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsxindex 531a9f9..7258aa8 100644--- a/src/components/SettingsView.tsx+++ b/src/components/SettingsView.tsx@@ -3,6 +3,7 @@ import { DEFAULT_VIDEO_SIGMA_SHIFT, DEFAULT_AUDIO_SIGMA_SHIFT, MIN_SIGMA_SHIFT,import { AdditionalSafetensorsEditor } from "./AdditionalSafetensorsEditor";import { GeneratorSharing } from "./GeneratorSharing";import { OtherWeightsSettings } from "./OtherWeightsSettings";+import { H3ComponentSettings } from "./H3ComponentSettings";import { AgentDock } from "./workspace/AgentDock";import { useAgentPane } from "../lib/useAgentPane";import { useShortcut } from "../lib/commands";@@ -450,7 +451,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine", titleBarprobe({ ...EMPTY_ENGINE_SETTINGS });};- const updateTemplate = (updates: Partial<Pick<typeof selectedTemplate, "editingModel" | "modelType" | "name" | "defaultSteps" | "videoSigmaShift" | "audioSigmaShift" | "attention" | "motionCache" | "loras" | "mode" | "additionalSafetensors">>) => {+ const updateTemplate = (updates: Partial<Pick<typeof selectedTemplate, "videoVaeId" | "audioVaeId" | "editingModel" | "modelType" | "name" | "defaultSteps" | "videoSigmaShift" | "audioSigmaShift" | "attention" | "motionCache" | "loras" | "mode" | "additionalSafetensors">>) => {setTemplateSettings((current) => {const next = {...current,@@ -625,7 +626,16 @@ export function SettingsView({ onClose, updates, initialTab = "engine", titleBar</SettingsGroup><SettingsGroup heading="Model files">- {generatorPathFields(selectedTemplate).map(pathCard)}+ {generatorPathFields(selectedTemplate).filter(({ id }) => selectedTemplate.modelType !== "minimax-h3" || id === "transformer").map(pathCard)}+ {selectedTemplate.modelType === "minimax-h3" && (["video", "audio"] as const).map((type) => {+ const key = type === "video" ? "videoVaeId" : "audioVaeId";+ const label = type === "video" ? "Video VAE" : "Audio VAE";+ return <SettingsCard key={type} icon={<ModelFile20 />} header={label}>+ <ComboBox aria-label={label} value={selectedTemplate[key] ?? ""}+ options={templateSettings.h3Components!.templates.filter((entry) => entry.type === type).map((entry) => ({ value: entry.id, label: entry.name }))}+ onChange={(id) => updateTemplate({ [key]: id })} />+ </SettingsCard>;+ })}</SettingsGroup><AdditionalSafetensorsEditor key={selectedTemplate.id} value={selectedTemplate.additionalSafetensors ?? []} disabled={Boolean(downloading)} animate={selectedTemplate.mode === "animate"} onChange={(additionalSafetensors) => updateTemplate({ additionalSafetensors })} />@@ -682,6 +692,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine", titleBar})}</div></SettingsGroup>)}+ {modelPage === "minimax-h3" && <H3ComponentSettings settings={templateSettings} desktop={desktop} />}<LoraLibrary key={modelPage} modelType={modelPage} onAdd={() => setEditingLoraId(`lora-${crypto.randomUUID()}`)} onEdit={setEditingLoraId} /></>}</>;diff --git a/src/lib/h3Components.test.ts b/src/lib/h3Components.test.tsnew file mode 100644index 0000000..0b517b0--- /dev/null+++ b/src/lib/h3Components.test.ts@@ -0,0 +1,108 @@+// @vitest-environment jsdom+import { beforeEach, expect, it, vi } from "vitest";+import { invoke } from "@tauri-apps/api/core";+import { H3_VIDEO_VAE_ID, H3_AUDIO_VAE_ID, H3_TEXT_ENCODER_ID, SOL_H3_VAE_URL } from "./h3Components";+import { engineProviderSetting, loadGeneratorTemplateSettings, minimaxOriginalTemplate, minimaxFastTemplate, mossImageTemplate, saveGeneratorTemplateSettings, templateNeedsDownload } from "./settings";+import { downloadH3Component, downloadTemplateWeights, getWeightDownloadState, refreshDownloadedWeights, removeTemplateWeights } from "./weightDownloads";++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 Map<string, string>();+beforeEach(() => {+ localStorage.clear(); files.clear(); vi.clearAllMocks();+ vi.mocked(invoke).mockImplementation(async (command, args: any) => {+ if (command === "weight_download_hardware") return [];+ if (command === "find_downloaded_weights") return Object.fromEntries(args.urls.filter((url: string) => files.has(url)).map((url: string) => [url, files.get(url)]));+ if (command === "check_weight_files") return Object.fromEntries(args.paths.map((path: string) => [path, [...files.values()].includes(path)]));+ if (command === "download_weight") { const path = `D:/weights/${args.url.split("/").pop()}`; files.set(args.url, path); return path; }+ if (command === "remove_downloaded_weights") for (const [url, path] of files) if (args.paths.includes(path)) files.delete(url);+ });+});+const downloads = () => vi.mocked(invoke).mock.calls.filter(([command]) => command === "download_weight").map(([, args]) => (args as { url: string }).url);++it("seeds typed VAEs including Sol and preserves FastH3's INT8 selection", () => {+ const settings = loadGeneratorTemplateSettings();+ expect(settings.h3Components?.templates).toEqual(expect.arrayContaining([+ expect.objectContaining({ id: H3_VIDEO_VAE_ID, type: "video" }),+ expect.objectContaining({ id: H3_AUDIO_VAE_ID, type: "audio" }),+ expect.objectContaining({ name: "Sol H3 VAE", type: "video", path: SOL_H3_VAE_URL }),+ ]));+ const fast = settings.templates.find(({ id }) => id === "minimax-h3-fast")!;+ expect(fast.paths.videoVae).toBe(minimaxFastTemplate().paths.videoVae);+ expect(fast.videoVaeId).not.toBe(H3_VIDEO_VAE_ID);+});++it("migrates custom paths and selects the old default generator's encoder once", () => {+ const custom = { ...minimaxOriginalTemplate(), id: "custom", name: "Custom", sources: {},+ paths: { transformer: "D:/model", videoVae: "D:/video", audioVae: "D:/audio", textEncoder: "D:/text", tokenizer: "D:/tokenizer" } };+ localStorage.setItem("slopus.generator-templates.v1", JSON.stringify({ templates: [minimaxOriginalTemplate(), custom], defaultTemplateId: custom.id, catalogVersion: 17 }));+ const migrated = loadGeneratorTemplateSettings();+ expect(migrated.templates[1].paths).toEqual(custom.paths);+ expect(migrated.templates[0].paths.textEncoder).toBe("D:/text");+ expect(migrated.h3Components!.templates.find((entry) => entry.id === migrated.h3Components!.defaultTextEncoderId)).toMatchObject({ path: "D:/text", tokenizer: "D:/tokenizer" });+ expect(loadGeneratorTemplateSettings()).toEqual(migrated);+});++it("resolves the latest default encoder for H3 submissions without changing MOSS", () => {+ const settings = loadGeneratorTemplateSettings();+ const template = settings.templates.find(({ id }) => id === "minimax-h3-original")!;+ settings.h3Components!.templates.push({ id: "custom-text", name: "Custom text", type: "textEncoder", path: "D:/custom-text", tokenizer: "D:/custom-tokenizer", sources: [] });+ settings.h3Components!.defaultTextEncoderId = "custom-text";+ saveGeneratorTemplateSettings(settings);+ const provider = engineProviderSetting(template.paths, undefined, template.attention, [], "prompt", [], false, template.sources, template);+ expect(provider.options).toMatchObject({ textEncoder: "D:/custom-text", tokenizer: "D:/custom-tokenizer" });+ const moss = mossImageTemplate(); moss.paths.textEncoder = "D:/moss-text";+ expect(engineProviderSetting(moss.paths, undefined, moss.attention, [], "prompt", [], false, moss.sources, moss).options.textEncoder).toBe("D:/moss-text");+});++it("downloads a linked Sol VAE and the default encoder, reuses them, and repairs a missing file", async () => {+ const settings = loadGeneratorTemplateSettings();+ for (const template of settings.templates.filter((entry) => ["minimax-h3-original", "minimax-h3-references"].includes(entry.id))) template.videoVaeId = "sol-h3-vae";+ saveGeneratorTemplateSettings(settings);+ await downloadTemplateWeights("minimax-h3-original");+ expect(getWeightDownloadState()?.error).toBeNull();+ expect(downloads()).toContain(SOL_H3_VAE_URL);+ expect(downloads()).toContain(minimaxOriginalTemplate().paths.textEncoder);+ expect(downloads()).not.toContain(minimaxOriginalTemplate().paths.videoVae);+ expect(templateNeedsDownload(loadGeneratorTemplateSettings().templates.find((entry) => entry.id === "minimax-h3-original")!)).toBe(false);+ vi.clearAllMocks();+ await downloadTemplateWeights("minimax-h3-references");+ expect(downloads()).toHaveLength(1);+ files.delete(SOL_H3_VAE_URL); vi.clearAllMocks();+ await downloadTemplateWeights("minimax-h3-original");+ expect(downloads()).toEqual([SOL_H3_VAE_URL]);+});++it("downloads shared templates on their own and keeps them when removing a generator", async () => {+ await downloadH3Component(H3_TEXT_ENCODER_ID);+ expect(getWeightDownloadState()).toMatchObject({ completed: 1, active: false, error: null });+ vi.clearAllMocks();+ await downloadTemplateWeights("minimax-h3-original");+ expect(downloads()).not.toContain(minimaxOriginalTemplate().paths.textEncoder);+ await removeTemplateWeights("minimax-h3-original");+ expect(files.has(minimaxOriginalTemplate().paths.textEncoder)).toBe(true);+ expect(files.has(minimaxOriginalTemplate().paths.videoVae)).toBe(true);+});++it("does not replace an edited shared source when a download completes", async () => {+ const normal = vi.mocked(invoke).getMockImplementation()!;+ vi.mocked(invoke).mockImplementation(async (command, args: any) => {+ if (command === "download_weight" && args.url === SOL_H3_VAE_URL) {+ const current = loadGeneratorTemplateSettings();+ const sol = current.h3Components!.templates.find((entry) => entry.id === "sol-h3-vae")!;+ sol.path = "D:/my-vae"; sol.sources = [];+ saveGeneratorTemplateSettings(current);+ }+ return normal(command, args);+ });+ await downloadH3Component("sol-h3-vae");+ expect(loadGeneratorTemplateSettings().h3Components!.templates.find((entry) => entry.id === "sol-h3-vae")?.path).toBe("D:/my-vae");+});++it("refreshes missing dependencies even when their generator has not been opened", async () => {+ await downloadTemplateWeights("minimax-h3-original");+ files.delete(minimaxOriginalTemplate().paths.textEncoder);+ await refreshDownloadedWeights();+ expect(loadGeneratorTemplateSettings().h3Components!.templates.find((entry) => entry.id === H3_TEXT_ENCODER_ID)?.path).toBe(minimaxOriginalTemplate().paths.textEncoder);+});diff --git a/src/lib/h3Components.ts b/src/lib/h3Components.tsnew file mode 100644index 0000000..69c6432--- /dev/null+++ b/src/lib/h3Components.ts@@ -0,0 +1,126 @@+import type { EnginePathId, GeneratorTemplate, WeightSource } from "./settings";++export type H3ComponentType = "video" | "audio" | "textEncoder";+export interface H3ComponentTemplate {+ id: string;+ name: string;+ type: H3ComponentType;+ path: string;+ sources: WeightSource[];+ tokenizer?: string;+}+export interface H3Components {+ templates: H3ComponentTemplate[];+ defaultTextEncoderId: string;+}++const root = "https://huggingface.co/Comfy-Org/MiniMax-H3/blob/main/";+export const H3_VIDEO_VAE_ID = "h3-video-vae";+export const H3_AUDIO_VAE_ID = "h3-audio-vae";+export const H3_FAST_VIDEO_VAE_ID = "h3-fast-video-vae";+export const H3_TEXT_ENCODER_ID = "h3-text-encoder";+export const SOL_H3_VAE_URL = "https://huggingface.co/Efficient-Large-Model/Sol-H3-VAE/resolve/main/sol_h3_vae.safetensors";+const isUrl = (path: string) => /^https?:\/\//i.test(path.trim());+export function initialH3Components(): H3Components {+ return { defaultTextEncoderId: H3_TEXT_ENCODER_ID, templates: [+ { id: H3_VIDEO_VAE_ID, name: "MiniMax H3 Video VAE", type: "video", path: root + "vae/minimax_h3_video_vae_fp16.safetensors" },+ { id: "sol-h3-vae", name: "Sol H3 VAE", type: "video", path: SOL_H3_VAE_URL },+ { id: H3_FAST_VIDEO_VAE_ID, name: "MiniMax H3 Video VAE INT8", type: "video", path: root + "vae/minimax_h3_video_vae_int8_convrot.safetensors" },+ { id: H3_AUDIO_VAE_ID, name: "MiniMax H3 Audio VAE", type: "audio", path: root + "vae/minimax_h3_audio_vae_fp32.safetensors" },+ { id: H3_TEXT_ENCODER_ID, name: "Qwen3 VL 32B MiniMax H3", type: "textEncoder", path: root + "text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors" },+ ].map((entry) => ({ ...entry, type: entry.type as H3ComponentType, sources: [{ url: entry.path, gpuModel: "", minVramGb: 0 }] })) };+}++function normalizeComponents(value: unknown): H3Components {+ if (!value || typeof value !== "object" || !Array.isArray((value as H3Components).templates)) return initialH3Components();+ const raw = value as H3Components;+ const ids = new Set<string>();+ const templates = raw.templates.flatMap((entry): H3ComponentTemplate[] => {+ if (!entry || typeof entry.id !== "string" || !entry.id || ids.has(entry.id) || !["video", "audio", "textEncoder"].includes(entry.type)) return [];+ ids.add(entry.id);+ const path = typeof entry.path === "string" ? entry.path : "";+ const sources = Array.isArray(entry.sources) ? entry.sources.flatMap((source): WeightSource[] => {+ if (!source || typeof source.url !== "string" || !isUrl(source.url)) return [];+ return [{ url: source.url.trim(), gpuModel: typeof source.gpuModel === "string" ? source.gpuModel : "",+ minVramGb: Number.isFinite(source.minVramGb) ? Math.max(0, source.minVramGb) : 0,+ ...(typeof source.downloadedPath === "string" && !isUrl(source.downloadedPath) ? { downloadedPath: source.downloadedPath } : {}) }];+ }) : [];+ if (isUrl(path) && !sources.some(({ url }) => url === path.trim())) sources.unshift({ url: path.trim(), gpuModel: "", minVramGb: 0 });+ return [{ id: entry.id, name: typeof entry.name === "string" && entry.name.trim() ? entry.name : "Untitled template", type: entry.type,+ path, sources, ...(typeof entry.tokenizer === "string" ? { tokenizer: entry.tokenizer } : {}) }];+ });+ return { templates, defaultTextEncoderId: templates.find((entry) => entry.id === raw.defaultTextEncoderId && entry.type === "textEncoder")?.id+ ?? templates.find((entry) => entry.type === "textEncoder")?.id ?? "" };+}++export function h3ComponentForField(template: GeneratorTemplate, field: EnginePathId, library: H3Components): H3ComponentTemplate | undefined {+ if (template.modelType !== "minimax-h3") return undefined;+ const type = field === "videoVae" ? "video" : field === "audioVae" ? "audio" : field === "textEncoder" || field === "tokenizer" ? "textEncoder" : undefined;+ const id = field === "videoVae" ? template.videoVaeId : field === "audioVae" ? template.audioVaeId : library.defaultTextEncoderId;+ return library.templates.find((entry) => entry.id === id && entry.type === type);+}++/** Keep resolved paths for native/worker consumers, but shared templates own them. */+export function resolveH3Components(template: GeneratorTemplate, library: H3Components): GeneratorTemplate {+ if (template.modelType !== "minimax-h3") return template;+ const paths = { ...template.paths }, sources = { ...template.sources };+ for (const field of ["videoVae", "audioVae", "textEncoder", "tokenizer"] as const) {+ const component = h3ComponentForField(template, field, library);+ paths[field] = field === "tokenizer" ? component?.tokenizer ?? "" : component?.path ?? "";+ const entries = field === "tokenizer" ? (isUrl(paths[field]) ? [{ url: paths[field], gpuModel: "", minVramGb: 0 }] : []) : component?.sources ?? [];+ if (entries.length) sources[field] = entries;+ else delete sources[field];+ }+ return { ...template, paths, sources };+}++/** Migrate old per-generator files once, including local files and GPU variants. */+export function normalizeH3Library(templates: GeneratorTemplate[], value: unknown, defaultGeneratorId: string) {+ const library = normalizeComponents(value);+ const migrating = !value;+ const canonical = (path: string) => path.trim().replace("/blob/", "/resolve/").replaceAll("\\", "/");+ const migrate = (template: GeneratorTemplate, field: "videoVae" | "audioVae" | "textEncoder") => {+ const type = field === "videoVae" ? "video" : field === "audioVae" ? "audio" : "textEncoder";+ const path = template.paths[field];+ const sources = template.sources?.[field] ?? [];+ if (!path && !sources.length) return field === "videoVae" ? H3_VIDEO_VAE_ID : field === "audioVae" ? H3_AUDIO_VAE_ID : H3_TEXT_ENCODER_ID;+ const sourceKey = (entries: WeightSource[]) => JSON.stringify(entries.map(({ url, gpuModel, minVramGb }) => ({ url: canonical(url), gpuModel, minVramGb })));+ let entry = library.templates.find((entry) => entry.type === type && (+ canonical(entry.path) === canonical(path) || sources.some((source) => source.downloadedPath === path && entry.sources.some((a) => canonical(a.url) === canonical(source.url)))+ || isUrl(path) && entry.sources.some((a) => canonical(a.url) === canonical(path))+ ) && (sourceKey(entry.sources) === sourceKey(sources)) && (+ !path || isUrl(path) || isUrl(entry.path) || canonical(entry.path) === canonical(path)+ ) && (field !== "textEncoder" || (entry.tokenizer ?? "") === template.paths.tokenizer));+ if (!entry) {+ entry = { id: `${template.id}-${field}`, name: `${template.name} ${type === "textEncoder" ? "Text Encoder" : type === "video" ? "Video VAE" : "Audio VAE"}`,+ type, path, sources, ...(field === "textEncoder" ? { tokenizer: template.paths.tokenizer } : {}) };+ library.templates.push(entry);+ } else {+ if (path && !isUrl(path) && (!entry.path || isUrl(entry.path))) entry.path = path;+ for (const source of sources) {+ const existing = entry.sources.find((item) => canonical(item.url) === canonical(source.url));+ if (!existing) entry.sources.push(source);+ else if (source.downloadedPath && !existing.downloadedPath) existing.downloadedPath = source.downloadedPath;+ }+ }+ return entry.id;+ };+ const linked = templates.map((template) => {+ if (template.modelType !== "minimax-h3") return template;+ const next = { ...template };+ for (const field of ["videoVae", "audioVae"] as const) {+ const key = field === "videoVae" ? "videoVaeId" : "audioVaeId";+ if (next[key] === undefined) next[key] = migrate(template, field);+ }+ if (migrating && template.mode !== "animate" && (template.paths.textEncoder || template.sources?.textEncoder?.length)) {+ const id = migrate(template, "textEncoder");+ if (template.id === defaultGeneratorId) library.defaultTextEncoderId = id;+ }+ return next;+ });+ // Prefer an existing local encoder on first migration if the former default had none.+ if (migrating && !templates.find((entry) => entry.id === defaultGeneratorId)?.paths.textEncoder) {+ library.defaultTextEncoderId = library.templates.find((entry) => entry.type === "textEncoder" && entry.path && !isUrl(entry.path))?.id ?? library.defaultTextEncoderId;+ }+ return { h3Components: library, templates: linked.map((template) => resolveH3Components(template, library)) };+}diff --git a/src/lib/settings.ts b/src/lib/settings.tsindex 945d0bb..693bb61 100644--- a/src/lib/settings.ts+++ b/src/lib/settings.ts@@ -13,6 +13,7 @@* silently drops that path.*/import { isSigmaShift, type SigmaShifts } from "./sampling";+import { normalizeH3Library, resolveH3Components, type H3Components } from "./h3Components";import { generatorModel } from "./generatorModels";export { generatorModel, GENERATOR_MODELS } from "./generatorModels";import { latentUpscalerPath } from "./upscalers";@@ -97,6 +98,8 @@ export interface GeneratorTemplate extends SigmaShifts {motionCache?: boolean;mode?: "prompt" | "animate";paths: EngineSettings;+ videoVaeId?: string;+ audioVaeId?: string;sources?: Partial<Record<EnginePathId, WeightSource[]>>;loras?: TemplateLora[];additionalSafetensors?: AdditionalSafetensor[];@@ -221,6 +224,7 @@ export interface GeneratorTemplateSettings {templates: GeneratorTemplate[];defaultTemplateId: string;catalogVersion?: number;+ h3Components?: H3Components;}const copyPaths = (paths: EngineSettings): EngineSettings => ({ ...paths });@@ -368,15 +372,15 @@ export function viggleAnimateTemplate(): GeneratorTemplate {};}-const initialTemplateSettings = (paths = EMPTY_ENGINE_SETTINGS): GeneratorTemplateSettings => ({+const initialTemplateSettings = (paths = EMPTY_ENGINE_SETTINGS): GeneratorTemplateSettings => normalizeTemplateSettings({templates: [{ id: "default", name: "Default", modelType: MINIMAX_H3_MODEL_TYPE, defaultSteps: DEFAULT_GENERATION_STEPS, attention: "sage2", paths: copyPaths(paths) }, minimaxOriginalTemplate(), minimaxReferencesTemplate(), minimaxFastTemplate(), minimaxSingularityTemplate(), viggleAnimateTemplate(), mossImageTemplate(), fiboImageTemplate(), fiboBaseTemplate(), ...musicTemplates()],defaultTemplateId: "default",catalogVersion: 17,-});+})!;-const normalizeTemplateSettings = (value: unknown): GeneratorTemplateSettings | null => {+const normalizeTemplateSettings = (value: unknown, shareComponents = true): GeneratorTemplateSettings | null => {if (!value || typeof value !== "object") return null;- const record = value as { templates?: unknown; defaultTemplateId?: unknown; catalogVersion?: unknown };+ const record = value as { templates?: unknown; defaultTemplateId?: unknown; catalogVersion?: unknown; h3Components?: unknown };if (!Array.isArray(record.templates)) return null;const ids = new Set<string>();const templates = record.templates.flatMap((item): GeneratorTemplate[] => {@@ -420,6 +424,8 @@ const normalizeTemplateSettings = (value: unknown): GeneratorTemplateSettings |...(typeof file.downloadedPath === "string" && file.downloadedPath.trim() && !isDownloadUrl(file.downloadedPath) ? { downloadedPath: file.downloadedPath } : {}) }];}) : [];return [{ id, name, modelType, defaultSteps, attention, paths, sources,+ ...(typeof candidate.videoVaeId === "string" ? { videoVaeId: candidate.videoVaeId } : {}),+ ...(typeof candidate.audioVaeId === "string" ? { audioVaeId: candidate.audioVaeId } : {}),...(typeof candidate.editingModel === "boolean" ? { editingModel: candidate.editingModel } : {}),...(isSigmaShift(candidate.videoSigmaShift) ? { videoSigmaShift: candidate.videoSigmaShift } : {}),...(isSigmaShift(candidate.audioSigmaShift) ? { audioSigmaShift: candidate.audioSigmaShift } : {}),@@ -430,10 +436,12 @@ const normalizeTemplateSettings = (value: unknown): GeneratorTemplateSettings |});if (templates.length === 0) return null;const requestedDefault = typeof record.defaultTemplateId === "string" ? record.defaultTemplateId : "";+ const shared = shareComponents ? normalizeH3Library(templates, record.h3Components, requestedDefault)+ : { templates, ...(record.h3Components ? { h3Components: record.h3Components as H3Components } : {}) };return {- templates,- defaultTemplateId: templates.find((template) => template.id === requestedDefault && templateUsable(template))?.id- ?? templates.find(templateUsable)?.id ?? "",+ ...shared,+ defaultTemplateId: shared.templates.find((template) => template.id === requestedDefault && templateUsable(template))?.id+ ?? shared.templates.find(templateUsable)?.id ?? "",catalogVersion: typeof record.catalogVersion === "number" && [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17].includes(record.catalogVersion) ? record.catalogVersion : 0,};};@@ -445,7 +453,7 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {try {const stored = migratedStorageItem(GENERATOR_TEMPLATES_KEY, LEGACY_GENERATOR_TEMPLATES_KEY);if (stored) {- let normalized = normalizeTemplateSettings(JSON.parse(stored));+ let normalized = normalizeTemplateSettings(JSON.parse(stored), false);if (normalized) {if ((normalized.catalogVersion ?? 0) < 2) {const bundled = minimaxOriginalTemplate();@@ -483,7 +491,7 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {existing.sources!.textEncoder = retained;}// A replaced local encoder may now need downloading and cannot remain the default.- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 3 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 3 }, false)!;}if ((normalized.catalogVersion ?? 0) < 4) {const original = normalized.templates.find((template) => template.id === "minimax-h3-original");@@ -503,13 +511,13 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {if (singularity && !singularity.loras?.some(({ loraId }) => loraId === TURBO_LORA.id)) {singularity.loras = [...(singularity.loras ?? []), { loraId: TURBO_LORA.id, enabled: true, strength: 1 }];}- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 6 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 6 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}if ((normalized.catalogVersion ?? 0) < 7) {const template = viggleAnimateTemplate();if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 7 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 7 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}if ((normalized.catalogVersion ?? 0) < 8) {@@ -517,7 +525,7 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {if (animate && !animate.additionalSafetensors?.some((file) => file.role === "promptEmbedding")) {animate.additionalSafetensors = [...(animate.additionalSafetensors ?? []), ...viggleAnimateTemplate().additionalSafetensors!];}- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 8 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 8 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}if ((normalized.catalogVersion ?? 0) < 9) {@@ -545,13 +553,13 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {}if (fast.defaultSteps === 6) fast.defaultSteps = bundled.defaultSteps;}- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 9 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 9 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}if ((normalized.catalogVersion ?? 0) < 10) {const template = mossImageTemplate();if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 10 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 10 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}if ((normalized.catalogVersion ?? 0) < 11) {@@ -571,7 +579,7 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {return { ...updated, url: bundled.paths.transformer };});}- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 11 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 11 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}if ((normalized.catalogVersion ?? 0) < 12) {@@ -596,7 +604,7 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {}if (sources.length || retained.length) fast.sources = { ...fast.sources, transformer: retained };}- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 12 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 12 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}if ((normalized.catalogVersion ?? 0) < 13) {@@ -613,24 +621,24 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {return { ...updated, url: MINIMAX_FL2VA_W4A8_URL };});}- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 13 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 13 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}if ((normalized.catalogVersion ?? 0) < 14) {const template = fiboImageTemplate();if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 14 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 14 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}if ((normalized.catalogVersion ?? 0) < 15) {const template = fiboBaseTemplate();if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 15 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 15 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}if ((normalized.catalogVersion ?? 0) < 16) {for (const template of musicTemplates()) if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 16 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 16 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}if ((normalized.catalogVersion ?? 0) < 17) {@@ -643,10 +651,12 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {|| sources.some((source) => source.url === bf16.url)) return template;return { ...template, sources: { ...template.sources, transformer: [bf16, ...sources] } };});- normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 17 })!;+ normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 17 }, false)!;localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));}- return normalized;+ const shared = normalizeTemplateSettings(normalized)!;+ if (!normalized.h3Components) localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(shared));+ return shared;}}const legacy = migratedStorageItem(ENGINE_KEY, LEGACY_ENGINE_KEY);@@ -657,7 +667,7 @@ export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {}export function saveGeneratorTemplateSettings(settings: GeneratorTemplateSettings, options: { strict?: boolean } = {}): void {- const normalized = normalizeTemplateSettings(settings) ?? initialTemplateSettings();+ const normalized = normalizeTemplateSettings(settings, (settings.catalogVersion ?? 17) >= 17) ?? initialTemplateSettings();try {localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));} catch (error) {@@ -705,6 +715,19 @@ export function saveEngineSettings(settings: EngineSettings): void {* an unset field falls through to whatever the project (or the Rust default)* already had rather than overwriting it with "". */export function engineProviderSetting(settings: EngineSettings, base?: ProviderSetting, attention = defaultGeneratorTemplate().attention, selection = defaultGeneratorTemplate().loras, mode = defaultGeneratorTemplate().mode, additionalSafetensors = defaultGeneratorTemplate().additionalSafetensors, motionCache = defaultGeneratorTemplate().motionCache ?? false, sources = defaultGeneratorTemplate().sources, shifts: SigmaShifts & { modelType?: string; editingModel?: boolean } = defaultGeneratorTemplate()): ProviderSetting {+ // Resolve again at submission: a queued generator may predate a default encoder change.+ if (shifts.modelType === MINIMAX_H3_MODEL_TYPE) {+ const library = loadGeneratorTemplateSettings().h3Components!;+ const resolved = resolveH3Components({ id: "", name: "", defaultSteps: 20, attention, ...shifts,+ modelType: MINIMAX_H3_MODEL_TYPE, mode, paths: settings, sources } as GeneratorTemplate, library);+ // Legacy callers may supply only paths; named VAE links are resolved by the settings loader.+ settings = { ...settings, textEncoder: resolved.paths.textEncoder, tokenizer: resolved.paths.tokenizer,+ ...("videoVaeId" in shifts ? { videoVae: resolved.paths.videoVae } : {}),+ ...("audioVaeId" in shifts ? { audioVae: resolved.paths.audioVae } : {}) };+ sources = { ...sources, textEncoder: resolved.sources?.textEncoder, tokenizer: resolved.sources?.tokenizer,+ ...("videoVaeId" in shifts ? { videoVae: resolved.sources?.videoVae } : {}),+ ...("audioVaeId" in shifts ? { audioVae: resolved.sources?.audioVae } : {}) };+ }// A LAN worker receives URLs for weights it should download itself.const remote = remoteWorkerSelected();const options: ProviderSetting["options"] = { ...(base?.options ?? {}), attention, inferenceBackend: loadInferenceBackend() };diff --git a/src/lib/weightDownloads.ts b/src/lib/weightDownloads.tsindex 4beb9fe..0aa4929 100644--- a/src/lib/weightDownloads.ts+++ b/src/lib/weightDownloads.ts@@ -7,10 +7,12 @@ import { chooseWeightSource, ENGINE_PATH_FIELDS, generatorPathFields, isDownloadtype EnginePathId, type GeneratorTemplate, type WeightGpu, type WeightSource } from "./settings";export type { WeightGpu } from "./settings";+import { h3ComponentForField, type H3ComponentTemplate } from "./h3Components";export { chooseWeightSource };export interface DownloadState {templateId: string;otherWeightId?: string;+ h3ComponentId?: string;currentFile?: string;loraId?: string;currentLoraId?: string;@@ -44,7 +46,7 @@ let queued: readonly DownloadState[] = [];export const getQueuedWeightDownloads = () => queued;const publishQueue = () => { queued = pending.map((job) => job.state); subscribers.forEach((listener) => listener()); };-function enqueueDownload(initial: Pick<DownloadState, "templateId" | "name" | "loraId" | "otherWeightId">, run: () => Promise<void>): Promise<void> {+function enqueueDownload(initial: Pick<DownloadState, "templateId" | "name" | "loraId" | "otherWeightId" | "h3ComponentId">, run: () => Promise<void>): Promise<void> {const existing = [running, ...pending].find((job) => job?.state.templateId === initial.templateId);if (existing) return existing.done;let resolve!: () => void, reject!: (reason: unknown) => void;@@ -91,12 +93,95 @@ export function updateWeightPath(template: GeneratorTemplate, field: EnginePathIreturn { ...template, paths: { ...template.paths, [field]: value }, sources };}+function saveH3Download(before: H3ComponentTemplate, tokenizer: boolean, url: string, path: string) {+ const current = loadGeneratorTemplateSettings();+ const library = current.h3Components!;+ saveGeneratorTemplateSettings({ ...current, h3Components: { ...library, templates: library.templates.map((entry) => {+ if (entry.id !== before.id) return entry;+ if (tokenizer) return entry.tokenizer === before.tokenizer ? { ...entry, tokenizer: path } : entry;+ if (!entry.sources.some((source) => source.url === url)) return entry;+ return { ...entry, path: entry.path === before.path ? path : entry.path,+ sources: entry.sources.map((source) => source.url === url ? { ...source, downloadedPath: path } : source) };+ }) } });+}++async function refreshH3Components() {+ const before = loadGeneratorTemplateSettings().h3Components!;+ const paths = [...new Set(before.templates.flatMap((entry) => [+ ...(entry.path && !isDownloadUrl(entry.path) ? [entry.path] : []),+ ...entry.sources.flatMap((source) => source.downloadedPath ? [source.downloadedPath] : []),+ ]))];+ const urls = [...new Set(before.templates.flatMap((entry) => entry.sources.map((source) => source.url)))];+ const [exists, found, devices] = await Promise.all([+ paths.length ? invoke<Record<string, boolean>>("check_weight_files", { paths }) : Promise.resolve({} as Record<string, boolean>),+ urls.length ? invoke<Record<string, string>>("find_downloaded_weights", { urls }) : Promise.resolve({} as Record<string, string>),+ invoke<WeightGpu[]>("weight_download_hardware"),+ ]);+ const current = loadGeneratorTemplateSettings();+ const library = current.h3Components!;+ let changed = false;+ const templates = library.templates.map((entry) => {+ if (!before.templates.some((old) => old.id === entry.id && JSON.stringify(old) === JSON.stringify(entry))) return entry;+ const sources = entry.sources.map((source) => ({ ...source,+ downloadedPath: source.downloadedPath && exists?.[source.downloadedPath] !== false ? source.downloadedPath : found?.[source.url] }));+ let path = entry.path;+ if (!path || isDownloadUrl(path) || exists?.[path] === false) {+ const source = chooseWeightSource(sources, devices ?? []);+ path = source?.downloadedPath ?? source?.url ?? path;+ }+ const next = { ...entry, sources, path };+ if (JSON.stringify(next) !== JSON.stringify(entry)) changed = true;+ return next;+ });+ if (changed) saveGeneratorTemplateSettings({ ...current, h3Components: { ...library, templates } });+}++export function downloadH3Component(id: string): Promise<void> {+ if (!isTauri()) return Promise.resolve();+ const component = loadGeneratorTemplateSettings().h3Components?.templates.find((entry) => entry.id === id);+ return enqueueDownload({ templateId: `h3:${id}`, h3ComponentId: id, name: component?.name }, async () => {+ publish({ templateId: `h3:${id}`, h3ComponentId: id, name: component?.name, field: null,+ downloaded: 0, total: null, completed: 0, files: 0, error: null, active: true });+ let unlisten: (() => void) | undefined;+ try {+ await refreshH3Components();+ const entry = loadGeneratorTemplateSettings().h3Components!.templates.find((item) => item.id === id);+ if (!entry) throw new Error("This template was removed.");+ const devices = await invoke<WeightGpu[]>("weight_download_hardware");+ const source = chooseWeightSource(entry.sources, devices ?? []);+ const downloads: { source: WeightSource; tokenizer: boolean }[] = [];+ if (!entry.path || isDownloadUrl(entry.path)) {+ if (!source) throw new Error("No download source matches this GPU and its memory.");+ downloads.push({ source, tokenizer: false });+ }+ if (entry.tokenizer && isDownloadUrl(entry.tokenizer)) downloads.push({ source: { url: entry.tokenizer, gpuModel: "", minVramGb: 0 }, tokenizer: true });+ 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 { source, tokenizer } of downloads) {+ if (cancelled) throw new Error("Download cancelled.");+ requestId = crypto.randomUUID();+ publish({ ...state!, field: tokenizer ? "tokenizer" : entry.type === "video" ? "videoVae" : entry.type === "audio" ? "audioVae" : "textEncoder", 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.");+ saveH3Download(entry, tokenizer, source.url, path);+ publish({ ...state!, completed: state!.completed + 1 });+ }+ publish({ ...state!, active: false, field: null });+ } catch (reason) {+ publish({ ...state!, active: false, error: reason instanceof Error ? reason.message : String(reason) });+ } finally { requestId = null; unlisten?.(); }+ });+}+let refreshPending: Promise<void> | null = null;export function refreshDownloadedWeights(): Promise<void> {if (!isTauri()) return Promise.resolve();if (refreshPending) return refreshPending;refreshPending = (async () => {await refreshDownloadedLoras();+ await refreshH3Components();const before = loadGeneratorTemplateSettings();const paths = [...new Set(before.templates.flatMap((template) => [...generatorPathFields(template).flatMap(({ id }) => (template.sources?.[id] ?? []).flatMap((source) => source.downloadedPath ? [source.downloadedPath] : [])),@@ -171,7 +256,7 @@ async function runTemplateDownload(templateId: string): Promise<void> {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] }];+ return [{ field: id, source, originalPath: template.paths[id], component: h3ComponentForField(template, id, loadGeneratorTemplateSettings().h3Components!) }];});const loraDownloads = downloadableTemplateLoras(template.loras);const additionalDownloads = (template.additionalSafetensors ?? []).filter((file) => !file.downloadedPath);@@ -179,12 +264,13 @@ async function runTemplateDownload(templateId: string): Promise<void> {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) {+ for (const { field, source, originalPath, component } 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.");+ if (component) saveH3Download(component, field === "tokenizer", source.url, path);const current = loadGeneratorTemplateSettings();const templates = current.templates.map((template) => {if (template.id !== templateId) return template;@@ -298,6 +384,7 @@ async function runLoraDownload(loraId: string): Promise<void> {}export function retryWeightDownload(): Promise<void> {+ if (state?.h3ComponentId) return downloadH3Component(state.h3ComponentId);if (state?.otherWeightId) return downloadOtherWeights(state.otherWeightId);if (state?.preparePath && state.loraId) return prepareLora({ id: state.loraId, name: state.name ?? "LoRA", path: state.preparePath }, state.allowDownload).catch(() => undefined); // The shared status retains the error for another retry.@@ -382,7 +469,7 @@ export async function removeTemplateWeights(templateId: string): Promise<void> {const template = loadGeneratorTemplateSettings().templates.find((template) => template.id === templateId);if (!template) return;const paths = [...new Set([- ...generatorPathFields(template).flatMap(({ id }) => (template.sources?.[id] ?? []).flatMap((source) => source.downloadedPath ? [source.downloadedPath] : [])),+ ...generatorPathFields(template).filter(({ id }) => template.modelType !== "minimax-h3" || id === "transformer").flatMap(({ id }) => (template.sources?.[id] ?? []).flatMap((source) => source.downloadedPath ? [source.downloadedPath] : [])),...(template.additionalSafetensors ?? []).flatMap((file) => file.downloadedPath ? [file.downloadedPath] : []),])];try {@@ -393,6 +480,7 @@ export async function removeTemplateWeights(templateId: string): Promise<void> {const restored = { ...template, paths: { ...template.paths }, sources: { ...template.sources } };restored.additionalSafetensors = template.additionalSafetensors?.map((file) => paths.includes(file.downloadedPath ?? "") ? { ...file, downloadedPath: undefined } : file);for (const { id } of generatorPathFields(template)) {+ if (template.modelType === "minimax-h3" && id !== "transformer") continue;const sources = template.sources?.[id];if (!sources?.length) continue;restored.paths[id] = (sources.find((source) => source.downloadedPath === template.paths[id]) ?? sources[0]).url;