Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Share and queue weight downloads

Bitti675d4284f26f
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index e013dae..151d0ac 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -32,6 +32,7 @@ This alpha update adds LAN generation workers, Linux support, expanded color gra
## Fixes and improvements
+- Upscaler downloads share the generator and LoRA download queue, with progress in Work Queue and cancellation for waiting downloads.
- Work queue activity indicators keep moving in the top bar and open queue when Windows interface animations are disabled.
- Image and video export offer None, Real-ESRGAN and SeedVR2 upscaling through SlopFab. Download their models from the new Other weights section in Settings → Generator.
- Image export offers sizes closest to the selected image's actual aspect ratio, even when project or saved generation settings differ.
diff --git a/src/App.tsx b/src/App.tsx
index f7eacce..e7ac5fd 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -5,7 +5,7 @@ import { CudaSetupDialog } from "./components/CudaSetupDialog";
import { ReleaseNotesDialog } from "./components/ReleaseNotesDialog";
import { hasSeenReleaseNotes } from "./lib/releaseNotes";
import { missingCudaDownload } from "./lib/cudaSupport";
-import { getWeightDownloadState, subscribeWeightDownloads } from "./lib/weightDownloads";
+import { getQueuedWeightDownloads, getWeightDownloadState, subscribeWeightDownloads } from "./lib/weightDownloads";
import { startWorkerDiscovery } from "./lib/workers";
import { Add16, FolderOpen16, FolderOpen48, GridView16, GridView16Filled, ListView16, ListView16Filled, Search16, Search32, Settings16, WorkQueue16 } from "./components/ui/icons";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent, type RefObject } from "react";
@@ -56,6 +56,7 @@ function App() {
}));
const workItems = useSyncExternalStore(workQueue.subscribe, workQueue.getSnapshot);
const weightDownloadActive = useSyncExternalStore(subscribeWeightDownloads, () => getWeightDownloadState()?.active ?? false);
+ const queuedDownloads = useSyncExternalStore(subscribeWeightDownloads, getQueuedWeightDownloads);
const iconConfirmationCount = useSyncExternalStore(workQueue.subscribe, workQueue.getIconConfirmationCount);
const [workQueueOpen, setWorkQueueOpen] = useState(false);
useEffect(() => workQueue.start(), [workQueue]);
@@ -154,7 +155,7 @@ function App() {
useEffect(() => {
void reportGenerationJobs(JSON.parse(guardKey) as GuardJob[]).catch(() => undefined);
}, [guardKey]);
- const queueCount = guardJobs.length + Number(weightDownloadActive);
+ const queueCount = guardJobs.length + Number(weightDownloadActive) + queuedDownloads.length;
/* Something is being worked on right now, not merely waiting its turn:
a generation or icon past the queue, an export, a weight download. */
const queueBusy = weightDownloadActive || exportingName !== null
diff --git a/src/components/LoraSettings.tsx b/src/components/LoraSettings.tsx
index a9b1162..f6b6044 100644
--- a/src/components/LoraSettings.tsx
+++ b/src/components/LoraSettings.tsx
@@ -5,7 +5,7 @@ import { highestLoraStepOverride, isLoraStepOverride, loadLoras, saveLoras, subs
import { MAX_GENERATION_STEPS } from "../lib/project";
import { isTauri } from "../lib/persistence";
import { chooseEnginePath } from "../lib/runtime";
-import { downloadLora, getWeightDownloadState, prepareLora, refreshDownloadedLoras, removeLora, subscribeWeightDownloads, weightDownloadProgress } from "../lib/weightDownloads";
+import { getQueuedWeightDownloads, downloadLora, getWeightDownloadState, prepareLora, refreshDownloadedLoras, removeLora, subscribeWeightDownloads, weightDownloadProgress } from "../lib/weightDownloads";
import { Checkbox, ComboBox, ContentDialog, InfoBar, ProgressBar, SettingsCard, SettingsGroup, ToggleSwitch } from "./ui";
import { OpenableCard } from "./OpenableCard";
@@ -18,6 +18,7 @@ function useLoras() {
export function LoraLibrary({ onAdd, onEdit }: { onAdd: () => void; onEdit: (id: string) => void }) {
const loras = useLoras();
const download = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);
+ const queuedDownloads = useSyncExternalStore(subscribeWeightDownloads, getQueuedWeightDownloads);
const [error, setError] = useState<string | null>(null);
const desktop = isTauri();
useEffect(() => {
@@ -34,16 +35,17 @@ export function LoraLibrary({ onAdd, onEdit }: { onAdd: () => void; onEdit: (id:
<div className="settings-card-list" role="list" aria-label="LoRAs">
{loras.map((lora) => {
const active = download?.active && download.loraId === lora.id;
+ const queued = queuedDownloads.some((item) => item.loraId === lora.id);
const preparing = active && download?.phase === "preparing";
const percent = download ? Math.floor(weightDownloadProgress(download)) : 0;
return <OpenableCard key={lora.id} icon={<Lora20 />} header={lora.name} openLabel={`Edit ${lora.name} LoRA`} onOpen={() => onEdit(lora.id)}
- description={<span data-tooltip={lora.path || undefined}>{active ? preparing ? "Preparing…" : `Downloading · ${percent}%` : lora.needsPreparation ? "Needs preparation" : lora.path ? "Available" : "Not downloaded"}</span>}
+ description={<span data-tooltip={lora.path || undefined}>{queued ? "Queued for download" : active ? preparing ? "Preparing…" : `Downloading · ${percent}%` : lora.needsPreparation ? "Needs preparation" : lora.path ? "Available" : "Not downloaded"}</span>}
progress={active && !preparing && <ProgressBar className="settings-progress" value={weightDownloadProgress(download!)} aria-label={`Downloading ${lora.name}`} />}
actions={<>
- {lora.path && <button className="icon-button" type="button" disabled={!desktop || download?.active} aria-label={`Prepare LoRA ${lora.name}`} data-tooltip="Prepare missing timestep grid"
+ {lora.path && <button className="icon-button" type="button" disabled={!desktop || active || queued} aria-label={`Prepare LoRA ${lora.name}`} data-tooltip="Prepare missing timestep grid"
onClick={() => { setError(null); void prepareLora(lora).catch((reason) => setError(String(reason))); }}>{preparing ? <Spinner16 className="spin" /> : <Wrench16 />}</button>}
{lora.url && !lora.path
- ? <button className="icon-button" type="button" disabled={!desktop || download?.active} aria-label={`Download LoRA ${lora.name}`} data-tooltip="Download" onClick={() => void downloadLora(lora.id)}><Download16 /></button>
+ ? <button className="icon-button" type="button" disabled={!desktop || active || queued} aria-label={`Download LoRA ${lora.name}`} data-tooltip="Download" onClick={() => void downloadLora(lora.id)}><Download16 /></button>
: <button className="icon-button" type="button" disabled={Boolean(download?.active)} aria-label={`Remove LoRA ${lora.name}`} data-tooltip="Remove" onClick={() => void removeLora(lora.id).catch((reason) => setError(String(reason)))}><Delete16 /></button>}
</>} />;
})}
diff --git a/src/components/OtherWeightsSettings.tsx b/src/components/OtherWeightsSettings.tsx
index 0b9e096..572f0b1 100644
--- a/src/components/OtherWeightsSettings.tsx
+++ b/src/components/OtherWeightsSettings.tsx
@@ -1,5 +1,6 @@
-import { useEffect, useState } from "react";
-import { OTHER_WEIGHT_TEMPLATES, cancelOtherDownload, downloadOtherWeights, otherDownloadState, otherWeightPaths, refreshOtherWeights, subscribeOtherWeights } from "../lib/upscalers";
+import { useEffect, useState, useSyncExternalStore } from "react";
+import { OTHER_WEIGHT_TEMPLATES, otherWeightPaths, refreshOtherWeights, subscribeOtherWeights } from "../lib/upscalers";
+import { cancelQueuedWeightDownload, cancelWeightDownload, downloadOtherWeights, getQueuedWeightDownloads, getWeightDownloadState, subscribeWeightDownloads, weightDownloadProgress } from "../lib/weightDownloads";
import { InfoBar, ProgressBar, SettingsCard, SettingsGroup } from "./ui";
import { Image20 } from "./ui/icons";
@@ -9,19 +10,22 @@ export function OtherWeightsSettings({ desktop }: { desktop: boolean }) {
useEffect(() => subscribeOtherWeights(() => refresh((value) => value + 1)), []);
useEffect(() => { void refreshOtherWeights().catch((reason) => setError(String(reason))); }, []);
const paths = otherWeightPaths();
- const download = otherDownloadState();
+ const download = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);
+ const queued = useSyncExternalStore(subscribeWeightDownloads, getQueuedWeightDownloads);
return <SettingsGroup heading="Other weights">
{OTHER_WEIGHT_TEMPLATES.map((template) => {
const ready = template.files.every((file) => paths[file.url]);
- const active = download?.active && download.templateId === template.id;
+ const active = download?.active && download.otherWeightId === template.id;
+ const waiting = queued.find((item) => item.otherWeightId === template.id);
return <SettingsCard key={template.id} icon={<Image20 />} header={template.name}
- description={active ? `Downloading ${download.file}` : ready ? "Ready for image and video export" : template.files.map((file) => file.name).join(" · ")}>
- {active ? <><ProgressBar value={download.progress} aria-label={`Downloading ${template.name} weights`} />
- <button type="button" onClick={() => void cancelOtherDownload().catch((reason) => setError(String(reason)))}>Cancel</button></>
- : <button type="button" className="secondary-button" disabled={!desktop || ready || download?.active}
+ description={waiting ? "Queued for download" : active ? `Downloading ${download.currentFile ?? template.name}` : ready ? "Ready for image and video export" : template.files.map((file) => file.name).join(" · ")}>
+ {waiting ? <button type="button" onClick={() => cancelQueuedWeightDownload(waiting.templateId)}>Cancel</button>
+ : active ? <><ProgressBar value={weightDownloadProgress(download)} aria-label={`Downloading ${template.name} weights`} />
+ <button type="button" onClick={() => void cancelWeightDownload().catch((reason) => setError(String(reason)))}>Cancel</button></>
+ : <button type="button" className="secondary-button" disabled={!desktop || ready}
onClick={() => void downloadOtherWeights(template.id)}>{ready ? "Downloaded" : "Download"}</button>}
</SettingsCard>;
})}
- {(error || download?.error) && <InfoBar severity="error" title="Couldn’t download weights" message={error ?? download!.error!} />}
+ {(error || (download?.otherWeightId && download.error)) && <InfoBar severity="error" title="Couldn’t download weights" message={error ?? download!.error!} />}
</SettingsGroup>;
}
diff --git a/src/components/SettingsView.downloads.test.tsx b/src/components/SettingsView.downloads.test.tsx
index b199ace..ce087fc 100644
--- a/src/components/SettingsView.downloads.test.tsx
+++ b/src/components/SettingsView.downloads.test.tsx
@@ -232,7 +232,7 @@ it("keeps a LoRA download alive outside Settings, shows progress and cancels thr
const settings = render(<SettingsView onClose={() => undefined} />);
fireEvent.click(screen.getByRole("button", { name: "Download LoRA TaoMate 3-Step" }));
await waitFor(() => expect(requestId).not.toBe(""));
- expect(screen.getByRole("button", { name: "Download generator First/Last Frame" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Download generator First/Last Frame" })).toBeEnabled();
settings.unmount();
render(<WorkQueuePanel queue={new WorkQueue()} items={[]} onClose={() => undefined} />);
act(() => progress({ payload: { requestId, downloaded: 50, total: 100 } }));
@@ -290,6 +290,45 @@ it("keeps downloading with Settings closed and restores progress in the template
expect(screen.getByRole("region", { name: "Weight downloads" })).toHaveTextContent("Download complete");
});
+it("queues Other weights from Settings and follows their progress after Settings closes", async () => {
+ let progress: (event: { payload: { requestId: string; downloaded: number; total: number | null } }) => void = () => undefined;
+ vi.mocked(listen).mockImplementation((async (_name, callback) => { progress = callback as typeof progress; return () => undefined; }) as typeof listen);
+ const original = vi.mocked(invoke).getMockImplementation()!;
+ const pending: { requestId: string; finish: () => void }[] = [];
+ vi.mocked(invoke).mockImplementation(async (command, args) => {
+ if (command !== "download_weight") return original(command, args);
+ const request = args as { requestId: string; url: string };
+ return new Promise<string>((resolve) => pending.push({ requestId: request.requestId, finish: () => resolve(`C:/weights/${request.url.split('/').at(-1)}`) }));
+ });
+ const settings = render(<SettingsView onClose={() => undefined} />);
+ const otherCard = (name: string) => within(screen.getByText(name).closest(".ui-settings-card") as HTMLElement);
+ fireEvent.click(otherCard("Real-ESRGAN").getByRole("button", { name: "Download" }));
+ await waitFor(() => expect(pending).toHaveLength(1));
+ fireEvent.click(otherCard("SeedVR2").getByRole("button", { name: "Download" }));
+ expect(otherCard("SeedVR2").getByText("Queued for download")).toBeInTheDocument();
+ fireEvent.click(otherCard("SeedVR2").getByRole("button", { name: "Cancel" }));
+ fireEvent.click(otherCard("SeedVR2").getByRole("button", { name: "Download" }));
+ settings.unmount();
+ const navigate = vi.fn();
+ render(<WorkQueuePanel queue={new WorkQueue()} items={[]} onClose={() => undefined} onNavigate={navigate} />);
+ expect(within(screen.getByRole("region", { name: "Upcoming work" })).getByText("SeedVR2")).toBeInTheDocument();
+ act(() => progress({ payload: { requestId: pending[0].requestId, downloaded: 50, total: 100 } }));
+ expect(screen.getByRole("progressbar", { name: "Real-ESRGAN download progress" })).toHaveAttribute("aria-valuenow", "50");
+ await act(async () => pending[0].finish());
+ await waitFor(() => expect(pending).toHaveLength(2));
+ expect(screen.queryByRole("region", { name: "Upcoming work" })).toBeNull();
+ act(() => progress({ payload: { requestId: pending[1].requestId, downloaded: 50, total: 100 } }));
+ expect(screen.getByRole("progressbar", { name: "SeedVR2 download progress" })).toHaveAttribute("aria-valuenow", "25");
+ await act(async () => pending[1].finish());
+ await waitFor(() => expect(pending).toHaveLength(3));
+ act(() => progress({ payload: { requestId: pending[2].requestId, downloaded: 50, total: 100 } }));
+ expect(screen.getByRole("progressbar", { name: "SeedVR2 download progress" })).toHaveAttribute("aria-valuenow", "75");
+ await act(async () => pending[2].finish());
+ await waitFor(() => expect(screen.getByText(/Download complete/)).toBeInTheDocument());
+ fireEvent.click(screen.getByRole("button", { name: "Open SeedVR2 download" }));
+ expect(navigate).toHaveBeenCalledWith({ kind: "download", download: expect.objectContaining({ otherWeightId: "seedvr2", completed: 2, active: false }) });
+});
+
it("downloads the sample, enables its default choice, and removes only weights to restore the download action", async () => {
render(<SettingsView onClose={() => undefined} />);
const makeDefault = () => screen.getByRole("button", { name: "Set First/Last Frame as default" });
diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsx
index 9565df5..953e121 100644
--- a/src/components/SettingsView.tsx
+++ b/src/components/SettingsView.tsx
@@ -17,7 +17,7 @@ import { OpenableCard } from "./OpenableCard";
import { TitleBar } from "./TitleBar";
import { downloadableTemplateLoras, loadLoras } from "../lib/loras";
import { retryWeightDownload } from "../lib/weightDownloads";
-import { cancelWeightDownload, downloadTemplateWeights, getWeightDownloadState, refreshDownloadedWeights, removeTemplateWeights, subscribeWeightDownloads, updateWeightPath, weightDownloadProgress, type DownloadState } from "../lib/weightDownloads";
+import { getQueuedWeightDownloads, cancelWeightDownload, downloadTemplateWeights, getWeightDownloadState, refreshDownloadedWeights, removeTemplateWeights, subscribeWeightDownloads, updateWeightPath, weightDownloadProgress, type DownloadState } from "../lib/weightDownloads";
import { chooseEnginePath, getAgentModels, getEngineStatus, type ModelStatus, type SlopfabStatus } from "../lib/runtime";
import {
EMPTY_ENGINE_SETTINGS, generatorPathFields,
@@ -296,6 +296,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine", titleBar
useEffect(() => { page.current?.focus(); }, []);
const [templateSettings, setTemplateSettings] = useState<GeneratorTemplateSettings>(() => loadGeneratorTemplateSettings());
const downloadState = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);
+ const queuedDownloads = useSyncExternalStore(subscribeWeightDownloads, getQueuedWeightDownloads);
const downloadPercent = downloadState ? weightDownloadProgress(downloadState) : 0;
const [editingTemplateId, setEditingTemplateId] = useState<string | null>(null);
const [editingLoraId, setEditingLoraId] = useState<string | null>(null);
@@ -529,7 +530,7 @@ export function SettingsView({ onClose, updates, initialTab = "engine", titleBar
const generatorEditor = editingTemplate && <>
<GeneratorSharing key={`sharing:${selectedTemplate.id}`} templates={[selectedTemplate]}>{({ exportButton }) => <div className="settings-page__actions">
- {templateNeedsDownload(selectedTemplate) && <button type="button" className="primary-button" disabled={!desktop || downloadState?.active} onClick={() => void downloadTemplateWeights(selectedTemplate.id)}><Download16 /> Download weights</button>}
+ {templateNeedsDownload(selectedTemplate) && <button type="button" className="primary-button" disabled={!desktop || downloading || queuedDownloads.some((item) => item.templateId === selectedTemplate.id)} onClick={() => void downloadTemplateWeights(selectedTemplate.id)}><Download16 /> {queuedDownloads.some((item) => item.templateId === selectedTemplate.id) ? "Queued for download" : "Download weights"}</button>}
<button type="button" className="secondary-button" disabled={Boolean(downloading)} onClick={clearAll}><Reset16 /> Clear generator paths</button>
<div className="settings-page__actions-end">{exportButton}</div>
</div>}</GeneratorSharing>
@@ -598,14 +599,15 @@ export function SettingsView({ onClose, updates, initialTab = "engine", titleBar
const needsDownload = templateNeedsDownload(template);
const isDefault = template.id === templateSettings.defaultTemplateId;
const active = downloadState?.active && downloadState.templateId === template.id;
+ const queued = queuedDownloads.some((item) => item.templateId === template.id);
const weights = hasDownloadedWeights(template);
return <OpenableCard key={template.id} icon={<Video20 />} header={template.name} openRef={`template:${template.id}`}
openLabel={`Edit ${template.name} generator`} onOpen={() => openTemplate(template.id)}
- description={active ? downloadState?.phase === "preparing" ? "Preparing LoRA…" : `Downloading · ${Math.floor(downloadPercent)}%`
+ description={queued ? "Queued for download" : active ? downloadState?.phase === "preparing" ? "Preparing LoRA…" : `Downloading · ${Math.floor(downloadPercent)}%`
: `${!needsDownload && isDefault ? "Used by default · " : ""}${templateSummary(template)}`}
progress={active && downloadState?.phase !== "preparing" && <ProgressBar className="settings-progress" value={downloadPercent} aria-label={`Downloading ${template.name} weights`} />}
actions={needsDownload
- ? <button type="button" className="icon-button" disabled={!desktop || downloadState?.active} onClick={() => void downloadTemplateWeights(template.id)} aria-label={`Download generator ${template.name}`} data-tooltip={`Download ${template.name} weights`}>
+ ? <button type="button" className="icon-button" disabled={!desktop || active || queued} onClick={() => void downloadTemplateWeights(template.id)} aria-label={`Download generator ${template.name}`} data-tooltip={`Download ${template.name} weights`}>
{active ? <Spinner16 className="spin" /> : <Download16 />}
</button>
: <>
diff --git a/src/components/WorkQueuePanel.tsx b/src/components/WorkQueuePanel.tsx
index 5561c8b..6e50976 100644
--- a/src/components/WorkQueuePanel.tsx
+++ b/src/components/WorkQueuePanel.tsx
@@ -4,7 +4,7 @@ import { GENERATION_FRAME_RATE } from "../lib/project";
import { isWorkActive, type WorkItem, type WorkQueue } from "../lib/workQueue";
import { loadGeneratorTemplateSettings } from "../lib/settings";
import { cancelExportJob, exportFraction, useExportJob } from "../lib/exportJob";
-import { cancelWeightDownload, retryWeightDownload, getWeightDownloadState, subscribeWeightDownloads, weightDownloadProgress, type DownloadState } from "../lib/weightDownloads";
+import { cancelQueuedWeightDownload, getQueuedWeightDownloads, cancelWeightDownload, retryWeightDownload, getWeightDownloadState, subscribeWeightDownloads, weightDownloadProgress, type DownloadState } from "../lib/weightDownloads";
import { Flyout, ProgressBar, ProgressRing } from "./ui";
/* The work queue, as a flyout hanging from its title-bar button: no scrim, no
@@ -40,6 +40,7 @@ export function WorkQueuePanel({ queue, items, open = true, anchor = null, onClo
}) {
// Downloads are observed here, never enqueued in the GPU generation scheduler.
const download = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);
+ const queuedDownloads = useSyncExternalStore(subscribeWeightDownloads, getQueuedWeightDownloads);
const [downloadError, setDownloadError] = useState<string | null>(null);
const downloadName = download ? download.name ?? loadGeneratorTemplateSettings().templates.find((template) => template.id === download.templateId)?.name ?? "Generator weights" : "";
/* A running export lives in lib/exportJob.ts, not in the generation queue;
@@ -78,7 +79,7 @@ export function WorkQueuePanel({ queue, items, open = true, anchor = null, onClo
{finished.length > 0 && <button type="button" className="work-queue__link" onClick={() => queue.clearFinished()}>Clear finished</button>}
</header>
<div className="work-queue__list">
- {items.length === 0 && !download && !exporting && <div className="work-queue__empty"><WorkQueue32 aria-hidden="true" /><strong>No work yet</strong><span>Generated scenes and images show up here.</span></div>}
+ {items.length === 0 && !download && !queuedDownloads.length && !exporting && <div className="work-queue__empty"><WorkQueue32 aria-hidden="true" /><strong>No work yet</strong><span>Generated scenes and images show up here.</span></div>}
{current.length > 0 && <section aria-label="In progress"><ul>{current.map(row)}</ul></section>}
{exporting && <section aria-label="Export"><ul><li className={`work-queue__row${onNavigate && exportJob.folderPath ? " work-queue__row--navigable" : ""}`}>
{onNavigate && exportJob.folderPath && <button type="button" className="work-queue__open" aria-label={`Open ${exportTitle}`} onClick={() => openTarget({ kind: "export", folderPath: exportJob.folderPath! })} />}
@@ -99,20 +100,28 @@ export function WorkQueuePanel({ queue, items, open = true, anchor = null, onClo
<span className="work-queue__title">{downloadName}</span>
<span className="work-queue__caption">
{download.loraId ? "LoRA download" : "Weight download"} · {download.active
- ? `${download.completed}/${download.files} files · ${(download.downloaded / 1024 ** 3).toFixed(2)} GB${download.total ? ` of ${(download.total / 1024 ** 3).toFixed(2)} GB` : ""} · ${Math.floor(weightDownloadProgress(download))}%`
+ ? download.phase === "preparing" ? "Preparing LoRA…" : `${download.currentFile ? `${download.currentFile} · ` : ""}${download.completed}/${download.files} files · ${(download.downloaded / 1024 ** 3).toFixed(2)} GB${download.total ? ` of ${(download.total / 1024 ** 3).toFixed(2)} GB` : ""} · ${Math.floor(weightDownloadProgress(download))}%`
: download.error ? "Failed" : "Download complete"}
</span>
- {download.active && <ProgressBar value={weightDownloadProgress(download)} aria-label={`${downloadName} download progress`} className="work-queue__progress" />}
+ {download.active && <ProgressBar value={download.phase === "preparing" ? undefined : weightDownloadProgress(download)} aria-label={`${downloadName} download progress`} className="work-queue__progress" />}
{download.error && <span className="work-queue__error">{download.error}</span>}
{download.error && <button type="button" className="work-queue__link" onClick={() => { setDownloadError(null); void retryWeightDownload(); }}>Retry download</button>}
{downloadError && <span className="work-queue__error" role="alert">{downloadError}</span>}
</div>
- {download.active && <button type="button" className="icon-button work-queue__cancel" aria-label={`Cancel ${downloadName} download`} data-tooltip="Cancel" onClick={() => {
+ {download.active && download.phase !== "preparing" && <button type="button" className="icon-button work-queue__cancel" aria-label={`Cancel ${downloadName} download`} data-tooltip="Cancel" onClick={() => {
setDownloadError(null);
void cancelWeightDownload().catch((reason) => setDownloadError(String(reason)));
}}><Dismiss16 /></button>}
</li></ul></section>}
- {upcoming.length > 0 && <section aria-label="Upcoming work"><h3 className="work-queue__group">Up next · {upcoming.length}</h3><ul>{upcoming.map(row)}</ul></section>}
+ {(upcoming.length > 0 || queuedDownloads.length > 0) && <section aria-label="Upcoming work"><h3 className="work-queue__group">Up next · {upcoming.length + queuedDownloads.length}</h3><ul>
+ {queuedDownloads.map((waiting) => <li key={waiting.templateId} className={`work-queue__row${onNavigate ? " work-queue__row--navigable" : ""}`}>
+ {onNavigate && <button type="button" className="work-queue__open" aria-label={`Open ${waiting.name} download`} onClick={() => openTarget({ kind: "download", download: waiting })} />}
+ <span className="work-queue__state work-queue__state--queued" aria-hidden="true"><Clock16 /></span>
+ <div className="work-queue__text"><span className="work-queue__title">{waiting.name ?? "Weights"}</span><span className="work-queue__caption">Queued for download</span></div>
+ <button type="button" className="icon-button work-queue__cancel" aria-label={`Cancel ${waiting.name} download`} data-tooltip="Cancel" onClick={() => cancelQueuedWeightDownload(waiting.templateId)}><Dismiss16 /></button>
+ </li>)}
+ {upcoming.map(row)}
+ </ul></section>}
{finished.length > 0 && <section aria-label="Finished work"><h3 className="work-queue__group">Finished</h3><ul>{finished.map(row)}</ul></section>}
</div>
</Flyout>
diff --git a/src/lib/upscalers.ts b/src/lib/upscalers.ts
index acc7135..465e372 100644
--- a/src/lib/upscalers.ts
+++ b/src/lib/upscalers.ts
@@ -1,5 +1,4 @@
import { invoke } from "@tauri-apps/api/core";
-import { listen } from "@tauri-apps/api/event";
import { isTauri } from "./persistence";
export type Upscaler = "none" | "realesrgan" | "seedvr2";
@@ -29,6 +28,7 @@ const savePaths = (paths: Record<string, string>) => {
localStorage.setItem(KEY, JSON.stringify(paths));
window.dispatchEvent(new Event(EVENT));
};
+export const saveOtherWeightPath = (url: string, path: string) => savePaths({ ...otherWeightPaths(), [url]: path });
export function subscribeOtherWeights(listener: () => void) {
window.addEventListener(EVENT, listener);
window.addEventListener("storage", listener);
@@ -48,40 +48,3 @@ export async function refreshOtherWeights() {
const found = await invoke<Record<string, string>>("find_downloaded_weights", { urls });
if (found) savePaths(found);
}
-export interface OtherDownload { templateId: string; file: string; progress: number; requestId: string; error?: string; active: boolean }
-let download: OtherDownload | null = null;
-let downloadCancelled = false;
-export const otherDownloadState = () => download;
-const publish = (value: OtherDownload) => { download = value; window.dispatchEvent(new Event(EVENT)); };
-export async function downloadOtherWeights(id: string) {
- if (!isTauri() || download?.active) return;
- const template = OTHER_WEIGHT_TEMPLATES.find((item) => item.id === id);
- if (!template) return;
- const requestId = crypto.randomUUID();
- downloadCancelled = false;
- publish({ templateId: id, file: "", progress: 0, requestId, active: true });
- let unlisten: (() => void) | undefined;
- try {
- let completed = 0;
- unlisten = await listen<{ requestId: string; downloaded: number; total: number | null }>("weight-download-progress", ({ payload }) => {
- if (payload.requestId === requestId && download?.active) publish({ ...download,
- progress: (completed + (payload.total ? payload.downloaded / payload.total : 0)) / template.files.length * 100 });
- });
- for (const file of template.files) {
- if (downloadCancelled) throw new Error("Download cancelled.");
- publish({ ...download!, file: file.name });
- const path = await invoke<string>("download_weight", { requestId, url: file.url });
- if (!path || /^https?:/i.test(path)) throw new Error("The download did not return a local file.");
- savePaths({ ...otherWeightPaths(), [file.url]: path });
- completed++;
- }
- publish({ ...download!, progress: 100, active: false });
- } catch (reason) { publish({ ...download!, active: false, error: String(reason) }); }
- finally { unlisten?.(); }
-}
-export async function cancelOtherDownload() {
- if (!download?.active) return;
- const requestId = download.requestId;
- downloadCancelled = true;
- await invoke("cancel_weight_download", { requestId });
-}
diff --git a/src/lib/weightDownloadQueue.test.ts b/src/lib/weightDownloadQueue.test.ts
new file mode 100644
index 0000000..59181d0
--- /dev/null
+++ b/src/lib/weightDownloadQueue.test.ts
@@ -0,0 +1,106 @@
+// @vitest-environment jsdom
+import { invoke } from "@tauri-apps/api/core";
+import { listen } from "@tauri-apps/api/event";
+import { beforeEach, expect, it, vi } from "vitest";
+
+vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));
+vi.mock("./persistence", () => ({ isTauri: () => true }));
+type Progress = { requestId: string; downloaded: number; total: number | null };
+let progress: (event: { payload: Progress }) => void;
+let transfers: { requestId: string; url: string; resolve: (path: string) => void; reject: (error: Error) => void }[];
+const unlisten = vi.fn();
+beforeEach(() => {
+ vi.resetModules(); vi.clearAllMocks(); localStorage.clear(); transfers = [];
+ vi.mocked(listen).mockImplementation((async (_name, callback) => { progress = callback as typeof progress; return unlisten; }) as typeof listen);
+ vi.mocked(invoke).mockImplementation(async (command, args) => {
+ if (command === "find_downloaded_weights") return {};
+ if (command === "weight_download_hardware") return [];
+ if (command === "download_weight") return new Promise<string>((resolve, reject) => transfers.push({ ...args as { requestId: string; url: string }, resolve, reject }));
+ if (command === "cancel_weight_download") transfers.find((transfer) => transfer.requestId === (args as { requestId: string }).requestId)?.reject(new Error("Download cancelled."));
+ });
+});
+
+it("serializes generator, upscaler and LoRA downloads and reports both SeedVR2 files", async () => {
+ const queue = await import("./weightDownloads");
+ const settings = await import("./settings");
+ const loras = await import("./loras");
+ const { OTHER_WEIGHT_TEMPLATES, upscaleConfig } = await import("./upscalers");
+ const template = settings.createGeneratorTemplate("Extra");
+ template.additionalSafetensors = [{ id: "extra", name: "Extra", url: "https://example.com/extra.safetensors" }];
+ settings.saveGeneratorTemplateSettings({ templates: [template], defaultTemplateId: template.id });
+ loras.saveLoras([{ id: "adapter", name: "Adapter", path: "", url: "https://example.com/adapter.safetensors" }]);
+ const generator = queue.downloadTemplateWeights(template.id);
+ const esrgan = queue.downloadOtherWeights("realesrgan");
+ const seed = queue.downloadOtherWeights("seedvr2");
+ const lora = queue.downloadLora("adapter");
+ expect(queue.downloadOtherWeights("seedvr2")).toBe(seed);
+ expect(queue.getQueuedWeightDownloads().map((job) => job.name)).toEqual(["Real-ESRGAN", "SeedVR2", "Adapter"]);
+ await vi.waitFor(() => expect(transfers).toHaveLength(1));
+ transfers[0].resolve("C:/extra.safetensors");
+ await generator;
+ await vi.waitFor(() => expect(transfers).toHaveLength(2));
+ expect(unlisten).toHaveBeenCalledTimes(1);
+ expect(transfers[1].url).toBe(OTHER_WEIGHT_TEMPLATES[0].files[0].url);
+ progress({ payload: { requestId: transfers[1].requestId, downloaded: 50, total: 100 } });
+ expect(queue.weightDownloadProgress(queue.getWeightDownloadState()!)).toBe(50);
+ transfers[1].resolve("C:/esrgan.safetensors");
+ await esrgan;
+ await vi.waitFor(() => expect(transfers).toHaveLength(3));
+ progress({ payload: { requestId: transfers[1].requestId, downloaded: 100, total: 100 } });
+ expect(queue.getWeightDownloadState()?.downloaded).toBe(0); // Ignore the previous job's late events.
+ progress({ payload: { requestId: transfers[2].requestId, downloaded: 50, total: 100 } });
+ expect(queue.weightDownloadProgress(queue.getWeightDownloadState()!)).toBe(25);
+ transfers[2].resolve("C:/seed.safetensors");
+ await vi.waitFor(() => expect(transfers).toHaveLength(4));
+ expect(transfers[3].url).toBe(OTHER_WEIGHT_TEMPLATES[1].files[1].url);
+ expect(queue.weightDownloadProgress(queue.getWeightDownloadState()!)).toBe(50);
+ progress({ payload: { requestId: transfers[3].requestId, downloaded: 50, total: 100 } });
+ expect(queue.weightDownloadProgress(queue.getWeightDownloadState()!)).toBe(75);
+ transfers[3].resolve("C:/vae.safetensors");
+ await seed;
+ expect(upscaleConfig("seedvr2")).toEqual({ method: "seedvr2", modelPath: "C:/seed.safetensors", vaePath: "C:/vae.safetensors" });
+ await vi.waitFor(() => expect(transfers).toHaveLength(5));
+ transfers[4].resolve("C:/adapter.safetensors");
+ await lora;
+ expect(invoke).toHaveBeenCalledWith("prepare_lora", { path: "C:/adapter.safetensors", allowDownload: true });
+ expect(queue.getQueuedWeightDownloads()).toEqual([]);
+ expect(queue.getWeightDownloadState()).toMatchObject({ active: false, error: null });
+});
+
+it("cancels queued downloads without touching the active transfer, then advances after cancellation", async () => {
+ const queue = await import("./weightDownloads");
+ const first = queue.downloadOtherWeights("realesrgan");
+ const removed = queue.downloadOtherWeights("seedvr2");
+ queue.cancelQueuedWeightDownload("other:seedvr2");
+ await removed;
+ expect(invoke).not.toHaveBeenCalledWith("cancel_weight_download", expect.anything());
+ const second = queue.downloadOtherWeights("seedvr2");
+ await vi.waitFor(() => expect(transfers).toHaveLength(1));
+ await queue.cancelWeightDownload(); await first;
+ await vi.waitFor(() => expect(transfers).toHaveLength(2));
+ expect(queue.getWeightDownloadState()).toMatchObject({ otherWeightId: "seedvr2", active: true });
+ transfers[1].resolve("C:/seed.safetensors");
+ await vi.waitFor(() => expect(transfers).toHaveLength(3));
+ transfers[2].resolve("C:/vae.safetensors");
+ await second;
+ expect(queue.getWeightDownloadState()).toMatchObject({ active: false, completed: 2, error: null });
+});
+
+it("retries a failed upscaler through the shared pipeline and reuses its completed file", async () => {
+ const queue = await import("./weightDownloads");
+ const { OTHER_WEIGHT_TEMPLATES } = await import("./upscalers");
+ const first = queue.downloadOtherWeights("seedvr2");
+ await vi.waitFor(() => expect(transfers).toHaveLength(1));
+ transfers[0].resolve("C:/seed.safetensors");
+ await vi.waitFor(() => expect(transfers).toHaveLength(2));
+ transfers[1].reject(new Error("Connection lost"));
+ await first;
+ expect(queue.getWeightDownloadState()).toMatchObject({ active: false, completed: 1, error: "Connection lost" });
+ vi.mocked(invoke).mockImplementationOnce(async () => ({ [OTHER_WEIGHT_TEMPLATES[1].files[0].url]: "C:/seed.safetensors" }));
+ const retry = queue.retryWeightDownload();
+ await vi.waitFor(() => expect(transfers).toHaveLength(3));
+ expect(transfers[2].url).toBe(OTHER_WEIGHT_TEMPLATES[1].files[1].url);
+ transfers[2].resolve("C:/vae.safetensors"); await retry;
+ expect(queue.getWeightDownloadState()).toMatchObject({ active: false, completed: 2, error: null });
+});
diff --git a/src/lib/weightDownloads.ts b/src/lib/weightDownloads.ts
index 6ca829d..15307f9 100644
--- a/src/lib/weightDownloads.ts
+++ b/src/lib/weightDownloads.ts
@@ -1,6 +1,7 @@
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { isTauri } from "./persistence";
+import { OTHER_WEIGHT_TEMPLATES, refreshOtherWeights, otherWeightPaths, saveOtherWeightPath } from "./upscalers";
import { downloadableTemplateLoras, loadLoras, saveLoras, type Lora } from "./loras";
import { chooseWeightSource, ENGINE_PATH_FIELDS, generatorPathFields, isDownloadUrl, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, templateNeedsDownload,
type EnginePathId, type GeneratorTemplate, type WeightGpu, type WeightSource } from "./settings";
@@ -9,6 +10,8 @@ export type { WeightGpu } from "./settings";
export { chooseWeightSource };
export interface DownloadState {
templateId: string;
+ otherWeightId?: string;
+ currentFile?: string;
loraId?: string;
currentLoraId?: string;
currentAdditionalId?: string;
@@ -34,6 +37,41 @@ 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()); };
+interface QueuedDownload { state: DownloadState; run: () => Promise<void>; done: Promise<void>; resolve: () => void; reject: (reason: unknown) => void }
+let pending: QueuedDownload[] = [];
+let running: QueuedDownload | null = null;
+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> {
+ const existing = [running, ...pending].find((job) => job?.state.templateId === initial.templateId);
+ if (existing) return existing.done;
+ let resolve!: () => void, reject!: (reason: unknown) => void;
+ const done = new Promise<void>((yes, no) => { resolve = yes; reject = no; });
+ pending.push({ state: { ...initial, field: null, downloaded: 0, total: null, completed: 0, files: 0, error: null, active: false }, run, done, resolve, reject });
+ pumpDownloads();
+ publishQueue();
+ return done;
+}
+
+function pumpDownloads() {
+ if (running || !pending.length) return;
+ const job = pending.shift()!;
+ running = job;
+ cancelled = false;
+ const finish = () => { running = null; pumpDownloads(); publishQueue(); };
+ // Wait for the transfer and event-listener cleanup before starting the next job.
+ void job.run().then(() => { finish(); job.resolve(); }, (reason) => { finish(); job.reject(reason); });
+}
+
+export function cancelQueuedWeightDownload(templateId: string) {
+ const job = pending.find((entry) => entry.state.templateId === templateId);
+ pending = pending.filter((entry) => entry !== job);
+ job?.resolve();
+ publishQueue();
+}
+
export function weightDownloadProgress(download: DownloadState): number {
if (!download.files) return 0;
const current = (download.field || download.loraId || download.currentLoraId || download.currentAdditionalId) && download.total && download.total > 0
@@ -113,8 +151,12 @@ export function refreshDownloadedWeights(): Promise<void> {
return refreshPending;
}
-export async function downloadTemplateWeights(templateId: string): Promise<void> {
- if (!isTauri() || state?.active) return;
+export function downloadTemplateWeights(templateId: string): Promise<void> {
+ if (!isTauri()) return Promise.resolve();
+ return enqueueDownload({ templateId, name: loadGeneratorTemplateSettings().templates.find((template) => template.id === templateId)?.name }, () => runTemplateDownload(templateId));
+}
+
+async function runTemplateDownload(templateId: string): Promise<void> {
cancelled = false;
publish({ templateId, field: null, downloaded: 0, total: null, completed: 0, files: 0, error: null, active: true });
let unlisten: (() => void) | undefined;
@@ -210,9 +252,12 @@ async function prepareLoraFile(path: string, allowDownload: boolean): Promise<vo
}
/** Explicit setup for a local or previously downloaded adapter. */
-export async function prepareLora(lora: Pick<Lora, "id" | "name" | "path">, allowDownload = true): Promise<void> {
- if (!isTauri()) throw new Error("LoRA preparation is available in the desktop app.");
- if (state?.active) throw new Error("Wait for the current download or preparation to finish.");
+export function prepareLora(lora: Pick<Lora, "id" | "name" | "path">, allowDownload = true): Promise<void> {
+ if (!isTauri()) return Promise.reject(new Error("LoRA preparation is available in the desktop app."));
+ return enqueueDownload({ templateId: `lora:${lora.id}`, loraId: lora.id, name: lora.name }, () => runLoraPreparation(lora, allowDownload));
+}
+
+async function runLoraPreparation(lora: Pick<Lora, "id" | "name" | "path">, allowDownload: boolean): Promise<void> {
publish({ templateId: `lora:${lora.id}`, loraId: lora.id, name: lora.name, field: null,
downloaded: 0, total: null, completed: 0, files: 1, error: null, active: true,
preparePath: lora.path, allowDownload, phase: "preparing" });
@@ -228,8 +273,12 @@ export async function prepareLora(lora: Pick<Lora, "id" | "name" | "path">, allo
}
/** Uses the same native transfer, storage, cancellation and app-wide lock as weights. */
-export async function downloadLora(loraId: string): Promise<void> {
- if (!isTauri() || state?.active) return;
+export function downloadLora(loraId: string): Promise<void> {
+ if (!isTauri()) return Promise.resolve();
+ return enqueueDownload({ templateId: `lora:${loraId}`, loraId, name: loadLoras().find((lora) => lora.id === loraId)?.name }, () => runLoraDownload(loraId));
+}
+
+async function runLoraDownload(loraId: string): Promise<void> {
const lora = loadLoras().find(({ id }) => id === loraId);
if (!lora?.url) return;
cancelled = false;
@@ -249,11 +298,41 @@ export async function downloadLora(loraId: string): Promise<void> {
}
export function retryWeightDownload(): Promise<void> {
+ 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.
return state?.loraId ? downloadLora(state.loraId) : state ? downloadTemplateWeights(state.templateId) : Promise.resolve();
}
+export function downloadOtherWeights(id: string): Promise<void> {
+ const template = OTHER_WEIGHT_TEMPLATES.find((item) => item.id === id);
+ if (!isTauri() || !template) return Promise.resolve();
+ return enqueueDownload({ templateId: `other:${id}`, otherWeightId: id, name: template.name }, async () => {
+ publish({ templateId: `other:${id}`, otherWeightId: id, name: template.name, field: null,
+ downloaded: 0, total: null, completed: 0, files: template.files.length, error: null, active: true });
+ let unlisten: (() => void) | undefined;
+ try {
+ await refreshOtherWeights();
+ 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 file of template.files) {
+ if (cancelled) throw new Error("Download cancelled.");
+ requestId = crypto.randomUUID();
+ publish({ ...state!, currentAdditionalId: file.id, currentFile: file.name, downloaded: 0, total: null });
+ const path = otherWeightPaths()[file.url] ?? await invoke<string>("download_weight", { requestId, url: file.url });
+ if (!path || isDownloadUrl(path)) throw new Error("The download did not return a local file.");
+ saveOtherWeightPath(file.url, path);
+ if (cancelled) throw new Error("Download cancelled.");
+ publish({ ...state!, completed: state!.completed + 1, currentAdditionalId: undefined, currentFile: undefined, downloaded: 0, total: null });
+ }
+ publish({ ...state!, active: false });
+ } catch (reason) {
+ publish({ ...state!, active: false, error: reason instanceof Error ? reason.message : String(reason) });
+ } finally { requestId = null; unlisten?.(); }
+ });
+}
+
let loraRefreshPending: Promise<void> | null = null;
export function refreshDownloadedLoras(): Promise<void> {
if (!isTauri()) return Promise.resolve();