AI media harness for planning, generating, and editing locally
TypeScript
Queue image and video exports
Bitti1166ab1e70e3
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.mdindex 151d0ac..0b2fd17 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+- Image and video exports share a work queue with progress, cancellation, and retained results. SeedVR2 upscaling runs on the selected CUDA worker, which prepares its own models.- Upscaler downloads share the generator and LoRA download queue, with progress in Work Queue and cancellation for waiting downloads.- 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.diff --git a/src/App.tsx b/src/App.tsxindex e7ac5fd..b0ccb93 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -20,7 +20,7 @@ import { CommandBar, CommandBarButton, EmptyState, InfoBadge, InfoBar, TextFieldimport { AppUpdater } from "./lib/updater";import { useShortcut } from "./lib/commands";import { APP_CHANNEL, APP_VERSION } from "./lib/version";-import { useRunningExportName } from "./lib/exportJob";+import { isExportActive, useExportActivity } from "./lib/exportJob";import { reportGenerationJobs, revealInExplorer, type GuardJob } from "./lib/nativeShell";import { describeDiagnosticError, errorContext, writeDiagnostic } from "./lib/diagnostics";import { chooseAndOpenProject, chooseNewProjectFolder, inspectNewProjectFolder, createProject, deleteProject, isTauri, listRecentProjects, saveProject, type NewProjectFolder } from "./lib/persistence";@@ -149,8 +149,8 @@ function App() {.map((item) => ({ title: `${item.title} · ${item.projectName}`, running: item.status !== "queued" }));/* An export keeps running when its tab (or its project) is left, andclosing the window ends it just the same, so it is on the list too. */- const exportingName = useRunningExportName();- if (exportingName !== null) guardJobs.push({ title: exportingName ? `Export ${exportingName}` : "Export", running: true });+ const exports = useExportActivity();+ for (const job of exports.filter(isExportActive)) guardJobs.push({ title: `Export ${job.projectName ?? ""}`, running: job.status === "running" });const guardKey = JSON.stringify(guardJobs);useEffect(() => {void reportGenerationJobs(JSON.parse(guardKey) as GuardJob[]).catch(() => undefined);@@ -158,7 +158,7 @@ function App() {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+ const queueBusy = weightDownloadActive || exports.some((job) => job.status === "running")|| workItems.some((item) => isWorkActive(item) && item.status !== "queued");useEffect(() => {@@ -224,7 +224,7 @@ function App() {const record = target.kind === "work" ? workQueue.projectRecord(target.item.projectKey): [activeProject, ...projects].find((record) => record?.folderPath === target.folderPath);if (!record) return;- let navigation: WorkspaceNavigation = { view: "export" };+ let navigation: WorkspaceNavigation = { view: "export", ...(target.kind === "export" ? { exportKind: target.exportKind ?? "video" } : {}) };if (target.kind === "work") {const item = target.item;if (item.kind === "image") {@@ -300,7 +300,7 @@ function App() {setDeletingProject(true);setError(null);try {- if (workQueue.hasActiveProject(target)) throw new Error("Cancel or finish this project’s work before deleting it.");+ if (workQueue.hasActiveProject(target) || exports.some((job) => job.folderPath === target.folderPath && isExportActive(job))) throw new Error("Cancel or finish this project’s work before deleting it.");await deleteProject(target);workQueue.forgetProject(target);setProjects((current) => current.filter((project) => project.config.id !== target.config.id || project.folderPath !== target.folderPath));diff --git a/src/WorkQueue.integration.test.tsx b/src/WorkQueue.integration.test.tsxindex 5dc7d7c..44e3b8c 100644--- a/src/WorkQueue.integration.test.tsx+++ b/src/WorkQueue.integration.test.tsx@@ -190,22 +190,23 @@ it("opens the matching LoRA for a standalone download", async () => {expect(screen.getByRole("textbox", { name: "LoRA name" })).toHaveValue("My adapter");});-it("opens a running export's project and export tab from the library", async () => {+it.each(["video", "image"] as const)("opens a running %s export's project and export tab from the library", async (kind) => {const config = createProjectConfig({ name: "Exported film", prompt: "A forest", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 15 });vi.mocked(listRecentProjects).mockResolvedValue({ projects: [{ folderPath: "C:/Exported film", config }], unreadable: [] });- setExportJobForTests({ folderPath: "C:/Exported film", projectName: config.name, progress: { phase: "rendering", framesDone: 1, frameCount: 10, detail: "Rendering" } });+ setExportJobForTests({ kind, folderPath: "C:/Exported film", projectName: config.name, progress: { phase: "rendering", framesDone: 1, frameCount: 10, detail: "Rendering" } });+ const openLabel = kind === "image" ? "Open Export image · Exported film" : "Open Export Exported film";render(<App />);await screen.findByRole("option", { name: "Exported film" });fireEvent.click(screen.getByRole("button", { name: "Work queue" }));- fireEvent.click(screen.getByRole("button", { name: "Open Export Exported film" }));+ fireEvent.click(screen.getByRole("button", { name: openLabel }));expect(screen.getByRole("tab", { name: "Export" })).toHaveAttribute("aria-selected", "true");expect(document.querySelector(".project-title")?.textContent).toBe("Exported film");expect(getExportJob().progress).not.toBeNull();- fireEvent.click(within(screen.getByRole("tablist", { name: "Export type" })).getByRole("tab", { name: "Image" }));+ fireEvent.click(within(screen.getByRole("tablist", { name: "Export type" })).getByRole("tab", { name: kind === "image" ? "Video" : "Image" }));fireEvent.click(screen.getByRole("button", { name: "Work queue" }));- fireEvent.click(screen.getByRole("button", { name: "Open Export Exported film" }));+ fireEvent.click(screen.getByRole("button", { name: openLabel }));expect(screen.getByRole("tab", { name: "Export" })).toHaveAttribute("aria-selected", "true");- expect(within(screen.getByRole("tablist", { name: "Export type" })).getByRole("tab", { name: "Video" })).toHaveAttribute("aria-selected", "true");+ expect(within(screen.getByRole("tablist", { name: "Export type" })).getByRole("tab", { name: kind === "image" ? "Image" : "Video" })).toHaveAttribute("aria-selected", "true");});it("opens an empty queue from the library and closes it with Escape", async () => {@@ -247,6 +248,6 @@ it("guards the window for a running export and lists it in the queue with a Cancexpect(getExportJob().cancelling).toBe(true);expect(cancel).toBeDisabled();act(() => setExportJobForTests({ progress: null, cancelling: false, outcome: { kind: "cancelled" } }));- expect(within(flyout).queryByRole("region", { name: "Export" })).toBeNull();+ expect(within(flyout).getByRole("region", { name: "Export" })).toHaveTextContent("Cancelled");await waitFor(() => expect(reportGenerationJobs).toHaveBeenLastCalledWith([]));});diff --git a/src/components/ImageProject.integration.test.tsx b/src/components/ImageProject.integration.test.tsxindex 1357f74..56a551e 100644--- a/src/components/ImageProject.integration.test.tsx+++ b/src/components/ImageProject.integration.test.tsx@@ -17,10 +17,11 @@ import fixture from "../../fixtures/project-v1-image.json";import videoFixture from "../../fixtures/project-v1-complete.json";import { invoke } from "@tauri-apps/api/core";import * as persistence from "../lib/persistence";+import { getExportJobs, resetExportJobForTests } from "../lib/exportJob";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));-afterEach(() => { cleanup(); localStorage.clear(); vi.restoreAllMocks(); });+afterEach(() => { cleanup(); resetExportJobForTests(); localStorage.clear(); vi.restoreAllMocks(); });const record = (): ProjectRecord => ({ folderPath: "D:/Images", config: parseProjectConfig(fixture) });it("opens template settings and executes only after configuring prompts and clothing references", () => {@@ -142,6 +143,7 @@ it("exports the selected image from the Export tab and handles cancellation andlet complete!: (value: boolean) => void;const exporting = new Promise<boolean>((resolve) => { complete = resolve; });vi.mocked(invoke).mockImplementation(async (command) => {+ if (command === "choose_image_export_destination") return "D:/out.jpg" as never;if (command === "export_generated_image") return await exporting as never;return undefined as never;});@@ -159,9 +161,11 @@ it("exports the selected image from the Export tab and handles cancellation andconst button = within(settings).getByRole("button", { name: "Export…" });fireEvent.click(button);await waitFor(() => expect(invoke).toHaveBeenCalledWith("export_generated_image", {+ jobId: expect.any(String), destination: "D:/out.jpg",folderPath: "D:/Images", relativePath: "media/generated/Second.jpg", options: { format: "jpg", width: 1024, height: 768, quality: 90 },}));- expect(within(settings).getByRole("button", { name: "Exporting…" })).toBeDisabled();+ expect(within(settings).getByRole("button", { name: "Cancel export" })).toBeEnabled();+ expect(getExportJobs()[0]).toMatchObject({ kind: "image", status: "running" });await act(async () => complete(false));expect(button).toBeEnabled();expect(button).toHaveTextContent("Export…");diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsxindex edaa21d..2f376f9 100644--- a/src/components/ProjectWorkspace.tsx+++ b/src/components/ProjectWorkspace.tsx@@ -24,7 +24,7 @@ import { outputDimensions, videoDurationMs } from "../lib/export";* a project "on the agent" still means something: the pane opens with it. */export type ProjectView = "timeline" | "generator" | "references" | "agent" | "export" | "editor";type ShownView = Exclude<ProjectView, "agent">;-export interface WorkspaceNavigation { view: ShownView; sceneId?: string; imageId?: string; referenceId?: string }+export interface WorkspaceNavigation { view: ShownView; sceneId?: string; imageId?: string; referenceId?: string; exportKind?: "video" | "image" }/** The scene badge includes native generation and the final encoding step. */export const isGenerationOngoing = (job: GenerationJob) =>@@ -163,7 +163,7 @@ export function ProjectWorkspace({ project, initialView, runtime = null, onBack,useEffect(() => {if (!navigation) return;setView(navigation.view);- if (navigation.view === "export") setMediaMode("video");+ if (navigation.view === "export") setMediaMode(navigation.exportKind ?? "video");if (navigation.sceneId) setSelectedGenerationJobId(navigation.sceneId);if (navigation.imageId) setImageNavigation({ id: navigation.imageId });if (navigation.referenceId) setReferenceNavigation({ id: navigation.referenceId });diff --git a/src/components/WorkQueuePanel.tsx b/src/components/WorkQueuePanel.tsxindex 6e50976..0cedca9 100644--- a/src/components/WorkQueuePanel.tsx+++ b/src/components/WorkQueuePanel.tsx@@ -1,9 +1,9 @@-import { Check16, Clock16, Dismiss16, Download16, Film16, Warning16, WorkQueue32 } from "./ui/icons";+import { Check16, Clock16, Dismiss16, Download16, Warning16, WorkQueue32 } from "./ui/icons";import { useState, useSyncExternalStore, type RefObject } from "react";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 { cancelExportJob, clearFinishedExports, exportFraction, isExportActive, useExportJobs } from "../lib/exportJob";import { cancelQueuedWeightDownload, getQueuedWeightDownloads, cancelWeightDownload, retryWeightDownload, getWeightDownloadState, subscribeWeightDownloads, weightDownloadProgress, type DownloadState } from "../lib/weightDownloads";import { Flyout, ProgressBar, ProgressRing } from "./ui";@@ -26,7 +26,7 @@ function StateGlyph({ item }: { item: WorkItem }) {export type WorkQueueTarget = { kind: "work"; item: WorkItem }| { kind: "download"; download: DownloadState }- | { kind: "export"; folderPath: string };+ | { kind: "export"; folderPath: string; exportKind?: "video" | "image" };export function WorkQueuePanel({ queue, items, open = true, anchor = null, onClose, onNavigate }: {queue: WorkQueue;@@ -45,10 +45,8 @@ export function WorkQueuePanel({ queue, items, open = true, anchor = null, onCloconst 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;it is shown here so it can be followed (and stopped) from anywhere. */- const exportJob = useExportJob();- const exporting = exportJob.progress;- const exportTitle = exportJob.projectName ? `Export ${exportJob.projectName}` : "Export";- const exportPercent = Math.floor(exportFraction(exporting) * 100);+ const exports = useExportJobs();+ const finishedExports = exports.filter((job) => !isExportActive(job));const current = items.filter((item) => isWorkActive(item) && item.status !== "queued");const upcoming = items.filter((item) => item.status === "queued").sort((a, b) => Number(a.kind === "reference-icons") - Number(b.kind === "reference-icons"));const finished = items.filter((item) => !isWorkActive(item)).slice().reverse();@@ -76,21 +74,26 @@ export function WorkQueuePanel({ queue, items, open = true, anchor = null, onClo<Flyout open={open} anchor={anchor} onClose={onClose} placement="bottom" aria-labelledby="work-queue-title" className="work-queue" width={360}><header className="work-queue__header"><h2 id="work-queue-title">Work queue</h2>- {finished.length > 0 && <button type="button" className="work-queue__link" onClick={() => queue.clearFinished()}>Clear finished</button>}+ {(finished.length > 0 || finishedExports.length > 0) && <button type="button" className="work-queue__link" onClick={() => { queue.clearFinished(); clearFinishedExports(); }}>Clear finished</button>}</header><div className="work-queue__list">- {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>}+ {items.length === 0 && !download && !queuedDownloads.length && !exports.length && <div className="work-queue__empty"><WorkQueue32 aria-hidden="true" /><strong>No work yet</strong><span>Generation, exports, and downloads 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! })} />}- <span className="work-queue__state work-queue__state--preparing" aria-hidden="true"><Film16 /></span>+ {exports.length > 0 && <section aria-label="Export"><ul>{exports.map((exportJob) => {+ const exportTitle = exportJob.kind === "image" ? `Export image · ${exportJob.projectName}` : `Export ${exportJob.projectName ?? ""}`;+ const exporting = exportJob.progress;+ const exportPercent = Math.floor(exportFraction(exporting) * 100);+ return <li key={exportJob.id} 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!, exportKind: exportJob.kind })} />}+ <span className={`work-queue__state work-queue__state--${exportJob.status}`} aria-hidden="true">{exportJob.status === "queued" ? <Clock16 /> : exportJob.status === "running" ? <ProgressRing size={16} /> : exportJob.status === "completed" ? <Check16 /> : exportJob.status === "failed" ? <Warning16 /> : <Dismiss16 />}</span><div className="work-queue__text"><span className="work-queue__title" data-tooltip={exportJob.destination ?? undefined}>{exportTitle}</span>- <span className="work-queue__caption">{exporting.detail || "Exporting"} · {exportPercent}%</span>- <ProgressBar value={exportPercent} aria-label={`${exportTitle} progress`} className="work-queue__progress" />+ <span className="work-queue__caption">{exporting ? `${exporting.detail || "Exporting"} · ${exportPercent}%` : exportJob.status === "queued" ? "Queued for export" : exportJob.status === "completed" ? `Saved · ${exportJob.destination}` : exportJob.status === "failed" ? "Export failed" : "Cancelled"}</span>+ {exporting && <ProgressBar value={exportJob.kind === "image" && exportPercent === 0 ? undefined : exportPercent} aria-label={`${exportTitle} progress`} className="work-queue__progress" />}+ {exportJob.outcome?.kind === "failed" && <span className="work-queue__error">{exportJob.outcome.message}</span>}</div>- <button type="button" className="icon-button work-queue__cancel" aria-label={`Cancel ${exportTitle}`} data-tooltip="Cancel" disabled={exportJob.cancelling} onClick={cancelExportJob}><Dismiss16 /></button>- </li></ul></section>}+ {isExportActive(exportJob) && <button type="button" className="icon-button work-queue__cancel" aria-label={`Cancel ${exportTitle}`} data-tooltip="Cancel" disabled={exportJob.cancelling} onClick={() => cancelExportJob(exportJob.id)}><Dismiss16 /></button>}+ </li>; })}</ul></section>}{download && <section aria-label="Weight downloads"><ul><li className={`work-queue__row${onNavigate ? " work-queue__row--navigable" : ""}`}>{onNavigate && <button type="button" className="work-queue__open" aria-label={`Open ${downloadName} download`} onClick={() => openTarget({ kind: "download", download })} />}<span className={`work-queue__state work-queue__state--${download.active ? "preparing" : download.error ? "failed" : "completed"}`} aria-hidden="true">diff --git a/src/components/workspace/ExportView.test.tsx b/src/components/workspace/ExportView.test.tsxindex 96fb5e7..8f045bc 100644--- a/src/components/workspace/ExportView.test.tsx+++ b/src/components/workspace/ExportView.test.tsx@@ -178,7 +178,8 @@ describe("a run in progress and a finished one", () => {render(<ExportView config={project([clip("a", 0, 3_000)])} folderPath="/tmp/project" />);expect(screen.getByRole("status").textContent).toContain("42% · 1:12 remaining · Encoding frame 30 of 72");expect(screen.getByRole("progressbar")).toBeTruthy();- expect(screen.getByRole("button", { name: "Exporting…" })).toHaveProperty("disabled", true);+ expect(screen.getByRole("button", { name: "Queue export" })).toBeTruthy();+ expect(screen.getByRole("combobox", { name: "Resolution" })).toHaveProperty("disabled", false);expect(screen.getByRole("button", { name: "Cancel" })).toBeTruthy();});@@ -202,7 +203,7 @@ describe("a run in progress and a finished one", () => {}));render(<ExportView config={project([clip("a", 0, 3_000)])} folderPath="/tmp/project" />);expect(screen.queryByRole("status")).toBeNull();- expect(screen.getByRole("alert").textContent).toContain("Another project is exporting");+ expect(screen.getByRole("alert").textContent).not.toContain("Another project is exporting");});});diff --git a/src/components/workspace/ExportView.tsx b/src/components/workspace/ExportView.tsxindex 0f81b06..052e9f9 100644--- a/src/components/workspace/ExportView.tsx+++ b/src/components/workspace/ExportView.tsx@@ -42,6 +42,7 @@ import { formatTimecode, frameAt, frameStartMs } from "../../lib/timeline";import { ProgramMonitor } from "./ProgramMonitor";import { ProjectStatus } from "./ProjectStatus";import { UPSCALERS, type Upscaler } from "../../lib/upscalers";+import { remoteWorkerSelected } from "../../lib/workers";import type { ProjectConfig } from "../../lib/project";import { ComboBox, InfoBar, ProgressBar, PropRow, PropSection, Slider, Splitter, tooltipProps, usePaneSize } from "../ui";@@ -107,7 +108,7 @@ export function ExportView({ config, folderPath, onClose }: {const [destination, setDestination] = useState<Destination | null>(null);const [destinationError, setDestinationError] = useState<string | null>(null);- const job = useExportJob();+ const job = useExportJob(folderPath, "video");const ours = job.folderPath === folderPath;const running = job.progress !== null;const runningHere = running && ours;@@ -221,6 +222,7 @@ export function ExportView({ config, folderPath, onClose }: {const codecProbe = probes?.find((probe) => probe.id === settings.codec) ?? null;const blockers = [...plan.blockers];+ if (settings.upscaler === "seedvr2" && !remoteWorkerSelected()) blockers.push("Select a worker in Settings → Workers to use SeedVR2 upscaling.");if (!support.desktop) {blockers.push("This is the browser preview. There is no project folder to read media from and nowhere on disk to write a file, so exporting is only available in the Slopus desktop app.",@@ -232,8 +234,7 @@ export function ExportView({ config, folderPath, onClose }: {if (codecProbe && !codecProbe.supported) {blockers.push(`This computer will not encode ${settings.codec.toUpperCase()} at ${plan.width}×${plan.height}: ${codecProbe.detail}`);}- if (running && !ours) blockers.push("Another project is exporting. Wait for it to finish.");- const canExport = blockers.length === 0 && !running;+ const canExport = blockers.length === 0;const browse = async (): Promise<Destination | null> => {setDestinationError(null);@@ -251,7 +252,7 @@ export function ExportView({ config, folderPath, onClose }: {const start = async () => {if (!canExport) return;- dismissExportOutcome();+ dismissExportOutcome(job.id);const target = destination ?? await browse();if (!target) return; // The user closed the save dialog. Nothing to say.if (!target.fromDialog) {@@ -415,7 +416,7 @@ export function ExportView({ config, folderPath, onClose }: {<buttontype="button"className="secondary-button export-destination__browse"- disabled={runningHere || !support.desktop}+ disabled={!support.desktop}aria-describedby="export-destination-label"onClick={() => void browse()}>Browse…</button>@@ -429,7 +430,6 @@ export function ExportView({ config, folderPath, onClose }: {<ComboBoxid="export-resolution"value={exportSizeKey(settings.width, settings.height)}- disabled={runningHere}onChange={(value) => {const size = sizeChoices.find((choice) => choice.value === value);if (size) setSettings({ ...settings, width: size.width, height: size.height });@@ -442,14 +442,13 @@ export function ExportView({ config, folderPath, onClose }: {<ComboBoxid="export-frame-rate"value={String(settings.frameRate)}- disabled={runningHere}onChange={(value) => setSettings({ ...settings, frameRate: Number(value) as FrameRate })}options={FRAME_RATES.map((rate) => ({ value: String(rate), label: `${rate} fps` }))}/></PropRow><PropRow label="Upscaler" htmlFor="export-upscaler">- <ComboBox id="export-upscaler" value={settings.upscaler ?? "none"} disabled={runningHere}+ <ComboBox id="export-upscaler" value={settings.upscaler ?? "none"}options={[...UPSCALERS]} onChange={(value) => setSettings({ ...settings, upscaler: value as Upscaler })} /></PropRow>@@ -457,7 +456,6 @@ export function ExportView({ config, folderPath, onClose }: {<ComboBoxid="export-codec"value={settings.codec}- disabled={runningHere}onChange={(value) => setSettings({ ...settings, codec: value as OutputCodecId })}options={OUTPUT_CODECS.map((codec) => {const probe = probes?.find((candidate) => candidate.id === codec.id);@@ -471,7 +469,6 @@ export function ExportView({ config, folderPath, onClose }: {<ComboBoxid="export-quality"value={settings.quality}- disabled={runningHere}onChange={(value) => setSettings({ ...settings, quality: value as QualityId })}options={QUALITY_PRESETS.map((preset) => ({value: preset.id,@@ -493,6 +490,7 @@ export function ExportView({ config, folderPath, onClose }: {</PropSection><div className="export-messages">+ {job.status === "queued" && <InfoBar severity="informational" title="Queued for export" message="Waiting for the current export to finish." />}{destinationError && <InfoBar severity="error" title="Save location" message={destinationError} onClose={() => setDestinationError(null)} />}{blockers.length > 0 && <InfoBar severity="error" title="Can’t export yet"><ul className="export-reasons">{blockers.map((blocker) => <li key={blocker}>{blocker}</li>)}</ul>@@ -525,19 +523,19 @@ export function ExportView({ config, folderPath, onClose }: {<button type="button" className="secondary-button" onClick={() => openFile(outcome.path)}>Open</button><button type="button" className="secondary-button" onClick={() => showInFolder(outcome.path)}>Show in folder</button></>}- onClose={dismissExportOutcome}+ onClose={() => dismissExportOutcome(job.id)}/>}{!progress && outcome?.kind === "cancelled" && <InfoBarseverity="informational"title="Export cancelled"message="Nothing was written."- onClose={dismissExportOutcome}+ onClose={() => dismissExportOutcome(job.id)}/>}- {!progress && outcome?.kind === "failed" && <InfoBar severity="error" title="Export failed" message={outcome.message} onClose={dismissExportOutcome} />}+ {!progress && outcome?.kind === "failed" && <InfoBar severity="error" title="Export failed" message={outcome.message} onClose={() => dismissExportOutcome(job.id)} />}</div><div className="export-settings__actions">- {runningHere- ? <button type="button" className="secondary-button" onClick={cancelExportJob} {...tooltipProps("Stop encoding. Nothing has been written yet.")}>Cancel</button>+ {runningHere || job.status === "queued"+ ? <button type="button" className="secondary-button" onClick={() => cancelExportJob(job.id)} {...tooltipProps("Cancel this export")}>Cancel</button>: onClose && <button type="button" className="secondary-button" onClick={onClose}>Cancel</button>}<buttontype="button"@@ -545,7 +543,7 @@ export function ExportView({ config, folderPath, onClose }: {disabled={!canExport}onClick={() => void start()}{...tooltipProps(canExport ? undefined : runningHere ? "Export is running" : blockers[0])}- >{runningHere ? "Exporting…" : "Export"}</button>+ >{runningHere || job.status === "queued" ? "Queue export" : "Export"}</button></div></div></section>diff --git a/src/components/workspace/ImageExportView.test.tsx b/src/components/workspace/ImageExportView.test.tsxindex 02f0ea4..94d6d46 100644--- a/src/components/workspace/ImageExportView.test.tsx+++ b/src/components/workspace/ImageExportView.test.tsx@@ -9,9 +9,11 @@ import { invoke } from "@tauri-apps/api/core";import { ImageExportView } from "./ImageExportView";import { imageGenerationSnapshot } from "../../lib/imageHistory";import { OTHER_WEIGHT_TEMPLATES } from "../../lib/upscalers";+import { resetExportJobForTests } from "../../lib/exportJob";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));-afterEach(() => { cleanup(); localStorage.clear(); vi.restoreAllMocks(); });+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));+afterEach(() => { cleanup(); resetExportJobForTests(); localStorage.clear(); vi.restoreAllMocks(); });function withOutput(patch: Partial<ProjectConfig["assets"][number]> = {}): ProjectConfig {const config = parseProjectConfig(fixture);@@ -47,8 +49,9 @@ it("refuses to export a draft and says why", () => {it.each(OTHER_WEIGHT_TEMPLATES)("exports with the selected $name model paths", async (template) => {vi.spyOn(persistence, "isTauri").mockReturnValue(true);vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue(null);- vi.mocked(invoke).mockResolvedValue(true);+ vi.mocked(invoke).mockImplementation(async (command) => command === "choose_image_export_destination" ? "D:/out.jpg" : 123);localStorage.setItem("slopus.other-weights.v1", JSON.stringify(Object.fromEntries(template.files.map((file) => [file.url, `C:/weights/${file.id}`]))));+ localStorage.setItem("slopus.generation-worker.v1", JSON.stringify({ id: "worker", name: "Worker", gpus: [] }));render(<ImageExportView config={withOutput({ width: 64, height: 32 })} folderPath="D:/Images" />);const selector = screen.getByRole("combobox", { name: "Upscaler" });expect(selector).toHaveTextContent("None");@@ -57,15 +60,14 @@ it.each(OTHER_WEIGHT_TEMPLATES)("exports with the selected $name model paths", afireEvent.click(screen.getByRole("option", { name: template.name }));fireEvent.click(screen.getByRole("button", { name: "Export…" }));await waitFor(() => expect(invoke).toHaveBeenCalledWith("export_generated_image", expect.objectContaining({- options: expect.objectContaining({ width: 64, height: 32, upscale: { method: template.id, modelPath: "C:/weights/model",- ...(template.id === "seedvr2" ? { vaePath: "C:/weights/vae" } : {}) } }),+ options: expect.objectContaining({ width: 64, height: 32, upscale: { method: template.id, modelPath: template.id === "seedvr2" ? "" : "C:/weights/model" } }),})));});it("sends the chosen size, format and JPG quality, and hides quality for PNG", async () => {vi.spyOn(persistence, "isTauri").mockReturnValue(true);vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue(null);- vi.mocked(invoke).mockResolvedValue(true);+ vi.mocked(invoke).mockImplementation(async (command) => command === "choose_image_export_destination" ? "D:/out.jpg" : 123);render(<ImageExportView config={withOutput({ width: 2048, height: 1152 })} folderPath="D:/Images" />);fireEvent.change(screen.getByRole("slider", { name: "JPG quality" }), { target: { value: "60" } });fireEvent.click(screen.getByRole("combobox", { name: "Resolution" }));@@ -75,6 +77,7 @@ it("sends the chosen size, format and JPG quality, and hides quality for PNG", afireEvent.click(screen.getByRole("option", { name: "3840 × 2160" }));fireEvent.click(screen.getByRole("button", { name: "Export…" }));await waitFor(() => expect(invoke).toHaveBeenCalledWith("export_generated_image", {+ jobId: expect.any(String), destination: "D:/out.jpg",folderPath: "D:/Images", relativePath: "media/generated/out.png",options: { format: "jpg", width: 3840, height: 2160, quality: 60 },}));@@ -116,7 +119,7 @@ it("keeps Original selected across images and omits duplicate presets", () => {it("shows the image bar and exports the image picked in it, leaving the Editor's image alone", async () => {vi.spyOn(persistence, "isTauri").mockReturnValue(true);vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue(null);- vi.mocked(invoke).mockResolvedValue(true);+ vi.mocked(invoke).mockImplementation(async (command) => command === "choose_image_export_destination" ? "D:/out.jpg" : 123);const config = withOutput({ width: 2048, height: 1152 });config.assets.push({ id: "second", name: "Second", kind: "image", relativePath: "media/generated/second.jpg", mimeType: "image/jpeg", width: 768, height: 1376, createdAt: config.createdAt } as ProjectConfig["assets"][number]);render(<ImageExportView config={config} folderPath="D:/Images" />);diff --git a/src/components/workspace/ImageExportView.tsx b/src/components/workspace/ImageExportView.tsxindex fb51f45..8724156 100644--- a/src/components/workspace/ImageExportView.tsx+++ b/src/components/workspace/ImageExportView.tsx@@ -3,11 +3,12 @@ import { useState } from "react";import { closestExportAspectRatio, exportSizeChoices } from "../../lib/export";import type { ProjectConfig } from "../../lib/project";import { isTauri } from "../../lib/persistence";-import { ComboBox, EmptyState, InfoBar, PropRow, PropSection, Slider, Splitter, tooltipProps, usePaneSize } from "../ui";+import { ComboBox, EmptyState, InfoBar, ProgressBar, PropRow, PropSection, Slider, Splitter, tooltipProps, usePaneSize } from "../ui";import { Image32 } from "../ui/icons";import { ImageBar } from "./ImageBar";import { ReferenceImage } from "./ReferenceImage";import { UPSCALERS, upscaleConfig, type Upscaler } from "../../lib/upscalers";+import { cancelExportJob, exportFraction, isExportActive, startImageExportJob, useExportJob } from "../../lib/exportJob";/* The image project's Export tab: the same page as the video export (seeexport.css) — the image on the stage, filling it, and the resizable settings@@ -33,6 +34,7 @@ export function ImageExportView({ config, folderPath }: { config: ProjectConfig;const [exporting, setExporting] = useState(false);const [upscaler, setUpscaler] = useState<Upscaler>("none");const [error, setError] = useState<string | null>(null);+ const job = useExportJob(folderPath, "image");/* Which image to export is this page's own choice: it starts on the one openin the Editor, and picking another here leaves the Editor where it was. */const images = config.assets.filter((asset) => asset.kind === "image");@@ -67,12 +69,10 @@ export function ImageExportView({ config, folderPath }: { config: ProjectConfig;if (!output?.relativePath || disabled) return;setExporting(true); setError(null);try {- await invoke("export_generated_image", {- folderPath,- relativePath: output.relativePath,- options: { format: preferences.format, width: size?.width, height: size?.height, quality: preferences.format === "jpg" ? preferences.quality : undefined,- ...(upscaler !== "none" ? { upscale: upscaleConfig(upscaler) } : {}) },- });+ const options = { format: preferences.format, width: size?.width, height: size?.height, quality: preferences.format === "jpg" ? preferences.quality : undefined,+ ...(upscaler !== "none" ? { upscale: upscaleConfig(upscaler) } : {}) };+ const destination = await invoke<string | null>("choose_image_export_destination", { options });+ if (destination) void startImageExportJob({ folderPath, projectName: config.name, relativePath: output.relativePath, options, destination });}catch (reason) { setError(String(reason)); }finally { setExporting(false); }@@ -128,12 +128,17 @@ export function ImageExportView({ config, folderPath }: { config: ProjectConfig;</PropRow>}</PropSection><div className="export-messages">+ {isExportActive(job) && <InfoBar severity="informational" title={job.status === "queued" ? "Queued for export" : "Exporting image"} message={job.progress?.detail ?? "Waiting for the current export to finish."} />}+ {job.progress && <ProgressBar value={job.progress.framesDone ? exportFraction(job.progress) * 100 : undefined} aria-label="Image export progress" />}+ {job.outcome?.kind === "saved" && <InfoBar severity="success" title="Image exported" message={job.outcome.path} />}+ {job.outcome?.kind === "failed" && <InfoBar severity="error" title="Couldn’t export image" message={job.outcome.message} />}{blocker && <InfoBar severity="informational" title="Nothing to export yet" message={blocker} />}{error && <InfoBar severity="error" title="Couldn’t export image" message={error} onClose={() => setError(null)} />}</div></div><div className="export-settings__foot"><div className="export-settings__actions">+ {isExportActive(job) && <button type="button" className="secondary-button" disabled={job.cancelling} onClick={() => cancelExportJob(job.id)}>Cancel export</button>}<buttontype="button"className="primary-button"diff --git a/src/lib/exportJob.test.ts b/src/lib/exportJob.test.tsnew file mode 100644index 0000000..8223fec--- /dev/null+++ b/src/lib/exportJob.test.ts@@ -0,0 +1,73 @@+// @vitest-environment jsdom+import { beforeEach, expect, it, vi } from "vitest";+import { invoke } from "@tauri-apps/api/core";+import { listen } from "@tauri-apps/api/event";+import { createProjectConfig } from "./project";+import { defaultExportSettings, buildExportPlan } from "./export";+import { runExport, writeExportFile, type ExportProgress, type ExportResult } from "./exportPipeline";+import { cancelExportJob, clearFinishedExports, getExportJobs, resetExportJobForTests, startExportJob, startImageExportJob } from "./exportJob";++vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));+vi.mock("./nativeShell", () => ({ setTaskbarProgress: vi.fn(async () => undefined) }));+vi.mock("./exportPipeline", async (original) => ({ ...await original<typeof import("./exportPipeline")>(), runExport: vi.fn(), writeExportFile: vi.fn(async () => 42) }));+beforeEach(() => { resetExportJobForTests(); vi.clearAllMocks(); vi.mocked(invoke).mockResolvedValue(24); });++const image = (destination = "D:/image.png") => ({ folderPath: "D:/Project", projectName: "Project", relativePath: "media/generated/image.png", destination, options: { format: "png" as const } });+const result = { bytes: new Uint8Array(42), audioProblems: [], audioShortfalls: [] } as unknown as ExportResult;+const video = () => {+ const config = createProjectConfig({ name: "Movie", prompt: "", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 5 });+ const settings = defaultExportSettings(config);+ return { folderPath: "D:/Movie", config, settings, plan: buildExportPlan(config, settings), bitrate: 1000, destination: "D:/movie.mp4" };+};++it("queues image and video exports together, snapshots settings, and retains their results", async () => {+ let finish!: (result: ExportResult) => void;+ vi.mocked(runExport).mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ const options = video();+ const first = startExportJob(options);+ const second = startImageExportJob(image());+ options.config.name = "Edited while exporting";+ expect(getExportJobs().map((job) => job.status)).toEqual(["running", "queued"]);+ expect(runExport).toHaveBeenCalledWith(expect.objectContaining({ config: expect.objectContaining({ name: "Movie" }) }));+ expect(invoke).not.toHaveBeenCalled();+ finish(result);+ await Promise.all([first, second]);+ expect(writeExportFile).toHaveBeenCalledWith("D:/movie.mp4", result.bytes);+ expect(invoke).toHaveBeenCalledWith("export_generated_image", expect.objectContaining({ destination: "D:/image.png", jobId: expect.any(String) }));+ expect(getExportJobs().map((job) => [job.kind, job.status])).toEqual([["video", "completed"], ["image", "completed"]]);+ clearFinishedExports(); expect(getExportJobs()).toEqual([]);+});++it("cancels waiting exports without starting them and continues after a running export fails", async () => {+ let fail!: (reason: Error) => void;+ vi.mocked(runExport).mockImplementation(() => new Promise((_resolve, reject) => { fail = reject; }));+ const first = startExportJob(video());+ const cancelled = startImageExportJob(image("D:/cancelled.png"));+ const next = startImageExportJob(image("D:/next.png"));+ cancelExportJob(getExportJobs()[1].id);+ await cancelled;+ fail(new Error("Encoder unavailable"));+ await Promise.all([first, next]);+ expect(getExportJobs().map((job) => job.status)).toEqual(["failed", "cancelled", "completed"]);+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(invoke).toHaveBeenCalledWith("export_generated_image", expect.objectContaining({ destination: "D:/next.png" }));+});++it("follows image progress outside its view and cancels the native export", async () => {+ let progress!: (event: { payload: ExportProgress & { jobId: string } }) => void;+ vi.mocked(listen).mockImplementation((async (_event, callback) => { progress = callback as typeof progress; return () => undefined; }) as typeof listen);+ let reject!: (reason: Error) => void;+ vi.mocked(invoke).mockImplementation(async (command) => {+ if (command === "export_generated_image") return new Promise((_resolve, no) => { reject = no; });+ if (command === "cancel_image_export") reject(new Error("Export cancelled."));+ });+ const done = startImageExportJob(image());+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledWith("export_generated_image", expect.anything()));+ const id = getExportJobs()[0].id!;+ progress({ payload: { jobId: id, phase: "rendering", framesDone: 0, frameCount: 1, detail: "Upscaling on worker" } });+ expect(getExportJobs()[0].progress?.detail).toBe("Upscaling on worker");+ cancelExportJob(id); await done;+ expect(invoke).toHaveBeenCalledWith("cancel_image_export", { jobId: id });+ expect(getExportJobs()[0]).toMatchObject({ status: "cancelled", cancelling: false });+});diff --git a/src/lib/exportJob.ts b/src/lib/exportJob.tsindex 56d9df1..fc4ec31 100644--- a/src/lib/exportJob.ts+++ b/src/lib/exportJob.ts@@ -1,4 +1,5 @@-/* The export that is running — held here rather than in ExportView.+/* Export jobs live independently of their views. Images and videos share one+ serial queue, and retain their results in Work Queue after completion.The Export screen used to own its run, so leaving the tab unmounted theview and cancelled the encode. The run is a promise chain that needs no@@ -11,7 +12,10 @@cleared when the file is saved or the run is cancelled, red when it failsuntil the failure is dismissed or another run starts. */-import { useSyncExternalStore } from "react";+import { useMemo, useSyncExternalStore } from "react";+import { invoke } from "@tauri-apps/api/core";+import { listen } from "@tauri-apps/api/event";+import type { UpscaleConfig } from "./upscalers";import type { ExportPlan, ExportSettings } from "./export";import { ExportCancelled, runExport, writeExportFile, type ExportProgress } from "./exportPipeline";import { setTaskbarProgress } from "./nativeShell";@@ -23,6 +27,9 @@ export type ExportOutcome =| { kind: "failed"; message: string };export interface ExportJobState {+ id: string | null;+ kind: "video" | "image";+ status: "queued" | "running" | "completed" | "cancelled" | "failed";/** The project folder the run (or its outcome) belongs to. */folderPath: string | null;/** The project's name, for the work queue and the exit guard. */@@ -37,14 +44,19 @@ export interface ExportJobState {cancelling: boolean;}-const IDLE: ExportJobState = { folderPath: null, projectName: null, destination: null, progress: null, remainingMs: null, outcome: null, cancelling: false };+const IDLE: ExportJobState = { id: null, kind: "video", status: "completed", folderPath: null, projectName: null, destination: null, progress: null, remainingMs: null, outcome: null, cancelling: false };let state: ExportJobState = IDLE;+let jobs: readonly ExportJobState[] = [];+interface PendingExport { id: string; run: () => Promise<void>; resolve: () => void }+let pending: PendingExport[] = [];+let running = false;let cancelRequested = false;const listeners = new Set<() => void>();function set(next: Partial<ExportJobState>) {state = { ...state, ...next };+ if (state.id) jobs = jobs.map((job) => job.id === state.id ? state : job);listeners.forEach((listener) => listener());}@@ -57,8 +69,46 @@ export function subscribeExportJob(listener: () => void): () => void {return () => { listeners.delete(listener); };}-export function useExportJob(): ExportJobState {- return useSyncExternalStore(subscribeExportJob, getExportJob, getExportJob);+export function useExportJob(folderPath?: string, kind?: "video" | "image"): ExportJobState {+ const snapshot = () => folderPath ? jobs.find((job) => job.folderPath === folderPath && job.kind === kind && isExportActive(job))+ ?? [...jobs].reverse().find((job) => job.folderPath === folderPath && job.kind === kind) ?? IDLE : state;+ return useSyncExternalStore(subscribeExportJob, snapshot, snapshot);+}++export const getExportJobs = () => jobs;+export const useExportJobs = () => useSyncExternalStore(subscribeExportJob, getExportJobs, getExportJobs);+export const isExportActive = (job: Pick<ExportJobState, "status">) => job.status === "queued" || job.status === "running";+type ExportActivity = Pick<ExportJobState, "id" | "folderPath" | "projectName" | "status">;+const activitySnapshot = () => JSON.stringify(jobs.filter(isExportActive).map(({ id, folderPath, projectName, status }) => ({ id, folderPath, projectName, status })));+/** The app shell needs status changes, not a re-render for every encoded frame. */+export function useExportActivity(): ExportActivity[] {+ const snapshot = useSyncExternalStore(subscribeExportJob, activitySnapshot, activitySnapshot);+ return useMemo(() => JSON.parse(snapshot) as ExportActivity[], [snapshot]);+}+export function clearFinishedExports() { jobs = jobs.filter(isExportActive); listeners.forEach((listener) => listener()); }++function enqueueExport(initial: Pick<ExportJobState, "folderPath" | "projectName" | "destination" | "kind">, run: () => Promise<void>) {+ const id = crypto.randomUUID();+ jobs = [...jobs, { ...IDLE, ...initial, id, status: "queued" }];+ const done = new Promise<void>((resolve) => pending.push({ id, run, resolve }));+ listeners.forEach((listener) => listener());+ pumpExports();+ return done;+}++function pumpExports() {+ if (running || !pending.length) return;+ const next = pending.shift()!;+ running = true;+ state = jobs.find((job) => job.id === next.id)!;+ cancelRequested = false;+ set({ status: "running", progress: { phase: "preparing", framesDone: 0, frameCount: 1, detail: "Starting…" } });+ void next.run().catch((reason) => set({ progress: null, outcome: { kind: "failed", message: String(reason) } })).finally(() => {+ set({ status: state.outcome?.kind === "saved" ? "completed" : state.outcome?.kind === "cancelled" ? "cancelled" : "failed", progress: null, cancelling: false });+ running = false;+ next.resolve();+ pumpExports();+ });}export const isExportRunning = () => state.progress !== null;@@ -78,16 +128,32 @@ export const exportFraction = (progress: ExportProgress | null) =>/** Stops the running export before the next frame. Nothing has been written* at any point before the end, so there is nothing to clean up. */-export function cancelExportJob() {+export function cancelExportJob(id = state.id) {+ const queued = pending.find((job) => job.id === id);+ if (queued) {+ pending = pending.filter((job) => job !== queued);+ jobs = jobs.map((job) => job.id === id ? { ...job, status: "cancelled", outcome: { kind: "cancelled" } } : job);+ queued.resolve();+ listeners.forEach((listener) => listener());+ return;+ }+ if (id !== state.id || !state.progress) return;cancelRequested = true;if (state.progress && !state.cancelling) set({ cancelling: true });+ if (state.kind === "image") void invoke("cancel_image_export", { jobId: id }).catch(() => undefined);}/** Forgets a finished run's outcome (and clears a red taskbar button). */-export function dismissExportOutcome() {- if (state.progress) return;- if (state.outcome?.kind === "failed") void setTaskbarProgress(null).catch(() => undefined);- set({ outcome: null });+export function dismissExportOutcome(id = state.id) {+ const job = jobs.find((item) => item.id === id);+ if (!job || isExportActive(job)) return;+ if (state.id === id) {+ if (state.outcome?.kind === "failed") void setTaskbarProgress(null).catch(() => undefined);+ set({ outcome: null });+ } else {+ jobs = jobs.map((item) => item.id === id ? { ...item, outcome: null } : item);+ listeners.forEach((listener) => listener());+ }}export interface StartExportOptions {@@ -102,9 +168,12 @@ export interface StartExportOptions {/** Renders, encodes and writes one export. Resolves when it has finished,* failed or been cancelled; the outcome is in the store either way. */export async function startExportJob(options: StartExportOptions): Promise<void> {- if (isExportRunning()) throw new Error("An export is already running.");+ const snapshot = structuredClone(options);+ return enqueueExport({ folderPath: options.folderPath, projectName: options.config.name, destination: options.destination, kind: "video" }, () => runVideoExport(snapshot));+}++async function runVideoExport(options: StartExportOptions): Promise<void> {const { folderPath, config, settings, plan, bitrate, destination } = options;- cancelRequested = false;/* The estimate starts once frames are coming out: mixing and encoder setuptake their own time, and folding them in would promise hours at frame 1. */let clockStart: { at: number; frames: number } | null = null;@@ -136,6 +205,7 @@ export async function startExportJob(options: StartExportOptions): Promise<void>void setTaskbarProgress(0).catch(() => undefined);try {const outcome = await runExport({ folderPath, config, settings, plan, bitrate, onProgress, cancelled: () => cancelRequested });+ if (cancelRequested) throw new ExportCancelled();set({progress: { phase: "writing", framesDone: plan.frameCount, frameCount: plan.frameCount, detail: "Writing the file…" },remainingMs: null,@@ -144,7 +214,7 @@ export async function startExportJob(options: StartExportOptions): Promise<void>set({ progress: null, outcome: { kind: "saved", path: destination, bytes, audioProblems: outcome.audioProblems, audioShortfalls: outcome.audioShortfalls } });void setTaskbarProgress(null).catch(() => undefined);} catch (reason) {- if (reason instanceof ExportCancelled) {+ if (cancelRequested || reason instanceof ExportCancelled) {set({ progress: null, outcome: { kind: "cancelled" } });void setTaskbarProgress(null).catch(() => undefined);} else {@@ -157,8 +227,37 @@ export async function startExportJob(options: StartExportOptions): Promise<void>}}+export interface ImageExportOptions { format: "jpg" | "png"; width?: number; height?: number; quality?: number; upscale?: UpscaleConfig }+export interface StartImageExportOptions { folderPath: string; projectName: string; relativePath: string; destination: string; options: ImageExportOptions }+export function startImageExportJob(options: StartImageExportOptions): Promise<void> {+ const snapshot = structuredClone(options);+ return enqueueExport({ folderPath: options.folderPath, projectName: options.projectName, destination: options.destination, kind: "image" }, async () => {+ const jobId = state.id!;+ let unlisten: (() => void) | undefined;+ void setTaskbarProgress(0).catch(() => undefined);+ try {+ unlisten = await listen<ExportProgress & { jobId: string }>("export-progress", ({ payload }) => {+ if (payload.jobId === jobId && state.id === jobId && state.status === "running") {+ set({ progress: payload });+ void setTaskbarProgress(exportFraction(payload)).catch(() => undefined);+ }+ });+ if (cancelRequested) throw new ExportCancelled();+ const { projectName: _name, ...args } = snapshot;+ const bytes = await invoke<number>("export_generated_image", { ...args, jobId });+ set({ progress: null, outcome: { kind: "saved", path: snapshot.destination, bytes, audioProblems: [], audioShortfalls: [] } });+ void setTaskbarProgress(null).catch(() => undefined);+ } catch (reason) {+ set({ progress: null, outcome: cancelRequested ? { kind: "cancelled" } : { kind: "failed", message: String(reason) } });+ void setTaskbarProgress(cancelRequested ? null : 1, cancelRequested ? undefined : "error").catch(() => undefined);+ } finally { unlisten?.(); }+ });+}+/** Test hook: put the store in a given state. */export function setExportJobForTests(next: Partial<ExportJobState>) {+ if (!state.id) { state = { ...IDLE, id: "test-export" }; jobs = [state]; }+ next.status ??= next.progress ? "running" : next.outcome?.kind === "cancelled" ? "cancelled" : "completed";set(next);}@@ -166,5 +265,6 @@ export function setExportJobForTests(next: Partial<ExportJobState>) {export function resetExportJobForTests() {cancelRequested = false;state = IDLE;+ jobs = []; pending = []; running = false;listeners.forEach((listener) => listener());}diff --git a/src/lib/exportPipeline.ts b/src/lib/exportPipeline.tsindex c88af3b..e54eeeb 100644--- a/src/lib/exportPipeline.ts+++ b/src/lib/exportPipeline.ts@@ -1365,7 +1365,7 @@ export async function runExport(options: ExportRunOptions): Promise<ExportResulttry {encoder.configure(encoderConfig(probe.codecString, plan, bitrate));if (upscale) {- report("preparing", 0, "Loading upscaler weights…");+ report("preparing", 0, upscale.method === "seedvr2" ? "Preparing SeedVR2 on worker…" : "Loading upscaler weights…");upscaler = await startUpscaleExport({ config: upscale, inputWidth: renderWidth, inputHeight: renderHeight,width: plan.width, height: plan.height, frameRate: plan.frameRate, frameCount: plan.frameCount, cancelled,output: async (frame, index) => {diff --git a/src/lib/upscalers.ts b/src/lib/upscalers.tsindex 465e372..1332f5c 100644--- a/src/lib/upscalers.ts+++ b/src/lib/upscalers.ts@@ -1,5 +1,6 @@import { invoke } from "@tauri-apps/api/core";import { isTauri } from "./persistence";+import { selectedWorker } from "./workers";export type Upscaler = "none" | "realesrgan" | "seedvr2";export const UPSCALERS = [@@ -37,10 +38,14 @@ export function subscribeOtherWeights(listener: () => void) {export interface UpscaleConfig { method: Exclude<Upscaler, "none">; modelPath: string; vaePath?: string }export function upscaleConfig(method: Upscaler): UpscaleConfig | undefined {if (method === "none") return undefined;+ if (method === "seedvr2") {+ if (!selectedWorker()) throw new Error("Select a worker in Settings → Workers to use SeedVR2 upscaling.");+ return { method, modelPath: "" };+ }const template = OTHER_WEIGHT_TEMPLATES.find((item) => item.id === method)!;const paths = otherWeightPaths();if (template.files.some((file) => !paths[file.url])) throw new Error(`Download ${template.name} in Settings → Generator → Other weights first.`);- return { method, modelPath: paths[template.files[0].url], ...(method === "seedvr2" ? { vaePath: paths[OTHER_WEIGHT_TEMPLATES[1].files[1].url] } : {}) };+ return { method, modelPath: paths[template.files[0].url] };}export async function refreshOtherWeights() {if (!isTauri()) return;diff --git a/src/lib/weightDownloadQueue.test.ts b/src/lib/weightDownloadQueue.test.tsindex 59181d0..57d074b 100644--- a/src/lib/weightDownloadQueue.test.ts+++ b/src/lib/weightDownloadQueue.test.ts@@ -25,7 +25,7 @@ it("serializes generator, upscaler and LoRA downloads and reports both SeedVR2 fconst queue = await import("./weightDownloads");const settings = await import("./settings");const loras = await import("./loras");- const { OTHER_WEIGHT_TEMPLATES, upscaleConfig } = await import("./upscalers");+ const { OTHER_WEIGHT_TEMPLATES, otherWeightPaths } = 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 });@@ -59,7 +59,7 @@ it("serializes generator, upscaler and LoRA downloads and reports both SeedVR2 fexpect(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" });+ expect(otherWeightPaths()).toMatchObject({ [OTHER_WEIGHT_TEMPLATES[1].files[0].url]: "C:/seed.safetensors", [OTHER_WEIGHT_TEMPLATES[1].files[1].url]: "C:/vae.safetensors" });await vi.waitFor(() => expect(transfers).toHaveLength(5));transfers[4].resolve("C:/adapter.safetensors");await lora;