Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Preserve scene generations and editable drafts

Bittif13366227170
diff --git a/src-tauri/src/project/scenes.rs b/src-tauri/src/project/scenes.rs
index 134db71..8ec3d45 100644
--- a/src-tauri/src/project/scenes.rs
+++ b/src-tauri/src/project/scenes.rs
@@ -40,6 +40,10 @@ pub(crate) struct SceneShot {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct GenerationJob {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(crate) generator_template_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(crate) generation_history: Option<SceneGenerationHistory>,
pub(crate) id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) scene_type: Option<String>,
@@ -165,6 +169,8 @@ impl GenerationJob {
) -> Self {
let now = timestamp.to_string();
Self {
+ generator_template_id: None,
+ generation_history: None,
id: id.to_string(),
scene_type: None,
backdrop_color: None,
@@ -211,3 +217,30 @@ impl GenerationJob {
}
}
}
+
+
+/// Input documents deliberately exclude outputs and nested history. An array
+/// keeps storage independent of the frontend's current retention limit.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct SceneGenerationHistory {
+ pub(crate) versions: Vec<SceneGenerationVersion>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(crate) primary_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(crate) selected_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(crate) draft: Option<serde_json::Value>,
+}
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct SceneGenerationVersion {
+ pub(crate) id: String,
+ pub(crate) created_at: String,
+ pub(crate) scene: serde_json::Value,
+ pub(crate) media: super::ProjectAsset,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(crate) generation_snapshot: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(crate) latent_relative_path: Option<String>,
+}
diff --git a/src-tauri/src/project/validation/scenes.rs b/src-tauri/src/project/validation/scenes.rs
index 8bf650f..efc9612 100644
--- a/src-tauri/src/project/validation/scenes.rs
+++ b/src-tauri/src/project/validation/scenes.rs
@@ -3,8 +3,14 @@ use crate::project::paths::*;
use crate::project::*;
use std::collections::BTreeSet;
pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
+ validate_jobs(&mut config.generation_jobs)
+}
+
+fn validate_jobs(jobs: &mut [GenerationJob]) -> Result<(), String> {
let mut previous_id = None;
- for job in &mut config.generation_jobs {
+ for job in jobs {
+ validate_history(job)?;
+ if job.generator_template_id.as_ref().is_some_and(|id| id.trim().is_empty()) { return Err("Scene generator template id cannot be empty.".into()); }
if job.use_previous_scene_last_frame == Some(true)
&& matches!(job.scene_type.as_deref(), None | Some("first-last-frame")) {
job.scene_type = Some("continue".into());
@@ -214,3 +220,98 @@ pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
}
Ok(())
}
+
+
+fn validate_input(input: &serde_json::Value) -> Result<(), String> {
+ let object = input.as_object().ok_or("Scene history inputs must be an object.")?;
+ if ["title", "prompt", "creativeBrief"].iter().any(|key| !input[*key].is_string()) || !object.contains_key("providerId") {
+ return Err("Scene history inputs need their title, prompts and provider.".into());
+ }
+ if ["generationHistory", "id", "status", "stage", "progress", "outputRelativePath", "latentRelativePath", "clipId", "generationSnapshot", "error", "createdAt", "updatedAt"]
+ .iter().any(|key| object.contains_key(*key)) { return Err("Scene history inputs cannot contain identity, outputs or nested history.".into()); }
+ // Reuse the current scene validator, including future model controls.
+ let draft = GenerationJob::draft("history-input", "History", "2026-01-01T00:00:00.000Z", crate::generation::models::default_model().defaults);
+ let mut value = serde_json::to_value(draft).map_err(|e| e.to_string())?;
+ value.as_object_mut().unwrap().extend(object.clone());
+ let mut job: GenerationJob = serde_json::from_value(value).map_err(|e| format!("Invalid scene history input: {e}"))?;
+ validate_jobs(std::slice::from_mut(&mut job))
+}
+
+fn validate_history(job: &mut GenerationJob) -> Result<(), String> {
+ let Some(history) = &mut job.generation_history else { return Ok(()); };
+ let mut ids = BTreeSet::new();
+ for version in &mut history.versions {
+ if version.id.trim().is_empty() || !ids.insert(version.id.clone()) { return Err("Scene generation IDs must be nonempty and unique.".into()); }
+ check_iso_datetime("Scene generation createdAt", &version.created_at)?;
+ validate_input(&version.scene)?;
+ let media = &mut version.media;
+ if media.kind != "generated" || media.mime_type != "video/mp4" || media.id.trim().is_empty() || media.name.trim().is_empty()
+ || media.source_path.is_some() || media.motion.is_some() || media.image_generation.is_some() || media.image_editing.is_some()
+ || media.width == Some(0) || media.height == Some(0) || media.duration_ms == Some(0) {
+ return Err("Scene generations require a saved video asset.".into());
+ }
+ check_iso_datetime("Scene generation media createdAt", &media.created_at)?;
+ media.relative_path = Some(normalize_project_path(media.relative_path.as_deref().ok_or("Scene generation video path is missing.")?)?);
+ version.latent_relative_path = version.latent_relative_path.as_deref().map(normalize_project_path).transpose()?;
+ if let Some(segments) = &mut media.scene_segments {
+ let mut end = 0u64;
+ for segment in segments {
+ if segment.scene_id.trim().is_empty() || segment.frame_count == 0 || u64::from(segment.start_frame) < end { return Err("Invalid scene generation segment.".into()); }
+ segment.latent_relative_path = normalize_project_path(&segment.latent_relative_path)?;
+ end = u64::from(segment.start_frame) + u64::from(segment.frame_count);
+ }
+ }
+ }
+ if [&history.primary_id, &history.selected_id].iter().any(|id| id.as_ref().is_some_and(|id| !ids.contains(id))) {
+ return Err("Scene history selection must name a saved generation.".into());
+ }
+ if let Some(draft) = &history.draft { validate_input(draft)?; }
+ Ok(())
+}
+
+
+#[cfg(test)]
+mod history_tests {
+ use super::*;
+ fn project_with_history() -> ProjectConfig {
+ let mut config: ProjectConfig = serde_json::from_str(include_str!("../../../../fixtures/project-v1-complete.json")).unwrap();
+ let job = &mut config.generation_jobs[0];
+ let mut input = serde_json::to_value(&job).unwrap();
+ for key in ["id", "status", "stage", "progress", "generationSnapshot", "clipId", "outputRelativePath", "latentRelativePath", "error", "createdAt", "updatedAt"] { input.as_object_mut().unwrap().remove(key); }
+ job.generator_template_id = Some("generator-original".into());
+ job.generation_history = Some(SceneGenerationHistory {
+ versions: vec![SceneGenerationVersion { id: "take-one".into(), created_at: job.created_at.clone(), scene: input.clone(),
+ media: config.assets.iter().find(|a| a.kind == "generated").unwrap().clone(), generation_snapshot: Some("saved-inputs".into()), latent_relative_path: Some("latents/one.safetensors".into()) }],
+ primary_id: Some("take-one".into()), selected_id: None, draft: Some(input),
+ });
+ config
+ }
+ #[test]
+ fn scene_history_and_draft_round_trip_without_a_four_take_schema_limit() {
+ let mut config = project_with_history();
+ let history = config.generation_jobs[0].generation_history.as_mut().unwrap();
+ let version = history.versions[0].clone();
+ for i in 2..=6 { let mut take = version.clone(); take.id = format!("take-{i}"); history.versions.push(take); }
+ validate(&mut config).unwrap();
+ let json = serde_json::to_value(&config).unwrap();
+ assert_eq!(json["generationJobs"][0]["generationHistory"]["versions"].as_array().unwrap().len(), 6);
+ let mut restored: ProjectConfig = serde_json::from_value(json).unwrap(); validate(&mut restored).unwrap();
+ assert_eq!(restored.generation_jobs[0].generation_history, config.generation_jobs[0].generation_history);
+ assert_eq!(restored.generation_jobs[0].generator_template_id.as_deref(), Some("generator-original"));
+ }
+ #[test]
+ fn history_rejects_unsafe_paths_invalid_settings_and_nested_history() {
+ for kind in ["path", "settings", "nested", "selection", "duplicate"] {
+ let mut config = project_with_history();
+ let history = config.generation_jobs[0].generation_history.as_mut().unwrap();
+ match kind {
+ "path" => history.versions[0].media.relative_path = Some("../outside.mp4".into()),
+ "settings" => history.versions[0].scene["steps"] = serde_json::json!(-1),
+ "nested" => history.versions[0].scene["generationHistory"] = serde_json::json!({}),
+ "selection" => history.selected_id = Some("missing".into()),
+ _ => history.versions.push(history.versions[0].clone()),
+ }
+ assert!(validate(&mut config).is_err(), "{kind}");
+ }
+ }
+}
diff --git a/src/lib/project.ts b/src/lib/project.ts
index 0c319a2..c1d2445 100644
--- a/src/lib/project.ts
+++ b/src/lib/project.ts
@@ -550,7 +550,8 @@ export function shotReferenceIds(shot: Pick<SceneShot, "action" | "speech">): st
return [...new Set([...actionReferenceIds(shot.action), ...actionReferenceIds(shot.speech ?? "")])];
}
-export const generationJobSchema = z.object({
+const generationJobBaseSchema = z.object({
+ generatorTemplateId: idSchema.nullish(),
id: idSchema,
sceneType: sceneTypeSchema.nullish(),
backdropColor: z.enum(["green", "blue", "black", "white"]).nullish(),
@@ -627,7 +628,27 @@ export const generationJobSchema = z.object({
error: z.string().min(1).nullable().optional(),
createdAt: isoDateSchema,
updatedAt: isoDateSchema,
-}).superRefine((job, context) => {
+});
+
+/** Input-only snapshots cannot contain history recursively. Keep new scene
+ * controls in the base schema so they automatically participate in history. */
+export const sceneInputSchema = generationJobBaseSchema.omit({ id: true, status: true, stage: true, progress: true,
+ generationSnapshot: true, clipId: true, outputRelativePath: true, latentRelativePath: true, error: true, createdAt: true, updatedAt: true });
+export type SceneInput = z.infer<typeof sceneInputSchema>;
+export const sceneGenerationVersionSchema = z.object({
+ id: idSchema, createdAt: isoDateSchema, scene: sceneInputSchema, media: projectAssetSchema,
+ generationSnapshot: z.string().nullish(), latentRelativePath: projectRelativePathSchema.nullish(),
+});
+export type SceneGenerationVersion = z.infer<typeof sceneGenerationVersionSchema>;
+const sceneGenerationHistorySchema = z.object({
+ versions: z.array(sceneGenerationVersionSchema), primaryId: idSchema.nullish(), selectedId: idSchema.nullish(), draft: sceneInputSchema.nullish(),
+}).superRefine((history, ctx) => {
+ const ids = new Set(history.versions.map(v => v.id));
+ if (ids.size !== history.versions.length || [history.primaryId, history.selectedId].some(id => id && !ids.has(id))
+ || history.versions.some(v => v.media.kind !== "generated" || !v.media.relativePath))
+ ctx.addIssue({ code: "custom", message: "Scene history must contain unique, saved video generations and valid selections." });
+});
+export const generationJobSchema = generationJobBaseSchema.extend({ generationHistory: sceneGenerationHistorySchema.nullish() }).superRefine((job, context) => {
/* A job carries the user's words in ONE of two places. A scene keeps them on
its shots; everything written before scenes existed keeps them in `prompt`
and `creativeBrief`, which is why those two may not both be blank when
diff --git a/src/lib/projectSession.ts b/src/lib/projectSession.ts
index 2653667..f7ec11d 100644
--- a/src/lib/projectSession.ts
+++ b/src/lib/projectSession.ts
@@ -1,3 +1,4 @@
+import { saveSceneDrafts } from "./sceneHistory";
import { describeDiagnosticError, writeDiagnostic } from "./diagnostics";
import type { ProjectConfig, ProjectRecord } from "./project";
import { saveImageDraft } from "./imageHistory";
@@ -69,7 +70,7 @@ export class ProjectSession {
private backgroundSeq = 0;
constructor(readonly record: ProjectRecord, private writer: ProjectWriter) {
this.savedConfig = record.config;
- const config = saveImageDraft(record.config);
+ const config = saveSceneDrafts(saveImageDraft(record.config));
const stamped = Date.parse(record.config.updatedAt);
this.state = { config, dirty: config !== record.config, saving: false, saveError: null, canUndo: false, canRedo: false, savedAt: Number.isFinite(stamped) ? stamped : null };
this.history.subscribe(() => {
@@ -91,7 +92,7 @@ export class ProjectSession {
/** A change the app makes on its own. Never an undo step (see above). */
update = (next: ProjectUpdate, dirty = true) => {
- const config = saveImageDraft(typeof next === "function" ? next(this.state.config) : next);
+ const config = saveSceneDrafts(saveImageDraft(typeof next === "function" ? next(this.state.config) : next), this.state.config);
if (config === this.state.config) return;
if (typeof next === "function") {
this.backgroundSeq += 1;
@@ -103,7 +104,7 @@ export class ProjectSession {
/** A change the person made: recorded for undo. Same `key` within 500ms = one step. */
edit = (next: ProjectUpdate, key = "edit") => {
- const config = saveImageDraft(addReferenceImageAssets(typeof next === "function" ? next(this.state.config) : next, this.state.config.references));
+ const config = saveSceneDrafts(saveImageDraft(addReferenceImageAssets(typeof next === "function" ? next(this.state.config) : next, this.state.config.references)), this.state.config);
if (config === this.state.config) return;
this.history.record({ config: this.state.config, mark: this.backgroundSeq }, key);
this.apply(config, true);
@@ -119,7 +120,7 @@ export class ProjectSession {
if (change.seq <= entry.mark) continue;
try { config = change.apply(config); } catch { /* A patch whose target is gone is simply skipped. */ }
}
- return saveImageDraft(config);
+ return saveSceneDrafts(saveImageDraft(config));
}
undo = (): boolean => {
diff --git a/src/lib/sceneHistory.test.ts b/src/lib/sceneHistory.test.ts
new file mode 100644
index 0000000..3ca74a9
--- /dev/null
+++ b/src/lib/sceneHistory.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it, vi } from "vitest";
+import { createProjectConfig, generationAssetId, parseProjectConfig, type ProjectConfig, type SceneGenerationVersion } from "./project";
+import { completeSceneGeneration, duplicateScene, makeSceneGenerationPrimary, saveSceneDrafts, sceneInput, selectSceneGeneration, SCENE_GENERATION_HISTORY_LIMIT } from "./sceneHistory";
+import { ProjectSession } from "./projectSession";
+
+const initial = () => createProjectConfig({ name: "History", prompt: "A quiet scene", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 5 });
+function take(config: ProjectConfig, id: string): SceneGenerationVersion {
+ const job = config.generationJobs[0];
+ return { id, createdAt: new Date(0).toISOString(), scene: sceneInput(job), generationSnapshot: id, latentRelativePath: `latents/${id}.safetensors`,
+ media: { id: generationAssetId(job.id), name: job.title, kind: "generated", mimeType: "video/mp4", relativePath: `media/${id}.mp4`, width: 736, height: 416, durationMs: 5000, createdAt: new Date(0).toISOString(), hasAudio: true } };
+}
+function finish(config: ProjectConfig, id: string) { return completeSceneGeneration(config, config.generationJobs[0].id, take(config, id)); }
+const edit = (config: ProjectConfig, music: string) => saveSceneDrafts({ ...config, generationJobs: config.generationJobs.map(j => ({ ...j, music, steps: music === "First" ? 4 : 8, seed: music === "First" ? 10 : 20,
+ shots: j.shots!.map(shot => ({ ...shot, action: music, speech: `${music} speech` })) })) }, config);
+
+describe("scene generation history", () => {
+ it("restores complete scene inputs while retaining a separate primary output and editable draft", () => {
+ let config = finish(edit(initial(), "First"), "one");
+ config = finish(edit(config, "Second"), "two");
+ const id = config.generationJobs[0].id;
+ config = edit(config, "Pending");
+ config = selectSceneGeneration(config, id, "one");
+ expect(config.generationJobs[0]).toMatchObject({ music: "First", steps: 4, seed: 10, outputRelativePath: "media/two.mp4", generationHistory: { selectedId: "one", primaryId: "two", draft: { music: "Pending" } } });
+ expect(config.generationJobs[0].shots![0]).toMatchObject({ action: "First", speech: "First speech" });
+ config = selectSceneGeneration(config, id, null);
+ expect(config.generationJobs[0]).toMatchObject({ music: "Pending", steps: 8, seed: 20 });
+ expect(config.generationJobs[0].generationHistory!.versions[0].scene.music).toBe("First");
+ });
+ it("removes optional settings when restoring a take that never had them", () => {
+ let config = finish(initial(), "one");
+ config = { ...config, generationJobs: config.generationJobs.map(j => ({ ...j, audioSteps: 8, latentUpscale: true, backdropColor: "green" as const })) };
+ const selected = selectSceneGeneration(config, config.generationJobs[0].id, "one").generationJobs[0];
+ expect(selected.audioSteps).toBeUndefined(); expect(selected.latentUpscale).toBeUndefined(); expect(selected.backdropColor).toBeUndefined();
+ expect(selected.generationHistory!.draft).toMatchObject({ audioSteps: 8, latentUpscale: true });
+ });
+ it("promotes an older take on the stable timeline asset without overwriting the draft", () => {
+ let config = finish(edit(initial(), "First"), "one"); config = finish(edit(config, "Second"), "two"); config = edit(config, "Pending");
+ const id = config.generationJobs[0].id, assetId = generationAssetId(id), track = config.timeline.tracks[0];
+ track.clips = [{ id: "clip", assetId, trackId: track.id, label: "Scene", startMs: 0, sourceStartMs: 0, durationMs: 5000, status: "generated" }];
+ config = makeSceneGenerationPrimary(config, id, "one");
+ expect(config.assets.find(a => a.id === assetId)?.relativePath).toBe("media/one.mp4");
+ expect(config.generationJobs[0]).toMatchObject({ music: "Pending", latentRelativePath: "latents/one.safetensors", outputRelativePath: "media/one.mp4", generationSnapshot: "one", generationHistory: { primaryId: "one", selectedId: null } });
+ expect(config.timeline.tracks[0].clips[0].assetId).toBe(assetId);
+ });
+ it("keeps edits made during rendering and replays completion without duplicate versions", () => {
+ let config = finish(initial(), "one"); const submitted = take(config, "two"), id = config.generationJobs[0].id;
+ config = edit(config, "Typed while rendering");
+ config = completeSceneGeneration(config, id, submitted);
+ expect(config.generationJobs[0]).toMatchObject({ music: "Typed while rendering", generationHistory: { selectedId: null, draft: { music: "Typed while rendering" }, primaryId: "two" } });
+ config = completeSceneGeneration(config, id, submitted);
+ expect(config.generationJobs[0].generationHistory!.versions).toHaveLength(2);
+ });
+ it("retains four complete takes using a policy independent of the serialized array", () => {
+ let config = initial();
+ for (let i = 0; i < 7; i++) config = finish(config, `take-${i}`);
+ const history = config.generationJobs[0].generationHistory!;
+ expect(history.versions.map(v => v.id)).toEqual(["take-3", "take-4", "take-5", "take-6"]);
+ expect(history.versions).toHaveLength(SCENE_GENERATION_HISTORY_LIMIT);
+ history.versions.push({ ...history.versions[0], id: "future" });
+ expect(parseProjectConfig(JSON.parse(JSON.stringify(config))).generationJobs[0].generationHistory!.versions).toHaveLength(5);
+ });
+ it("duplicates inputs and shots with fresh identity and no output or generation history", () => {
+ const config = finish(edit(initial(), "First"), "one");
+ const duplicated = duplicateScene(config, config.generationJobs[0].id)!;
+ const original = config.generationJobs[0], copy = duplicated.config.generationJobs[1];
+ expect(copy).toMatchObject({ title: `${original.title} copy`, music: "First", steps: 4, seed: 10, status: "draft" });
+ expect(copy.id).not.toBe(original.id); expect(copy.shots![0].id).not.toBe(original.shots![0].id);
+ expect(copy.outputRelativePath).toBeFalsy(); expect(copy.generationHistory).toBeUndefined(); expect(copy.clipId).toBeFalsy();
+ copy.shots![0].action = "Changed"; expect(original.shots![0].action).toBe("First");
+ });
+ it("preserves histories and drafts across project persistence and undo of edits", () => {
+ const config = finish(edit(initial(), "First"), "one");
+ const session = new ProjectSession({ folderPath: "C:/history", config }, vi.fn(async () => {}));
+ session.edit(c => edit(c, "Draft"));
+ const restored = parseProjectConfig(JSON.parse(JSON.stringify(session.getSnapshot().config)));
+ expect(restored.generationJobs[0].generationHistory!.draft?.music).toBe("Draft");
+ expect(session.undo()).toBe(true); expect(session.getSnapshot().config.generationJobs[0].music).toBe("First");
+ expect(session.redo()).toBe(true); expect(session.getSnapshot().config.generationJobs[0].music).toBe("Draft");
+ });
+ it("adopts an existing video before an edit and blocks switching while rendering", () => {
+ const config = initial(); config.generationJobs[0].outputRelativePath = "media/legacy.mp4"; config.generationJobs[0].status = "completed";
+ const edited = edit(config, "New");
+ expect(edited.generationJobs[0].generationHistory!.versions[0].scene.music).not.toBe("New");
+ edited.generationJobs[0].status = "generating";
+ expect(selectSceneGeneration(edited, edited.generationJobs[0].id, edited.generationJobs[0].generationHistory!.versions[0].id).generationJobs[0].music).toBe("New");
+ });
+});
diff --git a/src/lib/sceneHistory.ts b/src/lib/sceneHistory.ts
new file mode 100644
index 0000000..d96da3e
--- /dev/null
+++ b/src/lib/sceneHistory.ts
@@ -0,0 +1,115 @@
+import { createDraftGenerationJob, generationAssetId, sceneInputSchema, sceneShots, type GenerationJob, type ProjectConfig, type ProjectAsset, type SceneInput, type SceneGenerationVersion } from "./project";
+
+/** Retention policy, independent of the persisted array and the bar layout. */
+export const SCENE_GENERATION_HISTORY_LIMIT = 4;
+export const sceneInput = (job: GenerationJob): SceneInput => sceneInputSchema.parse(job);
+function canonical(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(canonical);
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).filter(([, v]) => v != null).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, canonical(v)]));
+ return value;
+}
+export const sameSceneInput = (a: SceneInput, b: SceneInput) => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
+function applyInput(job: GenerationJob, input: SceneInput): GenerationJob {
+ // Delete absent optional controls too: a newer take may have added one.
+ const next = { ...job };
+ for (const key of Object.keys(sceneInputSchema.shape)) delete (next as unknown as Record<string, unknown>)[key];
+ return { ...next, ...structuredClone(input), updatedAt: new Date().toISOString() };
+}
+
+/** Adopt old projects' existing result before any edit or new generation. */
+export function sceneHistory(job: GenerationJob, assets: readonly ProjectAsset[]) {
+ if (job.generationHistory) return job.generationHistory;
+ if (!job.outputRelativePath) return { versions: [], primaryId: null, selectedId: null, draft: sceneInput(job) };
+ const media = assets.find(a => a.id === generationAssetId(job.id) || a.kind === "generated" && a.relativePath === job.outputRelativePath);
+ const version: SceneGenerationVersion = { id: `legacy-${job.id}`, createdAt: job.updatedAt, scene: sceneInput(job),
+ media: { ...media, id: generationAssetId(job.id), name: job.title, kind: "generated", mimeType: "video/mp4", relativePath: job.outputRelativePath, createdAt: media?.createdAt ?? job.createdAt },
+ generationSnapshot: job.generationSnapshot, latentRelativePath: job.latentRelativePath };
+ return { versions: [version], primaryId: version.id, selectedId: version.id, draft: null };
+}
+
+/** Also called by sessions, so agent edits and edits during rendering create a
+ * draft just like inspector changes. Merely browsing a take is not an edit. */
+export function saveSceneDrafts(config: ProjectConfig, previous?: ProjectConfig): ProjectConfig {
+ let changed = false;
+ const generationJobs = config.generationJobs.map(job => {
+ const before = previous?.generationJobs.find(j => j.id === job.id);
+ let history = job.generationHistory;
+ if (!history && (job.outputRelativePath || before?.outputRelativePath)) history = sceneHistory(before ?? job, previous?.assets ?? config.assets);
+ if (!history) return job;
+ const input = sceneInput(job);
+ const selectedId = history.selectedId;
+ const selected = history.versions.find(v => v.id === selectedId);
+ if (selected && !sameSceneInput(input, selected.scene)) history = { ...history, selectedId: null, draft: input };
+ else if (!selected && (!history.draft || !sameSceneInput(input, history.draft))) history = { ...history, selectedId: null, draft: input };
+ if (history === job.generationHistory) return job;
+ changed = true; return { ...job, generationHistory: history };
+ });
+ return changed ? { ...config, generationJobs } : config;
+}
+
+export function selectSceneGeneration(config: ProjectConfig, sceneId: string, versionId: string | null): ProjectConfig {
+ const saved = saveSceneDrafts(config);
+ return { ...saved, generationJobs: saved.generationJobs.map(job => {
+ if (job.id !== sceneId || ["queued", "generating", "ready"].includes(job.status)) return job;
+ const history = sceneHistory(job, saved.assets);
+ const input = versionId ? history.versions.find(v => v.id === versionId)?.scene : history.draft;
+ if (!input) return job;
+ return { ...applyInput(job, input), generationHistory: { ...history, selectedId: versionId } };
+ }) };
+}
+
+/** Browsing changes the board's preview, never the primary output used by
+ * timeline clips, continuations and generation references. */
+export function scenePreviewJob(job: GenerationJob, assets: readonly ProjectAsset[]): GenerationJob {
+ if (["queued", "generating", "ready"].includes(job.status)) return job;
+ const history = sceneHistory(job, assets);
+ const selected = history.versions.find(v => v.id === history.selectedId);
+ if (selected) return { ...job, status: "completed", outputRelativePath: selected.media.relativePath, latentRelativePath: selected.latentRelativePath };
+ return job;
+}
+export function scenePreviewAsset(job: GenerationJob, assets: readonly ProjectAsset[]) {
+ const history = sceneHistory(job, assets);
+ return history.versions.find(v => v.id === history.selectedId)?.media ?? assets.find(a => a.id === generationAssetId(job.id));
+}
+
+export function makeSceneGenerationPrimary(config: ProjectConfig, sceneId: string, versionId: string): ProjectConfig {
+ const job = config.generationJobs.find(j => j.id === sceneId);
+ if (!job || ["queued", "generating", "ready"].includes(job.status)) return config;
+ const history = sceneHistory(job, config.assets), version = history.versions.find(v => v.id === versionId);
+ if (!version) return config;
+ const assetId = generationAssetId(sceneId);
+ const media = { ...structuredClone(version.media), id: assetId };
+ return { ...config,
+ generationJobs: config.generationJobs.map(j => j.id !== sceneId ? j : { ...j, generationHistory: { ...history, primaryId: versionId },
+ outputRelativePath: media.relativePath, latentRelativePath: version.latentRelativePath, generationSnapshot: version.generationSnapshot, status: "completed", stage: "completed", progress: 1, error: null }),
+ assets: [...config.assets.map(a => a.id === assetId || a.kind === "generated" && a.relativePath === job.outputRelativePath
+ ? { ...media, id: a.id, name: a.name } : a), ...(config.assets.some(a => a.id === assetId) ? [] : [media])],
+ };
+}
+
+/** Replay-safe background result: keep live edits and never duplicate a take
+ * when an undo replays this callback. Completed takes become primary. */
+export function completeSceneGeneration(config: ProjectConfig, sceneId: string, version: SceneGenerationVersion, note?: string | null): ProjectConfig {
+ const saved = saveSceneDrafts(config);
+ const job = saved.generationJobs.find(j => j.id === sceneId);
+ if (!job) return saved;
+ const history = sceneHistory(job, saved.assets);
+ const matching = sameSceneInput(sceneInput(job), version.scene);
+ const draft = matching ? (history.draft && !sameSceneInput(history.draft, version.scene) ? history.draft : null) : sceneInput(job);
+ const versions = [...history.versions.filter(v => v.id !== version.id), structuredClone(version)].slice(-SCENE_GENERATION_HISTORY_LIMIT);
+ const next = { ...saved, generationJobs: saved.generationJobs.map(j => j.id === sceneId ? { ...j, status: "completed" as const,
+ generationHistory: { versions, primaryId: version.id, selectedId: matching ? version.id : null, draft } } : j) };
+ const primary = makeSceneGenerationPrimary(next, sceneId, version.id);
+ return { ...primary, generationJobs: primary.generationJobs.map(j => j.id === sceneId ? { ...j, error: note } : j),
+ timeline: { ...primary.timeline, tracks: primary.timeline.tracks.map(track => ({ ...track, clips: track.clips.map(clip => clip.assetId === generationAssetId(sceneId) ? { ...clip, status: "generated" as const } : clip) })) } };
+}
+
+export function duplicateScene(config: ProjectConfig, sceneId: string): { config: ProjectConfig; id: string } | null {
+ const source = config.generationJobs.find(j => j.id === sceneId); if (!source) return null;
+ const id = `job-${crypto.randomUUID()}`;
+ const base = createDraftGenerationJob("", { id, title: `${source.title} copy` });
+ const job = applyInput(base, { ...sceneInput(source), title: `${source.title} copy`,
+ shots: sceneShots(source).map(shot => ({ ...structuredClone(shot), id: `shot-${crypto.randomUUID()}` })) });
+ const index = config.generationJobs.indexOf(source);
+ return { id, config: { ...config, generationJobs: [...config.generationJobs.slice(0, index + 1), job, ...config.generationJobs.slice(index + 1)] } };
+}
diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.ts
index 15a864c..069ee99 100644
--- a/src/lib/workQueue.test.ts
+++ b/src/lib/workQueue.test.ts
@@ -1307,3 +1307,21 @@ it.each([false, true])("freezes latent upscale %s and saves the selected output
await finish(queue, work.id);
expect(vi.mocked(saveGeneratedScene).mock.calls[0][0].outputSize).toEqual(latentUpscale ? { width: 736, height: 416 } : undefined);
});
+
+
+it("archives the submitted scene, retains edits made in flight, and preserves history through undo", async () => {
+ const { queue, first } = setup();
+ const run = submission(first);
+ run.job = { ...run.job, shots: run.job.shots!.map(shot => ({ ...shot, action: "Submitted" })), music: "Original music" };
+ first.edit(c => ({ ...c, generationJobs: [run.job] }));
+ const [id] = queue.enqueue(first, [run]);
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());
+ first.edit(c => ({ ...c, generationJobs: c.generationJobs.map(job => ({ ...job, music: "Draft music", shots: job.shots!.map(shot => ({ ...shot, action: "Edited while generating" })) })) }));
+ await finish(queue, id);
+ const job = first.getSnapshot().config.generationJobs[0];
+ expect(job.generationHistory).toMatchObject({ primaryId: id, selectedId: null, draft: { music: "Draft music" } });
+ expect(job.generationHistory!.versions[0].scene).toMatchObject({ music: "Original music", shots: [expect.objectContaining({ action: "Submitted" })] });
+ first.undo();
+ expect(first.getSnapshot().config.generationJobs[0].generationHistory!.versions.map(v => v.id)).toEqual([id]);
+ expect(first.getSnapshot().config.assets[0].relativePath).toBe("media/generated/result.mp4");
+});
diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.ts
index ed188b0..de53444 100644
--- a/src/lib/workQueue.ts
+++ b/src/lib/workQueue.ts
@@ -1,3 +1,4 @@
+import { completeSceneGeneration, sceneInput } from "./sceneHistory";
import { imageCfgScale } from "./generatorModels";
import { activeGenerationEffects } from "./generationEffects";
import { imageSettings } from "./imageSettings";
@@ -12,12 +13,12 @@ import { completeImageDraft, createTemplateImageDraft, imageFamilyRoot, imageGen
import type { ImageGenerationSnapshot, ProjectAsset } from "./project";
import { outputDimensions } from "./export";
import { projectItemPath, referenceDefinition, referenceImages, referenceRefmodInputs } from "./project";
-import { generationSigmaShiftsWithLoras, engineProviderSetting, generatorModel, templateSupportsEditing, templateSupportsOutpainting, templateSupportsImages, templateSupportsVideo, type GeneratorTemplate } from "./settings";
+import { generationSigmaShiftsWithLoras, engineProviderSetting, generatorModel, templateSupportsEditing, templateSupportsOutpainting, templateSupportsImages, templateSupportsVideo, defaultGeneratorTemplate, loadGeneratorTemplateSettings, type GeneratorTemplate } from "./settings";
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, generationLatentPath, GENERATION_FRAME_RATE, sceneOutputFrames, sceneGenerationSnapshot, type GenerationJob, type ProjectRecord, type ProjectConfig } from "./project";
+import { generationAssetId, generationLatentPath, GENERATION_FRAME_RATE, sceneOutputFrames, sceneGenerationSnapshot, type SceneInput, type GenerationJob, type ProjectRecord, type ProjectConfig } from "./project";
import { ProjectSession, type ProjectWriter } from "./projectSession";
import { cancelSlopfabGeneration, enqueueSlopfabGeneration, resolveSlopfabPlan, type SlopfabGenerationRequest } from "./runtime";
import { generationStepsWithLoras, withEngineSettings } from "./settings";
@@ -32,7 +33,7 @@ import type { SceneMediaSegment } from "./project";
import { exportReferenceRefmod, refmodExportBlocker, refmodExportRequest, type RefmodExportTarget } from "./refmodExport";
export type WorkStatus = "queued" | "preparing" | "generating" | "encoding" | "completed" | "failed" | "cancelled";
-export interface GenerationSubmission { job: GenerationJob; request: SlopfabGenerationRequest; snapshot: string }
+export interface GenerationSubmission { job: GenerationJob; request: SlopfabGenerationRequest; snapshot: string; template?: GeneratorTemplate }
export const MAX_IMAGE_BATCH_COUNT = 100;
function imageGenerationSeed(seed: number): number {
@@ -63,6 +64,7 @@ export interface WorkItem {
settings: { frames: number; steps: number; audioSteps?: number; videoSigmaShift?: number; audioSigmaShift?: number; latentUpscale?: boolean; seed: number; canvasWidth: number; canvasHeight: number };
}
interface PendingWork {
+ sceneInput?: SceneInput;
extend?: { sourceId: string; name: string; options: ExtendOptions };
characterSheet?: {
views: ReturnType<typeof compileCharacterSheet>; sourceId: string; name: string; index: number;
@@ -218,19 +220,22 @@ export class WorkQueue {
// Take every setting before the first await, including the selected engine
// template. Planning and native submission consume this same private copy.
const current = session.getSnapshot().config;
- const config = structuredClone(template ? { ...current, providerSettings: { ...current.providerSettings,
- slopfab: engineProviderSetting(template.paths, current.providerSettings.slopfab, template.attention, template.loras ?? [], template.mode ?? "prompt", template.additionalSafetensors ?? [], template.motionCache ?? false, template.sources ?? {}, template),
- } } : withEngineSettings(current));
const ids: string[] = [];
for (const submission of submissions) {
if (this.items.some((item) => item.projectKey === projectKey && item.sceneId === submission.job.id && isWorkActive(item))) continue;
+ const chosen = template ?? submission.template ?? loadGeneratorTemplateSettings().templates.find(t => t.id === submission.job.generatorTemplateId) ?? defaultGeneratorTemplate(undefined, "video");
+ const config = structuredClone({ ...current, providerSettings: { ...current.providerSettings,
+ slopfab: engineProviderSetting(chosen.paths, current.providerSettings.slopfab, chosen.attention, chosen.loras ?? [], chosen.mode ?? "prompt", chosen.additionalSafetensors ?? [], chosen.motionCache ?? false, chosen.sources ?? {}, chosen),
+ } });
+ const captured = { ...submission.job, generatorTemplateId: chosen.id || undefined, steps: submission.request.steps, seed: submission.request.seed };
+ config.generationJobs = config.generationJobs.map(j => j.id === captured.id ? structuredClone(captured) : j);
const id = `work-${crypto.randomUUID()}`;
ids.push(id);
let finish!: () => void;
const done = new Promise<void>((resolve) => { finish = resolve; });
const request = structuredClone({ ...submission.request, jobId: id, steps: generationStepsWithLoras(submission.request.steps, config),
...generationSigmaShiftsWithLoras(submission.request, config) });
- this.work.set(id, { id, session, sceneId: submission.job.id, request, config, snapshot: submission.snapshot, cancelled: false, submitted: false, done, finish });
+ this.work.set(id, { id, session, sceneId: submission.job.id, sceneInput: sceneInput(captured), 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(),
@@ -238,7 +243,7 @@ export class WorkQueue {
cancelling: false, needsSave: false,
settings: { frames: request.frames, steps: request.steps, audioSteps: request.audioSteps, videoSigmaShift: request.videoSigmaShift, audioSigmaShift: request.audioSigmaShift, latentUpscale: request.latentUpscale, 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.updateScene(this.work.get(id)!, { status: "queued", stage: "queued", progress: 0, error: null, generationSnapshot: submission.snapshot, generatorTemplateId: captured.generatorTemplateId, steps: captured.steps, seed: captured.seed });
}
this.publish();
if (this.items.some((item) => item.status === "queued" && item.kind !== "reference-icons")) this.icons.yieldToVideo();
@@ -746,8 +751,10 @@ export class WorkQueue {
segments: work.continuationSegments, from: work.request.continuationFrom,
} : undefined);
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(totalFrames / GENERATION_FRAME_RATE * 1000), sceneSegments };
- work.session.update(videoResultUpdate(work.sceneId, assetId, media, { status: "completed", stage: "completed", progress: 1,
- generationSnapshot: work.snapshot, outputRelativePath: saved.relativePath, latentRelativePath: generationLatentPath(work.id), error: saved.note }));
+ const version = { id: work.id, createdAt: new Date().toISOString(), scene: work.sceneInput!,
+ media: { ...media, id: assetId, name: work.sceneInput!.title, createdAt: new Date().toISOString() },
+ generationSnapshot: work.snapshot, latentRelativePath: generationLatentPath(work.id) };
+ work.session.update(sceneResultUpdate(work.sceneId, version, saved.note));
try {
await work.session.save();
this.patch(work.id, { status: "completed", progress: 1, detail: "Video saved", error: saved.note });
@@ -803,17 +810,8 @@ function derivedImageUpdate(id: string, sourceId: string, asset: ProjectAsset) {
});
}
-function videoResultUpdate(sceneId: string, assetId: string, media: Omit<ProjectAsset, "id" | "name" | "createdAt">, patch: Partial<GenerationJob>) {
- const update = sceneUpdate(sceneId, patch);
- return (current: ProjectConfig): ProjectConfig => ({
- ...update(current),
- assets: current.assets.some((asset) => asset.id === assetId)
- ? current.assets.map((asset) => asset.id === assetId ? { ...asset, ...media } : asset)
- : current.generationJobs.some((job) => job.id === sceneId)
- ? [...current.assets, { id: assetId, name: current.generationJobs.find((job) => job.id === 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) })) },
- });
+function sceneResultUpdate(sceneId: string, version: Parameters<typeof completeSceneGeneration>[2], note?: string | null) {
+ return (current: ProjectConfig) => completeSceneGeneration(current, sceneId, version, note);
}
function imageResultUpdate({ id, imageDraftId, imageParentId, imageGeneration, outputAssetId, imageEdit, saved }: {