AI media harness for planning, generating, and editing locally
TypeScript
Add Continue scenes with selectable latents
Bitti47c866477890
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.mdindex 80337a9..1595d48 100644--- a/RELEASE_NOTES.md+++ b/RELEASE_NOTES.md@@ -4,6 +4,7 @@ This alpha update adds DMAD LoRA support, resumable model downloads, and improve## What's new+- Continue scenes from a selected scene's saved latents, with adjustable overlap and a choice of beginning or end. This replaces Previous scene in First & last frame.- Copying or cutting prompts preserves reference chips when pasted into other prompt fields.- Choose Make Primary on an image version to show it in the main image bar and use it when creating scenes or references from that family.- Images imported through Timeline or References, including selected video reference frames, appear in the image bar and open for editing.diff --git a/docs/scene-types.md b/docs/scene-types.mdindex 12fc1f9..1e33e49 100644--- a/docs/scene-types.md+++ b/docs/scene-types.md@@ -3,6 +3,7 @@The Scene panel saves a type on each scene:- **First & Last Frame** keeps the existing shot descriptions, speech, Look, sound, music and optional frame anchors. Older scenes without a type use this type.+- **Continue** uses another scene's saved latents. Choose the source scene, beginning or end (default: end), and overlap in frames (default: 22; increments of 17 at 24 fps). Generate the source first, or use Generate All to render dependencies in order. Scene length controls the new segment. Old Previous scene selections become Continue scenes linked to their original source; reordering scenes keeps that link.- **Animate** uses an Animate generator, one driving video and one repainted scene frame. It does not send a text prompt.- **Pose** uses a selected video for body pose, movement and timing. The Scene panel places the video selector above the shot prompts, where optional references can define the target subject and setting. It uses the video's saved clip range without its soundtrack, attached stills or refmods. Only the selected pose video and references cited in the prompts are sent; frame anchors and previous-scene continuation are inactive. Pose requires a nonempty prompt and reference-capable MiniMax weights (References or Singularity), with the existing limits of three videos, nine images and 15 seconds of reference video.- **Character Replace** gives each shot a source video selector, a new character reference selector and an optional description identifying the character to replace. The character reference must contain an image. Blank target descriptions mean the main character.diff --git a/src-tauri/assets/h3-agent.md b/src-tauri/assets/h3-agent.mdindex bddaf53..11c1986 100644--- a/src-tauri/assets/h3-agent.md+++ b/src-tauri/assets/h3-agent.md@@ -1,4 +1,4 @@-Set usePreviousSceneLastFrame to true to continue the preceding Generator scene using its saved audio/video latents with 22 overlapping frames. Slopus saves those latents on each generation; the preceding scene must be generated first, or queued earlier with Generate All. The continued scene's seconds describe its new segment. This option replaces startFrame image conditioning and requires the same canvas dimensions as the source.+Set usePreviousSceneLastFrame to true to create a Continue scene linked to the preceding scene, using its final 22 frames of saved audio/video latents. The user can change the source, overlap, and beginning/end selection in the Continue scene panel. Slopus saves latents on each generation; generate the source first or use Generate All. The continued scene's seconds describe its new segment. Continue replaces frame image conditioning and requires the same canvas dimensions as the source.- Existing video references can guide movement, camera work, or appearance. Cite their reference IDs with the same @[ref:<reference-id>] tokens; Slopus supplies the <Video N> labels and the saved clip/soundtrack settings. A scene may use up to three video clips totaling 15 seconds. Do not invent video paths or add raw <Video N> labels to shot action.@@ -19,4 +19,3 @@ Use shot.settings when a supported setting materially clarifies how an individua- visualStyle is scene-wide and belongs only on the earliest shot. Single-choice groups take one option; cameraMovement, lighting, and mood may take more than one only when the choices are compatible.- A non-static cameraMovement must also have one cameraSpeed and one cameraAmplitude. static-shot cannot be combined with another movement, speed, or amplitude.- Keep settings consistent with shot.action, references, scene Look, and adjacent shots. Do not over-specify a short shot or add mutually contradictory choices.-diff --git a/src-tauri/core/Cargo.toml b/src-tauri/core/Cargo.tomlindex 7d42628..5f6801e 100644--- a/src-tauri/core/Cargo.toml+++ b/src-tauri/core/Cargo.toml@@ -22,11 +22,9 @@ jpeg-encoder = "0.6"image = { version = "=0.25.8", default-features = false, features = ["jpeg", "png"] }tiny_http = "0.12"mdns-sd = "0.21"+tempfile = "3"[target.'cfg(windows)'.dependencies]# DXGI reads GPU memory for weight selection without a CUDA toolkit.windows = { version = "0.61", features = ["Win32_Graphics_Dxgi", "Win32_Foundation"] }windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }--[dev-dependencies]-tempfile = "3"diff --git a/src-tauri/core/src/slopfab/continuation.rs b/src-tauri/core/src/slopfab/continuation.rsnew file mode 100644index 0000000..2375f67--- /dev/null+++ b/src-tauri/core/src/slopfab/continuation.rs@@ -0,0 +1,337 @@+//! Select opening latents without changing the source archive or runtime ABI.+//! The native setter owns its snapshot, so the temporary archive can be dropped+//! immediately after attachment. End selection uses the original archive.+use super::types::GenerationRequest;+use serde_json::{json, Value};+use std::{+ fs::File,+ io::{Read, Seek, SeekFrom, Write},+};++pub(super) fn validate(request: &GenerationRequest) -> Result<(), String> {+ let overlap = request.continuation_overlap_frames.unwrap_or(22);+ if !(22..=362).contains(&overlap) || overlap % 17 != 5 {+ return Err("Continuation overlap must be 22, 39, 56, … frames (at most 362).".into());+ }+ if request+ .continuation_from+ .as_deref()+ .is_some_and(|value| !matches!(value, "start" | "end"))+ {+ return Err("Choose the beginning or end of the source scene.".into());+ }+ if request+ .continuation_source_frames+ .is_some_and(|frames| frames < overlap)+ {+ return Err("The selected scene is shorter than the continuation overlap.".into());+ }+ Ok(())+}++fn integer(meta: &Value, key: &str) -> Result<usize, String> {+ meta[key]+ .as_str()+ .and_then(|value| value.parse().ok())+ .ok_or_else(|| format!("Invalid latent archive {key}."))+}++fn read_rows(+ file: &mut File,+ data_start: u64,+ header: &Value,+ name: &str,+ rows: usize,+ columns: usize,+ start: usize,+ count: usize,+) -> Result<Vec<u8>, String> {+ let tensor = &header[name];+ if tensor["dtype"] != "F32" || tensor["shape"] != json!([rows, columns]) {+ return Err(format!("Invalid {name} latent geometry."));+ }+ let begin = tensor["data_offsets"][0]+ .as_u64()+ .ok_or("Invalid latent offsets.")?;+ let end = tensor["data_offsets"][1]+ .as_u64()+ .ok_or("Invalid latent offsets.")?;+ let row_bytes = columns.checked_mul(4).ok_or("Latent row size overflow.")?;+ let size = rows+ .checked_mul(row_bytes)+ .ok_or("Latent tensor size overflow.")?;+ let file_size = file.metadata().map_err(|e| e.to_string())?.len();+ if end.checked_sub(begin) != Some(size as u64)+ || start.checked_add(count).is_none_or(|n| n > rows)+ || data_start.checked_add(end).is_none_or(|n| n > file_size)+ {+ return Err("Truncated or invalid latent tensor.".into());+ }+ let offset = data_start+ .checked_add(begin)+ .and_then(|n| n.checked_add((start * row_bytes) as u64))+ .ok_or("Latent offset overflow.")?;+ file.seek(SeekFrom::Start(offset))+ .map_err(|e| e.to_string())?;+ let mut bytes = vec![+ 0;+ count+ .checked_mul(row_bytes)+ .ok_or("Latent slice size overflow.")?+ ];+ file.read_exact(&mut bytes).map_err(|e| e.to_string())?;+ Ok(bytes)+}++pub(super) fn opening_archive(+ request: &GenerationRequest,+) -> Result<Option<tempfile::TempPath>, String> {+ validate(request)?;+ if request.continuation_from.as_deref() != Some("start") {+ return Ok(None);+ }+ let path = request+ .continuation_path+ .as_ref()+ .ok_or("The continuation source has not been resolved.")?;+ let mut source = File::open(path).map_err(|e| format!("Could not read source latents: {e}"))?;+ let mut length = [0; 8];+ source.read_exact(&mut length).map_err(|e| e.to_string())?;+ let header_len = u64::from_le_bytes(length);+ if header_len > 1024 * 1024 {+ return Err("Invalid latent archive header length.".into());+ }+ let mut bytes = vec![0; header_len as usize];+ source.read_exact(&mut bytes).map_err(|e| e.to_string())?;+ let header: Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;+ let mut meta = header["__metadata__"].clone();+ if meta["slopfab_latents"] != "h3-av-v1" || meta["fps"] != "24" || meta["sampled"] != "1" {+ return Err("Continue requires completed H3 video latents.".into());+ }+ let frames = integer(&meta, "frames")?;+ let width = integer(&meta, "width")?;+ let height = integer(&meta, "height")?;+ if frames < 22+ || frames > i32::MAX as usize+ || frames % 17 != 5+ || width == 0+ || height == 0+ || width > 8192+ || height > 8192+ || width % 32 != 0+ || height % 32 != 0+ {+ return Err("Invalid source latent geometry.".into());+ }+ let overlap = request.continuation_overlap_frames.unwrap_or(22) as usize;+ let scene_frames = request+ .continuation_source_frames+ .map(|n| n as usize)+ .unwrap_or(frames);+ if scene_frames < overlap || scene_frames > frames {+ return Err("Overlap exceeds the selected source scene.".into());+ }+ let latent_frames = |count: usize| (count - 5) / 17 * 5 + 2;+ let video_frames = latent_frames(frames);+ // Continued archives include earlier scenes. New frames add five latent+ // frames per 17 video frames; start at this scene's own latent contribution.+ let first_video = if scene_frames == frames {+ 0+ } else {+ if scene_frames % 17 != 0 {+ return Err("Invalid continued scene length.".into());+ }+ video_frames+ .checked_sub(scene_frames / 17 * 5)+ .ok_or("Invalid scene latent range.")?+ };+ let row_frames = (width / 32)+ .checked_mul(height / 32)+ .ok_or("Latent canvas overflow.")?;+ let all_video = video_frames+ .checked_mul(row_frames)+ .ok_or("Latent geometry overflow.")?;+ let selected_video = latent_frames(overlap)+ .checked_mul(row_frames)+ .ok_or("Latent geometry overflow.")?;+ let audio_frames = frames+ .checked_mul(5)+ .and_then(|n| n.checked_add(1))+ .ok_or("Latent audio overflow.")?+ / 3;+ let first_audio = ((frames - scene_frames) * 5 + 1) / 3;+ let selected_audio = (overlap * 5 + 1) / 3;+ let video = read_rows(+ &mut source,+ header_len + 8,+ &header,+ "video_rows",+ all_video,+ 96,+ first_video * row_frames,+ selected_video,+ )?;+ // Audio rows are planar stereo, not interleaved: crop each channel.+ let mut audio = read_rows(+ &mut source,+ header_len + 8,+ &header,+ "audio_rows",+ audio_frames * 2,+ 32,+ first_audio,+ selected_audio,+ )?;+ audio.extend(read_rows(+ &mut source,+ header_len + 8,+ &header,+ "audio_rows",+ audio_frames * 2,+ 32,+ audio_frames + first_audio,+ selected_audio,+ )?);+ meta["frames"] = json!(overlap.to_string());+ let mut output_header = json!({+ "__metadata__": meta,+ "video_rows": { "dtype": "F32", "shape": [selected_video, 96], "data_offsets": [0, video.len()] },+ "audio_rows": { "dtype": "F32", "shape": [selected_audio * 2, 32], "data_offsets": [video.len(), video.len() + audio.len()] },+ }).to_string();+ while output_header.len() % 8 != 0 {+ output_header.push(' ');+ }+ let mut output = tempfile::NamedTempFile::new().map_err(|e| e.to_string())?;+ output+ .write_all(&(output_header.len() as u64).to_le_bytes())+ .and_then(|_| output.write_all(output_header.as_bytes()))+ .and_then(|_| output.write_all(&video))+ .and_then(|_| output.write_all(&audio))+ .and_then(|_| output.flush())+ .map_err(|e| e.to_string())?;+ // Close the file handle before the DLL opens it (Windows sharing rules).+ Ok(Some(output.into_temp_path()))+}++#[cfg(test)]+mod tests {+ use super::super::{planning::resolve_plan, references::ReferenceVideos};+ use super::*;+ use std::collections::BTreeMap;++ fn archive(frames: usize) -> tempfile::NamedTempFile {+ let video_rows = ((frames - 5) / 17 * 5 + 2) * 2;+ let audio_rows = ((frames * 5 + 1) / 3) * 2;+ let video_bytes = video_rows * 96 * 4;+ let audio_bytes = audio_rows * 32 * 4;+ let mut header = json!({+ "__metadata__": { "slopfab_latents": "h3-av-v1", "width": "64", "height": "32", "frames": frames.to_string(), "fps": "24", "sampled": "1" },+ "video_rows": { "dtype": "F32", "shape": [video_rows, 96], "data_offsets": [0, video_bytes] },+ "audio_rows": { "dtype": "F32", "shape": [audio_rows, 32], "data_offsets": [video_bytes, video_bytes + audio_bytes] }+ }).to_string();+ while header.len() % 8 != 0 {+ header.push(' ');+ }+ let mut file = tempfile::NamedTempFile::new().unwrap();+ file.write_all(&(header.len() as u64).to_le_bytes())+ .unwrap();+ file.write_all(header.as_bytes()).unwrap();+ for (rows, columns) in [(video_rows, 96), (audio_rows, 32)] {+ for row in 0..rows {+ for _ in 0..columns {+ file.write_all(&(row as f32).to_le_bytes()).unwrap();+ }+ }+ }+ file.flush().unwrap();+ file+ }++ #[test]+ fn opening_continuation_crops_the_selected_scene_and_both_audio_channels() {+ let source = archive(124);+ let original = std::fs::read(source.path()).unwrap();+ let request = GenerationRequest {+ continuation_path: Some(source.path().into()),+ continuation_from: Some("start".into()),+ continuation_source_frames: Some(85),+ continuation_overlap_frames: Some(22),+ ..Default::default()+ };+ let cropped = opening_archive(&request).unwrap().unwrap();+ let bytes = std::fs::read(&cropped).unwrap();+ let start = u64::from_le_bytes(bytes[..8].try_into().unwrap()) as usize + 8;+ let header: Value = serde_json::from_slice(&bytes[8..start]).unwrap();+ assert_eq!(header["__metadata__"]["frames"], "22");+ assert_eq!(header["video_rows"]["shape"], json!([14, 96]));+ let value = |at: usize| f32::from_le_bytes(bytes[at..at + 4].try_into().unwrap());+ assert_eq!(value(start), 24.0); // First row of the selected scene, not the chain.+ let audio = start + header["audio_rows"]["data_offsets"][0].as_u64().unwrap() as usize;+ assert_eq!(value(audio), 65.0);+ assert_eq!(value(audio + 37 * 32 * 4), 272.0);+ assert_eq!(std::fs::read(source.path()).unwrap(), original);+ let temporary = cropped.to_path_buf();+ drop(cropped);+ assert!(!temporary.exists());+ }++ #[test]+ fn continuation_plans_custom_overlap_from_either_edge_with_the_bundled_runtime() {+ let source = archive(124).into_temp_path();+ for edge in ["start", "end"] {+ for overlap in [22, 39, 56] {+ let request = GenerationRequest {+ job_id: "continued".into(),+ prompt: "Keep moving".into(),+ frames: 18,+ steps: 4,+ seed: 1,+ canvas_width: 64,+ canvas_height: 32,+ continuation_path: Some(source.to_path_buf()),+ continuation_from: Some(edge.into()),+ continuation_overlap_frames: Some(overlap),+ continuation_source_frames: Some(85),+ ..Default::default()+ };+ let plan =+ resolve_plan(&request, &BTreeMap::new(), &ReferenceVideos::default()).unwrap();+ assert_eq!(plan.aligned_frames, 34);+ assert!((plan.duration_seconds - 34.0 / 24.0).abs() < 0.0001);+ let wire = serde_json::to_value(&request).unwrap();+ assert_eq!(wire["continuationFrom"], edge);+ assert_eq!(wire["continuationOverlapFrames"], overlap);+ assert_eq!(wire["continuationSourceFrames"], 85);+ }+ }+ }++ #[test]+ fn continuation_rejects_invalid_ranges_and_truncated_archives() {+ for overlap in [0, 21, 23, 379] {+ assert!(validate(&GenerationRequest {+ continuation_overlap_frames: Some(overlap),+ ..Default::default()+ })+ .is_err());+ }+ assert!(validate(&GenerationRequest {+ continuation_source_frames: Some(17),+ ..Default::default()+ })+ .is_err());+ assert!(validate(&GenerationRequest {+ continuation_from: Some("middle".into()),+ ..Default::default()+ })+ .is_err());+ let source = archive(39);+ source.as_file().set_len(1024).unwrap();+ assert!(opening_archive(&GenerationRequest {+ continuation_path: Some(source.path().into()),+ continuation_from: Some("start".into()),+ ..Default::default()+ })+ .is_err());+ }+}diff --git a/src-tauri/core/src/slopfab/h3.rs b/src-tauri/core/src/slopfab/h3.rsindex 00dfe70..9c8700e 100644--- a/src-tauri/core/src/slopfab/h3.rs+++ b/src-tauri/core/src/slopfab/h3.rs@@ -78,10 +78,11 @@ pub(super) fn configure_request(api.set_video_transition(handle, if mode == "bridge" { 2 } else { 1 })?;}if let Some(path) = &request.continuation_path {+ let opening = super::continuation::opening_archive(request)?;api.set_continuation_file(handle,- path,- crate::models::H3_CAPABILITIES.continuation_overlap,+ opening.as_ref().map_or(path.as_path(), |file| file.as_ref()),+ request.continuation_overlap_frames.unwrap_or(crate::models::H3_CAPABILITIES.continuation_overlap),)?;}if purpose == RequestPurpose::Generate {diff --git a/src-tauri/core/src/slopfab/mod.rs b/src-tauri/core/src/slopfab/mod.rsindex 1f9c388..07ae254 100644--- a/src-tauri/core/src/slopfab/mod.rs+++ b/src-tauri/core/src/slopfab/mod.rs@@ -11,6 +11,7 @@ pub fn prepare_lora_grid(ffi::Api::load(&default_dll_path())?.prepare_lora_grid(path, width, allow_download)}mod config;+mod continuation;mod events;mod ffi;mod generation;diff --git a/src-tauri/core/src/slopfab/planning.rs b/src-tauri/core/src/slopfab/planning.rsindex 4f1964d..9ab4a59 100644--- a/src-tauri/core/src/slopfab/planning.rs+++ b/src-tauri/core/src/slopfab/planning.rs@@ -57,6 +57,7 @@ pub fn resolve_plan(}pub(super) fn validate_generation_controls(request: &GenerationRequest) -> Result<(), String> {+ super::continuation::validate(request)?;if let Some(edit) = &request.image_edit {if !request.still_image || request.frames != 1 || request.continuation_relative_path.is_some() || request.continuation_path.is_some() || request.video_transition.is_some()|| edit.edits.is_empty() || edit.edits.len() > 500 || request.canvas_width > 8192 || request.canvas_height > 8192@@ -124,7 +125,7 @@ pub(super) fn scene_frame_window(* limits.frame_stride;let offset = total.checked_sub(frames)- .filter(|offset| *offset >= limits.continuation_overlap)+ .filter(|offset| *offset >= request.continuation_overlap_frames.unwrap_or(limits.continuation_overlap)).ok_or("Slopfab continuation output is missing its source frames.".to_string())?;Ok((offset, frames))}diff --git a/src-tauri/core/src/slopfab/types.rs b/src-tauri/core/src/slopfab/types.rsindex 8a9a931..d5274da 100644--- a/src-tauri/core/src/slopfab/types.rs+++ b/src-tauri/core/src/slopfab/types.rs@@ -68,6 +68,12 @@ pub struct GenerationRequest {pub refmods: Vec<RefmodInput>,#[serde(default)]pub continuation_relative_path: Option<String>,+ #[serde(default)]+ pub continuation_overlap_frames: Option<i32>,+ #[serde(default)]+ pub continuation_from: Option<String>,+ #[serde(default)]+ pub continuation_source_frames: Option<i32>,// Only the project commands resolve paths; IPC cannot supply save targets.#[serde(skip)]pub continuation_path: Option<PathBuf>,diff --git a/src-tauri/src/project/commands/scenes.rs b/src-tauri/src/project/commands/scenes.rsindex b4dcc35..16caf0b 100644--- a/src-tauri/src/project/commands/scenes.rs+++ b/src-tauri/src/project/commands/scenes.rs@@ -82,11 +82,13 @@ pub(super) fn apply(if let Some(value) = start_frame_reference_id.value() {job.start_frame_reference_id = value.clone();job.use_previous_scene_last_frame = None;+ if job.scene_type.as_deref() == Some("continue") { job.scene_type = Some("first-last-frame".into()); }}if let Some(value) = end_frame_reference_id.value() {job.end_frame_reference_id = value.clone();}if let Some(value) = use_previous_scene_last_frame {+ job.scene_type = Some("first-last-frame".into());job.use_previous_scene_last_frame = Some(*value);if *value {job.start_frame_reference_id = None;diff --git a/src-tauri/src/project/commands/tests.rs b/src-tauri/src/project/commands/tests.rsindex c2aeec8..15d3511 100644--- a/src-tauri/src/project/commands/tests.rs+++ b/src-tauri/src/project/commands/tests.rs@@ -79,8 +79,8 @@ fn scene_frame_commands_accept_continuity_and_clear_the_last_frame() {Some(image.as_str()));assert_eq!(- updated.generation_jobs[0].use_previous_scene_last_frame,- Some(true)+ updated.generation_jobs[0].scene_type.as_deref(),+ Some("continue"));let clear: ProjectCommand = serde_json::from_value(serde_json::json!({"op": "scene.set", "id": id, "endFrame": null, "startFrame": imagediff --git a/src-tauri/src/project/scenes.rs b/src-tauri/src/project/scenes.rsindex 8a9765e..8162026 100644--- a/src-tauri/src/project/scenes.rs+++ b/src-tauri/src/project/scenes.rs@@ -82,6 +82,12 @@ pub(crate) struct GenerationJob {pub(crate) end_frame_reference_id: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]pub(crate) use_previous_scene_last_frame: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub(crate) continuation_scene_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub(crate) continuation_overlap_frames: Option<i32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub(crate) continuation_from: Option<String>,/// The H3 vocabulary tags this shot was built from: group id -> option ids./// zod spells it `.nullish()` (src/lib/project.ts `shotTagSelectionSchema`),/// so `null` IS readable on the frontend — but the key is still skipped@@ -159,6 +165,9 @@ impl GenerationJob {start_frame_reference_id: None,end_frame_reference_id: None,use_previous_scene_last_frame: None,+ continuation_scene_id: None,+ continuation_overlap_frames: None,+ continuation_from: None,shot_tags: None,shots: Some(Vec::new()),duration_seconds: Some(defaults.duration_seconds),diff --git a/src-tauri/src/project/validation/scenes.rs b/src-tauri/src/project/validation/scenes.rsindex 6cbda7a..64d2854 100644--- a/src-tauri/src/project/validation/scenes.rs+++ b/src-tauri/src/project/validation/scenes.rs@@ -3,11 +3,26 @@ use crate::project::paths::*;use crate::project::*;use std::collections::BTreeSet;pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {+ let mut previous_id = None;for job in &mut config.generation_jobs {+ 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());+ job.continuation_scene_id = previous_id.clone();+ job.continuation_overlap_frames = Some(22);+ job.continuation_from = Some("end".into());+ job.use_previous_scene_last_frame = None;+ }+ previous_id = Some(job.id.clone());+ if job.continuation_scene_id.as_deref() == Some("")+ || job.continuation_from.as_deref().is_some_and(|value| !matches!(value, "start" | "end"))+ || job.continuation_overlap_frames.is_some_and(|frames| !(22..=362).contains(&frames) || frames % 17 != 5) {+ return Err(format!("Scene '{}' has invalid continuation settings. Overlap must be 22, 39, 56, … frames.", job.id));+ }if job.scene_type.as_deref().is_some_and(|value| {!matches!(value,- "first-last-frame" | "animate" | "pose" | "character-replace" | "extend" | "bridge"+ "first-last-frame" | "continue" | "animate" | "pose" | "character-replace" | "extend" | "bridge")}) {return Err(format!("Scene '{}' has an unsupported scene type.", job.id));diff --git a/src-tauri/src/tests/scenes.rs b/src-tauri/src/tests/scenes.rsindex 99d2554..c45ec87 100644--- a/src-tauri/src/tests/scenes.rs+++ b/src-tauri/src/tests/scenes.rs@@ -1,5 +1,36 @@use super::*;+#[test]+fn continuation_settings_migrate_and_survive_reordering_and_save() {+ let mut config = fixture();+ let source = config.generation_jobs[0].id.clone();+ let mut next = config.generation_jobs[0].clone();+ next.id = "continued".into();+ next.use_previous_scene_last_frame = Some(true);+ config.generation_jobs = vec![config.generation_jobs[0].clone(), next];+ let mut config = validate_and_normalize_config(config).unwrap();+ let next = &config.generation_jobs[1];+ assert_eq!(next.scene_type.as_deref(), Some("continue"));+ assert_eq!(next.continuation_scene_id.as_deref(), Some(source.as_str()));+ assert_eq!(next.continuation_overlap_frames, Some(22));+ assert_eq!(next.continuation_from.as_deref(), Some("end"));+ assert_eq!(next.use_previous_scene_last_frame, None);+ config.generation_jobs.reverse();+ config.generation_jobs[0].continuation_from = Some("start".into());+ config.generation_jobs[0].continuation_overlap_frames = Some(56);+ let folder = tempfile::tempdir().unwrap();+ write_project(folder.path(), &config).unwrap();+ let restored = read_project(folder.path()).unwrap().config;+ assert_eq!(restored.generation_jobs[0].continuation_scene_id.as_deref(), Some(source.as_str()));+ assert_eq!(restored.generation_jobs[0].continuation_from.as_deref(), Some("start"));+ assert_eq!(restored.generation_jobs[0].continuation_overlap_frames, Some(56));+ config.generation_jobs[0].continuation_overlap_frames = Some(23);+ assert!(validate_and_normalize_config(config.clone()).is_err());+ config.generation_jobs[0].continuation_overlap_frames = Some(22);+ config.generation_jobs[0].continuation_from = Some("middle".into());+ assert!(validate_and_normalize_config(config).is_err());+}+#[test]fn scene_frame_settings_survive_save_and_reopen_and_validate_images() {let mut config = fixture();@@ -22,8 +53,8 @@ fn scene_frame_settings_survive_save_and_reopen_and_validate_images() {Some(image_id.as_str()));assert_eq!(- restored.generation_jobs[0].use_previous_scene_last_frame,- Some(true)+ restored.generation_jobs[0].scene_type.as_deref(),+ Some("continue"));config.generation_jobs[0].end_frame_reference_id = Some("missing".into());assert!(validate_and_normalize_config(config.clone())diff --git a/src-tauri/src/worker/client.rs b/src-tauri/src/worker/client.rsindex 81ce151..a15e6a3 100644--- a/src-tauri/src/worker/client.rs+++ b/src-tauri/src/worker/client.rs@@ -892,6 +892,9 @@ mod tests {job_id: "work-1".into(),reference_paths: vec![image.to_string_lossy().into_owned(), image.to_string_lossy().into_owned()],continuation_path: Some(image.clone()),+ continuation_from: Some("start".into()),+ continuation_overlap_frames: Some(39),+ continuation_source_frames: Some(85),..Default::default()};let (job, sources) = build_job(&request, &settings).unwrap();@@ -902,6 +905,10 @@ mod tests {assert_eq!(entries.iter().map(|entry| entry.path.as_str()).collect::<Vec<_>>(), vec!["nested/merges.txt", "vocab.json"]);assert_eq!(job.request.reference_paths, vec![file_token(2), file_token(2)]);assert_eq!(job.continuation, Some(2));+ let wire = serde_json::to_value(&job).unwrap();+ assert_eq!(wire["request"]["continuationFrom"], "start");+ assert_eq!(wire["request"]["continuationOverlapFrames"], 39);+ assert_eq!(wire["request"]["continuationSourceFrames"], 85);assert_eq!(sources.len(), 2);assert!(build_job(&GenerationRequest { reference_paths: vec![folder.path().join("missing.png").to_string_lossy().into_owned()], ..Default::default() }, &BTreeMap::new()).is_err());}diff --git a/src/components/workspace/GeneratorView.test.tsx b/src/components/workspace/GeneratorView.test.tsxindex 584fcd7..6692a9e 100644--- a/src/components/workspace/GeneratorView.test.tsx+++ b/src/components/workspace/GeneratorView.test.tsx@@ -466,16 +466,64 @@ describe("Generator scene controls", () => {expect(state.latest().generationJobs[0].endFrameReferenceId).toBeUndefined();});- it("marks a linked scene yellow when its previous scene regenerates and clears it after regeneration", () => {+ it("continues a later scene with selectable overlap and edge, ignoring hidden frame anchors", () => {+ const initial = project();+ initial.generationJobs[1] = { ...initial.generationJobs[1], status: "completed", latentRelativePath: "latents/later.safetensors" };+ initial.references = [{ id: "still", kind: "image", name: "Still", description: "", intendedUse: [], sourcePath: "C:/still.png", createdAt: initial.createdAt }];+ initial.generationJobs[0].startFrameReferenceId = "still";+ initial.generationJobs[0].endFrameReferenceId = "still";+ const state = setup(initial);+ choose("Scene type", "Continue");+ const generate = within(screen.getByRole("region", { name: "First scene" })).getByRole("button", { name: "Generate" });+ expect(generate).toBeDisabled();+ expect(screen.queryByLabelText("Start frame for this scene")).toBeNull();+ expect(screen.queryByLabelText("Last frame for this scene")).toBeNull();+ expect(comboValue(screen.getByLabelText("Take continuation latents from"))).toBe("end");+ expect(comboValue(screen.getByLabelText("Continuation overlap frames"))).toBe("22");+ expect(optionNames(screen.getByLabelText("Source scene for continuation"))).not.toContain("First scene");+ choose("Source scene for continuation", "Second scene");+ choose("Take continuation latents from", "Beginning");+ choose("Continuation overlap frames", "39");+ expect(generate).toBeEnabled();+ fireEvent.click(generate);+ const saved = parseProjectConfig(JSON.parse(JSON.stringify(state.latest())));+ expect(saved.generationJobs[0]).toMatchObject({ sceneType: "continue", continuationSceneId: "scene-second", continuationFrom: "start", continuationOverlapFrames: 39 });+ expect(JSON.parse(saved.generationJobs[0].generationSnapshot!)).toMatchObject({+ previousSceneId: "scene-second", continuationRelativePath: "latents/later.safetensors", continuationFrom: "start", continuationOverlapFrames: 39, referencePaths: [],+ });+ });++ it("queues continuation dependencies before their dependents, regardless of board order", () => {+ const initial = project();+ initial.generationJobs = [+ { ...initial.generationJobs[0], sceneType: "continue", continuationSceneId: "middle" },+ { ...initial.generationJobs[1], id: "middle", sceneType: "continue", continuationSceneId: "source" },+ createDraftGenerationJob("Original", { id: "source" }),+ createDraftGenerationJob("Cycle A", { id: "cycle-a", sceneType: "continue" }),+ createDraftGenerationJob("Cycle B", { id: "cycle-b", sceneType: "continue" }),+ ];+ initial.generationJobs[3].continuationSceneId = "cycle-b";+ initial.generationJobs[4].continuationSceneId = "cycle-a";+ const submitted = vi.fn();+ render(<GeneratorView config={initial} folderPath="C:/project" runtime={readyRuntime}+ onChange={vi.fn()} onGenerate={submitted} onOpenTimeline={() => undefined} />);+ fireEvent.click(screen.getByRole("button", { name: "Generate all" }));+ expect(submitted).toHaveBeenCalledOnce();+ expect(submitted.mock.calls[0][0].map((item: { job: { id: string } }) => item.job.id)).toEqual(["source", "middle", "scene-first"]);+ expect(submitted.mock.calls[0][0][2].request).toMatchObject({ previousSceneId: "middle", continuationFrom: "end", continuationOverlapFrames: 22 });+ });++ it("marks a linked scene yellow when its source regenerates and clears it after regeneration", () => {const initial = project();initial.generationJobs[0] = { ...initial.generationJobs[0], status: "completed", outputRelativePath: "media/generated/work-original.mp4", latentRelativePath: "latents/work-original.safetensors" };const state = setup(initial);fireEvent.click(screen.getByRole("combobox", { name: "Start frame for this scene" }));- expect(screen.getByRole("option", { name: "Previous scene" })).toHaveAttribute("aria-disabled", "true");+ expect(screen.queryByRole("option", { name: "Previous scene" })).toBeNull();fireEvent.click(screen.getByRole("combobox", { name: "Start frame for this scene" }));fireEvent.click(screen.getByRole("button", { name: "Select scene Second scene" }));- chooseOption(screen.getByRole("combobox", { name: "Start frame for this scene" }), "Previous scene");- expect(state.latest().generationJobs[1].usePreviousSceneLastFrame).toBe(true);+ choose("Scene type", "Continue");+ choose("Source scene for continuation", "First scene");+ expect(state.latest().generationJobs[1].continuationSceneId).toBe("scene-first");const generateSecond = () => fireEvent.click(within(screen.getByRole("region", { name: "Second scene" })).getByRole("button", { name: "Generate" }));const finishSecond = () => state.replace({ ...state.latest(), generationJobs: state.latest().generationJobs.map((job, index) => index === 1 ? { ...job, status: "completed", outputRelativePath: "media/generated/work-second.mp4" } : job) });generateSecond();@@ -502,6 +550,7 @@ describe("Generator scene controls", () => {it("includes fixed-seed linked scenes when Generate All regenerates their source", () => {const initial = project();initial.generationJobs = initial.generationJobs.map((job, index) => ({ ...job, seed: 42, outputRelativePath: `media/generated/work-${index}.mp4`, latentRelativePath: `latents/work-${index}.safetensors`, usePreviousSceneLastFrame: index === 1 }));+ initial.assets.push({ id: "asset-scene-first", kind: "generated", mimeType: "video/mp4", name: "First scene", relativePath: "media/generated/work-0.mp4", durationMs: 6000, createdAt: initial.createdAt });const state = setup(initial);fireEvent.click(screen.getByRole("button", { name: "Generate all" }));state.replace({ ...state.latest(), generationJobs: state.latest().generationJobs.map((job) => ({ ...job, status: "completed" })) });diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsxindex a3f3ba2..c927d05 100644--- a/src/components/workspace/GeneratorView.tsx+++ b/src/components/workspace/GeneratorView.tsx@@ -1,7 +1,7 @@import type { GenerationSubmission } from "../../lib/workQueue";import { loadLoras, subscribeLoras } from "../../lib/loras";import { refreshDownloadedLoras } from "../../lib/weightDownloads";-import { audioReferenceBlocker, characterReplaceBlocker, poseBlocker, isVideoTransition, videoTransitionBlocker, usableAudioReferences, usableVideoReferences, type SceneType } from "../../lib/project";+import { audioReferenceBlocker, characterReplaceBlocker, continuationBlocker, continuationSceneId, poseBlocker, isVideoTransition, videoTransitionBlocker, usableAudioReferences, usableVideoReferences, type SceneType } from "../../lib/project";import { referenceRefmodInputs } from "../../lib/project";import { Add16, Delete16, GridView16, GridView16Filled, ListView16, ListView16Filled, Scene16, Scene32, Sparkle16, Stop14, Wand16 } from "../ui/icons";import { invoke } from "@tauri-apps/api/core";@@ -342,6 +342,8 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoprompt: sceneTypeFor(job) === "animate" ? "" : compileGenerationJobPrompt(inputs.job, bound, configRef.current.settings.defaultLook),...(inputs.previousSceneId ? { previousSceneId: inputs.previousSceneId } : {}),...(inputs.continuationRelativePath ? { continuationRelativePath: inputs.continuationRelativePath } : {}),+ ...(inputs.previousSceneId ? { continuationOverlapFrames: inputs.continuationOverlapFrames,+ continuationFrom: inputs.continuationFrom, continuationSourceFrames: inputs.continuationSourceFrames } : {}),// The scene's own length, not a fixed six seconds.frames: Math.round(sceneDurationSeconds(job) * GENERATION_FRAME_RATE),steps: sceneGenerationSteps(job, defaultGenerationSteps),@@ -442,34 +444,41 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo* reroll for random ones. A completed fixed-seed scene is current only when* both its output and the exact renderer-input snapshot still exist. */const batchScenesReady: GenerationJob[] = [];- for (const [index, job] of jobs.entries()) {- if (job.status === "queued" || job.status === "generating" || job.status === "ready") continue;- if (!isVideoTransition(job) && job.sceneType !== "pose" && job.sceneType !== "character-replace" && job.usePreviousSceneLastFrame && index === 0) continue;- if (templateSceneBlocker(sceneTypeFor(job), selectedTemplate) || sendBlocker(job, config.references)) continue;- const previous = jobs[index - 1];- const previousWillRender = !isVideoTransition(job) && job.sceneType !== "pose" && job.usePreviousSceneLastFrame && previous &&+ const visited = new Set<string>();+ const visitForBatch = (job: GenerationJob): boolean => {+ if (continuationBlocker(job, jobs) || templateSceneBlocker(sceneTypeFor(job), selectedTemplate) || sendBlocker(job, config.references)) return false;+ if (visited.has(job.id)) return true;+ if (["queued", "generating", "ready"].includes(job.status)) { visited.add(job.id); return true; }+ const previous = jobs.find((candidate) => candidate.id === continuationSceneId(job, jobs));+ if (previous && !visitForBatch(previous)) return false;+ visited.add(job.id);+ const previousWillRender = previous &&(batchScenesReady.includes(previous) || ["queued", "generating", "ready"].includes(previous.status));if (previousWillRender || sceneGenerationSeed(job) === RANDOM_GENERATION_SEED || job.status !== "completed"|| !job.outputRelativePath- || (!job.latentRelativePath && jobs[index + 1]?.usePreviousSceneLastFrame)+ || (!job.latentRelativePath && jobs.some((candidate) => continuationSceneId(candidate, jobs) === job.id))|| !job.generationSnapshot|| job.generationSnapshot !== snapshotFor(job)) batchScenesReady.push(job);- }+ return true;+ };+ jobs.forEach(visitForBatch);const generateAll = () => submit(batchScenesReady);const generationBlocker = (job: GenerationJob): string | null => {if (!runtimeReady) return runtimeError ?? generatorRuntime?.detail ?? "The video generator is not ready.";if (job.status === "ready") return "Saving this scene.";- if (!isVideoTransition(job) && job.sceneType !== "pose" && job.sceneType !== "character-replace" && job.usePreviousSceneLastFrame && jobs[0]?.id === job.id) return "Needs a previous scene to continue from.";- return templateSceneBlocker(sceneTypeFor(job), selectedTemplate) ?? sendBlocker(job, config.references);+ const source = jobs.find((candidate) => candidate.id === continuationSceneId(job, jobs));+ return continuationBlocker(job, jobs)+ ?? (source && (!source.latentRelativePath || source.status !== "completed") ? "Generate the selected source scene first, or use Generate all." : null)+ ?? templateSceneBlocker(sceneTypeFor(job), selectedTemplate) ?? sendBlocker(job, config.references);};const changedJobIds = new Set(jobs- .filter((job, index) => job.status === "completed"+ .filter((job) => job.status === "completed"&& Boolean(job.generationSnapshot)&& (job.generationSnapshot !== snapshotFor(job)- || (job.usePreviousSceneLastFrame && ["queued", "generating", "ready"].includes(jobs[index - 1]?.status))))+ || jobs.some((source) => source.id === continuationSceneId(job, jobs) && ["queued", "generating", "ready"].includes(source.status)))).map((job) => job.id));const selectedIndicator = selected && changedJobIds.has(selected.id) ? "changed" : selected?.status;@@ -685,7 +694,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCofolderPath={folderPath}importAvailable={isTauri()}importError={startFrameError}- previousScene={jobs[jobs.findIndex((job) => job.id === selected.id) - 1]}+ scenes={jobs}onAddStartFrame={() => void addFrame(selected, "start")}onAddEndFrame={() => void addFrame(selected, "end")}onChange={(updates) => changeSceneSettings(selected, updates)}diff --git a/src/components/workspace/SceneEditor.tsx b/src/components/workspace/SceneEditor.tsxindex d18c0cd..7178dc6 100644--- a/src/components/workspace/SceneEditor.tsx+++ b/src/components/workspace/SceneEditor.tsx@@ -39,6 +39,7 @@ import {type ShotTagSelection,} from "../../lib/shot-tags";import { CommittedNumberInput } from "./CommittedNumberInput";+import { DEFAULT_CONTINUATION_OVERLAP, MAX_CONTINUATION_OVERLAP } from "../../lib/project";import { PromptTextField } from "./PromptTextField";import { ReferenceIcon } from "./ReferenceIcon";@@ -262,6 +263,7 @@ function CharacterReplaceInputs({ shot, references, disabled, onChange }: {const SCENE_TYPES: { value: SceneType; label: string }[] = [{ value: "first-last-frame", label: "First & last frame" },+ { value: "continue", label: "Continue" },{ value: "animate", label: "Animate" },{ value: "pose", label: "Pose" },{ value: "character-replace", label: "Character replace" },@@ -273,14 +275,14 @@ const SCENE_TYPES: { value: SceneType; label: string }[] = [* §4.1), and the two sound fields defined per prompt (§4.6, §4.7). Length* lives in the scene header where it stays visible. Simple label + control* pairs are inspector rows; the free-text fields stay full width. */-export function SceneInspector({ job, shots, references, folderPath = "", previousScene, defaultSteps, defaultLook, disabled, importAvailable, importError, onAddStartFrame, onAddEndFrame, onChange, onShots, sceneType = job.sceneType ?? "first-last-frame" }: {+export function SceneInspector({ job, shots, references, folderPath = "", scenes = [], defaultSteps, defaultLook, disabled, importAvailable, importError, onAddStartFrame, onAddEndFrame, onChange, onShots, sceneType = job.sceneType ?? "first-last-frame" }: {sceneType?: SceneType;defaultLook?: string | null;job: GenerationJob;shots: SceneShot[];references: ProjectReference[];folderPath?: string;- previousScene?: GenerationJob;+ scenes?: GenerationJob[];defaultSteps: number;disabled: boolean;importAvailable: boolean;@@ -291,6 +293,7 @@ export function SceneInspector({ job, shots, references, folderPath = "", previoonShots: (next: SceneShot[]) => void;}) {const animate = sceneType === "animate";+ const continuing = sceneType === "continue";const pose = sceneType === "pose";const characterReplace = sceneType === "character-replace";const transition = isVideoTransition({ sceneType });@@ -321,6 +324,32 @@ export function SceneInspector({ job, shots, references, folderPath = "", previoonChange={(value) => onChange({ sceneType: value as SceneType, usePreviousSceneLastFrame: undefined,...(value === "animate" ? { endFrameReferenceId: undefined } : {}) })} /></PropRow>+ {continuing && <>+ <PropRow label="Source scene" htmlFor={`${id}-source-scene`}>+ <ComboBox id={`${id}-source-scene`} aria-label="Source scene for continuation" disabled={disabled}+ value={job.continuationSceneId ?? ""}+ options={[{ value: "", label: "None" },+ ...(job.continuationSceneId && !scenes.some((scene) => scene.id === job.continuationSceneId)+ ? [{ value: job.continuationSceneId, label: "Unavailable scene", disabled: true }] : []),+ ...scenes.filter((scene) => scene.id !== job.id).map((scene) => ({ value: scene.id, label: scene.title }))]}+ onChange={(value) => onChange({ continuationSceneId: value || null })} />+ </PropRow>+ <PropRow label="Take latents from" htmlFor={`${id}-continuation-from`}>+ <ComboBox id={`${id}-continuation-from`} aria-label="Take continuation latents from" disabled={disabled}+ value={job.continuationFrom ?? "end"} options={[{ value: "end", label: "End" }, { value: "start", label: "Beginning" }]}+ onChange={(value) => onChange({ continuationFrom: value as "start" | "end" })} />+ </PropRow>+ <PropRow label="Overlap frames" htmlFor={`${id}-overlap`}>+ <ComboBox id={`${id}-overlap`} aria-label="Continuation overlap frames" disabled={disabled}+ value={String(job.continuationOverlapFrames ?? DEFAULT_CONTINUATION_OVERLAP)}+ options={Array.from({ length: (MAX_CONTINUATION_OVERLAP - DEFAULT_CONTINUATION_OVERLAP) / 17 + 1 }, (_, index) => {+ const frames = DEFAULT_CONTINUATION_OVERLAP + index * 17;+ return { value: String(frames), label: String(frames) };+ })}+ onChange={(value) => onChange({ continuationOverlapFrames: Number(value) })} />+ </PropRow>+ <p className="prop-caption">Uses the selected scene’s saved latents. Generate it first, or use Generate all. Overlap uses 22, 39, 56, … frames at 24 fps.</p>+ </>}{pose && <><PropRow label="Pose video" htmlFor={`${id}-pose`}><ComboBox id={`${id}-pose`} aria-label="Pose video reference for this scene" value={job.poseVideoReferenceId ?? ""} disabled={disabled}@@ -378,23 +407,22 @@ export function SceneInspector({ job, shots, references, folderPath = "", previo/></PropRow>}{!animate && !chosen && defaultLook && <p className="prop-caption">Using project Look: {look.options.find((option) => option.id === defaultLook)?.label ?? defaultLook}.</p>}- {!transition && !pose && <>+ {!transition && !pose && !continuing && <><PropRow label={animate ? "Repainted frame" : "Start frame"} htmlFor={`${id}-start`}><ComboBoxid={`${id}-start`}value={animate? job.startFrameReferenceId ?? imageReferences.find((reference) => job.referenceIds.includes(reference.id))?.id ?? ""- : job.usePreviousSceneLastFrame ? "previous-scene" : job.startFrameReferenceId ?? ""}+ : job.startFrameReferenceId ?? ""}disabled={disabled}aria-label="Start frame for this scene"options={[{ value: "", label: "None" },- ...(!animate ? [{ value: "previous-scene", label: "Previous scene", disabled: !previousScene }] : []),...imageReferences.map((reference) => ({ value: reference.id, label: reference.name })),]}onChange={(value) => onChange({- usePreviousSceneLastFrame: value === "previous-scene" || undefined,- startFrameReferenceId: value === "previous-scene" ? undefined : value || undefined,+ usePreviousSceneLastFrame: undefined,+ startFrameReferenceId: value || undefined,...(animate ? {endFrameReferenceId: undefined,referenceIds: job.referenceIds.filter((referenceId) => !imageReferences.some((reference) => reference.id === referenceId)),@@ -403,11 +431,9 @@ export function SceneInspector({ job, shots, references, folderPath = "", previo/>{addImageButton(animate ? "Add repainted frame" : "Add start frame", onAddStartFrame)}</PropRow>- {(animate || job.usePreviousSceneLastFrame) && <p className="prop-caption">{animate- ? "A frame of the driving video with the character repainted. Keep its pose, framing, background and lighting."- : previousScene ? `Continues “${previousScene.title}” from its saved latents with 22 overlapping frames. Generate that scene first, or use Generate all.` : "Move this scene after another scene to continue it."}</p>}+ {animate && <p className="prop-caption">A frame of the driving video with the character repainted. Keep its pose, framing, background and lighting.</p>}</>}- {!animate && !transition && !pose && <PropRow label="Last frame" htmlFor={`${id}-end`}>+ {!animate && !transition && !pose && !continuing && <PropRow label="Last frame" htmlFor={`${id}-end`}><ComboBox id={`${id}-end`} value={job.endFrameReferenceId ?? ""} disabled={disabled} aria-label="Last frame for this scene"options={[{ value: "", label: "None" }, ...imageReferences.map((reference) => ({ value: reference.id, label: reference.name }))]}onChange={(value) => onChange({ endFrameReferenceId: value || undefined })} />diff --git a/src/lib/project.continue.test.ts b/src/lib/project.continue.test.tsnew file mode 100644index 0000000..59471bf--- /dev/null+++ b/src/lib/project.continue.test.ts@@ -0,0 +1,58 @@+import { expect, it } from "vitest";+import { compileGenerationJobPrompt, continuationBlocker, createDraftGenerationJob, createProjectConfig, parseProjectConfig, sceneFrameInputs, sceneGenerationSnapshot } from "./project";++const project = () => {+ const config = createProjectConfig({ name: "Continue", prompt: "A cyclist", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 6 });+ config.generationJobs = [createDraftGenerationJob("A cyclist", { id: "source" }), createDraftGenerationJob("Keeps riding", { id: "next", sceneType: "continue" })];+ return config;+};++it("migrates previous-scene links to stable explicit sources with the old defaults", () => {+ const config = project();+ config.generationJobs[1] = { ...config.generationJobs[1], sceneType: "first-last-frame", usePreviousSceneLastFrame: true };+ const restored = parseProjectConfig(config);+ expect(restored.generationJobs[1]).toMatchObject({ sceneType: "continue", continuationSceneId: "source", continuationOverlapFrames: 22, continuationFrom: "end" });+ restored.generationJobs.reverse();+ expect(sceneFrameInputs(restored.generationJobs[0], restored).previousSceneId).toBe("source");+ expect(parseProjectConfig(JSON.parse(JSON.stringify(restored)))).toEqual(restored);+});++it("uses the selected source and ignores saved first/last-frame selections", () => {+ const config = project();+ config.references = [{ id: "frame", kind: "image", name: "Frame", description: "", intendedUse: [], sourcePath: "C:/frame.png", createdAt: config.createdAt }];+ config.generationJobs[0].latentRelativePath = "latents/source.safetensors";+ config.assets = [{ id: "asset-source", kind: "generated", mimeType: "video/mp4", name: "Source", relativePath: "media/source.mp4", durationMs: 5167, createdAt: config.createdAt }];+ const next = { ...config.generationJobs[1], continuationSceneId: "source", continuationFrom: "start" as const, continuationOverlapFrames: 39, startFrameReferenceId: "frame", endFrameReferenceId: "frame" };+ const inputs = sceneFrameInputs(next, config);+ expect(inputs).toMatchObject({ previousSceneId: "source", continuationRelativePath: "latents/source.safetensors", continuationFrom: "start", continuationOverlapFrames: 39, continuationSourceFrames: 124, references: [] });+ expect(inputs.job.startFrameReferenceId).toBeUndefined();+ expect(inputs.job.endFrameReferenceId).toBeUndefined();+ expect(compileGenerationJobPrompt(next, config.references)).not.toContain("<Picture");+ const snapshot = JSON.parse(sceneGenerationSnapshot(next, { ...inputs, prompt: "Continue", frames: 100, steps: 4, seed: 1, canvasWidth: 64, canvasHeight: 32, referencePaths: [] }));+ expect(snapshot).toMatchObject({ continuationFrom: "start", continuationOverlapFrames: 39, previousSceneId: "source" });+});++it("blocks missing, self-referencing and cyclic continuation sources", () => {+ const config = project();+ const next = config.generationJobs[1];+ expect(continuationBlocker(next, config.generationJobs)).toContain("Select");+ next.continuationSceneId = "gone";+ expect(continuationBlocker(next, config.generationJobs)).toContain("no longer exists");+ next.continuationSceneId = "next";+ expect(continuationBlocker(next, config.generationJobs)).toContain("cycle");+ next.continuationSceneId = "source";+ expect(continuationBlocker(next, config.generationJobs)).toBeNull();+ Object.assign(config.generationJobs[0], { sceneType: "continue", continuationSceneId: "next" });+ expect(continuationBlocker(next, config.generationJobs)).toContain("cycle");+});++it("validates overlap increments and edge choices when loading", () => {+ for (const overlap of [0, 21, 23, 39.5, 379]) {+ const config = project();+ config.generationJobs[1].continuationOverlapFrames = overlap;+ expect(() => parseProjectConfig(config)).toThrow();+ }+ const config = project();+ config.generationJobs[1].continuationOverlapFrames = 56;+ expect(parseProjectConfig(config).generationJobs[1].continuationOverlapFrames).toBe(56);+});diff --git a/src/lib/project.ts b/src/lib/project.tsindex 6ad2c78..6f2e741 100644--- a/src/lib/project.ts+++ b/src/lib/project.ts@@ -406,8 +406,10 @@ export const SCENE_MIN_SECONDS = 0;* length is read as — the length every shot has always been generated at. */export const DEFAULT_SCENE_SECONDS = 6;-export const sceneTypeSchema = z.enum(["first-last-frame", "animate", "pose", "character-replace", "extend", "bridge"]);+export const sceneTypeSchema = z.enum(["first-last-frame", "continue", "animate", "pose", "character-replace", "extend", "bridge"]);export type SceneType = z.infer<typeof sceneTypeSchema>;+export const DEFAULT_CONTINUATION_OVERLAP = 22;+export const MAX_CONTINUATION_OVERLAP = 362;export const isVideoTransition = (job: Pick<GenerationJob, "sceneType">): boolean => job.sceneType === "extend" || job.sceneType === "bridge";export const sceneShotSchema = z.object({@@ -518,6 +520,10 @@ export const generationJobSchema = z.object({startFrameReferenceId: idSchema.nullish(),endFrameReferenceId: idSchema.nullish(),usePreviousSceneLastFrame: z.boolean().nullish(),+ continuationSceneId: idSchema.nullish(),+ continuationOverlapFrames: z.number().int().min(DEFAULT_CONTINUATION_OVERLAP).max(MAX_CONTINUATION_OVERLAP)+ .refine((frames) => (frames - 5) % 17 === 0, "Overlap must be 22, 39, 56, … frames.").nullish(),+ continuationFrom: z.enum(["start", "end"]).nullish(),latentRelativePath: projectRelativePathSchema.nullish(),// `.nullish()` because Rust holds it as an Option — see the note on// projectAssetSchema.durationMs. Every project written before shot tags@@ -906,7 +912,7 @@ export function audioReferenceBlocker(job: GenerationJob, bound: ProjectReferencif (sounds.length > 3) return "Use at most three sound references per scene.";if (sounds.reduce((total, reference) => total + (reference.audio?.durationSeconds ?? 15), 0) > 15) return "Sound references must total no more than 15 seconds. Shorten them in References.";const anchored = usableReferenceImages(bound).length > 0 || usableVideoReferences(bound).length > 0- || bound.some((reference) => activeReferenceRefmods(reference).length > 0) || Boolean(job.usePreviousSceneLastFrame);+ || bound.some((reference) => activeReferenceRefmods(reference).length > 0) || job.sceneType === "continue" || Boolean(job.usePreviousSceneLastFrame);return anchored ? null : "Sound references need an image or video reference in the same scene.";}@@ -935,8 +941,8 @@ export function sceneGenerationReferences(job: GenerationJob, references: Projecconst ids = sceneShots(job).flatMap((shot) => [shot.videoReferenceId, shot.characterReferenceId]);return references.filter((reference) => ids.includes(reference.id));}- const start = references.find((reference) => reference.id === job.startFrameReferenceId && referenceImages(reference).length > 0 && isReferenceUsable(reference));- const end = references.find((reference) => reference.id === job.endFrameReferenceId && referenceImages(reference).length > 0 && isReferenceUsable(reference));+ const start = job.sceneType !== "continue" && references.find((reference) => reference.id === job.startFrameReferenceId && referenceImages(reference).length > 0 && isReferenceUsable(reference));+ const end = job.sceneType !== "continue" && references.find((reference) => reference.id === job.endFrameReferenceId && referenceImages(reference).length > 0 && isReferenceUsable(reference));const anchors = [start, end].filter((reference, index, all): reference is ProjectReference => Boolean(reference) && all.indexOf(reference) === index).map((reference) => ({ ...reference, kind: "text" as const, video: undefined, relativePath: null, sourcePath: null, intendedUse: [], images: referenceImages(reference).slice(0, 1) }));// Animate stores its dedicated motion/frame selections in referenceIds.@@ -945,14 +951,54 @@ export function sceneGenerationReferences(job: GenerationJob, references: Projecreturn [...anchors, ...references.filter((reference) => ids.includes(reference.id) && !anchors.some((anchor) => anchor.id === reference.id))];}-/** Resolve the adjacent scene when preparing a request; queued work captures- * its id so subsequent board edits cannot change the source of that run. */+/** Legacy links are resolved only until the project is migrated on load. */+export function continuationSceneId(job: GenerationJob, jobs: readonly GenerationJob[]): string | undefined {+ if (job.sceneType === "continue") return job.continuationSceneId ?? undefined;+ if ((!job.sceneType || job.sceneType === "first-last-frame") && job.usePreviousSceneLastFrame)+ return jobs[jobs.findIndex((candidate) => candidate.id === job.id) - 1]?.id;+ return undefined;+}++export function continuationBlocker(job: GenerationJob, jobs: readonly GenerationJob[]): string | null {+ if (job.sceneType !== "continue" && !job.usePreviousSceneLastFrame) return null;+ if (job.sceneType && !["continue", "first-last-frame"].includes(job.sceneType)) return null;+ const seen = new Set([job.id]);+ let current = job;+ while (true) {+ const id = continuationSceneId(current, jobs);+ if (!id) return current === job ? "Select a source scene to continue." : "The source scene needs a continuation source.";+ if (seen.has(id)) return "Continuation scenes cannot form a cycle or continue themselves.";+ seen.add(id);+ const source = jobs.find((candidate) => candidate.id === id);+ if (!source) return "The selected source scene no longer exists.";+ if (source.sceneType !== "continue" && !continuationSceneId(source, jobs)) return null;+ current = source;+ }+}++/** The saved scene's output length, not the current editable duration. */+export function sceneOutputFrames(job: GenerationJob, config: ProjectConfig): number | undefined {+ const asset = config.assets.find((candidate) => candidate.id === generationAssetId(job.id));+ if (asset?.durationMs) return Math.round(asset.durationMs * GENERATION_FRAME_RATE / 1000);+ try {+ const snapshot = JSON.parse(job.generationSnapshot ?? "null");+ if (Number.isInteger(snapshot?.frames) && snapshot.frames > 0)+ return snapshot.continuationRelativePath ? Math.ceil(snapshot.frames / 17) * 17 : Math.max(22, Math.ceil((snapshot.frames - 5) / 17) * 17 + 5);+ } catch { /* Older projects may not have a usable snapshot. */ }+ return undefined;+}++/** Capture the selected source id so reordering the board cannot retarget work. */export function sceneFrameInputs(job: GenerationJob, config: ProjectConfig) {- if (isVideoTransition(job) || job.sceneType === "pose" || job.sceneType === "character-replace" || !job.usePreviousSceneLastFrame) return { job, references: sceneGenerationReferences(job, config.references) };- const previous = config.generationJobs[config.generationJobs.findIndex((candidate) => candidate.id === job.id) - 1];- const resolved = { ...job, startFrameReferenceId: undefined };+ const sourceId = continuationSceneId(job, config.generationJobs);+ if (job.sceneType !== "continue" && !sourceId) return { job, references: sceneGenerationReferences(job, config.references) };+ const previous = config.generationJobs.find((candidate) => candidate.id === sourceId);+ const resolved = { ...job, startFrameReferenceId: undefined, endFrameReferenceId: undefined };return { job: resolved, references: sceneGenerationReferences(resolved, config.references),- previousSceneId: previous?.id, continuationRelativePath: previous?.latentRelativePath ?? undefined };+ previousSceneId: sourceId, continuationRelativePath: previous?.latentRelativePath ?? undefined,+ continuationOverlapFrames: job.continuationOverlapFrames ?? DEFAULT_CONTINUATION_OVERLAP,+ continuationFrom: job.continuationFrom ?? "end",+ continuationSourceFrames: previous ? sceneOutputFrames(previous, config) : undefined };}export function generationLatentPath(jobId: string): string {@@ -1055,6 +1101,9 @@ export interface SceneGenerationInput {refmods?: readonly { path: string; strength: number; copies: number }[];previousSceneId?: string;continuationRelativePath?: string;+ continuationOverlapFrames?: number;+ continuationFrom?: "start" | "end";+ continuationSourceFrames?: number;}/** A stable record of everything sent to the renderer. Shot ids are retained@@ -1081,6 +1130,8 @@ export function sceneGenerationSnapshot(job: GenerationJob, input: SceneGenerati...(input.refmods?.length ? { refmods: input.refmods } : {}),...(input.previousSceneId ? { previousSceneId: input.previousSceneId } : {}),...(input.continuationRelativePath ? { continuationRelativePath: input.continuationRelativePath } : {}),+ ...(input.previousSceneId ? { continuationOverlapFrames: input.continuationOverlapFrames ?? DEFAULT_CONTINUATION_OVERLAP,+ continuationFrom: input.continuationFrom ?? "end", ...(input.continuationSourceFrames ? { continuationSourceFrames: input.continuationSourceFrames } : {}) } : {}),shots,});}@@ -1115,6 +1166,9 @@ export function compileMiniMaxH3PromptSegments(}export function compileGenerationJobSegments(job: GenerationJob, references: ProjectReference[] = [], defaultLook?: string | null): PromptSegment[] {+ if (job.sceneType === "continue") return compileScenePromptSegments({+ shots: sceneShots(job), soundscape: job.soundscape, music: job.music,+ }, sceneGenerationReferences(job, references), defaultLook);if (job.sceneType === "pose") return compileScenePromptSegments({shots: sceneShots(job), poseVideoReferenceId: job.poseVideoReferenceId, soundscape: job.soundscape, music: job.music,}, sceneGenerationReferences(job, references), defaultLook);@@ -1740,6 +1794,11 @@ export function seedProjectWorkspace(config: ProjectConfig, seed = 0): ProjectCoexport function parseProjectConfig(value: unknown): ProjectConfig {const config = projectConfigSchema.parse(value);+ config.generationJobs = config.generationJobs.map((job, index) =>+ job.usePreviousSceneLastFrame && (!job.sceneType || job.sceneType === "first-last-frame")+ ? { ...job, sceneType: "continue", continuationSceneId: config.generationJobs[index - 1]?.id,+ continuationOverlapFrames: DEFAULT_CONTINUATION_OVERLAP, continuationFrom: "end", usePreviousSceneLastFrame: undefined }+ : job);return { ...config, timeline: { tracks: normalizeTimelineTracks(config.timeline.tracks) } };}diff --git a/src/lib/runtime.ts b/src/lib/runtime.tsindex ee0b01c..9618201 100644--- a/src/lib/runtime.ts+++ b/src/lib/runtime.ts@@ -103,6 +103,9 @@ export interface SlopfabGenerationRequest {/** Resolved by the app queue before native submission. */previousSceneId?: string;continuationRelativePath?: string;+ continuationOverlapFrames?: number;+ continuationFrom?: "start" | "end";+ continuationSourceFrames?: number;}export interface ResolvedPlan {@@ -385,9 +388,11 @@ function executeDemoCommands(config: ProjectConfig, commands: ProjectCommand[]):if ("startFrame" in command) {job.startFrameReferenceId = command.startFrame;job.usePreviousSceneLastFrame = false;+ if (job.sceneType === "continue") job.sceneType = "first-last-frame";}if ("endFrame" in command) job.endFrameReferenceId = command.endFrame;if ("usePreviousSceneLastFrame" in command) {+ job.sceneType = "first-last-frame";job.usePreviousSceneLastFrame = command.usePreviousSceneLastFrame;if (command.usePreviousSceneLastFrame) job.startFrameReferenceId = undefined;}diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.tsindex 6995acc..aa90752 100644--- a/src/lib/workQueue.test.ts+++ b/src/lib/workQueue.test.ts@@ -394,25 +394,28 @@ describe("application work queue", () => {expect(enqueueSlopfabGeneration).not.toHaveBeenCalled();});- it("continues from the newly saved latents after the previous scene finishes", async () => {+ it("keeps the captured source, overlap and edge after reordering, and uses freshly saved latents", async () => {const { queue, first } = setup();- first.update((config) => ({ ...config, generationJobs: [config.generationJobs[0], { ...config.generationJobs[0], id: "linked", usePreviousSceneLastFrame: true }] }));+ first.update((config) => ({ ...config, generationJobs: [config.generationJobs[0], { ...config.generationJobs[0], id: "linked", sceneType: "continue", continuationSceneId: config.generationJobs[0].id }] }));const source = submission(first);- const linked = { ...submission(first), job: first.getSnapshot().config.generationJobs[1], request: { ...source.request, previousSceneId: source.job.id, referencePaths: ["subject.png"] } };+ const linked = { ...submission(first), job: first.getSnapshot().config.generationJobs[1], request: { ...source.request, previousSceneId: source.job.id, continuationFrom: "start" as const, continuationOverlapFrames: 39, referencePaths: ["subject.png"] } };queue.enqueue(first, [source, linked]);await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1));+ first.update((config) => ({ ...config, generationJobs: [...config.generationJobs].reverse() }));expect(saveSceneLastFrame).not.toHaveBeenCalled();await finish(queue, queue.getSnapshot()[0].id);await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(2));expect(saveSceneLastFrame).not.toHaveBeenCalled();const latentPath = `latents/${queue.getSnapshot()[0].id}.safetensors`;- expect(vi.mocked(enqueueSlopfabGeneration).mock.calls[1][0]).toMatchObject({ referencePaths: ["subject.png"], continuationRelativePath: latentPath });+ expect(vi.mocked(enqueueSlopfabGeneration).mock.calls[1][0]).toMatchObject({ referencePaths: ["subject.png"], continuationRelativePath: latentPath,+ continuationFrom: "start", continuationOverlapFrames: 39, continuationSourceFrames: 120 });expect(vi.mocked(enqueueSlopfabGeneration).mock.calls[1][2]).toBe("C:/First");await finish(queue, queue.getSnapshot()[1].id);- const snapshot = JSON.parse(first.getSnapshot().config.generationJobs[1].generationSnapshot!);+ const snapshot = JSON.parse(first.getSnapshot().config.generationJobs[0].generationSnapshot!);expect(snapshot.previousSceneId).toBe(source.job.id);expect(snapshot.continuationRelativePath).toBe(latentPath);- expect(parseProjectConfig(JSON.parse(JSON.stringify(first.getSnapshot().config))).generationJobs[1].latentRelativePath)+ expect(snapshot).toMatchObject({ continuationFrom: "start", continuationOverlapFrames: 39, continuationSourceFrames: 120 });+ expect(parseProjectConfig(JSON.parse(JSON.stringify(first.getSnapshot().config))).generationJobs[0].latentRelativePath).toBe(`latents/${queue.getSnapshot()[1].id}.safetensors`);});@@ -437,7 +440,7 @@ describe("application work queue", () => {await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1));emit("slopfab-job", { jobId: queue.getSnapshot()[0].id, state: "failed", detail: "Render failed" });await waitFor(() => expect(queue.getSnapshot()[1].status).toBe("failed"));- expect(queue.getSnapshot()[1].error).toContain("previous scene");+ expect(queue.getSnapshot()[1].error).toContain("selected source scene");expect(saveSceneLastFrame).not.toHaveBeenCalled();expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1);});diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.tsindex dbb6f64..08c9879 100644--- a/src/lib/workQueue.ts+++ b/src/lib/workQueue.ts@@ -12,7 +12,7 @@ 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, sceneGenerationSnapshot, type GenerationJob, type ProjectRecord, type ProjectConfig } from "./project";+import { generationAssetId, generationLatentPath, GENERATION_FRAME_RATE, sceneOutputFrames, sceneGenerationSnapshot, 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";@@ -280,9 +280,10 @@ export class WorkQueue {if (work.request.previousSceneId) {const previous = work.session.getSnapshot().config.generationJobs.find((job) => job.id === work.request.previousSceneId);if (!previous?.latentRelativePath || previous.status !== "completed") {- throw new Error("Generate the previous scene successfully to save its latents before continuing it. You can also use Generate All.");+ throw new Error("Generate the selected source scene successfully to save its latents before continuing it. You can also use Generate All.");}work.request.continuationRelativePath = previous.latentRelativePath;+ work.request.continuationSourceFrames = sceneOutputFrames(previous, work.session.getSnapshot().config);const captured = work.config.generationJobs.find((job) => job.id === work.sceneId)!;work.snapshot = sceneGenerationSnapshot(captured, work.request);this.updateScene(work, { generationSnapshot: work.snapshot });