Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Save cancelled previews as Takes

Bitti18fcab82955f
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index cc2bcef..a8c4bf7 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -12,7 +12,7 @@ Changes since 0.3.2.
- **Single Shot:** Continue with Context and Previous video anchors, optional generated endings, improved overlap joining and consistent Tone. Context guidance now matches the original anchor to reduce appearance degradation across continuations. Use Bridge for new connections instead of Long Shot.
- **Motions and agents:** Create editable JavaScript animations for the timeline or references. Agents can inspect media frames, generate music and sync Motions to audio.
- **Image editing:** Combine or subtract lasso selections, queue batches of up to 100 images, and edit bounded regions of larger images while preserving their original resolution.
-- **Live previews:** Watch MiniMax H3 video and image generation in the editor. Optional TAEH3 preview weights are available in Settings.
+- **Live previews:** Watch MiniMax H3 video and image generation in the editor. Cancelling a video generation saves its latest available preview as the Take's video. Optional TAEH3 preview weights are available in Settings.
- **Generation effects:** LCS color steering, tone, sharpness and color stabilization, with step ranges and optional regions.
- **Generator controls:** Compatible sampler/scheduler choices, including ER-SDE and Beta; global LoRAs, application ordering, scene overrides, Pika H3 Flex and Hyperflow 8-Step adapters.
- **Generator selection:** Video, image and music remember separate active generators. Saved takes show the used seed and generator, with a button to select that generator again.
diff --git a/src/lib/generatedVideo.test.ts b/src/lib/generatedVideo.test.ts
index ef15c20..efdd234 100644
--- a/src/lib/generatedVideo.test.ts
+++ b/src/lib/generatedVideo.test.ts
@@ -2,9 +2,11 @@
import { invoke } from "@tauri-apps/api/core";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { audioSamplesFromIpc, bytesFromIpc, releaseRendered, renderedSummary, resampleInterleaved, saveGeneratedScene } from "./generatedVideo";
+import { audioSamplesFromIpc, bytesFromIpc, releaseRendered, renderedSummary, resampleInterleaved, saveGeneratedScene, saveGenerationPreview } from "./generatedVideo";
+import { encodeGenerationPreview } from "./generationPreview";
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
+vi.mock("./generationPreview", () => ({ encodeGenerationPreview: vi.fn() }));
const muxed = vi.hoisted(() => ({
configs: [] as Array<Record<string, unknown>>,
@@ -33,8 +35,34 @@ const summary = (over: Record<string, unknown> = {}) => ({
const desktop = () => { scope.__TAURI_INTERNALS__ = {}; };
+it("writes a cancelled preview as a silent video with its actual dimensions and duration", async () => {
+ desktop();
+ const preview = { jobId: "work-preview", step: 3, width: 168, height: 96, fps: 2, frames: ["a", "b", "c"] };
+ const bytes = new Uint8Array([1, 2, 3, 4]);
+ vi.mocked(encodeGenerationPreview).mockResolvedValue({ arrayBuffer: async () => bytes.buffer } as Blob);
+ invoked.mockResolvedValue({ relativePath: "media/generated/work-preview.mp4", bytes: 4 });
+ await expect(saveGenerationPreview("C:/My Project", "work-preview", preview)).resolves.toEqual({
+ relativePath: "media/generated/work-preview.mp4", bytes: 4, hasAudio: false, note: null,
+ width: 168, height: 96, durationMs: 1500,
+ });
+ expect(encodeGenerationPreview).toHaveBeenCalledWith(preview, expect.any(AbortSignal));
+ expect(invoked).toHaveBeenCalledExactlyOnceWith("write_generated_video", bytes, {
+ headers: { "x-generated-folder": "C%3A%2FMy%20Project", "x-generated-job": "work-preview" },
+ });
+});
+
+it("does not write a file when preview encoding fails", async () => {
+ desktop();
+ vi.mocked(encodeGenerationPreview).mockRejectedValue(new Error("Preview encoding is unavailable."));
+ await expect(saveGenerationPreview("C:/Project", "work-preview", {
+ jobId: "work-preview", step: 0, width: 2, height: 2, fps: 2, frames: ["jpeg"],
+ })).rejects.toThrow("Preview encoding is unavailable");
+ expect(invoked).not.toHaveBeenCalled();
+});
+
beforeEach(() => {
invoked.mockReset().mockResolvedValue(true);
+ vi.mocked(encodeGenerationPreview).mockReset();
muxed.configs.length = 0;
muxed.audioChunks = 0;
muxed.videoChunks = 0;
diff --git a/src/lib/generatedVideo.ts b/src/lib/generatedVideo.ts
index 9ae3a05..a675c8c 100644
--- a/src/lib/generatedVideo.ts
+++ b/src/lib/generatedVideo.ts
@@ -3,6 +3,7 @@ import { writeDiagnostic } from "./diagnostics";
import { bitrateFor, outputCodec } from "./export";
import { isTauri } from "./persistence";
import { TIMELINE_THUMBNAIL_INTERVAL_MS, writeTimelineThumbnail } from "./timelineThumbnails";
+import { encodeGenerationPreview, type GenerationPreview } from "./generationPreview";
/* Turning a finished render into a file in the project folder.
*
@@ -168,6 +169,15 @@ async function writeGeneratedVideo(folderPath: string, jobId: string, bytes: Uin
});
}
+/** Promote a cancelled render's latest preview to a normal project video. */
+export async function saveGenerationPreview(folderPath: string, jobId: string, preview: GenerationPreview): Promise<SavedGeneration> {
+ if (!isTauri()) throw new Error("Saving a generation preview needs the desktop app.");
+ const video = await encodeGenerationPreview(preview, new AbortController().signal);
+ const written = await writeGeneratedVideo(folderPath, jobId, new Uint8Array(await video.arrayBuffer()));
+ return { ...written, note: null, hasAudio: false, width: preview.width, height: preview.height,
+ durationMs: Math.round(preview.frames.length / preview.fps * 1000) };
+}
+
/** The codec string this machine actually accepts for this picture, asked of
* the encoder rather than assumed from the name. */
async function pickCodec(width: number, height: number, fps: number, bitrate: number): Promise<{ codec: string; tried: string[] }> {
diff --git a/src/lib/generationPreview.ts b/src/lib/generationPreview.ts
index 094c83f..37669f9 100644
--- a/src/lib/generationPreview.ts
+++ b/src/lib/generationPreview.ts
@@ -4,7 +4,7 @@ export interface GenerationPreview {
width: number;
height: number;
fps: number;
- /** Base64 JPEG frames; transient and never written into the project. */
+ /** Base64 JPEG frames; kept in memory until discarded or saved as a cancelled Take. */
frames: string[];
}
@@ -17,7 +17,7 @@ export function validGenerationPreview(value: GenerationPreview): boolean {
&& value.frames.reduce((bytes, frame) => bytes + frame.length, 0) <= 8 * 1024 * 1024);
}
-/** Small silent MP4 for the scene card. WebCodecs owns encoding; no files or FFmpeg. */
+/** Small silent MP4 for playback or saving a cancelled Take. WebCodecs owns encoding. */
export async function encodeGenerationPreview(preview: GenerationPreview, signal: AbortSignal): Promise<Blob> {
if (!validGenerationPreview(preview)) throw new Error("Invalid generation preview.");
signal.throwIfAborted();
diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.ts
index 86a1679..5269bc6 100644
--- a/src/lib/workQueue.test.ts
+++ b/src/lib/workQueue.test.ts
@@ -5,7 +5,7 @@ import { waitFor } from "@testing-library/react";
import { listen } from "@tauri-apps/api/event";
import { invoke } from "@tauri-apps/api/core";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { releaseRendered, saveGeneratedScene } from "./generatedVideo";
+import { releaseRendered, saveGeneratedScene, saveGenerationPreview } from "./generatedVideo";
import { createProjectConfig, parseProjectConfig, sceneGenerationSnapshot, type ProjectRecord } from "./project";
import { ProjectSession } from "./projectSession";
import { cancelSlopfabGeneration, enqueueSlopfabGeneration, resolveSlopfabPlan } from "./runtime";
@@ -32,7 +32,7 @@ import { DMAD_LORA, saveLoras, loadLoras, moveLibraryLora } from "./loras";
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("./generatedVideo", () => ({ saveGeneratedScene: vi.fn(), saveGenerationPreview: vi.fn(), releaseRendered: vi.fn(async () => true) }));
vi.mock("./timelineThumbnails", () => ({ purgeTimelineThumbnails: vi.fn(async () => undefined) }));
vi.mock("./sceneLastFrame", () => ({ saveSceneLastFrame: vi.fn(async () => "cache/scene-last/work-new.png") }));
vi.mock("./referenceVideo", () => ({ prepareReferenceVideos: vi.fn(async () => ["video-1"]), releaseReferenceVideos: vi.fn(async () => undefined) }));
@@ -52,6 +52,10 @@ beforeEach(() => {
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 });
+ vi.mocked(saveGenerationPreview).mockReset().mockImplementation(async (_folder, id, preview) => ({
+ relativePath: `media/generated/${id}.mp4`, bytes: 100, hasAudio: false, note: null,
+ width: preview.width, height: preview.height, durationMs: Math.round(preview.frames.length / preview.fps * 1000),
+ }));
});
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 }) });
@@ -198,6 +202,133 @@ it("isolates live previews by native job and clears them on disable, cancel and
emit("slopfab-preview", { ...preview, jobId: other });
expect(queue.getSnapshot().find((item) => item.id === other)?.preview).toBeUndefined();
emit("slopfab-job", { jobId: other, state: "cancelled", detail: "Cancelled" });
+ await waitFor(() => expect(queue.getSnapshot().find((item) => item.id === other)?.status).toBe("cancelled"));
+});
+
+it.each(["cancelled", "framesReady", "failed"])("saves the latest cancelled preview as a Take when the native result is %s", async (state) => {
+ const { queue, first, second } = setup();
+ const source = submission(first);
+ first.update(config => completeSceneGeneration(config, source.job.id, {
+ id: "original", createdAt: config.createdAt, scene: sceneInput(source.job), latentRelativePath: "latents/original.safetensors",
+ media: { id: `asset-${source.job.id}`, kind: "generated", mimeType: "video/mp4", name: source.job.title, relativePath: "media/original.mp4", createdAt: config.createdAt },
+ }));
+ const [id] = queue.enqueue(first, [submission(first)]);
+ const child = { ...source.job, id: "child" }, grandchild = { ...source.job, id: "grandchild" };
+ first.update(config => ({ ...config, generationJobs: [...config.generationJobs, child, grandchild] }));
+ const descendants = queue.enqueue(first, [child, grandchild].map((job, index) => ({ ...source, job,
+ request: { ...source.request, previousSceneId: index ? child.id : source.job.id } })));
+ const [other] = queue.enqueue(second, [submission(second)]);
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());
+ const preview = { jobId: id, step: 2, width: 168, height: 96, fps: 4, frames: ["/9j/AA==", "/9j/AQ=="] };
+ emit("slopfab-preview", { ...preview, step: 1, frames: ["old"] });
+ emit("slopfab-preview", preview);
+ let saved!: (result: Awaited<ReturnType<typeof saveGenerationPreview>>) => void;
+ vi.mocked(saveGenerationPreview).mockImplementationOnce(() => new Promise(resolve => { saved = resolve; }));
+ await queue.cancel(id);
+ expect(cancelSlopfabGeneration).toHaveBeenCalledExactlyOnceWith(id);
+ emit("slopfab-preview", { ...preview, step: 3, frames: ["too-late"] });
+ emit("slopfab-job", { jobId: id, state, detail: "Stopped" });
+ await waitFor(() => expect(saveGenerationPreview).toHaveBeenCalledExactlyOnceWith(first.record.folderPath, id, preview));
+ emit("slopfab-job", { jobId: id, state: "cancelled", detail: "Duplicate" });
+ expect(descendants.map(childId => queue.getSnapshot().find(item => item.id === childId)?.status)).toEqual(["cancelled", "cancelled"]);
+ expect(queue.getSnapshot().find(item => item.id === other)?.status).toBe("queued");
+ expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce();
+ saved({ relativePath: `media/generated/${id}.mp4`, bytes: 100, note: null, hasAudio: false, width: 168, height: 96, durationMs: 500 });
+ await expect(queue.waitFor(id, new AbortController().signal)).resolves.toMatchObject({ status: "cancelled", needsSave: false });
+ const config = parseProjectConfig(JSON.parse(JSON.stringify(first.getSnapshot().config)));
+ const result = config.generationJobs[0];
+ expect(result).toMatchObject({ status: "completed", outputRelativePath: `media/generated/${id}.mp4`, latentRelativePath: null });
+ expect(result.generationHistory).toMatchObject({ primaryId: id, selectedId: id });
+ expect(result.generationHistory!.versions).toHaveLength(2);
+ expect(result.generationHistory!.versions[0].latentRelativePath).toBe("latents/original.safetensors");
+ expect(result.generationHistory!.versions[1].media).toMatchObject({ width: 168, height: 96, durationMs: 500, hasAudio: false });
+ expect(result.generationHistory!.versions[1].media.sceneSegments).toBeUndefined();
+ expect(config.assets.find(asset => asset.id === `asset-${source.job.id}`)?.relativePath).toBe(`media/generated/${id}.mp4`);
+ expect(JSON.stringify(config)).not.toContain("/9j/");
+ expect(saveGenerationPreview).toHaveBeenCalledOnce();
+ expect(saveGeneratedScene).not.toHaveBeenCalled();
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(2));
+});
+
+it("retains the last preview for cancellation after live previews are disabled", async () => {
+ const { queue, first } = setup();
+ const [id] = queue.enqueue(first, [submission(first)]);
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());
+ const preview = { jobId: id, step: 1, width: 2, height: 2, fps: 4, frames: ["jpeg"] };
+ emit("slopfab-preview", preview);
+ saveGenerationPreviewsEnabled(false);
+ await queue.cancel(id);
+ emit("slopfab-job", { jobId: id, state: "cancelled", detail: "Stopped" });
+ await expect(queue.waitFor(id, new AbortController().signal)).resolves.toMatchObject({ status: "cancelled" });
+ expect(saveGenerationPreview).toHaveBeenCalledExactlyOnceWith(first.record.folderPath, id, preview);
+});
+
+it("finishes saving a preview before advancing the queue when cancellation arrives during encoding", async () => {
+ const { queue, first, second } = setup();
+ let encoded!: (result: Awaited<ReturnType<typeof saveGeneratedScene>>) => void;
+ let previewSaved!: (result: Awaited<ReturnType<typeof saveGenerationPreview>>) => void;
+ vi.mocked(saveGeneratedScene).mockImplementationOnce(() => new Promise(resolve => { encoded = resolve; }));
+ vi.mocked(saveGenerationPreview).mockImplementationOnce(() => new Promise(resolve => { previewSaved = resolve; }));
+ const [id] = queue.enqueue(first, [submission(first)]);
+ queue.enqueue(second, [submission(second)]);
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());
+ emit("slopfab-preview", { jobId: id, step: 1, width: 2, height: 2, fps: 4, frames: ["jpeg"] });
+ emit("slopfab-job", { jobId: id, state: "framesReady" });
+ await waitFor(() => expect(saveGeneratedScene).toHaveBeenCalledOnce());
+ await queue.cancel(id);
+ encoded({ relativePath: "media/full.mp4", bytes: 100, note: null });
+ await waitFor(() => expect(saveGenerationPreview).toHaveBeenCalledOnce());
+ expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce();
+ expect(queue.getSnapshot()[0].status).toBe("encoding");
+ previewSaved({ relativePath: "media/preview.mp4", bytes: 100, note: null, width: 2, height: 2, hasAudio: false, durationMs: 250 });
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(2));
+ expect(queue.getSnapshot()[0].status).toBe("cancelled");
+ expect(first.getSnapshot().config.generationJobs[0].outputRelativePath).toBe("media/preview.mp4");
+});
+
+it.each([false, true])("keeps cancellation without a valid video preview unchanged (malformed preview: %s)", async (malformed) => {
+ const { queue, first } = setup();
+ const [id] = queue.enqueue(first, [submission(first)]);
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());
+ if (malformed) emit("slopfab-preview", { jobId: id, step: 1, width: 2, height: 2, fps: 4, frames: [] });
+ await queue.cancel(id);
+ emit("slopfab-job", { jobId: id, state: "cancelled", detail: "Stopped" });
+ await expect(queue.waitFor(id, new AbortController().signal)).resolves.toMatchObject({ status: "cancelled" });
+ expect(saveGenerationPreview).not.toHaveBeenCalled();
+ expect(first.getSnapshot().config.generationJobs[0].outputRelativePath).toBeFalsy();
+});
+
+it("keeps the prior Take when saving a cancelled preview fails", async () => {
+ const { queue, first } = setup();
+ const source = submission(first);
+ first.update(config => completeSceneGeneration(config, source.job.id, {
+ id: "original", createdAt: config.createdAt, scene: sceneInput(source.job), latentRelativePath: "latents/original.safetensors",
+ media: { id: `asset-${source.job.id}`, kind: "generated", mimeType: "video/mp4", name: source.job.title, relativePath: "media/original.mp4", createdAt: config.createdAt },
+ }));
+ const [id] = queue.enqueue(first, [submission(first)]);
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());
+ emit("slopfab-preview", { jobId: id, step: 1, width: 2, height: 2, fps: 4, frames: ["jpeg"] });
+ vi.mocked(saveGenerationPreview).mockRejectedValueOnce(new Error("Disk full"));
+ await queue.cancel(id);
+ emit("slopfab-job", { jobId: id, state: "cancelled", detail: "Stopped" });
+ await expect(queue.waitFor(id, new AbortController().signal)).resolves.toMatchObject({ status: "cancelled", detail: expect.stringContaining("Disk full") });
+ expect(first.getSnapshot().config.generationJobs[0]).toMatchObject({ outputRelativePath: "media/original.mp4", latentRelativePath: "latents/original.safetensors" });
+ expect(first.getSnapshot().config.generationJobs[0].generationHistory!.versions).toHaveLength(1);
+});
+
+it("retries project persistence for a saved cancelled preview without encoding it again", async () => {
+ const { queue, first, saved } = setup();
+ const [id] = queue.enqueue(first, [submission(first)]);
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());
+ emit("slopfab-preview", { jobId: id, step: 1, width: 2, height: 2, fps: 4, frames: ["jpeg"] });
+ await queue.cancel(id);
+ saved.mockRejectedValueOnce(new Error("Project save failed"));
+ emit("slopfab-job", { jobId: id, state: "cancelled", detail: "Stopped" });
+ await expect(queue.waitFor(id, new AbortController().signal)).resolves.toMatchObject({ status: "cancelled", needsSave: true });
+ await queue.retrySave(id);
+ expect(queue.getSnapshot()[0]).toMatchObject({ status: "cancelled", needsSave: false, error: null });
+ expect(saveGenerationPreview).toHaveBeenCalledOnce();
+ expect(first.getSnapshot().config.generationJobs[0].generationHistory!.versions).toHaveLength(1);
});
it("upscales selected Takes repeatedly without diffusion, preserving source lineage and joined scene ranges", async () => {
diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.ts
index 3ea8e88..b58012c 100644
--- a/src/lib/workQueue.ts
+++ b/src/lib/workQueue.ts
@@ -22,7 +22,7 @@ import { describeDiagnosticError, writeDiagnostic } from "./diagnostics";
import { GenerationTimingEstimator, type CompletedGenerationTiming, type GenerationTimingProgress } from "./generationTiming";
import { validGenerationPreview, type GenerationPreview } from "./generationPreview";
import { loadGenerationPreviewsEnabled, subscribeGenerationPreviews } from "./generationPreviewSettings";
-import { releaseRendered, saveGeneratedScene } from "./generatedVideo";
+import { releaseRendered, saveGeneratedScene, saveGenerationPreview } from "./generatedVideo";
import { isTauri, saveProject } from "./persistence";
import { continuationBlocker, generationAssetId, generationLatentPath, GENERATION_FRAME_RATE, sceneSiblings, sceneOutputFrames, sceneGenerationSnapshot, type SceneInput, type GenerationJob, type ProjectRecord, type ProjectConfig } from "./project";
import { ProjectSession, type ProjectWriter } from "./projectSession";
@@ -73,6 +73,8 @@ export interface WorkItem {
settings: { frames: number; steps: number; audioSteps?: number; videoSigmaShift?: number; audioSigmaShift?: number; latentUpscale?: boolean; seed: number; canvasWidth: number; canvasHeight: number };
}
interface PendingWork {
+ lastPreview?: GenerationPreview;
+ cancellation?: Promise<void>;
generatorName?: string;
albumCoverSongId?: string;
upscaleSource?: import("./project").SceneGenerationVersion;
@@ -653,7 +655,7 @@ export class WorkQueue {
work.submitted = true;
if (work.cancelled) await this.requestNativeCancellation(work);
await work.done;
- } catch (reason) { this.fail(work, reason); }
+ } catch (reason) { await this.fail(work, reason); }
finally {
if (work.extend) await invoke("discard_extend_image", { folderPath: next.folderPath, jobId: work.id }).catch((reason) =>
writeDiagnostic("error", "work-queue", "extend.cleanup_failed", describeDiagnosticError(reason), { workId: work.id }));
@@ -716,7 +718,7 @@ export class WorkQueue {
return;
}
if (item.status === "queued" || item.status === "preparing") {
- this.cancelled(work);
+ await this.cancelled(work);
if (item.status === "queued") this.work.delete(id);
// Stops files that are still being sent to a LAN worker for this job.
if (item.status === "preparing" && remoteWorkerSelected()) void cancelSlopfabGeneration(work.request.jobId).catch(() => undefined);
@@ -735,17 +737,50 @@ export class WorkQueue {
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.") {
+ private cancelled(work: PendingWork, detail = "Generation cancelled before it started."): Promise<void> {
+ // Native cancellation, a late result and an enqueue error can race.
+ // Finalize once and keep the queue occupied until the preview is saved.
+ return work.cancellation ??= this.finishCancellation(work, detail);
+ }
+ private async finishCancellation(work: PendingWork, detail: string) {
this.timing.clear(work.id);
+ work.cancelled = true;
+ const preview = work.lastPreview;
+ work.lastPreview = undefined;
+ if (preview) {
+ this.patch(work.id, { status: "encoding", detail: "Saving cancelled generation preview", cancelling: true, completionAt: null });
+ this.updateScene(work, { status: "ready", stage: "encoding", error: null }, false);
+ try {
+ const saved = await saveGenerationPreview(work.session.record.folderPath, work.id, preview);
+ const createdAt = new Date().toISOString();
+ work.session.update(sceneResultUpdate(work.sceneId, {
+ id: work.id, createdAt, scene: work.sceneInput!, generatorName: work.generatorName,
+ generationSnapshot: work.snapshot, latentRelativePath: null,
+ media: { id: generationAssetId(work.sceneId), name: work.sceneInput!.title, kind: "generated", createdAt,
+ relativePath: saved.relativePath, sourcePath: null, mimeType: "video/mp4", hasAudio: false,
+ width: saved.width, height: saved.height, durationMs: saved.durationMs },
+ }));
+ try {
+ await work.session.save();
+ this.patch(work.id, { status: "cancelled", detail: "Cancelled; preview saved as Take", cancelling: false, progress: 1, error: null });
+ } catch (reason) {
+ this.patch(work.id, { status: "cancelled", detail: "Preview saved; project save failed", cancelling: false,
+ progress: 1, needsSave: true, error: describeDiagnosticError(reason) });
+ }
+ return;
+ } catch (reason) {
+ detail = `Generation cancelled; preview could not be saved: ${describeDiagnosticError(reason)}`;
+ writeDiagnostic("error", "work-queue", "preview.save_failed", detail, { workId: work.id, sceneId: work.sceneId });
+ } finally { work.finish(); }
+ }
this.patch(work.id, { status: "cancelled", detail, cancelling: false, completionAt: null });
this.updateScene(work, work.upscaleSource ? { status: "completed", stage: "completed", progress: 1, error: detail } : { status: "cancelled", stage: "failed", error: detail });
void work.session.save().catch(() => undefined);
work.finish();
}
- private fail(work: PendingWork, reason: unknown) {
+ private async fail(work: PendingWork, reason: unknown) {
if (work.cancelled) {
- if (this.items.find((item) => item.id === work.id)?.status !== "cancelled") this.cancelled(work);
- work.finish();
+ await this.cancelled(work);
return;
}
const detail = describeDiagnosticError(reason);
@@ -764,6 +799,7 @@ export class WorkQueue {
|| (work.config.providerSettings.slopfab?.options.modelType ?? "minimax-h3") !== "minimax-h3"
|| (work.image && event.frames.length !== 1)
|| !["preparing", "generating"].includes(item.status)) return;
+ if (!item.kind) work.lastPreview = event;
this.patch(work.id, { preview: event });
}
private progress(event: GenerationTimingProgress) {
@@ -802,7 +838,10 @@ export class WorkQueue {
return;
}
if (!isWorkActive(item)) { if (event.state === "framesReady") void releaseRendered(event.jobId); return; }
- if (item.status === "encoding") return;
+ if (item.status === "encoding") {
+ if (work.cancellation && event.state === "framesReady") void releaseRendered(event.jobId);
+ return;
+ }
if (work.characterSheet) {
if (event.state === "framesReady") work.characterSheet.ready?.resolve();
else if (event.state === "failed" || event.state === "cancelled") {
@@ -816,8 +855,8 @@ export class WorkQueue {
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);
+ } else if (event.state === "failed") void this.fail(work, event.detail);
+ else if (event.state === "cancelled") void this.cancelled(work, event.detail);
// A queued acknowledgement can arrive after progress. It must not rewind it.
}
private nativeWork(jobId: string) {
@@ -851,7 +890,7 @@ export class WorkQueue {
if (work.cancelled) await this.requestNativeCancellation(work);
await ready;
sheet.ready = undefined;
- if (work.cancelled) { this.cancelled(work); return; }
+ if (work.cancelled) { await this.cancelled(work); return; }
this.patch(work.id, { status: "encoding", detail: `Saving character sheet view ${index + 1}/${sheet.order.length}` });
await invoke("save_character_sheet_view", { folderPath, sheetId: work.id, jobId: work.request.jobId, index: viewIndex });
await releaseRendered(work.request.jobId);
@@ -890,7 +929,7 @@ export class WorkQueue {
this.updateScene(work, { progress }, false);
},
});
- if (work.cancelled) { this.cancelled(work); return; }
+ if (work.cancelled) { await this.cancelled(work); return; }
const assetId = generationAssetId(work.sceneId);
const totalFrames = saved.durationMs ? Math.round(saved.durationMs * GENERATION_FRAME_RATE / 1000) : work.outputFrames ?? work.request.frames;
const sceneSegments = work.upscaleSource ? work.upscaleSource.media.sceneSegments : work.request.latentBridge
@@ -911,12 +950,12 @@ export class WorkQueue {
work.session.update(sceneResultUpdate(work.sceneId, version, saved.note));
try {
await work.session.save();
- if (work.cancelled) { this.cancelled(work); return; }
+ if (work.cancelled) { await this.cancelled(work); return; }
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); }
+ } catch (reason) { await this.fail(work, reason); }
finally { await releaseRendered(work.id); work.finish(); }
}
async retrySave(id: string) {
@@ -924,7 +963,7 @@ export class WorkQueue {
const item = this.items.find((candidate) => candidate.id === id);
const session = item && this.projects.get(item.projectKey);
if (!item?.needsSave || !session) return;
- try { await session.save(); this.patch(id, { status: "completed", needsSave: false, error: null, detail: item.kind === "music" ? "Music saved" : item.kind === "album-cover" ? "Album cover saved" : item.kind === "image" ? "Image saved" : "Video saved" }); }
+ try { await session.save(); this.patch(id, { status: item.status === "cancelled" ? "cancelled" : "completed", needsSave: false, error: null, detail: item.status === "cancelled" ? "Cancelled; preview saved as Take" : item.kind === "music" ? "Music saved" : item.kind === "album-cover" ? "Album cover saved" : item.kind === "image" ? "Image saved" : "Video saved" }); }
catch (reason) { this.patch(id, { error: describeDiagnosticError(reason) }); }
}
private async saveMusic(work: PendingWork) {
@@ -941,7 +980,7 @@ export class WorkQueue {
} catch (reason) {
this.patch(id, { status: "failed", progress: 1, needsSave: true, detail: "Music created; project save failed", error: describeDiagnosticError(reason) });
}
- } catch (reason) { this.fail(work, reason); }
+ } catch (reason) { await this.fail(work, reason); }
finally { await releaseRendered(work.id); work.finish(); }
}
private async saveImage(work: PendingWork) {
@@ -963,7 +1002,7 @@ export class WorkQueue {
}
try { await work.session.save(); this.patch(work.id, { status: "completed", progress: 1, detail: work.albumCoverSongId ? "Album cover saved" : "Image saved" }); }
catch (reason) { this.patch(work.id, { status: "failed", progress: 1, needsSave: true, detail: "Image created; project save failed", error: describeDiagnosticError(reason) }); }
- } catch (reason) { this.fail(work, reason); }
+ } catch (reason) { await this.fail(work, reason); }
finally {
try { await releaseRendered(work.id); }
finally { work.finish(); }