AI media harness for planning, generating, and editing locally
TypeScript
Add application work queue
Bitti93c49719b512
diff --git a/src/App.tsx b/src/App.tsxindex 334908d..c8ecaee 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -1,7 +1,9 @@+import { WorkQueue, isWorkActive, projectQueueKey } from "./lib/workQueue";+import { WorkQueuePanel } from "./components/WorkQueuePanel";import { invoke } from "@tauri-apps/api/core";import { listen } from "@tauri-apps/api/event";-import { FolderOpen, Grid2X2, List, Plus, Search, Settings } from "lucide-react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { FolderOpen, Grid2X2, List, ListTodo, Plus, Search, Settings } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";import { Brand } from "./components/Brand";import { DeleteProjectDialog } from "./components/DeleteProjectDialog";import { ExitGuardDialog, type OngoingGeneration } from "./components/ExitGuardDialog";@@ -28,6 +30,14 @@ const logFailure = (event: string, reason: unknown, context: Record<string, unknfunction App() {const [projects, setProjects] = useState<ProjectRecord[]>([]);+ const [workQueue] = useState(() => new WorkQueue(async (record) => {+ const saved = await saveProject(record);+ setProjects((current) => [saved, ...current.filter((item) => projectQueueKey(item) !== projectQueueKey(saved))]);+ return saved;+ }));+ const workItems = useSyncExternalStore(workQueue.subscribe, workQueue.getSnapshot);+ const [workQueueOpen, setWorkQueueOpen] = useState(false);+ useEffect(() => workQueue.start(), [workQueue]);const [activeProject, setActiveProject] = useState<ProjectRecord | null>(null);const [activeProjectInitialView, setActiveProjectInitialView] = useState<ProjectView>("timeline");const [loading, setLoading] = useState(true);@@ -56,11 +66,11 @@ function App() {/* ── Exit guard: the window's close button ───────────────────────────────The video engine runs inside this process, so closing the window ends a- generation outright, and nothing partial is written on the way. The open- project reports what it has running; Rust holds the close request back+ generation outright, and nothing partial is written on the way. The app+ queue reports work across all projects; Rust holds the close request backonly while that list is non-empty, and this is where the question is putand answered. See the fenced block in src-tauri/src/lib.rs. */- const [ongoingGenerations, setOngoingGenerations] = useState<OngoingGeneration[]>([]);+ const ongoingGenerations: OngoingGeneration[] = workItems.filter(isWorkActive).map((item) => ({ id: item.id, title: `${item.title} · ${item.projectName}`, running: item.status !== "queued" }));const [closeRequested, setCloseRequested] = useState(false);const answerClose = useCallback((confirmed: boolean) => {@@ -88,7 +98,7 @@ function App() {}, [closeRequested, ongoingGenerations.length, answerClose]);const exitGuard = closeRequested && ongoingGenerations.length > 0- ? <ExitGuardDialog jobs={ongoingGenerations} destination="quit" onConfirm={() => answerClose(true)} onCancel={() => answerClose(false)} />+ ? <ExitGuardDialog jobs={ongoingGenerations} onConfirm={() => answerClose(true)} onCancel={() => answerClose(false)} />: null;useEffect(() => {@@ -186,7 +196,9 @@ function App() {setDeletingProject(true);setError(null);try {+ if (workQueue.hasActiveProject(target)) 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));setProjectToDelete(null);} catch (reason) {@@ -206,14 +218,17 @@ function App() {</button>);+ const queueLauncher = <button className="settings-launcher work-queue-launcher" type="button" onClick={() => setWorkQueueOpen(true)} title="Work Queue" aria-label="Work Queue" aria-haspopup="dialog" aria-expanded={workQueueOpen}>+ <ListTodo size={22} aria-hidden="true" /><span>Work Queue</span>{ongoingGenerations.length > 0 && <b>{ongoingGenerations.length}</b>}+ </button>;+ const queuePanel = workQueueOpen ? <WorkQueuePanel queue={workQueue} items={workItems} onClose={() => setWorkQueueOpen(false)} /> : null;+if (activeProject) {return <>- <ProjectWorkspace project={activeProject} initialView={activeProjectInitialView} runtime={runtime} onGeneratorRuntimeChange={(slopfab) => setRuntime((current) => ({ providers: current?.providers ?? CHECKING_PROVIDERS, slopfab }))} onOngoingGenerationsChange={setOngoingGenerations} onBack={() => setActiveProject(null)} onSave={async (project) => {- const saved = await saveProject(project);- setActiveProject(saved);- setProjects((current) => [saved, ...current.filter((item) => item.config.id !== saved.config.id)]);- }} />+ <ProjectWorkspace key={projectQueueKey(activeProject)} project={activeProject} initialView={activeProjectInitialView} runtime={runtime} workQueue={workQueue} onGeneratorRuntimeChange={(slopfab) => setRuntime((current) => ({ providers: current?.providers ?? CHECKING_PROVIDERS, slopfab }))} onBack={() => setActiveProject(null)} onSave={async () => { await workQueue.project(activeProject).save(); }} />{settingsLauncher}+ {queueLauncher}+ {queuePanel}{settingsOpen && <SettingsView onClose={closeSettings} />}{exitGuard}</>;@@ -264,6 +279,8 @@ function App() {</div></main>{settingsLauncher}+ {queueLauncher}+ {queuePanel}{newProjectOpen && <PromptComposer busy={busy} onCreate={createFromPrompt} onClose={() => setNewProjectOpen(false)} />}{settingsOpen && <SettingsView onClose={closeSettings} />}{projectToDelete && <DeleteProjectDialog project={projectToDelete} deleting={deletingProject} onConfirm={() => void confirmProjectDeletion()} onCancel={() => setProjectToDelete(null)} />}diff --git a/src/WorkQueue.integration.test.tsx b/src/WorkQueue.integration.test.tsxnew file mode 100644index 0000000..95e77d7--- /dev/null+++ b/src/WorkQueue.integration.test.tsx@@ -0,0 +1,74 @@+// @vitest-environment jsdom+import "@testing-library/jest-dom/vitest";+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { listen } from "@tauri-apps/api/event";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import App from "./App";+import { saveGeneratedScene } from "./lib/generatedVideo";+import { listRecentProjects, saveProject } from "./lib/persistence";+import { createProjectConfig, type ProjectRecord } from "./lib/project";+import { enqueueSlopfabGeneration, type SlopfabStatus } from "./lib/runtime";++vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn(async () => undefined) }));+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));+vi.mock("./lib/generatedVideo", () => ({ saveGeneratedScene: vi.fn(), releaseRendered: vi.fn(async () => true) }));+vi.mock("./lib/timelineThumbnails", async (original) => ({ ...await original<typeof import("./lib/timelineThumbnails")>(), purgeTimelineThumbnails: vi.fn(async () => undefined) }));+vi.mock("./lib/persistence", async (original) => ({ ...await original<typeof import("./lib/persistence")>(), isTauri: () => true, listRecentProjects: vi.fn(), saveProject: vi.fn() }));+vi.mock("./lib/runtime", async (original) => ({+ ...await original<typeof import("./lib/runtime")>(),+ getRuntimeStatus: async () => ({ providers: [], slopfab: { state: "ready", detail: "Ready", models: [] } as unknown as SlopfabStatus }),+ resolveSlopfabPlan: vi.fn(async () => ({ alignedFrames: 120, canvasWidth: 736, canvasHeight: 416 })),+ enqueueSlopfabGeneration: vi.fn(async () => undefined),+}));+const handlers = new Map<string, (event: { payload: unknown }) => void>();+beforeEach(() => {+ vi.clearAllMocks(); localStorage.clear(); handlers.clear();+ vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => undefined);+ vi.mocked(listen).mockImplementation((async (name: string, handler: (event: { payload: unknown }) => void) => { handlers.set(name, handler); return () => handlers.delete(name); }) as unknown as typeof listen);+ vi.mocked(saveProject).mockImplementation(async (record) => record);+ vi.mocked(saveGeneratedScene).mockResolvedValue({ relativePath: "media/generated/queued-result.mp4", bytes: 42, note: null });+});+afterEach(() => { cleanup(); vi.restoreAllMocks(); });++it("keeps the application queue alive while switching projects and saves results to their original project", async () => {+ const record = (name: string): ProjectRecord => ({ folderPath: `C:/${name}`, config: createProjectConfig({ name, prompt: "A quiet scene", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 30 }) });+ const first = record("First project"), second = record("Second project");+ first.config.generationJobs.push({ ...first.config.generationJobs[0], id: "scene-next", title: "Upcoming scene" });+ vi.mocked(listRecentProjects).mockResolvedValue({ projects: [first, second], unreadable: [] });+ render(<App />);+ fireEvent.click(await screen.findByRole("button", { name: "Open First project" }));+ fireEvent.click(screen.getByRole("button", { name: "Generator" }));+ fireEvent.click(screen.getByRole("button", { name: "Generate All" }));+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1));+ const workId = vi.mocked(enqueueSlopfabGeneration).mock.calls[0][0].jobId;+ fireEvent.click(screen.getByRole("button", { name: "Back to project library" }));+ expect(screen.queryByRole("alertdialog")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Open Second project" }));+ fireEvent.click(screen.getByRole("button", { name: "Work Queue" }));+ const panel = screen.getByRole("dialog", { name: "Work Queue" });+ expect(within(panel).getByRole("region", { name: "In progress" })).toHaveTextContent("First project");+ expect(within(panel).getByRole("region", { name: "Upcoming work" })).toHaveTextContent("Upcoming scene");+ fireEvent.click(within(panel).getByRole("button", { name: "Cancel Upcoming scene in First project" }));+ expect(within(panel).queryByRole("region", { name: "Upcoming work" })).toBeNull();+ fireEvent.click(within(panel).getByRole("button", { name: "Close work queue" }));+ await act(async () => { handlers.get("slopfab-job")?.({ payload: { jobId: workId, state: "framesReady", detail: "Ready" } }); });+ await waitFor(() => expect(saveProject).toHaveBeenCalledWith(expect.objectContaining({ folderPath: first.folderPath, config: expect.objectContaining({ generationJobs: expect.arrayContaining([expect.objectContaining({ status: "completed", outputRelativePath: "media/generated/queued-result.mp4" })]) }) })));+ expect(document.querySelector(".project-title")?.textContent).toBe("Second project");+ expect(saveGeneratedScene).toHaveBeenCalledWith(expect.objectContaining({ jobId: workId, folderPath: first.folderPath }));+ expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByRole("button", { name: "Back to project library" }));+ fireEvent.click(screen.getByRole("button", { name: "Open First project" }));+ fireEvent.click(screen.getByRole("button", { name: "Generator" }));+ expect(screen.getByRole("region", { name: "First scene" })).toHaveTextContent("FINISHED");+});++it("opens an empty queue from the library and closes it with Escape", async () => {+ vi.mocked(listRecentProjects).mockResolvedValue({ projects: [], unreadable: [] });+ render(<App />);+ const trigger = screen.getByRole("button", { name: "Work Queue" });+ trigger.focus(); fireEvent.click(trigger);+ expect(screen.getByRole("dialog", { name: "Work Queue" })).toHaveTextContent("No work yet");+ fireEvent.keyDown(window, { key: "Escape" });+ expect(screen.queryByRole("dialog", { name: "Work Queue" })).toBeNull();+ expect(document.activeElement).toBe(trigger);+});diff --git a/src/components/ExitGuardDialog.test.tsx b/src/components/ExitGuardDialog.test.tsxindex e644ea8..63420b0 100644--- a/src/components/ExitGuardDialog.test.tsx+++ b/src/components/ExitGuardDialog.test.tsx@@ -48,79 +48,13 @@ describe("the one definition of an ongoing generation", () => {});describe("leaving a project", () => {- it("goes straight back when nothing is generating", () => {+ it("returns to the library without a generation warning", () => {const onBack = vi.fn();- workspace(withJobs(["draft", "completed", "failed", "cancelled"]), onBack);+ workspace(withJobs(["generating", "queued", "ready"]), onBack);fireEvent.click(screen.getByRole("button", { name: "Back to project library" }));expect(onBack).toHaveBeenCalledTimes(1);expect(screen.queryByRole("alertdialog")).toBeNull();});-- it("asks first mid-generation, and stays put until the answer comes", () => {- const onBack = vi.fn();- workspace(withJobs(["generating", "queued"]), onBack);- fireEvent.click(screen.getByRole("button", { name: "Back to project library" }));-- const dialog = screen.getByRole("alertdialog");- expect(onBack).not.toHaveBeenCalled();- // It says what is running and what confirming costs — both checkable- // claims about this codebase, not a vague warning.- expect(dialog.textContent).toContain("1 shot is rendering now and 1 shot is waiting in the queue.");- expect(dialog.textContent).toContain("No video file is written until a shot finishes");- expect(dialog.textContent).toContain("can’t pick one back up");- });-- it("puts the user back exactly where they were when they cancel", () => {- const onBack = vi.fn();- workspace(withJobs(["generating"]), onBack);- const back = screen.getByRole("button", { name: "Back to project library" });- // jsdom does not move focus on a click the way a browser does, and the- // whole point of this test is where focus goes back TO.- back.focus();- fireEvent.click(back);- fireEvent.click(screen.getByRole("button", { name: "Keep generating" }));-- expect(onBack).not.toHaveBeenCalled();- expect(screen.queryByRole("alertdialog")).toBeNull();- // Still in the project, on the same view, with the same shot generating.- expect(screen.getByRole("heading", { name: "Timeline", level: 2 })).toBeTruthy();- // And focus is back on the control that opened the question.- expect(document.activeElement).toBe(back);- });-- it("closes on Escape without leaving", () => {- const onBack = vi.fn();- workspace(withJobs(["queued"]), onBack);- fireEvent.click(screen.getByRole("button", { name: "Back to project library" }));- fireEvent.keyDown(window, { key: "Escape" });- expect(screen.queryByRole("alertdialog")).toBeNull();- expect(onBack).not.toHaveBeenCalled();- });-- it("leaves once, and only once, when the answer is yes", () => {- const onBack = vi.fn();- workspace(withJobs(["generating"]), onBack);- fireEvent.click(screen.getByRole("button", { name: "Back to project library" }));- fireEvent.click(screen.getByRole("button", { name: "Stop and leave" }));- expect(onBack).toHaveBeenCalledTimes(1);- });-- it("reports what is generating to the app around it, and reports nothing once it unmounts", async () => {- const reported: string[][] = [];- const { unmount } = render(createElement(ProjectWorkspace, {- project: { folderPath: "C:\\Ceramic Lamp", config: withJobs(["generating", "queued", "draft"]) },- initialView: "timeline",- onBack: () => undefined,- onSave: async () => undefined,- onOngoingGenerationsChange: (jobs) => reported.push(jobs.map((job) => job.id)),- }));- await waitFor(() => expect(reported.length).toBeGreaterThan(0));- // The draft is not ongoing — a shot nobody has started costs nothing to- // walk away from.- expect(reported.at(-1)).toEqual(["job-0", "job-1"]);- unmount();- expect(reported.at(-1)).toEqual([]);- });});describe("the dialog on its own", () => {@@ -130,7 +64,7 @@ describe("the dialog on its own", () => {];it("keeps Tab inside itself and starts on the answer that changes nothing", () => {- render(createElement(ExitGuardDialog, { jobs, destination: "quit", onConfirm: () => undefined, onCancel: () => undefined }));+ render(createElement(ExitGuardDialog, { jobs, onConfirm: () => undefined, onCancel: () => undefined }));const keep = screen.getByRole("button", { name: "Keep generating" });const stop = screen.getByRole("button", { name: "Stop and close" });expect(document.activeElement).toBe(keep);@@ -145,13 +79,13 @@ describe("the dialog on its own", () => {});it("names the shots at stake and says which are only queued", () => {- const { container } = render(createElement(ExitGuardDialog, { jobs, destination: "quit", onConfirm: () => undefined, onCancel: () => undefined }));+ const { container } = render(createElement(ExitGuardDialog, { jobs, onConfirm: () => undefined, onCancel: () => undefined }));const rows = Array.from(container.querySelectorAll(".exit-guard__jobs li")).map((row) => row.textContent);expect(rows).toEqual(["Macro model detailsRendering now", "Hands sketching elevationWaiting to render"]);});it("says the window is what ends the run when that is the exit", () => {- render(createElement(ExitGuardDialog, { jobs, destination: "quit", onConfirm: () => undefined, onCancel: () => undefined }));+ render(createElement(ExitGuardDialog, { jobs, onConfirm: () => undefined, onCancel: () => undefined }));expect(screen.getByRole("alertdialog").textContent).toContain("The video engine runs inside Slopus, so closing the window stops them.");});});diff --git a/src/components/ExitGuardDialog.tsx b/src/components/ExitGuardDialog.tsxindex 3d18564..82c0bc8 100644--- a/src/components/ExitGuardDialog.tsx+++ b/src/components/ExitGuardDialog.tsx@@ -10,8 +10,6 @@ export interface OngoingGeneration {running: boolean;}-/** Where the user was heading when the guard stopped them. */-export type ExitDestination = "library" | "quit";const FOCUSABLE = "button:not([disabled]), [href], input, select, textarea, [tabindex]:not([tabindex=\"-1\"])";@@ -20,16 +18,15 @@ const FOCUSABLE = "button:not([disabled]), [href], input, select, textarea, [tab* Every claim it makes is a claim about this codebase, not a hedge:* • slopfab writes no file of its own (see `run_generation` in slopfab.rs). Its* frames reach the app through the `slopfab-job` event, and only once the- * app has encoded them (useGenerationEvents → lib/generatedVideo.ts) is- * there an .mp4 in the project folder. Leave before that and there is+ * app has encoded them (WorkQueue → lib/generatedVideo.ts) is+ * there an .mp4 in the project folder. Quit before that and there is* nothing on disk to come back to — which is why a scene that is still- * being encoded counts as ongoing too (see isGenerationOngoing).+ * being encoded counts as ongoing too (see isWorkActive).* • Nothing resumes. The only route back to a stopped shot is the Generator's* "Run it again", which starts the whole render from the first step.*/-export function ExitGuardDialog({ jobs, destination, onConfirm, onCancel }: {+export function ExitGuardDialog({ jobs, onConfirm, onCancel }: {jobs: OngoingGeneration[];- destination: ExitDestination;onConfirm: () => void;onCancel: () => void;}) {@@ -75,7 +72,6 @@ export function ExitGuardDialog({ jobs, destination, onConfirm, onCancel }: {const rendering = jobs.filter((job) => job.running);const queued = jobs.filter((job) => !job.running);- const leaving = destination === "library";return (<div className="exit-guard-backdrop" onMouseDown={(event) => { if (event.target === event.currentTarget) onCancel(); }}>@@ -90,16 +86,14 @@ export function ExitGuardDialog({ jobs, destination, onConfirm, onCancel }: {<div className="exit-guard__head"><span className="exit-guard__mark" aria-hidden="true"><AlertCircle size={20} /></span><h2 id="exit-guard-title">- {leaving ? "Leave the project and stop generating?" : "Close Slopus and stop generating?"}+ Close Slopus and stop generating?</h2></div><div className="exit-guard__body" id="exit-guard-body"><p>{summary(rendering.length, queued.length)}</p><p>- {leaving- ? "Going back to your projects stops them. "- : "The video engine runs inside Slopus, so closing the window stops them. "}+ The video engine runs inside Slopus, so closing the window stops them.{" "}No video file is written until a shot finishes, so an unfinished run leaves nothing behind — and Slopuscan’t pick one back up. You would run those shots again from the beginning.</p>@@ -123,7 +117,7 @@ export function ExitGuardDialog({ jobs, destination, onConfirm, onCancel }: {Keep generating</button><button className="exit-guard__confirm" type="button" onClick={onConfirm}>- {leaving ? "Stop and leave" : "Stop and close"}+ Stop and close</button></div></div>diff --git a/src/components/ProjectWorkspace.test.ts b/src/components/ProjectWorkspace.test.tsindex 7fffd53..bb8035e 100644--- a/src/components/ProjectWorkspace.test.ts+++ b/src/components/ProjectWorkspace.test.ts@@ -1,3 +1,4 @@+import { WorkQueue } from "../lib/workQueue";// @vitest-environment jsdomimport { act, cleanup, createEvent, fireEvent, render, screen, waitFor, within } from "@testing-library/react";@@ -17,7 +18,7 @@ import { saveDebugOptionsEnabled } from "../lib/settings";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));-vi.mock("../lib/generatedVideo", () => ({ saveGeneratedScene: vi.fn() }));+vi.mock("../lib/generatedVideo", () => ({ saveGeneratedScene: vi.fn(), releaseRendered: vi.fn(async () => true) }));afterEach(() => {cleanup();@@ -241,21 +242,30 @@ describe("project workspace timecode", () => {const mediaLoad = HTMLMediaElement.prototype.load;HTMLMediaElement.prototype.load = vi.fn();+ const runtimeModule = await import("../lib/runtime");+ const resolvePlan = vi.spyOn(runtimeModule, "resolveSlopfabPlan").mockResolvedValue({ alignedFrames: 120, canvasWidth: 736, canvasHeight: 416 } as Awaited<ReturnType<typeof runtimeModule.resolveSlopfabPlan>>);+ const enqueue = vi.spyOn(runtimeModule, "enqueueSlopfabGeneration").mockResolvedValue(undefined);+ const queue = new WorkQueue(onSave);+ const record = { folderPath: "C:/Ceramic Lamp", config };+ const stop = queue.start();+ queue.enqueue(queue.project(record), [{ job: config.generationJobs[0], snapshot: "test", request: { jobId, prompt: "A quiet film", frames: 120, steps: 12, seed: 42, canvasWidth: 736, canvasHeight: 416, referencePaths: [] } }]);try {+ await waitFor(() => expect(enqueue).toHaveBeenCalled());render(createElement(ProjectWorkspace, {- project: { folderPath: "C:\\Ceramic Lamp", config },+ project: record,+ workQueue: queue,initialView: "timeline",onBack: () => undefined,onSave,}));await waitFor(() => expect(handlers.has("slopfab-job")).toBe(true));await act(async () => {- handlers.get("slopfab-job")?.({ payload: { jobId, state: "framesReady", detail: "Frames ready." } });+ handlers.get("slopfab-job")?.({ payload: { jobId: queue.getSnapshot()[0].id, state: "framesReady", detail: "Frames ready." } });await Promise.resolve();});- await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(2));- const saved = onSave.mock.calls[0][0];+ const saved = onSave.mock.calls[1][0];expect(saved.config.generationJobs[0]).toMatchObject({status: "completed",outputRelativePath: "media/generated/job-initial-brief.mp4",@@ -263,6 +273,7 @@ describe("project workspace timecode", () => {expect(parseProjectConfig(saved.config)).toBeTruthy();await waitFor(() => expect((screen.getByRole("button", { name: "Save" }) as HTMLButtonElement).disabled).toBe(true));} finally {+ stop(); resolvePlan.mockRestore(); enqueue.mockRestore();cleanup();HTMLMediaElement.prototype.load = mediaLoad;delete scope.__TAURI_INTERNALS__;diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsxindex aee907c..934cbba 100644--- a/src/components/ProjectWorkspace.tsx+++ b/src/components/ProjectWorkspace.tsx@@ -1,28 +1,18 @@import { ArrowLeft, BookOpen, Bot, Download, Film, Save, Sparkles } from "lucide-react";-import { useEffect, useMemo, useRef, useState } from "react";-import { describeDiagnosticError, errorContext, writeDiagnostic } from "../lib/diagnostics";+import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";import type { GenerationJob, ProjectConfig, ProjectRecord } from "../lib/project";-import { cancelSlopfabGeneration, CHECKING_PROVIDERS, executeAgentCommands, type RuntimeStatus, type SlopfabStatus } from "../lib/runtime";+import { CHECKING_PROVIDERS, executeAgentCommands, type RuntimeStatus, type SlopfabStatus } from "../lib/runtime";import { purgeTimelineThumbnails } from "../lib/timelineThumbnails";-import { ExitGuardDialog, type OngoingGeneration } from "./ExitGuardDialog";+import { WorkQueue, projectQueueKey } from "../lib/workQueue";import { AgentDock } from "./workspace/AgentDock";import { ExportView } from "./workspace/ExportView";import { GeneratorView } from "./workspace/GeneratorView";import { ReferencesView } from "./workspace/ReferencesView";import { TimelineView, type ConfigUpdate } from "./workspace/TimelineView";-import { useGenerationEvents } from "./workspace/useGenerationEvents";export type ProjectView = "timeline" | "generator" | "references" | "agent" | "export";-/** A generation the app is still working on: waiting for the engine, being- * rendered by it, or — `ready` — rendered and being encoded into the file that- * will land in the project folder.- *- * That last one belongs here for the same reason as the other two: until the- * .mp4 is written there is nothing on disk, and closing the window in the- * seconds it takes to encode throws away the whole render. The topbar count- * and the exit guard both read this one predicate, so a badge saying "2" and a- * warning about what leaving costs can never disagree. */+/** The scene badge includes native generation and the final encoding step. */export const isGenerationOngoing = (job: GenerationJob) =>job.status === "generating" || job.status === "queued" || job.status === "ready";@@ -34,7 +24,7 @@ export function formatDurationTimecode(totalSeconds: number): string {return [hours, minutes, remainder].map((value) => String(value).padStart(2, "0")).join(":");}-export function ProjectWorkspace({ project, initialView = "timeline", runtime = null, onBack, onSave, onOngoingGenerationsChange, onGeneratorRuntimeChange }: {+export function ProjectWorkspace({ project, initialView = "timeline", runtime = null, onBack, onSave, workQueue, onGeneratorRuntimeChange }: {project: ProjectRecord;initialView?: ProjectView;/** What is installed on this computer, probed once at startup by App. Null@@ -42,91 +32,28 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =runtime?: RuntimeStatus | null;onBack: () => void;onSave: (project: ProjectRecord) => Promise<void>;- /** Told what is still generating whenever that changes, and told nothing is- * the moment this screen goes away. App needs it for the window's close- * button: the jobs live in this component's config, which the library never- * sees. Optional, so a test can mount the workspace on its own. */- onOngoingGenerationsChange?: (jobs: OngoingGeneration[]) => void;+ workQueue?: WorkQueue;/** Keeps the app-wide probe result aligned when the active generator is* changed directly from the Generator screen. */onGeneratorRuntimeChange?: (runtime: SlopfabStatus) => void;}) {- const [config, setConfigState] = useState(project.config);- const configRef = useRef(config);- configRef.current = config;+ const saveRef = useRef(onSave);+ saveRef.current = onSave;+ const [localQueue] = useState(() => new WorkQueue((record) => saveRef.current(record)));+ const queue = workQueue ?? localQueue;+ const session = useMemo(() => queue.project(project), [queue, project.folderPath, project.config.id]);+ const { config, saving, dirty, saveError } = useSyncExternalStore(session.subscribe, session.getSnapshot);+ const items = useSyncExternalStore(queue.subscribe, queue.getSnapshot);const [view, setView] = useState<ProjectView>(initialView);const [selectedGenerationJobId, setSelectedGenerationJobId] = useState<string | undefined>(project.config.generationJobs[0]?.id);- const [saving, setSaving] = useState(false);- const [dirty, setDirty] = useState(false);- const [saveError, setSaveError] = useState<string | null>(null);- const [leaveGuard, setLeaveGuard] = useState(false);- const [generationCompletionTimes, setGenerationCompletionTimes] = useState<Readonly<Record<string, number>>>({});- /** Every save is ordered. Without this, an older manual save and a generation- * completion save could race and whichever disk write happened to finish- * last would win, even if it held the older project. */- const saveQueue = useRef<Promise<void>>(Promise.resolve());- const pendingSaves = useRef(0);- // Measurements also replace the config object, but deliberately do not make- // the project dirty. A revision counts only writes that the Save button is- // responsible for, so a measurement landing during a save cannot make a- // successfully persisted project look unsaved.- const dirtyRevision = useRef(0);const knownSceneIds = useRef(new Set(project.config.generationJobs.map((job) => job.id)));-- const applyConfig = (next: ConfigUpdate): ProjectConfig => {- const resolved = typeof next === "function" ? next(configRef.current) : next;- configRef.current = resolved;- setConfigState(resolved);- return resolved;- };-- const persist = (record: ProjectRecord): Promise<void> => {- const savedRevision = dirtyRevision.current;- pendingSaves.current += 1;- setSaving(true);- const attempt = saveQueue.current- .catch(() => undefined)- .then(async () => {- setSaveError(null);- await onSave(record);- });- saveQueue.current = attempt.then(() => undefined, () => undefined);- return attempt- .then(() => {- // A later edit did not ride in this write, so its Save button must stay- // enabled. Background measurements do not advance this revision.- if (dirtyRevision.current === savedRevision) setDirty(false);- })- .catch((reason) => {- const detail = describeDiagnosticError(reason);- writeDiagnostic("error", "workspace", "project.save_failed", detail, { projectId: configRef.current.id, ...errorContext(reason) });- setSaveError(detail);- })- .finally(() => {- pendingSaves.current -= 1;- if (pendingSaves.current === 0) setSaving(false);- });- };-- /* What the engine says about a render, and the saving of the file it- produces. Mounted HERE, not in the Generator: a render takes minutes, and- a user who spends them on the timeline used to unmount the only listeners- there were — the finished frames then arrived at nobody and were dropped. */- useGenerationEvents({- folderPath: project.folderPath,- onChange: (update) => { applyConfig(update); dirtyRevision.current += 1; setDirty(true); },- onCompleted: () => { void persist({ ...project, config: configRef.current }); },- onEstimate: (jobId, completionAt) => setGenerationCompletionTimes((current) => {- if (completionAt === null) {- if (!(jobId in current)) return current;- const next = { ...current };- delete next[jobId];- return next;- }- if (current[jobId] === completionAt) return current;- return { ...current, [jobId]: completionAt };- }),- });+ const projectItems = items.filter((item) => item.projectKey === projectQueueKey(project));+ const generationCompletionTimes = Object.fromEntries(projectItems.filter((item) => item.completionAt !== null).map((item) => [item.sceneId, item.completionAt as number]));+ const cancellingJobIds = new Set(projectItems.filter((item) => item.cancelling).map((item) => item.sceneId));+ useEffect(() => workQueue ? undefined : queue.start(), [queue, workQueue]);+ const changeConfig = (next: ConfigUpdate) => session.update(next);+ const recordMeasurement = (update: (current: ProjectConfig) => ProjectConfig) => session.update(update, false);+ const save = () => session.save().catch(() => undefined);/* Scene removal can come from the Generator or from Slop replacing theproject document. Keep derived disk caches honest at this shared boundary@@ -139,69 +66,14 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =knownSceneIds.current = current;}, [config.generationJobs, project.folderPath]);- /* Derived through a key of identity and status rather than from the job- objects: a render in progress rewrites generationJobs on every progress- tick, and a list rebuilt from that would push a new array at App several- times a second for a change nobody can see. */- const ongoingKey = config.generationJobs.filter(isGenerationOngoing).map((job) => `${job.id} · ${job.status} · ${job.title}`).join(" | ");- const ongoing = useMemo<OngoingGeneration[]>(- () => config.generationJobs.filter(isGenerationOngoing).map((job) => ({ id: job.id, title: job.title, running: job.status === "generating" })),- // eslint-disable-next-line react-hooks/exhaustive-deps- [ongoingKey],- );- useEffect(() => { onOngoingGenerationsChange?.(ongoing); }, [ongoing, onOngoingGenerationsChange]);- /* Leaving this screen leaves nothing generating as far as the window's close- button is concerned: whatever the engine is still doing, its events land in- the Generator, which unmounts with everything else here. */- useEffect(() => () => onOngoingGenerationsChange?.([]), [onOngoingGenerationsChange]);-- /* The question stops being worth asking if the last run finishes while it is- on screen. Close it rather than navigate: the user never answered it, and- leaving on their behalf is not an answer. */- useEffect(() => { if (ongoing.length === 0) setLeaveGuard(false); }, [ongoing.length]);-- const leave = () => {- /* Nothing resumes, and a render that finishes after this screen is gone has- nowhere to be recorded: the listeners that save it (useGenerationEvents)- belong to this component and go with it. Rather than burn the GPU for a- result no one will keep, the runs are stopped the same way their own stop- button stops them. */- ongoing.forEach((job) => { void cancelSlopfabGeneration(job.id).catch(() => undefined); });- onBack();- };-- /* Takes an updater as well as a value, because a write built from something- asynchronous cannot safely name the config it starts from — see- TimelineView's measurement flush. Views that only ever change the project- from a click still pass a plain value. */- const changeConfig = (next: ConfigUpdate) => {- applyConfig(next);- dirtyRevision.current += 1;- setDirty(true);- };-- /* A file's length and size, read off the file by the media panel's decode.- It is new information and the project keeps it — the next save writes it —- but the user edited nothing by opening a panel, so it must not turn Save- on. That button is the app's whole claim about what is and is not on disk,- and "you have unsaved changes" was false: there was nothing the user could- lose. Everything measured here is re-derivable from the files themselves,- so a measurement that never rides along with a real save costs a re-decode- and nothing else. */- const recordMeasurement = (update: (current: ProjectConfig) => ProjectConfig) => { applyConfig(update); };-- const save = async (record?: ProjectRecord) => {- await persist(record ?? { ...project, config: configRef.current });- };-return <div className="project-shell"><header className="project-topbar"><div className="project-topbar__lead"><buttonclassName="icon-button icon-button--strong"- onClick={() => (ongoing.length > 0 ? setLeaveGuard(true) : onBack())}+ onClick={onBack}aria-label="Back to project library"- title={ongoing.length > 0 ? "Back to your projects — asks first, because leaving stops what is generating" : "Back to your projects"}+ title="Back to your projects"><ArrowLeft size={18} /></button>{/* The name column is the topbar's elastic column and truncates on narrowwindows, so the full name stays available on hover. */}@@ -210,7 +82,7 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =<nav className="project-nav" aria-label="Project views">{([ ["agent", Bot, "Agent"], ["timeline", Film, "Timeline"], ["generator", Sparkles, "Generator"], ["references", BookOpen, "References"] ] as const).map(([id, Icon, label]) => {- const running = id === "generator" ? ongoing.length : 0;+ const running = id === "generator" ? config.generationJobs.filter(isGenerationOngoing).length : 0;return <button key={id} type="button" className={view === id ? "active" : ""} aria-current={view === id ? "page" : undefined} onClick={() => setView(id)}><Icon size={18} aria-hidden="true" /> {label}{running > 0 && <span title={`${running} generation${running === 1 ? "" : "s"} running or queued`}>{running}</span>}@@ -241,7 +113,7 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =<div className={`project-content project-content--${view}`}>{view === "timeline" && <TimelineView config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} onChange={changeConfig} onMeasured={recordMeasurement} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} />}- {view === "generator" && <GeneratorView config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} runtime={runtime?.slopfab ?? null} onRuntimeChange={onGeneratorRuntimeChange} onChange={changeConfig} selectedJobId={selectedGenerationJobId} onOpenTimeline={() => setView("timeline")} />}+ {view === "generator" && <GeneratorView onGenerate={(submissions) => queue.enqueue(session, submissions)} onCancelGeneration={(ids) => queue.cancelScenes(session, ids)} cancellingJobIds={cancellingJobIds} config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} runtime={runtime?.slopfab ?? null} onRuntimeChange={onGeneratorRuntimeChange} onChange={changeConfig} selectedJobId={selectedGenerationJobId} onOpenTimeline={() => setView("timeline")} />}{view === "references" && <ReferencesView config={config} folderPath={project.folderPath} onChange={changeConfig} />}{view === "export" && <ExportView config={config} folderPath={project.folderPath} />}</div>@@ -251,18 +123,15 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =providers={runtime?.providers ?? CHECKING_PROVIDERS}expanded={view === "agent"}onPromptStart={() => setView("agent")}- /* The provider only proposes typed commands. Apply them to configRef's+ /* The provider only proposes typed commands. Apply them to the session'slatest state—edits can continue while it thinks—then route the resultthrough the same ordered save queue as the Save button. */onCommands={async (commands) => {- const next = await executeAgentCommands(configRef.current, commands);- applyConfig(next);- dirtyRevision.current += 1;- setDirty(true);- await save({ ...project, config: next });+ const next = await executeAgentCommands(session.getSnapshot().config, commands);+ session.update(next);+ await save();}}/></footer>- {leaveGuard && <ExitGuardDialog jobs={ongoing} destination="library" onConfirm={leave} onCancel={() => setLeaveGuard(false)} />}- {saveError && <div className="toast" role="alert"><strong>Couldn’t save project</strong><span>{saveError}</span><button onClick={() => setSaveError(null)}>Dismiss</button></div>}+ {saveError && <div className="toast" role="alert"><strong>Couldn’t save project</strong><span>{saveError}</span><button onClick={session.dismissError}>Dismiss</button></div>}</div>;}diff --git a/src/components/WorkQueuePanel.tsx b/src/components/WorkQueuePanel.tsxnew file mode 100644index 0000000..6a60471--- /dev/null+++ b/src/components/WorkQueuePanel.tsx@@ -0,0 +1,57 @@+import { Check, Clock3, ListTodo, LoaderCircle, TriangleAlert, X } from "lucide-react";+import { useEffect, useRef } from "react";+import { createPortal } from "react-dom";+import { GENERATION_FRAME_RATE } from "../lib/project";+import { isWorkActive, type WorkItem, type WorkQueue } from "../lib/workQueue";++export function WorkQueuePanel({ queue, items, onClose }: { queue: WorkQueue; items: readonly WorkItem[]; onClose: () => void }) {+ const panel = useRef<HTMLElement>(null);+ const close = useRef<HTMLButtonElement>(null);+ useEffect(() => {+ const opener = document.activeElement as HTMLElement | null;+ close.current?.focus();+ return () => { if (opener?.isConnected) opener.focus(); };+ }, []);+ useEffect(() => {+ const keyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); onClose(); }+ if (event.key === "Tab") {+ const buttons = Array.from(panel.current?.querySelectorAll<HTMLElement>("button:not(:disabled), summary, [tabindex='0']") ?? []);+ const first = buttons[0], last = buttons.at(-1);+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }+ }+ };+ window.addEventListener("keydown", keyDown, true);+ return () => window.removeEventListener("keydown", keyDown, true);+ }, [onClose]);+ const current = items.filter((item) => isWorkActive(item) && item.status !== "queued");+ const upcoming = items.filter((item) => item.status === "queued");+ const finished = items.filter((item) => !isWorkActive(item)).slice().reverse();+ const row = (item: WorkItem) => <li className="work-queue__item" key={item.id}>+ <div className="work-queue__item-heading">+ <span className={`work-queue__state work-queue__state--${item.status}`} aria-hidden="true">+ {item.status === "completed" ? <Check size={17} /> : item.status === "failed" ? <TriangleAlert size={17} /> : item.status === "queued" ? <Clock3 size={17} /> : item.status === "cancelled" ? <X size={17} /> : <LoaderCircle className="work-queue__spinner" size={17} />}+ </span>+ <div><strong>{item.title}</strong><span title={item.folderPath}>{item.projectName}</span></div>+ {isWorkActive(item) && item.status !== "encoding" && <button type="button" className="icon-button" disabled={item.cancelling} aria-label={`Cancel ${item.title} in ${item.projectName}`} title="Cancel this work" onClick={() => void queue.cancel(item.id)}><X size={16} /></button>}+ </div>+ <div className="work-queue__detail"><span>{item.detail}</span>{isWorkActive(item) && item.status !== "queued" && <b>{Math.floor(item.progress * 100)}%</b>}</div>+ {isWorkActive(item) && item.status !== "queued" && <progress max={1} value={item.progress} aria-label={`${item.title} progress`} />}+ <p className="work-queue__settings">{item.settings.canvasWidth} × {item.settings.canvasHeight} · {(item.settings.frames / GENERATION_FRAME_RATE).toFixed(1)}s · {item.settings.steps} steps · {item.settings.seed === -1 ? "Random seed" : `Seed ${item.settings.seed}`}</p>+ {item.error && <p className="work-queue__error">{item.error}</p>}+ {item.needsSave && <button type="button" className="secondary-button" onClick={() => void queue.retrySave(item.id)}>Retry project save</button>}+ </li>;+ return createPortal(<div className="work-queue-backdrop" onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>+ <section ref={panel} className="work-queue-panel" role="dialog" aria-modal="true" aria-labelledby="work-queue-title">+ <header className="work-queue__header"><div><ListTodo size={20} /><h2 id="work-queue-title">Work Queue</h2></div><button ref={close} type="button" className="icon-button icon-button--strong" aria-label="Close work queue" onClick={onClose}><X size={18} /></button></header>+ <p className="work-queue__intro">Work continues across projects, using the settings from when it was added.</p>+ <div className="work-queue__list">+ {items.length === 0 && <div className="work-queue__empty"><ListTodo size={28} /><strong>No work yet</strong><p>Generate a scene to add it to the queue.</p></div>}+ {current.length > 0 && <section aria-label="In progress"><h3>In progress</h3><ul>{current.map(row)}</ul></section>}+ {upcoming.length > 0 && <section aria-label="Upcoming work"><h3>Up next <span>{upcoming.length}</span></h3><ul>{upcoming.map(row)}</ul></section>}+ {finished.length > 0 && <section aria-label="Finished work"><h3>Finished <button type="button" onClick={() => queue.clearFinished()}>Clear</button></h3><ul>{finished.map(row)}</ul></section>}+ </div>+ </section>+ </div>, document.body);+}diff --git a/src/components/workspace/GeneratorView.test.tsx b/src/components/workspace/GeneratorView.test.tsxindex bfb185e..1298a4e 100644--- a/src/components/workspace/GeneratorView.test.tsx+++ b/src/components/workspace/GeneratorView.test.tsx@@ -76,6 +76,7 @@ function setup(initial = project()) {let replace: (next: ProjectConfig) => void = () => undefined;function Harness() {const [config, setConfig] = useState(latest);+ const [cancellingIds, setCancellingIds] = useState<ReadonlySet<string>>(() => new Set());latest = config;replace = (next) => setConfig(next);return <GeneratorView@@ -83,6 +84,16 @@ function setup(initial = project()) {folderPath="C:\\project"runtime={readyRuntime}onChange={setConfig}+ onGenerate={(submissions) => setConfig((current) => ({ ...current, generationJobs: current.generationJobs.map((job) => {+ const submission = submissions.find((item) => item.job.id === job.id);+ return submission ? { ...job, status: "queued", stage: "queued", progress: 0, error: null, generationSnapshot: submission.snapshot } : job;+ }) }))}+ cancellingJobIds={cancellingIds}+ onCancelGeneration={async (ids) => {+ const next = ids.filter((id) => !cancellingIds.has(id));+ setCancellingIds((current) => new Set([...current, ...next]));+ await Promise.all(next.map((id) => cancelSlopfabGeneration(id)));+ }}onOpenTimeline={() => undefined}/>;}diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsxindex 7dc0075..bb9b275 100644--- a/src/components/workspace/GeneratorView.tsx+++ b/src/components/workspace/GeneratorView.tsx@@ -1,11 +1,11 @@+import type { GenerationSubmission } from "../../lib/workQueue";import { ChevronDown, Plus, Sparkles, Square, Trash2, WandSparkles } from "lucide-react";import { invoke } from "@tauri-apps/api/core";import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";-import { describeDiagnosticError, errorContext, writeDiagnostic } from "../../lib/diagnostics";import { actionReferenceIds, compileGenerationJobPrompt, compileGenerationJobSegments, createDraftGenerationJob, danglingReferenceTokens, GENERATION_FRAME_RATE, RANDOM_GENERATION_SEED, sceneDurationSeconds, sceneGenerationReferences, sceneGenerationSeed, sceneGenerationSnapshot, sceneGenerationSteps, sceneShots, SCENE_MAX_SECONDS, SCENE_MIN_SECONDS, projectItemPath, usableReferenceImages, type GenerationJob, type ProjectConfig, type ProjectReference, type SceneShot } from "../../lib/project";import { generationDimensions } from "../../lib/export";import { isTauri } from "../../lib/persistence";-import { cancelSlopfabGeneration, enqueueSlopfabGeneration, getEngineStatus, resolveSlopfabPlan, type SlopfabGenerationRequest, type SlopfabStatus } from "../../lib/runtime";+import { getEngineStatus, type SlopfabGenerationRequest, type SlopfabStatus } from "../../lib/runtime";import { SceneBoard, type GeneratorSelection } from "./SceneBoard";import { SceneInspector, ShotInspector, STEP_SECONDS, writeShots } from "./SceneEditor";import { statusIcon } from "./sceneStatus";@@ -20,6 +20,9 @@ interface GeneratorViewProps {runtime?: SlopfabStatus | null;generationCompletionTimes?: Readonly<Record<string, number>>;onChange: (next: ProjectConfig) => void;+ onGenerate?: (submissions: GenerationSubmission[]) => void;+ onCancelGeneration?: (sceneIds: string[]) => Promise<void>;+ cancellingJobIds?: ReadonlySet<string>;onOpenTimeline: () => void;selectedJobId?: string;onRuntimeChange?: (runtime: SlopfabStatus) => void;@@ -40,7 +43,7 @@ type RemovalTarget =* The panel is whatever is open — one shot, or the scene itself. Nothing is* edited on the board, and nothing is duplicated in the panel: there is exactly* one place to change any given thing. */-export function GeneratorView({ config, folderPath, runtime = null, generationCompletionTimes = {}, onChange, selectedJobId, onRuntimeChange }: GeneratorViewProps) {+export function GeneratorView({ config, folderPath, runtime = null, generationCompletionTimes = {}, onChange, selectedJobId, onRuntimeChange, onGenerate, onCancelGeneration, cancellingJobIds = new Set() }: GeneratorViewProps) {const jobs = config.generationJobs;const [templateSettings, setTemplateSettings] = useState(loadGeneratorTemplateSettings);const selectedTemplate = defaultGeneratorTemplate(templateSettings);@@ -50,20 +53,10 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst runtimeProbe = useRef(0);const configRef = useRef(config);configRef.current = config;- // A scene is displayed as queued while its plan is resolving, just before- // the backend receives it. Remember cancellation here as well as sending it- // to slopfab, so a click in that small window prevents the later enqueue.- const cancellationRequests = useRef(new Set<string>());- // The ref above protects asynchronous work; this set exists so the cards- // repaint immediately when Cancel is pressed, before slopfab reports the- // terminal cancelled state.- const [cancellingJobIds, setCancellingJobIds] = useState<ReadonlySet<string>>(() => new Set());-/* A scene is always what is named; the shot inside it is what a card opens.Opening the Generator, or arriving from a clip in the timeline, opens theSCENE — the thing that has a state, a prompt and a Generate button. */const [selection, setSelection] = useState<GeneratorSelection>(() => ({ jobId: selectedJobId ?? jobs.find((job) => job.status === "generating")?.id ?? jobs[0]?.id ?? "", shotId: null }));- const [, setPlanNotes] = useState<Record<string, string>>({});const [removalTarget, setRemovalTarget] = useState<RemovalTarget | null>(null);const [showDebugPrompt, setShowDebugPrompt] = useState(false);const debugEnabled = useSyncExternalStore(subscribeDebugOptions, loadDebugOptionsEnabled);@@ -299,57 +292,18 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst snapshotFor = (job: GenerationJob, request = requestFor(job)): string =>sceneGenerationSnapshot(job, request);- const logRequest = (event: string, message: string, request: SlopfabGenerationRequest) => writeDiagnostic("info", "generator", event, message, {- jobId: request.jobId,- frames: request.frames,- steps: request.steps,- canvasWidth: request.canvasWidth,- canvasHeight: request.canvasHeight,- referenceCount: request.referencePaths.length,- inputChars: request.prompt.length,- });-- const logFailure = (event: string, jobId: string, reason: unknown) => {- const detail = describeDiagnosticError(reason);- writeDiagnostic("error", "generator", event, detail, { jobId, ...errorContext(reason) });- return detail;- };-const purgeSceneThumbnails = async (job: GenerationJob) => {if (job.outputRelativePath) forgetShotPosters(folderPath, job.outputRelativePath);await purgeTimelineThumbnails(folderPath, job.id).catch(() => undefined);};- /* The engine's own events are listened for by the project screen- (useGenerationEvents), not here: a render outlives this view, and the- encode that turns its frames into a file has to happen wherever the user- happens to be. What this view does with a scene is start it, stop it, and- show what became of it. */-- const prepareOrRetry = async (job: GenerationJob) => {- cancellationRequests.current.delete(job.id);- setCancellingJobIds((current) => current.has(job.id)- ? new Set([...current].filter((id) => id !== job.id))- : current);- const now = new Date().toISOString();- const request = requestFor(job);- if (runtimeReady) await purgeSceneThumbnails(job);- updateJob(job.id, {- status: runtimeReady ? "queued" : "draft",- stage: "queued",- progress: 0,- error: runtimeReady ? null : runtimeError ?? generatorRuntime?.detail ?? "The video engine isn’t available on this computer right now.",- generationSnapshot: runtimeReady ? snapshotFor(job, request) : job.generationSnapshot,- updatedAt: now,+ const submit = (scenes: GenerationJob[]) => {+ if (!runtimeReady) return;+ const submissions = scenes.map((job) => {+ const request = requestFor(job);+ return { job, request, snapshot: snapshotFor(job, request) };});- if (runtimeReady) {- logRequest("generation.retry_requested", "Generation retry requested.", request);- try {- await enqueueSlopfabGeneration(request, configRef.current);- } catch (reason) {- updateJob(job.id, { status: "failed", stage: "failed", error: logFailure("generation.retry_failed", job.id, reason) });- }- }+ onGenerate?.(submissions);};/* A scene now starts EMPTY. There is no box that turns a sentence into a@@ -374,7 +328,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst at = current.generationJobs.findIndex((item) => item.id === job.id);if (at < 0) return;void purgeSceneThumbnails(job);- if (job.status === "generating" || job.status === "queued") void cancelSlopfabGeneration(job.id);+ if (job.status === "generating" || job.status === "queued") void onCancelGeneration?.([job.id]);const generationJobs = current.generationJobs.filter((item) => item.id !== job.id);onChange({ ...current, generationJobs });if (selection.jobId === job.id) {@@ -383,75 +337,10 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo}};- const startDraft = async (job: GenerationJob) => {- if (!runtimeReady) return;- await purgeSceneThumbnails(job);- cancellationRequests.current.delete(job.id);- setCancellingJobIds((current) => current.has(job.id)- ? new Set([...current].filter((id) => id !== job.id))- : current);- const request = requestFor(job);- logRequest("generation.requested", "Generation requested from the scene board.", request);- updateJob(job.id, {- status: "queued",- stage: "queued",- error: null,- generationSnapshot: snapshotFor(job, request),- updatedAt: new Date().toISOString(),- });- try {- /* Resolved before the job is handed over, so "What actually happened"- reports the real frame count and canvas this run was planned as. The- composer used to do this for a scene it had just created; a scene is- now created empty and generated from here, so the plan is resolved- here or nobody ever sees it. */- const plan = await resolveSlopfabPlan(request, configRef.current);- setPlanNotes((current) => ({ ...current, [job.id]: `Planned as ${plan.alignedFrames} frames at ${plan.canvasWidth}×${plan.canvasHeight}. ${plan.boundary}` }));- if (cancellationRequests.current.has(job.id)) return;- await enqueueSlopfabGeneration(request, configRef.current);- } catch (reason) {- if (cancellationRequests.current.has(job.id)) return;- updateJob(job.id, { status: "failed", stage: "failed", error: logFailure("generation.prepare_failed", job.id, reason) });- }- };-- const cancelScenes = async (scenes: GenerationJob[]) => {- const next = scenes.filter((job) =>- (job.status === "queued" || job.status === "generating")- && !cancellationRequests.current.has(job.id));- if (next.length === 0) return;- next.forEach((job) => cancellationRequests.current.add(job.id));- setCancellingJobIds((current) => new Set([...current, ...next.map((job) => job.id)]));- const accepted = await Promise.all(next.map(async (job) => {- try {- return await cancelSlopfabGeneration(job.id);- } catch (reason) {- logFailure("generation.cancel_failed", job.id, reason);- return false;- }- }));- // False means the scene was still in frontend planning and never reached- // slopfab. No backend event will arrive for it, so finish that cancellation- // locally; accepted cancellations are finalized by the normal event path.- const beforeEnqueue = new Set(next.filter((_, index) => !accepted[index]).map((job) => job.id));- if (beforeEnqueue.size > 0) {- const current = configRef.current;- onChange({- ...current,- generationJobs: current.generationJobs.map((job) => beforeEnqueue.has(job.id)- ? { ...job, status: "cancelled", stage: "failed", error: "Generation cancelled before it started.", updatedAt: new Date().toISOString() }- : job),- });- }- };-+ const cancelScenes = (scenes: GenerationJob[]) => onCancelGeneration?.(scenes.map((job) => job.id));const generateScene = (job: GenerationJob) => {- if (job.status === "queued" || job.status === "generating") {- void cancelScenes([job]);- return;- }- if (job.status === "draft") void startDraft(job);- else void prepareOrRetry(job);+ if (job.status === "queued" || job.status === "generating") void cancelScenes([job]);+ else submit([job]);};/** Generate All is an idempotent update for fixed seeds, but a deliberate@@ -467,40 +356,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo|| job.generationSnapshot !== snapshotFor(job);});- const generateAll = async () => {- if (!runtimeReady || batchScenesReady.length === 0) return;- await Promise.all(batchScenesReady.map(purgeSceneThumbnails));- batchScenesReady.forEach((job) => cancellationRequests.current.delete(job.id));- const startingIds = new Set(batchScenesReady.map((job) => job.id));- setCancellingJobIds((current) => {- const next = new Set([...current].filter((id) => !startingIds.has(id)));- return next.size === current.size ? current : next;- });- const current = configRef.current;- const requests = batchScenesReady.map((job) => ({ job, request: requestFor(job) }));- requests.forEach(({ request }) => logRequest("generation.requested", "Generation requested by Generate All.", request));- const ids = new Map(requests.map(({ job, request }) => [job.id, snapshotFor(job, request)]));- const now = new Date().toISOString();- onChange({- ...current,- generationJobs: current.generationJobs.map((job) => ids.has(job.id)- ? { ...job, status: "queued", stage: "queued", progress: 0, error: null, generationSnapshot: ids.get(job.id), updatedAt: now }- : job),- });-- for (const { job, request } of requests) {- if (cancellationRequests.current.has(job.id)) continue;- try {- const plan = await resolveSlopfabPlan(request, current);- setPlanNotes((notes) => ({ ...notes, [job.id]: `Planned as ${plan.alignedFrames} frames at ${plan.canvasWidth}×${plan.canvasHeight}. ${plan.boundary}` }));- if (cancellationRequests.current.has(job.id)) continue;- await enqueueSlopfabGeneration(request, current);- } catch (reason) {- if (cancellationRequests.current.has(job.id)) continue;- updateJob(job.id, { status: "failed", stage: "failed", error: logFailure("generation.prepare_failed", job.id, reason) });- }- }- };+ const generateAll = () => submit(batchScenesReady);const generationBlocker = (job: GenerationJob): string | null => {if (!runtimeReady) return runtimeError ?? generatorRuntime?.detail ?? "The video generator is not ready.";diff --git a/src/components/workspace/useGenerationEvents.test.tsx b/src/components/workspace/useGenerationEvents.test.tsxdeleted file mode 100644index f0a8813..0000000--- a/src/components/workspace/useGenerationEvents.test.tsx+++ /dev/null@@ -1,235 +0,0 @@-// @vitest-environment jsdom--import { listen } from "@tauri-apps/api/event";-import { act, cleanup, render } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { saveGeneratedScene } from "../../lib/generatedVideo";-import { createProjectConfig, parseProjectConfig, type ProjectConfig } from "../../lib/project";-import { useGenerationEvents } from "./useGenerationEvents";--vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));-vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));-vi.mock("../../lib/generatedVideo", () => ({ saveGeneratedScene: vi.fn() }));--const scope = globalThis as unknown as Record<string, unknown>;-/** Handlers the hook registered, by event name. */-const handlers = new Map<string, (event: { payload: unknown }) => void>();--beforeEach(() => {- handlers.clear();- localStorage.clear();- scope.__TAURI_INTERNALS__ = {};- // Cleared, not just re-implemented: one test asserts it was never called.- vi.mocked(listen).mockReset();- vi.mocked(listen).mockImplementation((async (name: string, handler: (event: { payload: unknown }) => void) => {- handlers.set(name, handler);- return () => handlers.delete(name);- }) as unknown as typeof listen);- vi.mocked(saveGeneratedScene).mockReset();-});-afterEach(() => {- cleanup();- delete scope.__TAURI_INTERNALS__;-});--/** A project with one draft scene, and a harness that keeps whatever the hook- * writes — the same shape the workspace holds it in. */-function harness(onCompleted?: (jobId: string) => void, onEstimate?: (jobId: string, completionAt: number | null) => void) {- const fresh = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });- const state = { config: fresh };- function Harness() {- useGenerationEvents({ folderPath: "C:\\Ceramic Lamp", onChange: (update) => { state.config = update(state.config); }, onCompleted, onEstimate });- return null;- }- render(<Harness />);- return { state, jobId: fresh.generationJobs[0].id, job: () => state.config.generationJobs[0] };-}--const emit = async (name: string, payload: unknown) => {- await act(async () => {- handlers.get(name)?.({ payload });- await Promise.resolve();- });-};--const timingProgress = (jobId: string, updates: Record<string, unknown> = {}) => ({- jobId,- stage: "denoising",- step: 0,- totalSteps: 4,- plannedSteps: 4,- elapsedSeconds: 20,- frames: 360,- canvasWidth: 416,- canvasHeight: 416,- referenceCount: 0,- timingProfile: "slopfab=1.4.0|platform=CUDA 13|transformer=test.safetensors",- ...updates,-});--describe("what the app does with the engine's events", () => {- it("saves the frames the moment the engine says they are ready, and records the file", async () => {- vi.mocked(saveGeneratedScene).mockResolvedValue({ relativePath: "media/generated/job-01.mp4", bytes: 4_200_000, note: null });- const completed = vi.fn();- const { jobId, job, state } = harness(completed);- await emit("slopfab-job", { jobId, state: "framesReady", detail: "Frames and audio are ready to be encoded." });-- expect(saveGeneratedScene).toHaveBeenCalledWith(expect.objectContaining({ folderPath: "C:\\Ceramic Lamp", jobId }));- expect(job()).toMatchObject({- status: "completed",- stage: "completed",- progress: 1,- outputRelativePath: "media/generated/job-01.mp4",- error: null,- });- expect(completed).toHaveBeenCalledWith(jobId);- // What was written has to survive a save and a reload, so it has to parse.- expect(parseProjectConfig(state.config)).toBeTruthy();- });-- it("keeps the note when something was left out of the file", async () => {- vi.mocked(saveGeneratedScene).mockResolvedValue({ relativePath: "media/generated/job-01.mp4", bytes: 10, note: "Saved without sound: this computer's encoder would not take the render's audio." });- const { jobId, job } = harness();- await emit("slopfab-job", { jobId, state: "framesReady", detail: "" });- // Finished, with the file — and still saying what is missing from it.- expect(job().status).toBe("completed");- expect(job().error).toMatch(/without sound/);- });-- it("turns a scene placed before generation into playable generated media", async () => {- vi.mocked(saveGeneratedScene).mockResolvedValue({ relativePath: "media/generated/job-initial-brief.mp4", bytes: 10, note: null });- const fresh = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });- const jobId = fresh.generationJobs[0].id;- const assetId = `asset-${jobId}`;- const state = { config: parseProjectConfig({- ...fresh,- assets: [{ id: assetId, kind: "generated", name: "First scene", relativePath: null, sourcePath: null, mimeType: "video/mp4", durationMs: 6000, width: null, height: null, createdAt: fresh.createdAt }],- timeline: { tracks: fresh.timeline.tracks.map((track, index) => index === 0 ? { ...track, clips: [{ id: "clip-scene", assetId, trackId: track.id, startMs: 0, durationMs: 6000, sourceStartMs: 0, label: "First scene", color: null, status: "draft" }] } : track) },- }) };- function Harness() {- useGenerationEvents({ folderPath: "C:\\Ceramic Lamp", onChange: (update) => { state.config = update(state.config); } });- return null;- }- render(<Harness />);- await emit("slopfab-job", { jobId, state: "framesReady", detail: "" });-- expect(state.config.assets[0].relativePath).toBe("media/generated/job-initial-brief.mp4");- expect(state.config.timeline.tracks[0].clips[0].status).toBe("generated");- expect(parseProjectConfig(state.config)).toBeTruthy();- });-- it("calls a render that could not be written a failure, not a finished scene", async () => {- vi.mocked(saveGeneratedScene).mockRejectedValue(new Error("This computer's encoder refused every H.264 configuration."));- const { jobId, job } = harness();- await emit("slopfab-job", { jobId, state: "framesReady", detail: "" });- expect(job()).toMatchObject({ status: "failed", stage: "failed" });- expect(job().error).toMatch(/rendered but could not be saved/);- // Nothing to insert into a timeline, and the job must not claim otherwise.- expect(job().outputRelativePath ?? null).toBeNull();- });-- it("encodes one set of frames once, however many times the event arrives", async () => {- let release = () => undefined as void;- vi.mocked(saveGeneratedScene).mockImplementation(() => new Promise((resolve) => {- release = () => resolve({ relativePath: "media/generated/job-01.mp4", bytes: 1, note: null });- }));- const { jobId } = harness();- await emit("slopfab-job", { jobId, state: "framesReady", detail: "" });- await emit("slopfab-job", { jobId, state: "framesReady", detail: "" });- expect(saveGeneratedScene).toHaveBeenCalledTimes(1);- await act(async () => { release(); await Promise.resolve(); });- });-- it("carries progress through the render and then through the encode", async () => {- let report: ((encoded: number, total: number) => void) | undefined;- vi.mocked(saveGeneratedScene).mockImplementation(async (options) => {- report = options.onProgress;- return { relativePath: "media/generated/job-01.mp4", bytes: 1, note: null };- });- const { jobId, job } = harness();-- await emit("slopfab-progress", { jobId, stage: "denoising", step: 25, totalSteps: 50 });- const rendering = job().progress;- expect(job().status).toBe("generating");- // Rendering never reaches the part of the bar encoding owns, so a finished- // render cannot look like a stalled one.- expect(rendering).toBeGreaterThan(0.12);- expect(rendering).toBeLessThan(0.9);-- await emit("slopfab-job", { jobId, state: "framesReady", detail: "" });- await act(async () => { report?.(60, 120); await Promise.resolve(); });- expect(job().status).toBe("completed");- });-- it("never rolls overall progress back when a later stage reports a smaller local counter", async () => {- const { jobId, job } = harness();- await emit("slopfab-progress", { jobId, stage: "denoising", step: 40, totalSteps: 50 });- const furthest = job().progress;- await emit("slopfab-progress", { jobId, stage: "audioDecode", step: 0, totalSteps: 0 });- expect(job().progress).toBe(furthest);- expect(job().progress).toBeGreaterThan(0.7);- });-- it("estimates render completion from slopfab elapsed time and completed steps", async () => {- const onEstimate = vi.fn();- const now = vi.spyOn(Date, "now").mockReturnValue(1_000);- const { jobId } = harness(undefined, onEstimate);-- await emit("slopfab-progress", timingProgress(jobId));- expect(onEstimate).toHaveBeenLastCalledWith(jobId, null);-- now.mockReturnValue(11_000);- await emit("slopfab-progress", timingProgress(jobId, { step: 1, elapsedSeconds: 30 }));- const completionAt = onEstimate.mock.lastCall?.[1];- // Ten measured seconds per step and two steps remain.- expect(completionAt).toBe(31_000);-- vi.mocked(saveGeneratedScene).mockResolvedValue({ relativePath: "media/generated/job-01.mp4", bytes: 1, note: null });- await emit("slopfab-job", { jobId, state: "framesReady", detail: "" });- expect(onEstimate).toHaveBeenLastCalledWith(jobId, null);- now.mockRestore();- });-- it("passes queued, failed and cancelled through as themselves", async () => {- const { jobId, job } = harness();- await emit("slopfab-job", { jobId, state: "queued", detail: "Queued behind any active slopfab generation." });- expect(job()).toMatchObject({ status: "queued", stage: "queued" });-- await emit("slopfab-job", { jobId, state: "failed", detail: "The transformer weights could not be read." });- expect(job()).toMatchObject({ status: "failed", stage: "failed", error: "The transformer weights could not be read." });-- await emit("slopfab-job", { jobId, state: "cancelled", detail: "Generation cancelled at the next slopfab checkpoint." });- expect(job()).toMatchObject({ status: "cancelled", stage: "failed" });- expect(saveGeneratedScene).not.toHaveBeenCalled();- });-- it("listens for nothing in the browser preview, where there is no engine", () => {- delete scope.__TAURI_INTERNALS__;- harness();- expect(listen).not.toHaveBeenCalled();- });-});--/** The workspace holds the config this hook writes into; a stale copy would- * undo whatever else the app did while a render was running. */-describe("how the hook writes", () => {- it("hands up an updater rather than a config it read minutes ago", async () => {- vi.mocked(saveGeneratedScene).mockResolvedValue({ relativePath: "media/generated/job-01.mp4", bytes: 1, note: null });- const writes: Array<(current: ProjectConfig) => ProjectConfig> = [];- const fresh = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });- function Harness() {- useGenerationEvents({ folderPath: "C:\\Ceramic Lamp", onChange: (update) => { writes.push(update); } });- return null;- }- render(<Harness />);- await emit("slopfab-job", { jobId: fresh.generationJobs[0].id, state: "framesReady", detail: "" });- expect(writes.length).toBeGreaterThan(0);- expect(writes.every((write) => typeof write === "function")).toBe(true);- // Applied to a config the hook never saw — a project renamed while the- // render ran — the rename survives and the scene is still finished.- const renamed = { ...fresh, name: "Renamed mid-render" };- const result = writes.reduce((config, write) => write(config), renamed);- expect(result.name).toBe("Renamed mid-render");- expect(result.generationJobs[0].outputRelativePath).toBe("media/generated/job-01.mp4");- });-});diff --git a/src/components/workspace/useGenerationEvents.ts b/src/components/workspace/useGenerationEvents.tsdeleted file mode 100644index 5a7ed23..0000000--- a/src/components/workspace/useGenerationEvents.ts+++ /dev/null@@ -1,228 +0,0 @@-import { listen } from "@tauri-apps/api/event";-import { useEffect, useRef } from "react";-import { describeDiagnosticError, errorContext, writeDiagnostic } from "../../lib/diagnostics";-import { GenerationTimingEstimator, type CompletedGenerationTiming, type GenerationTimingProgress } from "../../lib/generationTiming";-import { saveGeneratedScene } from "../../lib/generatedVideo";-import { isTauri } from "../../lib/persistence";-import { generationAssetId, type GenerationJob, type ProjectConfig } from "../../lib/project";--/* Everything the video engine says about a scene, and what to do about it.- *- * This lives in the WORKSPACE rather than in the Generator, and that is the- * point: a render takes minutes, and the natural thing to do while it runs is- * to go and work on the timeline. When these listeners were mounted by the- * Generator, doing that unmounted them — progress stopped landing, and the- * event announcing a finished render arrived at nobody. Now the whole project- * screen carries them, so a scene that finishes while the user is somewhere- * else is still recorded and still saved.- *- * Saving is the second half. slopfab produces pictures and frees them; a finished- * render is a few hundred megabytes waiting in Rust's memory that nothing else- * will claim. As soon as the engine says the frames are ready, this encodes- * them (see lib/generatedVideo.ts) and writes the .mp4 into the project. */--/** The event the queue emits when a scene's state changes. */-interface JobEvent {- jobId: string;- state: "queued" | "framesReady" | "failed" | "cancelled" | string;- detail: string;- output?: CompletedGenerationTiming | null;-}--type ProgressEvent = GenerationTimingProgress;--/** Rendering is most of the wait, so it owns most of the bar; encoding is the- * last slice, and it gets its own so a finished render does not sit at 92%- * looking stalled while the encoder works. */-const RENDER_CEILING = 0.9;-const ENCODE_FLOOR = 0.9;-const RENDER_PROGRESS_END = RENDER_CEILING - 0.02;--export function useGenerationEvents({ folderPath, onChange, onCompleted, onEstimate }: {- folderPath: string;- /** The updater form, always: every write here happens after an await, so the- * config this component last saw is not the one to build from. */- onChange: (update: (current: ProjectConfig) => ProjectConfig) => void;- /** Called only after the MP4 path, generated asset, and timeline clip state- * have all been committed to the in-memory project. The workspace uses this- * exact boundary to persist the finished generation without waiting for the- * user to click Save. */- onCompleted?: (jobId: string) => void;- /** A transient prediction of when rendering (not file encoding) will finish,- * based on slopfab's elapsed time and completed steps. It is deliberately- * kept out of ProjectConfig: an estimate is live UI telemetry, not project- * data worth saving. */- onEstimate?: (jobId: string, completionAt: number | null) => void;-}) {- /* Held in refs so the subscription is made ONCE. It has to be: re-subscribing- on every progress tick would drop events in the gap, and these events are- the only record that a render happened at all. */- const write = useRef(onChange);- write.current = onChange;- const completed = useRef(onCompleted);- completed.current = onCompleted;- const estimate = useRef(onEstimate);- estimate.current = onEstimate;- const folder = useRef(folderPath);- folder.current = folderPath;- /** Scenes already being encoded, so a repeated event — or a remount in- * StrictMode — cannot start a second encode of the same frames. */- const saving = useRef(new Set<string>());- const timingEstimator = useRef<GenerationTimingEstimator | null>(null);- if (timingEstimator.current === null) timingEstimator.current = new GenerationTimingEstimator();-- useEffect(() => {- if (!isTauri()) return;- let disposed = false;- const updateJob = (jobId: string, updates: Partial<GenerationJob>) => {- write.current((current) => ({- ...current,- generationJobs: current.generationJobs.map((job) => (job.id === jobId ? { ...job, ...updates, updatedAt: new Date().toISOString() } : job)),- }));- };- const updateProgress = (jobId: string, progress: number, stage: GenerationJob["stage"]) => {- write.current((current) => ({- ...current,- generationJobs: current.generationJobs.map((job) => {- if (job.id !== jobId || job.status === "ready" || job.status === "completed" || job.status === "failed" || job.status === "cancelled") return job;- return {- ...job,- status: "generating",- stage,- // slopfab stages do not share one counter. A later stage can report- // a smaller local percentage, but overall progress cannot regress.- progress: Math.max(job.progress, progress),- updatedAt: new Date().toISOString(),- };- }),- }));- };- const clearEstimate = (jobId: string) => {- timingEstimator.current?.clear(jobId);- estimate.current?.(jobId, null);- };-- /** Encode the frames the engine just finished, and write the file.- *- * This deliberately keeps going after `disposed`: the project screen can- * unmount while an encode is in flight, and stopping there would leave the- * frames in memory and the scene with nothing to show for the render. The- * writes it makes are updaters against whatever config is current, and the- * Rust side is told to let the frames go either way. */- const save = async (jobId: string) => {- if (saving.current.has(jobId)) return;- saving.current.add(jobId);- writeDiagnostic("info", "generation", "encoding.started", "Encoding rendered frames into a project video.", { jobId });- updateJob(jobId, { status: "ready", stage: "encoding", progress: ENCODE_FLOOR, error: null });- try {- const saved = await saveGeneratedScene({- folderPath: folder.current,- jobId,- onProgress: (encoded, total) => {- if (total > 0) updateJob(jobId, { progress: Math.min(0.99, ENCODE_FLOOR + (encoded / total) * (1 - ENCODE_FLOOR)) });- },- });- const completedAt = new Date().toISOString();- const assetId = generationAssetId(jobId);- write.current((current) => ({- ...current,- generationJobs: current.generationJobs.map((job) => job.id === jobId ? {- ...job,- status: "completed",- stage: "completed",- progress: 1,- outputRelativePath: saved.relativePath,- // A note means something was left out of the file — the file exists- // and the scene is finished, so this is not a failure, but it is not- // silence either.- error: saved.note,- updatedAt: completedAt,- } : job),- assets: current.assets.map((asset) => asset.id === assetId ? {- ...asset,- kind: "generated",- relativePath: saved.relativePath,- sourcePath: null,- mimeType: "video/mp4",- hasAudio: saved.hasAudio ?? asset.hasAudio ?? null,- } : asset),- timeline: {- tracks: current.timeline.tracks.map((track) => ({- ...track,- clips: track.clips.map((clip) => clip.assetId === assetId ? { ...clip, status: "generated" } : clip),- })),- },- }));- writeDiagnostic(saved.note ? "warn" : "info", "generation", "encoding.completed", saved.note ?? "Rendered scene was encoded and written.", {- jobId, bytes: saved.bytes, relativePath: saved.relativePath, hasAudio: saved.hasAudio ?? null,- });- completed.current?.(jobId);- } catch (reason) {- /* The render happened and the file did not. Failed is the honest state:- there is nothing to insert into the timeline, and the only way to get- this scene is to run it again. */- const detail = describeDiagnosticError(reason);- writeDiagnostic("error", "generation", "encoding.failed", detail, { jobId, ...errorContext(reason) });- updateJob(jobId, {- status: "failed",- stage: "failed",- error: `The scene rendered but could not be saved as a video file. ${detail}`,- });- } finally {- saving.current.delete(jobId);- }- };-- const subscriptions = Promise.all([- listen<ProgressEvent>("slopfab-progress", ({ payload }) => {- if (disposed) return;- const progress = payload.totalSteps > 0- ? Math.min(RENDER_PROGRESS_END, 0.12 + (Math.max(0, payload.step) / payload.totalSteps) * (RENDER_CEILING - 0.14))- : payload.stage === "delivering" ? RENDER_PROGRESS_END : 0.08;- estimate.current?.(payload.jobId, timingEstimator.current?.update(payload) ?? null);- updateProgress(- payload.jobId,- progress,- payload.stage === "starting" || payload.stage === "transformerLoad" ? "preparing" : "generating",- );- }),- listen<JobEvent>("slopfab-job", ({ payload }) => {- if (disposed) return;- writeDiagnostic(payload.state === "failed" ? "error" : payload.state === "cancelled" ? "warn" : "info", "generation", "native_event.received", payload.detail || `Generation state changed to ${payload.state}.`, {- jobId: payload.jobId, state: payload.state,- });- if (payload.state === "framesReady") {- if (payload.output) {- timingEstimator.current?.record(payload.output);- writeDiagnostic("info", "generation", "timing.calibrated", "Generation timing calibration was updated.", {- jobId: payload.jobId,- secondsConditioning: payload.output.secondsConditioning,- secondsDenoise: payload.output.secondsDenoise,- secondsVideoDecode: payload.output.secondsVideoDecode,- secondsAudioDecode: payload.output.secondsAudioDecode,- secondsTotal: payload.output.secondsTotal,- stepsComputed: payload.output.stepsComputed,- stepsSkipped: payload.output.stepsSkipped,- });- }- clearEstimate(payload.jobId);- void save(payload.jobId);- return;- }- clearEstimate(payload.jobId);- updateJob(payload.jobId, payload.state === "failed"- ? { status: "failed", stage: "failed", error: payload.detail }- : payload.state === "cancelled"- ? { status: "cancelled", stage: "failed", error: payload.detail }- : { status: "queued", stage: "queued" });- }),- ]);- void subscriptions.catch((reason) => {- writeDiagnostic("error", "generation", "event_subscription.failed", describeDiagnosticError(reason), errorContext(reason));- });- return () => {- disposed = true;- void subscriptions.then((unlisten) => unlisten.forEach((stop) => stop()));- };- }, []);-}diff --git a/src/lib/generatedVideo.ts b/src/lib/generatedVideo.tsindex 1c5a47f..1693bf1 100644--- a/src/lib/generatedVideo.ts+++ b/src/lib/generatedVideo.ts@@ -45,6 +45,9 @@ export interface SavedGeneration {note: string | null;/** Whether the saved MP4 actually contains an audio stream. */hasAudio?: boolean;+ width?: number;+ height?: number;+ durationMs?: number;}/** How often a keyframe is written: every two seconds, so the file can be@@ -326,6 +329,8 @@ async function encodeAudio(export async function saveGeneratedScene(options: {folderPath: string;jobId: string;+ /** Queue runs have unique IDs; timeline caches still belong to the scene. */+ thumbnailJobId?: string;/** Called as frames go into the encoder, for the progress bar. */onProgress?: (encoded: number, total: number) => void;}): Promise<SavedGeneration> {@@ -427,8 +432,8 @@ export async function saveGeneratedScene(options: {muxer.finalize();const written = await writeGeneratedVideo(folderPath, jobId, new Uint8Array(target.buffer));await Promise.allSettled(timelineThumbnails.map((thumbnail) =>- writeTimelineThumbnail(folderPath, jobId, thumbnail.timeMs, thumbnail.bytes)));- return { relativePath: written.relativePath, bytes: written.bytes, note, hasAudio: withAudio };+ writeTimelineThumbnail(folderPath, options.thumbnailJobId ?? jobId, thumbnail.timeMs, thumbnail.bytes)));+ return { relativePath: written.relativePath, bytes: written.bytes, note, hasAudio: withAudio, width: summary.width, height: summary.height, durationMs: Math.round(summary.frameCount / summary.fps * 1000) };} finally {// Whatever happened, the render stops occupying memory here.await releaseRendered(jobId);diff --git a/src/lib/project.ts b/src/lib/project.tsindex e75db98..2c189e6 100644--- a/src/lib/project.ts+++ b/src/lib/project.ts@@ -161,7 +161,7 @@ export const projectAssetSchema = z.object({checkOneLocation(asset, context, `Asset '${asset.id}'`);/* A scene may be arranged on the timeline before it has been rendered. Its* generated asset is the stable thing the clip points at while the file is- * still absent; useGenerationEvents fills the path in when rendering ends. */+ * still absent; WorkQueue fills the path in when rendering ends. */if (asset.kind !== "generated" && !asset.relativePath && !asset.sourcePath) {context.addIssue({code: z.ZodIssueCode.custom, path: ["relativePath"],diff --git a/src/lib/projectSession.ts b/src/lib/projectSession.tsnew file mode 100644index 0000000..3d0f174--- /dev/null+++ b/src/lib/projectSession.ts@@ -0,0 +1,49 @@+import { describeDiagnosticError, writeDiagnostic } from "./diagnostics";+import type { ProjectConfig, ProjectRecord } from "./project";++export type ProjectUpdate = ProjectConfig | ((current: ProjectConfig) => ProjectConfig);+export type ProjectWriter = (record: ProjectRecord) => Promise<ProjectRecord | void>;++/** The editable document and its ordered writes outlive any workspace view. */+export class ProjectSession {+ private state: { config: ProjectConfig; dirty: boolean; saving: boolean; saveError: string | null };+ private listeners = new Set<() => void>();+ private writes = Promise.resolve();+ private revision = 0;+ private pending = 0;+ constructor(readonly record: ProjectRecord, private writer: ProjectWriter) {+ this.state = { config: record.config, dirty: false, saving: false, saveError: null };+ }+ getSnapshot = () => this.state;+ subscribe = (listener: () => void) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; };+ private publish(patch: Partial<typeof this.state>) {+ this.state = { ...this.state, ...patch };+ this.listeners.forEach((listener) => listener());+ }+ update = (next: ProjectUpdate, dirty = true) => {+ const config = typeof next === "function" ? next(this.state.config) : next;+ if (config === this.state.config) return;+ if (dirty) this.revision += 1;+ this.publish({ config, dirty: this.state.dirty || dirty });+ };+ dismissError = () => this.publish({ saveError: null });+ save = (): Promise<void> => {+ const revision = this.revision;+ const record = { ...this.record, config: this.state.config };+ this.pending += 1;+ this.publish({ saving: true, saveError: null });+ const write = this.writes.catch(() => undefined).then(() => this.writer(record));+ this.writes = write.then(() => undefined, () => undefined);+ return write.then(() => {+ if (this.revision === revision) this.publish({ dirty: false });+ }).catch((reason) => {+ const detail = describeDiagnosticError(reason);+ this.publish({ saveError: detail });+ writeDiagnostic("error", "project-session", "project.save_failed", detail, { projectId: record.config.id, folderPath: record.folderPath });+ throw reason;+ }).finally(() => {+ this.pending -= 1;+ if (this.pending === 0) this.publish({ saving: false });+ });+ };+}diff --git a/src/lib/runtime.ts b/src/lib/runtime.tsindex 6606be7..bac65b0 100644--- a/src/lib/runtime.ts+++ b/src/lib/runtime.ts@@ -7,7 +7,7 @@ import {} from "./project";import {agentEndpointProviderSettings, endpointProviderSetting, engineProviderSetting,- loadDefaultGenerationSteps, loadEngineSettings, withAgentEndpointSettings, withEngineSettings,+ loadDefaultGenerationSteps, loadEngineSettings, withAgentEndpointSettings,type EndpointProviderId, type EndpointProviderSettings, type EnginePathField,} from "./settings";@@ -198,7 +198,7 @@ export async function cancelAgentTurn(requestId: string): Promise<boolean> {}export async function resolveSlopfabPlan(request: SlopfabGenerationRequest, config: ProjectConfig): Promise<ResolvedPlan> {- if (isTauri()) return invoke<ResolvedPlan>("resolve_slopfab_plan", { request, config: withEngineSettings(config) });+ if (isTauri()) return invoke<ResolvedPlan>("resolve_slopfab_plan", { request, config });const alignedFrames = Math.ceil(Math.max(5, request.frames - 5) / 17) * 17 + 5;return {canvasWidth: request.canvasWidth,@@ -214,7 +214,7 @@ export async function resolveSlopfabPlan(request: SlopfabGenerationRequest, conf}export async function enqueueSlopfabGeneration(request: SlopfabGenerationRequest, config: ProjectConfig): Promise<void> {- if (isTauri()) await invoke("enqueue_slopfab_generation", { request, config: withEngineSettings(config) });+ if (isTauri()) await invoke("enqueue_slopfab_generation", { request, config });}export async function cancelSlopfabGeneration(jobId: string): Promise<boolean> {diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.tsnew file mode 100644index 0000000..1888ca2--- /dev/null+++ b/src/lib/workQueue.test.ts@@ -0,0 +1,221 @@+// @vitest-environment jsdom+import { waitFor } from "@testing-library/react";+import { listen } from "@tauri-apps/api/event";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { releaseRendered, saveGeneratedScene } from "./generatedVideo";+import { createProjectConfig, parseProjectConfig, type ProjectRecord } from "./project";+import { ProjectSession } from "./projectSession";+import { cancelSlopfabGeneration, enqueueSlopfabGeneration, resolveSlopfabPlan } from "./runtime";+import { saveEngineSettings, EMPTY_ENGINE_SETTINGS } from "./settings";+import { WorkQueue, type GenerationSubmission } from "./workQueue";++vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));+vi.mock("./generatedVideo", () => ({ saveGeneratedScene: vi.fn(), releaseRendered: vi.fn(async () => true) }));+vi.mock("./timelineThumbnails", () => ({ purgeTimelineThumbnails: vi.fn(async () => undefined) }));+vi.mock("./runtime", () => ({ cancelSlopfabGeneration: vi.fn(), enqueueSlopfabGeneration: vi.fn(), resolveSlopfabPlan: vi.fn() }));+const handlers = new Map<string, (event: { payload: unknown }) => void>();+const stops: (() => void)[] = [];+const plan = { alignedFrames: 120, canvasWidth: 736, canvasHeight: 416, boundary: "Test plan" };+beforeEach(() => {+ localStorage.clear();+ handlers.clear();+ vi.clearAllMocks();+ Object.assign(window, { __TAURI_INTERNALS__: {} });+ vi.mocked(listen).mockImplementation((async (name: string, handler: (event: { payload: unknown }) => void) => { handlers.set(name, handler); return () => { handlers.delete(name); }; }) as typeof listen);+ vi.mocked(resolveSlopfabPlan).mockResolvedValue(plan as Awaited<ReturnType<typeof resolveSlopfabPlan>>);+ vi.mocked(enqueueSlopfabGeneration).mockResolvedValue(undefined);+ vi.mocked(cancelSlopfabGeneration).mockResolvedValue(true);+ vi.mocked(saveGeneratedScene).mockResolvedValue({ relativePath: "media/generated/result.mp4", bytes: 100, hasAudio: true, note: null });+});+afterEach(() => { stops.splice(0).forEach((stop) => stop()); delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__; vi.restoreAllMocks(); });+const project = (name: string): ProjectRecord => ({ folderPath: `C:/${name}`, config: createProjectConfig({ name, prompt: "A quiet scene", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 30 }) });+const submission = (session: ProjectSession): GenerationSubmission => ({+ job: session.getSnapshot().config.generationJobs[0], snapshot: "submitted settings",+ request: { jobId: "job-initial-brief", prompt: "Original prompt", frames: 120, steps: 12, seed: 42, canvasWidth: 736, canvasHeight: 416, referencePaths: ["C:/reference.png"] },+});+const setup = () => {+ const saved = vi.fn(async (record: ProjectRecord) => record);+ const queue = new WorkQueue(saved);+ stops.push(queue.start());+ return { queue, saved, first: queue.project(project("First")), second: queue.project(project("Second")) };+};+const emit = (name: string, payload: unknown) => handlers.get(name)?.({ payload });+const finish = async (queue: WorkQueue, id: string) => {+ emit("slopfab-job", { jobId: id, state: "framesReady", detail: "Frames ready" });+ await waitFor(() => expect(queue.getSnapshot().find((item) => item.id === id)?.status).toBe("completed"));+};++describe("application work queue", () => {+ it("isolates identical scene IDs across projects and freezes inputs before any asynchronous preparation", async () => {+ const { queue, first, second } = setup();+ saveEngineSettings({ ...EMPTY_ENGINE_SETTINGS, transformer: "C:/original-model" });+ const next = submission(second);+ queue.enqueue(first, [submission(first)]);+ queue.enqueue(second, [next]);+ const [a, b] = queue.getSnapshot();+ expect(a.id).not.toBe(b.id);+ expect(a.sceneId).toBe(b.sceneId);+ expect(b.status).toBe("queued");+ next.request.prompt = "Mutated input";+ next.request.referencePaths.push("C:/other.png");+ second.update((current) => ({ ...current, name: "Edited later", settings: { ...current.settings, resolution: "1344p" }, generationJobs: current.generationJobs.map((job) => ({ ...job, soundscape: "Rain added later", steps: 30 })) }));+ saveEngineSettings({ ...EMPTY_ENGINE_SETTINGS, transformer: "C:/different-model" });+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1));+ await finish(queue, a.id);+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(2));+ const [request, frozen] = vi.mocked(enqueueSlopfabGeneration).mock.calls[1];+ expect(request).toMatchObject({ jobId: b.id, prompt: "Original prompt", steps: 12, canvasWidth: 736, referencePaths: ["C:/reference.png"] });+ expect(frozen.name).toBe("Second");+ expect(frozen.settings.resolution).toBe("416p");+ expect(JSON.stringify(frozen.providerSettings)).toContain("C:/original-model");+ await finish(queue, b.id);+ expect(saveGeneratedScene).toHaveBeenLastCalledWith(expect.objectContaining({ folderPath: "C:/Second", jobId: b.id, thumbnailJobId: b.sceneId }));+ expect(second.getSnapshot().config.name).toBe("Edited later");+ expect(second.getSnapshot().config.generationJobs[0]).toMatchObject({ status: "completed", steps: 30, soundscape: "Rain added later", generationSnapshot: "submitted settings" });+ expect(second.getSnapshot().config.assets[0]).toMatchObject({ id: `asset-${b.sceneId}`, relativePath: "media/generated/result.mp4", width: 736, height: 416, durationMs: 5000 });+ expect(parseProjectConfig(second.getSnapshot().config)).toBeTruthy();+ });++ it("cancels queued work immediately and never submits it to the engine", async () => {+ const { queue, first, second } = setup();+ queue.enqueue(first, [submission(first)]);+ queue.enqueue(second, [submission(second)]);+ const [a, b] = queue.getSnapshot();+ await queue.cancel(b.id);+ expect(queue.getSnapshot()[1].status).toBe("cancelled");+ expect(second.getSnapshot().config.generationJobs[0].status).toBe("cancelled");+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1));+ await finish(queue, a.id);+ expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1);+ expect(cancelSlopfabGeneration).not.toHaveBeenCalled();+ });++ it("cancels during planning without a late enqueue", async () => {+ let planned!: (value: Awaited<ReturnType<typeof resolveSlopfabPlan>>) => void;+ vi.mocked(resolveSlopfabPlan).mockImplementationOnce(() => new Promise((resolve) => { planned = resolve; }));+ const { queue, first } = setup();+ queue.enqueue(first, [submission(first)]);+ await waitFor(() => expect(resolveSlopfabPlan).toHaveBeenCalled());+ await queue.cancel(queue.getSnapshot()[0].id);+ planned(plan as Awaited<ReturnType<typeof resolveSlopfabPlan>>);+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(enqueueSlopfabGeneration).not.toHaveBeenCalled();+ });++ it("cancels a render even when cancellation races with the native enqueue acknowledgement", async () => {+ let accepted!: () => void;+ vi.mocked(enqueueSlopfabGeneration).mockImplementationOnce(() => new Promise((resolve) => { accepted = resolve; }));+ const { queue, first } = setup();+ queue.enqueue(first, [submission(first)]);+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalled());+ const id = queue.getSnapshot()[0].id;+ await queue.cancel(id);+ accepted();+ await waitFor(() => expect(cancelSlopfabGeneration).toHaveBeenCalledWith(id));+ emit("slopfab-job", { jobId: id, state: "cancelled", detail: "Stopped" });+ expect(queue.getSnapshot()[0].status).toBe("cancelled");+ });++ it("waits for encoding and project persistence, and encodes duplicate completion events only once", async () => {+ let encoded!: (value: Awaited<ReturnType<typeof saveGeneratedScene>>) => void;+ vi.mocked(saveGeneratedScene).mockImplementationOnce(() => new Promise((resolve) => { encoded = resolve; }));+ const { queue, first, second, saved } = setup();+ queue.enqueue(first, [submission(first)]);+ queue.enqueue(second, [submission(second)]);+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1));+ const id = queue.getSnapshot()[0].id;+ emit("slopfab-job", { jobId: id, state: "framesReady" });+ emit("slopfab-job", { jobId: id, state: "framesReady" });+ expect(saveGeneratedScene).toHaveBeenCalledTimes(1);+ expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1);+ expect(queue.getSnapshot()[0].status).toBe("encoding");+ let persisted!: (record: ProjectRecord) => void;+ saved.mockImplementationOnce(() => new Promise((resolve) => { persisted = resolve; }));+ encoded({ relativePath: "media/generated/finished.mp4", bytes: 100, note: "Saved without sound" });+ await waitFor(() => expect(saved).toHaveBeenCalledTimes(2));+ expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1);+ persisted({ ...first.record, config: first.getSnapshot().config });+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(2));+ expect(first.getSnapshot().config.generationJobs[0].error).toBe("Saved without sound");+ });++ it("moves on after a failure, ignores stale events, and can retry a failed project save without rerendering", async () => {+ const { queue, first, second, saved } = setup();+ queue.enqueue(first, [submission(first)]);+ queue.enqueue(second, [submission(second)]);+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1));+ const [a, b] = queue.getSnapshot();+ emit("slopfab-job", { jobId: a.id, state: "failed", detail: "Missing weights" });+ emit("slopfab-progress", { jobId: a.id, step: 5, totalSteps: 10 });+ expect(first.getSnapshot().config.generationJobs[0].status).toBe("failed");+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(2));+ saved.mockRejectedValueOnce(new Error("Project file locked"));+ emit("slopfab-job", { jobId: b.id, state: "framesReady" });+ await waitFor(() => expect(queue.getSnapshot()[1].needsSave).toBe(true));+ queue.clearFinished();+ expect(queue.getSnapshot()).toHaveLength(1);+ await queue.retrySave(b.id);+ expect(queue.getSnapshot()[0]).toMatchObject({ status: "completed", needsSave: false });+ expect(saveGeneratedScene).toHaveBeenCalledTimes(1);+ });++ it("preserves monotonic progress and clears the estimate when encoding begins", async () => {+ const { queue, first } = setup();+ queue.enqueue(first, [submission(first)]);+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1));+ const id = queue.getSnapshot()[0].id;+ emit("slopfab-progress", { jobId: id, stage: "denoising", step: 40, totalSteps: 50 });+ const progress = queue.getSnapshot()[0].progress;+ emit("slopfab-progress", { jobId: id, stage: "audioDecode", step: 0, totalSteps: 0 });+ emit("slopfab-job", { jobId: id, state: "queued" });+ expect(queue.getSnapshot()[0]).toMatchObject({ progress, status: "generating" });+ expect(progress).toBeGreaterThan(0.7);+ await finish(queue, id);+ expect(queue.getSnapshot()[0].completionAt).toBeNull();+ });++ it("rejects duplicate submissions and prevents deletion of a project with unfinished work", () => {+ const { queue, first } = setup();+ queue.enqueue(first, [submission(first), submission(first)]);+ expect(queue.getSnapshot()).toHaveLength(1);+ expect(() => queue.forgetProject(first.record)).toThrow(/Cancel or finish/);+ expect(queue.project(first.record)).toBe(first);+ });++ it("does not revive cancelled work when a late rendered event arrives", async () => {+ const { queue, first, second } = setup();+ queue.enqueue(first, [submission(first)]);+ queue.enqueue(second, [submission(second)]);+ const id = queue.getSnapshot()[1].id;+ await queue.cancel(id);+ emit("slopfab-job", { jobId: id, state: "framesReady" });+ expect(releaseRendered).toHaveBeenCalledWith(id);+ expect(saveGeneratedScene).not.toHaveBeenCalled();+ });+ it("makes interrupted scenes restartable after the application has closed", () => {+ const record = project("Interrupted");+ record.config.generationJobs[0].status = "generating";+ const queue = new WorkQueue(async () => undefined);+ const job = queue.project(record).getSnapshot().config.generationJobs[0];+ expect(job.status).toBe("failed");+ expect(job.error).toContain("interrupted");+ expect(queue.getSnapshot()).toEqual([]);+ });+});++describe("project sessions", () => {+ it("orders saves and keeps edits made during a save dirty", async () => {+ let finish!: () => void;+ const writer = vi.fn((_record: ProjectRecord) => new Promise<void>((resolve) => { finish = resolve; }));+ const session = new ProjectSession(project("First"), writer);+ session.update((config) => ({ ...config, name: "Before save" }));+ const saving = session.save();+ await waitFor(() => expect(writer).toHaveBeenCalledTimes(1));+ session.update((config) => ({ ...config, name: "After save" }));+ finish(); await saving;+ expect(session.getSnapshot().dirty).toBe(true);+ expect(session.getSnapshot().config.name).toBe("After save");+ expect(writer.mock.calls[0][0].config.name).toBe("Before save");+ });+});diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.tsnew file mode 100644index 0000000..f3848fe--- /dev/null+++ b/src/lib/workQueue.ts@@ -0,0 +1,284 @@+import { listen } from "@tauri-apps/api/event";+import { describeDiagnosticError, writeDiagnostic } from "./diagnostics";+import { GenerationTimingEstimator, type CompletedGenerationTiming, type GenerationTimingProgress } from "./generationTiming";+import { releaseRendered, saveGeneratedScene } from "./generatedVideo";+import { isTauri, saveProject } from "./persistence";+import { generationAssetId, GENERATION_FRAME_RATE, type GenerationJob, type ProjectRecord, type ProjectConfig } from "./project";+import { ProjectSession, type ProjectWriter } from "./projectSession";+import { cancelSlopfabGeneration, enqueueSlopfabGeneration, resolveSlopfabPlan, type SlopfabGenerationRequest } from "./runtime";+import { withEngineSettings } from "./settings";+import { purgeTimelineThumbnails } from "./timelineThumbnails";++export type WorkStatus = "queued" | "preparing" | "generating" | "encoding" | "completed" | "failed" | "cancelled";+export interface GenerationSubmission { job: GenerationJob; request: SlopfabGenerationRequest; snapshot: string }+export interface WorkItem {+ id: string;+ projectKey: string;+ folderPath: string;+ projectName: string;+ sceneId: string;+ title: string;+ submittedAt: string;+ status: WorkStatus;+ progress: number;+ detail: string;+ error: string | null;+ completionAt: number | null;+ cancelling: boolean;+ needsSave: boolean;+ settings: { frames: number; steps: number; seed: number; canvasWidth: number; canvasHeight: number };+}+interface PendingWork {+ id: string;+ session: ProjectSession;+ sceneId: string;+ request: SlopfabGenerationRequest;+ config: ProjectConfig;+ snapshot: string;+ cancelled: boolean;+ submitted: boolean;+ done: Promise<void>;+ finish: () => void;+}+interface JobEvent { jobId: string; state: string; detail: string; output?: CompletedGenerationTiming | null }++export const isWorkActive = (work: WorkItem) => !["completed", "failed", "cancelled"].includes(work.status);+export const projectQueueKey = (record: ProjectRecord) => {+ const path = record.folderPath.replaceAll("\\", "/").replace(/\/$/, "");+ const normalized = /^[a-z]:\//i.test(path) || path.startsWith("//") ? path.toLowerCase() : path;+ return `${normalized}::${record.config.id}`;+};++/** App-owned FIFO. A render includes encoding and saving before the next one+ * starts, so native frame buffers cannot evict work still being encoded. */+export class WorkQueue {+ private projects = new Map<string, ProjectSession>();+ private work = new Map<string, PendingWork>();+ private items: readonly WorkItem[] = [];+ private listeners = new Set<() => void>();+ private pumping = false;+ private timing = new GenerationTimingEstimator();+ private connections = 0;+ private disconnect: (() => void) | null = null;+ ready: Promise<void> = Promise.resolve();++ constructor(private writer: ProjectWriter = saveProject) {}+ getSnapshot = () => this.items;+ subscribe = (listener: () => void) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; };+ private publish() { this.listeners.forEach((listener) => listener()); }+ private patch(id: string, patch: Partial<WorkItem>) {+ this.items = this.items.map((item) => item.id === id ? { ...item, ...patch } : item);+ this.publish();+ }+ project(record: ProjectRecord): ProjectSession {+ const key = projectQueueKey(record);+ let session = this.projects.get(key);+ if (!session) {+ // The queue belongs to this app run. A persisted in-flight status from a+ // previous run has no worker behind it and must be restartable.+ const config = isTauri() ? { ...record.config, generationJobs: record.config.generationJobs.map((job) =>+ ["queued", "generating", "ready"].includes(job.status) ? { ...job, status: "failed" as const, stage: "failed" as const, error: "Generation was interrupted when Slopus closed. Generate again to restart." } : job) } : record.config;+ session = new ProjectSession({ ...record, config }, this.writer);+ this.projects.set(key, session);+ }+ return session;+ }+ hasActiveProject(record: ProjectRecord) { return this.items.some((item) => item.projectKey === projectQueueKey(record) && isWorkActive(item)); }+ forgetProject(record: ProjectRecord) {+ if (this.hasActiveProject(record)) throw new Error("Cancel or finish this project's work before deleting it.");+ this.projects.delete(projectQueueKey(record));+ }+ clearFinished() {+ const cleared = this.items.filter((item) => !isWorkActive(item) && !item.needsSave);+ cleared.forEach((item) => this.work.delete(item.id));+ this.items = this.items.filter((item) => isWorkActive(item) || item.needsSave);+ this.publish();+ }+ start = () => {+ this.connections += 1;+ if (this.connections === 1 && isTauri()) {+ let disposed = false;+ const stops: (() => void)[] = [];+ const subscribe = async <T,>(name: string, handler: (payload: T) => void) => {+ const stop = await listen<T>(name, ({ payload }) => { if (!disposed) handler(payload); });+ if (disposed) stop(); else stops.push(stop);+ };+ this.ready = Promise.all([+ subscribe<GenerationTimingProgress>("slopfab-progress", (event) => this.progress(event)),+ subscribe<JobEvent>("slopfab-job", (event) => this.event(event)),+ ]).then(() => undefined);+ void this.ready.catch((reason) => writeDiagnostic("error", "work-queue", "subscription.failed", describeDiagnosticError(reason), {}));+ this.disconnect = () => { disposed = true; stops.forEach((stop) => stop()); };+ }+ return () => {+ this.connections -= 1;+ if (this.connections === 0) { this.disconnect?.(); this.disconnect = null; }+ };+ };++ enqueue(session: ProjectSession, submissions: GenerationSubmission[]) {+ const projectKey = projectQueueKey(session.record);+ // Take every setting before the first await, including the selected engine+ // template. Planning and native submission consume this same private copy.+ const config = structuredClone(withEngineSettings(session.getSnapshot().config));+ for (const submission of submissions) {+ if (this.items.some((item) => item.projectKey === projectKey && item.sceneId === submission.job.id && isWorkActive(item))) continue;+ const id = `work-${crypto.randomUUID()}`;+ let finish!: () => void;+ const done = new Promise<void>((resolve) => { finish = resolve; });+ const request = structuredClone({ ...submission.request, jobId: id });+ this.work.set(id, { id, session, sceneId: submission.job.id, request, config, snapshot: submission.snapshot, cancelled: false, submitted: false, done, finish });+ this.items = [...this.items, {+ id, projectKey, folderPath: session.record.folderPath, projectName: config.name,+ sceneId: submission.job.id, title: submission.job.title, submittedAt: new Date().toISOString(),+ status: "queued", progress: 0, detail: "Waiting to generate", error: null, completionAt: null,+ cancelling: false, needsSave: false,+ settings: { frames: request.frames, steps: request.steps, seed: request.seed, canvasWidth: request.canvasWidth, canvasHeight: request.canvasHeight },+ }];+ this.updateScene(this.work.get(id)!, { status: "queued", stage: "queued", progress: 0, error: null, generationSnapshot: submission.snapshot });+ }+ this.publish();+ void this.pump();+ }+ private updateScene(work: PendingWork, patch: Partial<GenerationJob>, dirty = true) {+ work.session.update((current) => ({+ ...current, generationJobs: current.generationJobs.map((job) => job.id === work.sceneId ? { ...job, ...patch, updatedAt: new Date().toISOString() } : job),+ }), dirty);+ }+ private async pump() {+ if (this.pumping) return;+ this.pumping = true;+ try {+ while (true) {+ const next = this.items.find((item) => item.status === "queued");+ if (!next) break;+ const work = this.work.get(next.id)!;+ this.patch(work.id, { status: "preparing", detail: "Preparing generation" });+ try {+ await this.ready;+ if (work.cancelled) continue;+ // Newly created scenes/references must exist on disk before any+ // background result can be attached to this project.+ await work.session.save();+ if (work.cancelled) continue;+ await purgeTimelineThumbnails(next.folderPath, work.sceneId).catch(() => undefined);+ if (work.cancelled) continue;+ const plan = await resolveSlopfabPlan(work.request, work.config);+ if (work.cancelled) continue;+ this.patch(work.id, { status: "generating", detail: `Generating ${plan.alignedFrames} frames at ${plan.canvasWidth} × ${plan.canvasHeight}` });+ this.updateScene(work, { status: "generating", stage: "preparing" }, false);+ await enqueueSlopfabGeneration(work.request, work.config);+ work.submitted = true;+ if (work.cancelled) await this.requestNativeCancellation(work);+ await work.done;+ } catch (reason) { this.fail(work, reason); }+ }+ } finally { this.pumping = false; }+ }+ async cancel(id: string): Promise<void> {+ const item = this.items.find((candidate) => candidate.id === id);+ const work = this.work.get(id);+ if (!item || !work || !isWorkActive(item) || item.status === "encoding" || item.cancelling) return;+ work.cancelled = true;+ if (item.status === "queued" || item.status === "preparing") {+ this.cancelled(work);+ return;+ }+ this.patch(id, { cancelling: true, detail: "Cancelling generation" });+ if (work.submitted) await this.requestNativeCancellation(work);+ }+ private async requestNativeCancellation(work: PendingWork) {+ try { await cancelSlopfabGeneration(work.id); }+ catch (reason) {+ work.cancelled = false;+ this.patch(work.id, { cancelling: false, detail: "Generating video", error: `Could not cancel: ${describeDiagnosticError(reason)}` });+ }+ }+ cancelScenes(session: ProjectSession, sceneIds: string[]) {+ return Promise.all(this.items.filter((item) => item.projectKey === projectQueueKey(session.record) && sceneIds.includes(item.sceneId) && isWorkActive(item)).map((item) => this.cancel(item.id))).then(() => undefined);+ }+ private cancelled(work: PendingWork, detail = "Generation cancelled before it started.") {+ this.timing.clear(work.id);+ this.patch(work.id, { status: "cancelled", detail, cancelling: false, completionAt: null });+ this.updateScene(work, { status: "cancelled", stage: "failed", error: detail });+ void work.session.save().catch(() => undefined);+ work.finish();+ }+ private fail(work: PendingWork, reason: unknown) {+ if (work.cancelled) {+ if (this.items.find((item) => item.id === work.id)?.status !== "cancelled") this.cancelled(work);+ work.finish();+ return;+ }+ const detail = describeDiagnosticError(reason);+ this.timing.clear(work.id);+ this.patch(work.id, { status: "failed", detail: "Generation failed", error: detail, completionAt: null, cancelling: false });+ this.updateScene(work, { status: "failed", stage: "failed", error: detail });+ writeDiagnostic("error", "work-queue", "generation.failed", detail, { workId: work.id, sceneId: work.sceneId, folderPath: work.session.record.folderPath });+ void work.session.save().catch(() => undefined);+ work.finish();+ }+ private progress(event: GenerationTimingProgress) {+ const work = this.work.get(event.jobId);+ const item = this.items.find((candidate) => candidate.id === event.jobId);+ if (!work || !item || !["preparing", "generating"].includes(item.status)) return;+ const progress = Math.max(item.progress, event.totalSteps > 0 ? Math.min(0.88, 0.12 + Math.max(0, event.step) / event.totalSteps * 0.76) : event.stage === "delivering" ? 0.88 : 0.08);+ this.patch(work.id, { status: "generating", progress, completionAt: this.timing.update(event), detail: item.cancelling ? "Cancelling generation" : event.stage === "starting" || event.stage === "transformerLoad" ? "Loading video engine" : "Generating video" });+ this.updateScene(work, { status: "generating", stage: event.stage === "starting" || event.stage === "transformerLoad" ? "preparing" : "generating", progress }, false);+ }+ private event(event: JobEvent) {+ const work = this.work.get(event.jobId);+ const item = this.items.find((candidate) => candidate.id === event.jobId);+ if (!work || !item) return;+ if (!isWorkActive(item)) { if (event.state === "framesReady") void releaseRendered(work.id); return; }+ if (item.status === "encoding") return;+ if (event.state === "framesReady") {+ if (event.output) this.timing.record(event.output);+ this.timing.clear(work.id);+ if (work.cancelled) { void releaseRendered(work.id).then(() => this.cancelled(work)); return; }+ void this.encode(work);+ } else if (event.state === "failed") this.fail(work, event.detail);+ else if (event.state === "cancelled") this.cancelled(work, event.detail);+ // A queued acknowledgement can arrive after progress. It must not rewind it.+ }+ private async encode(work: PendingWork) {+ this.patch(work.id, { status: "encoding", progress: 0.9, detail: "Saving video", completionAt: null });+ this.updateScene(work, { status: "ready", stage: "encoding", progress: 0.9, error: null }, false);+ try {+ const saved = await saveGeneratedScene({+ folderPath: work.session.record.folderPath, jobId: work.id, thumbnailJobId: work.sceneId,+ onProgress: (encoded, total) => {+ if (total <= 0) return;+ const progress = Math.min(0.99, 0.9 + encoded / total * 0.1);+ this.patch(work.id, { progress });+ this.updateScene(work, { progress }, false);+ },+ });+ const assetId = generationAssetId(work.sceneId);+ const media = { kind: "generated" as const, relativePath: saved.relativePath, sourcePath: null, mimeType: "video/mp4", hasAudio: saved.hasAudio ?? null, width: saved.width ?? work.request.canvasWidth, height: saved.height ?? work.request.canvasHeight, durationMs: saved.durationMs ?? Math.round(work.request.frames / GENERATION_FRAME_RATE * 1000) };+ work.session.update((current) => ({+ ...current,+ generationJobs: current.generationJobs.map((job) => job.id === work.sceneId ? { ...job, status: "completed", stage: "completed", progress: 1, generationSnapshot: work.snapshot, outputRelativePath: saved.relativePath, error: saved.note, updatedAt: new Date().toISOString() } : job),+ assets: current.assets.some((asset) => asset.id === assetId)+ ? current.assets.map((asset) => asset.id === assetId ? { ...asset, ...media } : asset)+ : current.generationJobs.some((job) => job.id === work.sceneId)+ ? [...current.assets, { id: assetId, name: current.generationJobs.find((job) => job.id === work.sceneId)!.title, createdAt: new Date().toISOString(), ...media }]+ : current.assets,+ timeline: { tracks: current.timeline.tracks.map((track) => ({ ...track, clips: track.clips.map((clip) => clip.assetId === assetId ? { ...clip, status: "generated" } : clip) })) },+ }));+ try {+ await work.session.save();+ this.patch(work.id, { status: "completed", progress: 1, detail: "Video saved", error: saved.note });+ } catch (reason) {+ this.patch(work.id, { status: "failed", progress: 1, needsSave: true, detail: "Video created; project save failed", error: describeDiagnosticError(reason) });+ }+ } catch (reason) { this.fail(work, reason); }+ finally { await releaseRendered(work.id); work.finish(); }+ }+ async retrySave(id: string) {+ const work = this.work.get(id);+ if (!work) return;+ try { await work.session.save(); this.patch(id, { status: "completed", needsSave: false, error: null, detail: "Video saved" }); }+ catch (reason) { this.patch(id, { error: describeDiagnosticError(reason) }); }+ }+}diff --git a/src/styles/index.css b/src/styles/index.cssindex c0fba50..7adebb1 100644--- a/src/styles/index.css+++ b/src/styles/index.css@@ -17,6 +17,7 @@/* Application surfaces */@import "./shell.css";+@import "./work-queue.css";@import "./library.css";@import "./workspace.css";@import "./generator.css";diff --git a/src/styles/work-queue.css b/src/styles/work-queue.cssnew file mode 100644index 0000000..f69c947--- /dev/null+++ b/src/styles/work-queue.css@@ -0,0 +1,79 @@+.work-queue-launcher {+ display: flex;+ border-radius: var(--radius-pill);+ left: auto;+ right: var(--space-4);+ width: auto;+ padding: 0 var(--space-3);+ gap: var(--space-2);+ font-size: var(--text-sm);+}+.work-queue-launcher b {+ display: grid;+ place-items: center;+ min-width: 20px;+ height: 20px;+ padding: 0 4px;+ border-radius: var(--radius-pill);+ background: var(--accent);+ color: var(--on-accent);+ font-size: var(--text-xs);+}+.work-queue-backdrop {+ position: fixed;+ inset: 0;+ z-index: 150;+ background: var(--scrim);+}+.work-queue-panel {+ position: absolute;+ right: var(--space-4);+ bottom: 76px;+ display: flex;+ flex-direction: column;+ width: min(440px, calc(100vw - 32px));+ max-height: calc(100dvh - 108px);+ border: 1px solid var(--line-strong);+ border-radius: var(--radius-lg);+ background: var(--panel);+ color: var(--text-primary);+ box-shadow: var(--shadow);+ overflow: hidden;+}+.work-queue__header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: var(--space-3) var(--space-4);+}+.work-queue__header > div { display: flex; gap: var(--space-2); align-items: center; }+.work-queue__header h2 { margin: 0; font-size: var(--text-lg); }+.work-queue__intro { margin: 0; padding: 0 var(--space-4) var(--space-3); color: var(--text-muted); font-size: var(--text-sm); }+.work-queue__list { overflow-y: auto; overscroll-behavior: contain; padding: 0 var(--space-4) var(--space-4); }+.work-queue__list h3 { display: flex; align-items: center; gap: var(--space-2); margin: var(--space-3) 0 var(--space-2); font-size: var(--text-sm); color: var(--text-secondary); }+.work-queue__list h3 > button { margin-left: auto; border: 0; background: transparent; color: var(--text-muted); font-size: var(--text-xs); }+.work-queue__list h3 > button:hover { color: var(--text-primary); }+.work-queue__list ul { list-style: none; margin: 0; padding: 0; }+.work-queue__item { margin-bottom: var(--space-2); padding: var(--space-3); border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--panel-2); }+.work-queue__item-heading { display: flex; gap: var(--space-2); align-items: center; }+.work-queue__item-heading > div { display: grid; flex: 1; min-width: 0; gap: 2px; }+.work-queue__item-heading strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--text-base); font-weight: var(--weight-medium); }+.work-queue__item-heading div > span { color: var(--text-muted); font-size: var(--text-xs); }+.work-queue__state { display: grid; place-items: center; color: var(--text-muted); }+.work-queue__state--completed { color: var(--success); }+.work-queue__state--failed { color: var(--danger); }+.work-queue__state--generating, .work-queue__state--encoding, .work-queue__state--preparing { color: var(--accent-bright); }+.work-queue__detail { display: flex; justify-content: space-between; gap: var(--space-2); margin-top: var(--space-3); font-size: var(--text-xs); color: var(--text-secondary); }+.work-queue__detail b { font-variant-numeric: tabular-nums; }+.work-queue__item progress { display: block; width: 100%; height: 4px; margin-top: var(--space-2); border: 0; border-radius: var(--radius-pill); overflow: hidden; accent-color: var(--accent); }+.work-queue__item progress::-webkit-progress-bar { background: var(--line); }+.work-queue__item progress::-webkit-progress-value { background: var(--accent); }+.work-queue__settings { margin: var(--space-2) 0 0; font-size: var(--text-xs); color: var(--text-muted); }+.work-queue__error { margin: var(--space-2) 0 0; font-size: var(--text-xs); color: var(--danger); overflow-wrap: anywhere; }+.work-queue__empty { display: grid; justify-items: center; gap: var(--space-2); padding: var(--space-6) 0; color: var(--text-muted); }+.work-queue__empty p { margin: 0; font-size: var(--text-sm); }+.work-queue__spinner { animation: work-queue-spin 1s linear infinite; }+@keyframes work-queue-spin { to { transform: rotate(360deg); } }+@media (max-width: 1180px) {+ .work-queue-launcher > span { display: none; }+}