AI media harness for planning, generating, and editing locally
TypeScript
Add Single Shot generation with ending anchors
Bittifa499fbadcfa
diff --git a/README.md b/README.mdindex c49e2cd..d651242 100644--- a/README.md+++ b/README.md@@ -25,7 +25,7 @@ Slopus combines an AI assistant, local image, video and music generation, reusab## Features- **Agent.** Plan scenes, generate media, inspect frames and song inputs, and match Motions to music with Claude Code, Codex, OpenRouter or a local OpenAI-compatible model. Toggle the pane with Ctrl+Shift+A.-- **Video.** Generate Prompt, First & last frame and other [scene types](docs/scene-types.md), with shot timing, dialogue, camera and sound controls. Keep up to four takes and an editable Draft; use **Make Primary** to choose the timeline video.+- **Video.** Generate Prompt, Single Shot, First & last frame and other [scene types](docs/scene-types.md), with shot timing, dialogue, camera and sound controls. Keep up to four takes and an editable Draft; use **Make Primary** to choose the timeline video.- **Images.** Generate with MiniMax H3, MOSS Image or Fibo 2.0. Use whole-image, box, lasso and Zoom edits where supported, with drafts and versions in the image bar.- **Music.** Generate with YuE2 or MiniMax Music3, edit lyrics and style, organize songs in folders, browse grid/list views, and play songs in sequence or reuse them as references and timeline audio.- **References.** Reuse descriptions, images, trimmed video clips and [H3 RefMods](docs/refmods.md) across scenes.diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.mdindex 8afd178..a2c7ed4 100644--- a/RELEASE_NOTES.md+++ b/RELEASE_NOTES.md@@ -4,6 +4,7 @@ Changes since 0.3.2.## What's new+- **Single Shot.** Generate a short ending first, then anchor a continuous shot to it. Supports references in both prompts and optional continuation from any generated scene.- **Music.** YuE2 and MiniMax Music3 generation with folders, drag-and-drop organization, grid/list views, background playback, references and timeline audio. Playback appears in the Music tab and pauses when Timeline, Video or Export playback starts. YuE2 selects BF16 above 8 GiB VRAM, otherwise INT8.- **Motions.** Create JavaScript animations with the agent, edit elements and parameters, and export them on the timeline or as reference videos.- **Scene history.** Keep up to four takes and an editable Draft, restore take settings, choose the primary timeline video, and duplicate scenes.@@ -23,4 +24,4 @@ Changes since 0.3.2.- Image edits preserve source images, prompts and settings; queued results get separate entries, and whole-image edits disable feathering.- Imported images now expose steps, seed and resolution; new images use generator step defaults, and renamed image roots retain their names.- Generation effects reuse VAE fingerprint checks to avoid repeated calibration work.-- Updated SlopFab to API 1.40 with music performance improvements; LAN protocol 18. Update workers alongside the app.+- Updated SlopFab to API 1.40 with music performance improvements; LAN protocol 19. Update workers alongside the app.diff --git a/docs/scene-types.md b/docs/scene-types.mdindex 1752a26..c364031 100644--- a/docs/scene-types.md+++ b/docs/scene-types.md@@ -3,6 +3,7 @@The Scene panel saves a type on each scene:- **Prompt** is the default for ordinary video scenes. It supports shot descriptions, speech, Look, sound, music and references cited in prompts, without start- or last-frame selectors. Stored frame anchors and continuation links are inactive.+- **Single Shot** has one prompt and an optional **Ending prompt**, both with reference support. It generates a short ending first, then uses those latents to anchor the full shot. A blank ending prompt uses the main prompt. **Starting video** can select any other generated scene; ending latents from its full clip guide the new shot's beginning. Generate all handles dependency order. Use matching resolution and latent-upscale settings, a duration of at least two seconds, and updated LAN workers.- **First & Last Frame** adds optional start- and last-frame anchors to the same controls. Older scenes without a type retain this type when they have frame selections; otherwise they use Prompt. Switching types retains saved frame selections for later use.- **Backdrop** generates the described subject and action against a selected green, blue, black or white background (green by default). The compiled prompt requests a uniform color across all shots, with no scenery, floor, horizon, texture, gradients or backdrop shadows. Prompt references guide the subject; their original settings are replaced. Stored frame anchors and continuation links are inactive. Apply Chroma Key to the generated timeline clip and select the matching backdrop or Auto to remove it. Generation still produces ordinary video: transparency is applied by the effect. Choose a color absent from the subject and describe action that fits inside the frame.- **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. The saved video keeps Slopfab's full joined video and audio; adjacent source and continuation clips use that shared decode in preview and export, while trims remain relative to each scene. Regenerate older Continue scenes to preserve both sides of the decoded boundary. Old Previous scene selections become Continue scenes linked to their original source; reordering scenes keeps that link.diff --git a/docs/slopfab-compatibility.md b/docs/slopfab-compatibility.mdindex 14277cb..d7543fd 100644--- a/docs/slopfab-compatibility.md+++ b/docs/slopfab-compatibility.md@@ -5,14 +5,40 @@Windows and Linux runtimes use SlopFab commit `af664eb94519fec7604c265a76a602be597fa12b`from `D:\Projects\slopfab`, with CUDA and Vulkan enabled and FFmpeg disabled.This update includes music performance improvements and additive ending-anchor-APIs. Slopus's existing requests remain compatible; the new ending-anchor APIs-are not yet exposed by the app. LAN protocol remains 18. Restart Slopus and+APIs. Single Shot uses the latent ending-anchor API. LAN protocol is 19. Restart Slopus andupdate workers to load the new runtime.Both runtimes pass C API and embedded-tokenizer checks. Slopus core and desktopRust tests pass against the Windows DLL. Linux retains the Fibo text-rendererlinker workaround documented below and passes unresolved-symbol checks.+## Single Shot++Single Shot has one reference-aware prompt, an optional ending prompt and an+optional starting scene of any type with saved video latents. Its full clip's+ending context guides the new beginning. An empty ending prompt uses the main prompt.+Both stages share the same ordered reference bindings, generator settings and+seed. Generate all orders starting scenes before their dependents and rejects+cycles. Queued prompts remain captured while source latents resolve after the+starting scene finishes.++The worker generates a 22-frame ending into a temporary latent archive, releases+its decoded buffers, then attaches that archive with+`slopfab_request_set_end_anchor_file`. The full generation uses the requested+scene duration minus those 22 frames as its lead-in or gap. An optional starting+archive contributes its ending context; both boundaries are locked. MotionCache+is disabled for the anchored pass. The native frame stride still determines the+final duration; Single Shot requires at least two seconds.++Only the final joined output and latents enter scene history. Timeline ranges+identify each scene's own portion, retaining the shared decode at joins.+Temporary endings are removed on success, failure and cancellation. Starting+scenes must use compatible resolution and latent-upscale settings. Protocol 19+prevents older workers from silently skipping the ending pass.++Checks cover prompt/reference compilation, persistence, dependency ordering,+queue snapshots, cancellation, temporary cleanup and native anchored planning.+## Music (API 1.38)Bundled Windows and Linux runtimes support YuE2 and MiniMax Music3 on CUDA anddiff --git a/src-tauri/core/src/slopfab/config.rs b/src-tauri/core/src/slopfab/config.rsindex 125e765..1e3781d 100644--- a/src-tauri/core/src/slopfab/config.rs+++ b/src-tauri/core/src/slopfab/config.rs@@ -123,6 +123,9 @@ impl Configuration {}pub(super) fn validate_inputs(&self, request: &GenerationRequest) -> Result<(), String> {+ if request.single_shot.is_some() && (self.model_type != "minimax-h3" || self.animate) {+ return Err("Single Shot requires a MiniMax H3 prompt generator.".into());+ }if request.music.is_some() { return super::music::validate(request, self); }let features = crate::models::generator_features(&self.model_type);if let Some(negative) = &request.negative_prompt {diff --git a/src-tauri/core/src/slopfab/continuation.rs b/src-tauri/core/src/slopfab/continuation.rsindex cdf2eaf..1152f63 100644--- a/src-tauri/core/src/slopfab/continuation.rs+++ b/src-tauri/core/src/slopfab/continuation.rs@@ -282,6 +282,38 @@ mod tests {assert_eq!(wire["latentBridge"]["rightMarginFrames"], 34);}+ #[test]+ fn single_shot_anchor_plan_matches_preview_with_and_without_a_starting_source() {+ use super::super::{ffi::{Api, RequestHandle}, h3::configure_request, config::Configuration,+ platform::ComputePlatform, planning::{RequestPurpose, validate_generation_controls}, types::SingleShotRequest};+ let source = archive(124).into_temp_path();+ let ending = archive(22).into_temp_path();+ let original = std::fs::read(&source).unwrap();+ let api = Api::load(&crate::slopfab::default_dll_path()).unwrap();+ for continued in [false, true] {+ let mut request = GenerationRequest { prompt: "Walk forward".into(), frames: 48, steps: 4, seed: 1,+ canvas_width: 64, canvas_height: 32,+ single_shot: Some(SingleShotRequest { ending_prompt: "Wave goodbye".into(), ending_path: None }),+ continuation_path: continued.then(|| source.to_path_buf()), continuation_overlap_frames: Some(22),+ continuation_from: Some("end".into()), continuation_lock_overlap: true, ..Default::default() };+ let settings = BTreeMap::new();+ let preview = resolve_plan(&request, &settings, &ReferenceVideos::default()).unwrap();+ request.single_shot.as_mut().unwrap().ending_path = Some(ending.to_path_buf());+ let handle = RequestHandle::new(&api).unwrap();+ configure_request(&api, &handle, &request, &Configuration::from_settings(&settings), ComputePlatform::Cuda13,+ RequestPurpose::Plan, &ReferenceVideos::default()).unwrap();+ let actual = api.resolve(&handle).unwrap();+ assert_eq!(actual.aligned_frames, if continued { 175 } else { 56 });+ assert_eq!(actual.aligned_frames, preview.aligned_frames);+ assert_eq!(preview.model_evaluations, actual.num_model_evaluations * 2);+ assert_eq!(std::fs::read(&source).unwrap(), original);+ let wire = serde_json::to_value(&request).unwrap();+ assert!(wire["singleShot"].get("endingPath").is_none());+ request.frames = 22;+ assert!(validate_generation_controls(&request).unwrap_err().contains("at least 2 seconds"));+ }+ }+#[test]fn opening_continuation_crops_the_selected_scene_and_both_audio_channels() {let source = archive(124);diff --git a/src-tauri/core/src/slopfab/ffi/mod.rs b/src-tauri/core/src/slopfab/ffi/mod.rsindex 8ddfb54..3687691 100644--- a/src-tauri/core/src/slopfab/ffi/mod.rs+++ b/src-tauri/core/src/slopfab/ffi/mod.rs@@ -162,6 +162,11 @@ impl Api {self.check(r)?;self.inner.set_latent_bridge_files(r.pointer.as_ptr(), left, right, left_margin, right_margin, context)}+ pub fn require_end_anchor(&self) -> Result<(), String> { self.inner.require_end_anchor() }+ pub fn set_end_anchor_file(&self, r: &RequestHandle, path: &Path) -> Result<(), String> {+ self.check(r)?;+ self.inner.set_end_anchor_file(r.pointer.as_ptr(), path)+ }pub fn set_continuation_file(&self,r: &RequestHandle,diff --git a/src-tauri/core/src/slopfab/ffi/raw/mod.rs b/src-tauri/core/src/slopfab/ffi/raw/mod.rsindex 36d261a..563c0b7 100644--- a/src-tauri/core/src/slopfab/ffi/raw/mod.rs+++ b/src-tauri/core/src/slopfab/ffi/raw/mod.rs@@ -106,6 +106,7 @@ pub struct Api {set_outpaint_langevin_steps: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,set_save_latents: Option<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>,set_continuation_file: Option<unsafe extern "C" fn(*mut Request, *const c_char, i32) -> i32>,+ set_end_anchor_file: Option<unsafe extern "C" fn(*mut Request, *const c_char, i32) -> i32>,set_latent_bridge_files: Option<unsafe extern "C" fn(*mut Request, *const c_char, *const c_char, i32, i32, i32) -> i32>,set_continuation_lock_overlap: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,set_video_transition: Option<unsafe extern "C" fn(*mut Request, i32) -> i32>,@@ -281,6 +282,7 @@ impl Api {).ok().map(|symbol| *symbol),+ set_end_anchor_file: library.get::<unsafe extern "C" fn(*mut Request, *const c_char, i32) -> i32>(b"slopfab_request_set_end_anchor_file\0").ok().map(|symbol| *symbol),set_continuation_lock_overlap: library.get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(b"slopfab_request_set_continuation_lock_overlap\0").ok().map(|symbol| *symbol),@@ -526,6 +528,14 @@ impl Api {let right = path_cstring(right)?;self.error(unsafe { set(r, left.as_ptr(), right.as_ptr(), left_margin, right_margin, context) })}+ pub fn require_end_anchor(&self) -> Result<(), String> {+ self.set_end_anchor_file.map(|_| ()).ok_or("Single Shot requires SlopFab API 1.40 or newer. Update the app and workers.".into())+ }+ pub fn set_end_anchor_file(&self, r: *mut Request, path: &Path) -> Result<(), String> {+ self.require_end_anchor()?;+ let path = CString::new(path.to_string_lossy().as_bytes()).map_err(|_| "Ending path contains a null byte.")?;+ self.error(unsafe { self.set_end_anchor_file.unwrap()(r, path.as_ptr(), 22) })+ }pub fn set_continuation_file(&self,r: *mut Request,diff --git a/src-tauri/core/src/slopfab/generation.rs b/src-tauri/core/src/slopfab/generation.rsindex 64f8764..c32f498 100644--- a/src-tauri/core/src/slopfab/generation.rs+++ b/src-tauri/core/src/slopfab/generation.rs@@ -26,9 +26,86 @@ impl rendered::FrameSource for FrameSource {pub(super) fn run_generation(item: &QueueItem,) -> Result<(OutputMetadata, rendered::RenderedVideo), String> {+ if item.request.single_shot.is_some() {+ ffi::Api::load(&item.configuration.dll_path)?.require_end_anchor()?;+ return run_single_shot(item, run_single_generation);+ }run_edit_sequence(item, run_single_generation)}+fn run_single_shot(+ item: &QueueItem,+ mut generate: impl FnMut(&QueueItem) -> Result<(OutputMetadata, rendered::RenderedVideo), String>,+) -> Result<(OutputMetadata, rendered::RenderedVideo), String> {+ let single = item.request.single_shot.as_ref().ok_or("Missing Single Shot settings.")?;+ let temporary = tempfile::tempdir().map_err(|error| format!("Could not prepare ending latents: {error}"))?;+ let ending_path = temporary.path().join("ending.safetensors");+ let mut elapsed = 0.0;+ let mut timings = [0.0; 4];+ let mut computed = 0;+ let mut skipped = 0;+ for index in 0..2 {+ if item.cancel.load(Ordering::Acquire) { return Err("Single Shot generation cancelled.".into()); }+ let mut request = item.request.clone();+ if index == 0 {+ request.single_shot = None;+ request.prompt = single.ending_prompt.clone();+ request.frames = 22;+ request.continuation_relative_path = None;+ request.continuation_path = None;+ request.continuation_source_frames = None;+ request.continuation_overlap_frames = None;+ request.continuation_from = None;+ request.continuation_lock_overlap = false;+ request.save_latents_path = Some(ending_path.clone());+ } else {+ request.single_shot.as_mut().unwrap().ending_path = Some(ending_path.clone());+ }+ let sink = item.events.clone();+ let offset = elapsed;+ let stage = QueueItem { request, configuration: item.configuration.clone(), references: item.references.clone(), cancel: item.cancel.clone(),+ events: std::sync::Arc::new(move |event| {+ let event = match event {+ super::events::NativeEvent::Progress(mut progress) => {+ let steps = progress.planned_steps.max(1);+ progress.step = index * steps + progress.step.clamp(0, steps);+ progress.total_steps = steps * 2;+ progress.planned_steps = progress.total_steps;+ progress.elapsed_seconds += offset;+ progress.stage = if index == 0 { "singleShotEnding" } else { "singleShotFull" };+ progress.timing_profile.push_str("|singleShot=2");+ super::events::NativeEvent::Progress(progress)+ }+ event => event,+ };+ sink(event);+ }),+ };+ let (mut metadata, result) = generate(&stage)?;+ if item.cancel.load(Ordering::Acquire) { return Err("Single Shot generation cancelled.".into()); }+ elapsed += metadata.seconds_total;+ timings[0] += metadata.seconds_conditioning;+ timings[1] += metadata.seconds_denoise;+ timings[2] += metadata.seconds_video_decode;+ timings[3] += metadata.seconds_audio_decode;+ computed += metadata.steps_computed;+ skipped += metadata.steps_skipped;+ if index == 1 {+ metadata.seconds_total = elapsed;+ metadata.seconds_conditioning = timings[0]; metadata.seconds_denoise = timings[1];+ metadata.seconds_video_decode = timings[2]; metadata.seconds_audio_decode = timings[3];+ metadata.steps_computed = computed; metadata.steps_skipped = skipped;+ metadata.timing_profile.push_str("|singleShot=2");+ return Ok((metadata, result));+ }+ // The ending is only an anchor, never a separate scene/history result.+ // Release its decoded buffers before allocating the full generation.+ drop(result);+ if !ending_path.is_file() { return Err("The ending generation did not save its latents.".into()); }+ }+ unreachable!()+}+fn run_edit_sequence(item: &QueueItem,mut generate: impl FnMut(&QueueItem) -> Result<(OutputMetadata, rendered::RenderedVideo), String>,diff --git a/src-tauri/core/src/slopfab/generation_tests.rs b/src-tauri/core/src/slopfab/generation_tests.rsindex d0694e7..2f76ae9 100644--- a/src-tauri/core/src/slopfab/generation_tests.rs+++ b/src-tauri/core/src/slopfab/generation_tests.rs@@ -73,6 +73,78 @@ fn item() -> QueueItem {events: Arc::new(|_| {}), cancel: Arc::new(AtomicBool::new(false)) }}+fn single_shot_item() -> QueueItem {+ let mut item = item();+ item.request.image_edit = None;+ item.request.still_image = false;+ item.request.frames = 48;+ item.request.single_shot = Some(crate::slopfab::types::SingleShotRequest { ending_prompt: "Waves goodbye".into(), ending_path: None });+ item.request.reference_paths = vec!["reference.png".into()];+ item.request.continuation_path = Some("source.safetensors".into());+ item.request.continuation_relative_path = Some("latents/source.safetensors".into());+ item.request.continuation_source_frames = Some(124);+ item.request.continuation_overlap_frames = Some(22);+ item.request.continuation_lock_overlap = true;+ item.request.save_latents_path = Some("final.safetensors".into());+ item+}++#[test]+fn single_shot_generates_ending_first_then_attaches_it_with_the_starting_source() {+ let item = single_shot_item();+ let mut calls = 0;+ let mut ending_path = std::path::PathBuf::new();+ let (metadata, _) = run_single_shot(&item, |stage| {+ calls += 1;+ assert_eq!(stage.request.reference_paths, item.request.reference_paths);+ assert_eq!(stage.request.seed, item.request.seed);+ if calls == 1 {+ assert!(stage.request.single_shot.is_none());+ assert_eq!(stage.request.prompt, "Waves goodbye");+ assert_eq!(stage.request.frames, 22);+ assert!(stage.request.continuation_path.is_none());+ assert!(stage.request.continuation_relative_path.is_none());+ ending_path = stage.request.save_latents_path.clone().unwrap();+ std::fs::write(&ending_path, b"completed ending").unwrap();+ } else {+ assert_eq!(stage.request.prompt, item.request.prompt);+ assert_eq!(stage.request.frames, 48);+ assert_eq!(stage.request.continuation_path, item.request.continuation_path);+ assert_eq!(stage.request.save_latents_path, item.request.save_latents_path);+ assert_eq!(stage.request.single_shot.as_ref().unwrap().ending_path.as_ref(), Some(&ending_path));+ assert!(ending_path.is_file());+ }+ Ok(result(1))+ }).unwrap();+ assert_eq!(calls, 2);+ assert_eq!(metadata.seconds_total, 2.0);+ assert_eq!(metadata.steps_computed, 4);+ assert!(!ending_path.exists());+}++#[test]+fn single_shot_stops_on_ending_failure_missing_latents_or_cancellation_and_cleans_up() {+ for mode in ["failure", "missing", "cancel-before", "cancel-between", "full-failure"] {+ let item = single_shot_item();+ if mode == "cancel-before" { item.cancel.store(true, Ordering::Release); }+ let mut calls = 0;+ let mut path = None;+ let error = run_single_shot(&item, |stage| {+ calls += 1;+ if calls == 2 { return Err("full shot failed".into()); }+ let ending = stage.request.save_latents_path.clone().unwrap();+ path = Some(ending.clone());+ if mode != "missing" { std::fs::write(&ending, b"ending").unwrap(); }+ if mode == "failure" { return Err("ending failed".into()); }+ if mode == "cancel-between" { item.cancel.store(true, Ordering::Release); }+ Ok(result(1))+ }).err().unwrap();+ assert!(!error.is_empty());+ assert_eq!(calls, if mode == "cancel-before" { 0 } else if mode == "full-failure" { 2 } else { 1 });+ assert!(path.is_none_or(|path| !path.exists()));+ }+}+#[test]fn sequential_image_edits_feed_previous_pixels_and_report_combined_progress() {let mut item = item();diff --git a/src-tauri/core/src/slopfab/h3.rs b/src-tauri/core/src/slopfab/h3.rsindex a93df59..4a39de2 100644--- a/src-tauri/core/src/slopfab/h3.rs+++ b/src-tauri/core/src/slopfab/h3.rs@@ -19,6 +19,7 @@ pub(super) fn configure_request() -> Result<(), String> {if request.music.is_some() { return super::music::configure(api, handle, request, configuration, platform); }configuration.validate_inputs(request)?;+ if request.single_shot.is_some() { api.require_end_anchor()?; }if crate::models::generator_features(&configuration.model_type).cuda_only {if platform == ComputePlatform::Vulkan {return Err(format!("{} requires CUDA. Select a CUDA backend or worker.", crate::models::generator_features(&configuration.model_type).label));@@ -58,7 +59,9 @@ pub(super) fn configure_request(} else {request.frames};- api.set_frames(handle, frames)?;+ // Ending-anchor APIs count new lead-in/gap frames, while Slopus scene+ // duration includes the short ending. Planning uses equivalent full geometry.+ api.set_frames(handle, if request.single_shot.as_ref().is_some_and(|single| single.ending_path.is_some()) { frames - 22 } else { frames })?;if request.still_image && !matches!(configuration.model_type.as_str(), "moss" | "fibo2") {api.set_still_image(handle)?;}@@ -135,7 +138,7 @@ pub(super) fn configure_request(let lock_overlap = request.continuation_path.is_some() && request.continuation_lock_overlap;let independent_audio = request.audio_steps.is_some_and(|steps| steps != video_steps);// Overlap locking and different audio/video step counts require full evaluations.- api.set_motion_cache(handle, configuration.motion_cache && !dmad && request.image_edit.is_none() && !lock_overlap && !independent_audio && request.latent_bridge.is_none())?;+ api.set_motion_cache(handle, configuration.motion_cache && !dmad && request.image_edit.is_none() && !lock_overlap && !independent_audio && request.latent_bridge.is_none() && request.single_shot.is_none())?;if let Some(bridge) = &request.latent_bridge {api.set_latent_bridge_files(handle,request.bridge_left_path.as_deref().ok_or("Missing left Long Shot archive.")?,@@ -155,6 +158,9 @@ pub(super) fn configure_request()?;api.set_continuation_lock_overlap(handle, lock_overlap)?;}+ if let Some(path) = request.single_shot.as_ref().and_then(|single| single.ending_path.as_ref()) {+ api.set_end_anchor_file(handle, path)?;+ }if purpose == RequestPurpose::Generate {if let Some(path) = &request.save_latents_path {api.set_save_latents(handle, path)?;diff --git a/src-tauri/core/src/slopfab/planning.rs b/src-tauri/core/src/slopfab/planning.rsindex 4e534f0..539c082 100644--- a/src-tauri/core/src/slopfab/planning.rs+++ b/src-tauri/core/src/slopfab/planning.rs@@ -46,7 +46,7 @@ pub fn resolve_plan(canvas_height: if request.latent_upscale { request.canvas_height } else { plan.canvas_height },aligned_frames: frames,duration_seconds: if request.music.is_some() { plan.duration_seconds } else { plan.duration_seconds * frames as f64 / plan.aligned_frames as f64 },- model_evaluations: plan.num_model_evaluations * request.image_edit.as_ref().map_or(1, |edit| edit.edits.len() as i32),+ model_evaluations: plan.num_model_evaluations * if request.single_shot.is_some() { 2 } else { request.image_edit.as_ref().map_or(1, |edit| edit.edits.len() as i32) },sequence_rows_without_text: plan.sequence_rows_without_text,latent_frames: plan.latent_frames,latent_width: plan.latent_width,@@ -57,6 +57,14 @@ pub fn resolve_plan(}pub(super) fn validate_generation_controls(request: &GenerationRequest) -> Result<(), String> {+ if let Some(single) = &request.single_shot {+ if request.music.is_some() || request.still_image || request.image_edit.is_some() || request.video_transition.is_some() || request.latent_bridge.is_some()+ || request.frames < 48 || single.ending_prompt.trim().is_empty() || single.ending_prompt.contains('\0') || single.ending_prompt.len() > 1024 * 1024+ || request.continuation_from.as_deref().is_some_and(|from| from != "end")+ || request.continuation_overlap_frames.is_some_and(|frames| frames != 22) {+ return Err("Single Shot requires a video of at least 2 seconds, an ending prompt and optional ending latents from a starting scene.".into());+ }+ }if let Some(music) = &request.music { return music.validate(); }if let Some(scale) = request.guidance_scale { crate::models::validate_cfg_scale(f64::from(scale))?; }if let Some(effects) = &request.generation_effects { effects.validate()?; }diff --git a/src-tauri/core/src/slopfab/types.rs b/src-tauri/core/src/slopfab/types.rsindex c237cf6..91457d4 100644--- a/src-tauri/core/src/slopfab/types.rs+++ b/src-tauri/core/src/slopfab/types.rs@@ -54,6 +54,8 @@ pub struct LatentBridgeRequest {#[derive(Debug, Clone, Default, Deserialize, Serialize)]#[serde(rename_all = "camelCase")]pub struct GenerationRequest {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub single_shot: Option<SingleShotRequest>,#[serde(default, skip_serializing_if = "Option::is_none")]pub music: Option<super::music::MusicSettings>,#[serde(default, skip_serializing_if = "Option::is_none")]@@ -120,6 +122,15 @@ pub struct GenerationRequest {pub save_latents_path: Option<PathBuf>,}+#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct SingleShotRequest {+ pub ending_prompt: String,+ /// Generated locally on the execution host; never accepted over IPC/LAN.+ #[serde(skip)]+ pub ending_path: Option<PathBuf>,+}+#[derive(Debug, Clone, Deserialize, Serialize)]#[serde(rename_all = "camelCase")]pub struct ImageEditRequest {diff --git a/src-tauri/core/src/worker/protocol.rs b/src-tauri/core/src/worker/protocol.rsindex c59eaca..024966d 100644--- a/src-tauri/core/src/worker/protocol.rs+++ b/src-tauri/core/src/worker/protocol.rs@@ -23,7 +23,8 @@ pub const SERVICE_TYPE: &str = "_slopus-worker._tcp.local.";// v6 added custom upscale weights.// v5 added overlap locking.// v4 added SeedVR2 export streams. v3 added inverted image masks.-pub const PROTOCOL_VERSION: u32 = 18;+// v19 carries Single Shot ending-first generation; older workers would ignore it.+pub const PROTOCOL_VERSION: u32 = 19;/// Streaming SeedVR2 restoration; model paths are resolved on the worker.#[derive(Debug, Clone, Serialize, Deserialize)]@@ -331,6 +332,20 @@ mod tests {assert_eq!(restored.negative_prompt.as_deref(), Some("watermark"));}+ #[test]+ fn single_shot_roundtrip_keeps_ending_prompt_but_never_host_temporary_paths() {+ let request = GenerationRequest { single_shot: Some(crate::slopfab::SingleShotRequest {+ ending_prompt: "The subject waves goodbye".into(), ending_path: Some("C:/host/temporary.safetensors".into()),+ }), ..Default::default() };+ let wire = serde_json::to_string(&request).unwrap();+ assert!(!wire.contains("temporary.safetensors"));+ let restored: GenerationRequest = serde_json::from_str(&wire).unwrap();+ let single = restored.single_shot.unwrap();+ assert_eq!(single.ending_prompt, "The subject waves goodbye");+ assert!(single.ending_path.is_none());+ assert_eq!(PROTOCOL_VERSION, 19);+ }+#[test]fn moss_tokenizer_is_transferred_as_a_file_instead_of_a_folder() {let mut settings = settings(&[("modelType", "moss"), ("tokenizer", "C:/weights/tokenizer.json")]);diff --git a/src-tauri/src/project/scenes.rs b/src-tauri/src/project/scenes.rsindex 8ec3d45..20501f1 100644--- a/src-tauri/src/project/scenes.rs+++ b/src-tauri/src/project/scenes.rs@@ -48,6 +48,8 @@ pub(crate) struct GenerationJob {#[serde(default, skip_serializing_if = "Option::is_none")]pub(crate) scene_type: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]+ pub(crate) ending_prompt: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]pub(crate) backdrop_color: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]pub(crate) bridge_left_margin: Option<i32>,@@ -173,6 +175,7 @@ impl GenerationJob {generation_history: None,id: id.to_string(),scene_type: None,+ ending_prompt: None,backdrop_color: None,bridge_left_margin: None,bridge_right_margin: None,diff --git a/src-tauri/src/project/validation/scenes.rs b/src-tauri/src/project/validation/scenes.rsindex efc9612..73f6e7d 100644--- a/src-tauri/src/project/validation/scenes.rs+++ b/src-tauri/src/project/validation/scenes.rs@@ -20,6 +20,9 @@ fn validate_jobs(jobs: &mut [GenerationJob]) -> Result<(), String> {job.use_previous_scene_last_frame = None;}previous_id = Some(job.id.clone());+ if job.ending_prompt.as_ref().is_some_and(|prompt| prompt.chars().count() > 30000) {+ return Err(format!("Scene '{}' has an ending prompt longer than 30000 characters.", job.id));+ }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) {@@ -28,7 +31,7 @@ fn validate_jobs(jobs: &mut [GenerationJob]) -> Result<(), String> {if job.scene_type.as_deref().is_some_and(|value| {!matches!(value,- "prompt" | "first-last-frame" | "continue" | "animate" | "pose" | "character-replace" | "extend" | "bridge" | "backdrop" | "long-shot"+ "prompt" | "single-shot" | "first-last-frame" | "continue" | "animate" | "pose" | "character-replace" | "extend" | "bridge" | "backdrop" | "long-shot")}) {return Err(format!("Scene '{}' has an unsupported scene type.", job.id));@@ -273,6 +276,18 @@ fn validate_history(job: &mut GenerationJob) -> Result<(), String> {#[cfg(test)]mod history_tests {use super::*;+ #[test]+ fn single_shot_fields_survive_native_project_roundtrip() {+ let mut config: ProjectConfig = serde_json::from_str(include_str!("../../../../fixtures/project-v1-complete.json")).unwrap();+ config.generation_jobs[0].scene_type = Some("single-shot".into());+ config.generation_jobs[0].ending_prompt = Some("@[ref:hero] waves goodbye".into());+ config.generation_jobs[0].continuation_scene_id = Some("start".into());+ validate(&mut config).unwrap();+ let restored: ProjectConfig = serde_json::from_slice(&serde_json::to_vec(&config).unwrap()).unwrap();+ assert_eq!(restored.generation_jobs[0].ending_prompt, config.generation_jobs[0].ending_prompt);+ assert_eq!(restored.generation_jobs[0].scene_type.as_deref(), Some("single-shot"));+ assert_eq!(restored.generation_jobs[0].continuation_scene_id.as_deref(), Some("start"));+ }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];diff --git a/src/components/workspace/GeneratorView.test.tsx b/src/components/workspace/GeneratorView.test.tsxindex 0b6ffaf..4bd46cf 100644--- a/src/components/workspace/GeneratorView.test.tsx+++ b/src/components/workspace/GeneratorView.test.tsx@@ -111,6 +111,49 @@ it("queues Long Shot anchors before their intervening bridges", () => {expect(submitted.mock.calls[0][0][2].request.latentBridge).toMatchObject({ leftSceneId: "1", rightSceneId: "3", leftMarginFrames: 17, rightMarginFrames: 17 });});+it("edits reference-aware Single Shot prompts and allows other scene types as starting videos", () => {+ const initial = project();+ initial.references = [{ id: "hero", kind: "image", name: "Hero", description: "", intendedUse: [], relativePath: "references/hero.png", createdAt: initial.createdAt }];+ initial.generationJobs[1].sceneType = "single-shot";+ initial.generationJobs.push(createDraftGenerationJob("A regular scene", { id: "ordinary", title: "Ordinary" }));+ const state = setup(initial);+ choose("Scene type", "Single Shot");+ const main = screen.getByLabelText("Single Shot prompt"), ending = screen.getByLabelText("Ending prompt");+ typePrompt(main, "Walk forward.");+ typePrompt(ending, "Wave goodbye.");+ placePromptCaret(ending);+ fireEvent.focus(ending);+ fireEvent.click(within(screen.getByRole("toolbar", { name: "Ending prompt tools" })).getByRole("button", { name: "Reference" }));+ fireEvent.click(screen.getByRole("button", { name: /^Hero\b/ }));+ expect(state.latest().generationJobs[0].endingPrompt).toContain("@[ref:hero]");+ expect(screen.queryByRole("button", { name: "Add a shot to First scene" })).not.toBeInTheDocument();+ const source = screen.getByRole("combobox", { name: "Single Shot starting video" });+ expect(optionNames(source)).toEqual(["None", "Second scene", "Ordinary"]);+ chooseOption(source, "Second scene");+ expect(state.latest().generationJobs[0].continuationSceneId).toBe("scene-second");+ fireEvent.click(screen.getByRole("button", { name: "Shot 1 of First scene" }));+ expect(screen.getByLabelText("Ending prompt")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Add scene" }));+ expect(state.latest().generationJobs.at(-1)?.sceneType).toBe("single-shot");+});++it.each(["prompt", "single-shot"] as const)("queues a starting %s scene before Single Shot dependents even when board order is reversed", (type) => {+ const initial = project();+ initial.generationJobs = [+ { ...createDraftGenerationJob("Next", { id: "next", sceneType: "single-shot" }), endingPrompt: "Finish next", continuationSceneId: "start" },+ createDraftGenerationJob("Start", { id: "start", sceneType: type }),+ ];+ const submitted = vi.fn();+ render(<GeneratorView config={initial} folderPath="C:/project" runtime={readyRuntime} onChange={vi.fn()} onGenerate={submitted} onOpenTimeline={() => {}} />);+ fireEvent.click(screen.getByRole("button", { name: "Generate all" }));+ const submissions = submitted.mock.calls[0][0];+ expect(submissions.map((item: { job: { id: string } }) => item.job.id)).toEqual(["start", "next"]);+ if (type === "single-shot") expect(submissions[0].request.singleShot.endingPrompt).toBe(submissions[0].request.prompt);+ else expect(submissions[0].request.singleShot).toBeUndefined();+ expect(submissions[1].request.singleShot.endingPrompt).toContain("Finish next");+ expect(submissions[1].request.previousSceneId).toBe("start");+});+it("persists Long Shot boundary controls and inherits the scene type for new scenes", () => {const initial = project();initial.generationJobs.push(createDraftGenerationJob("Keep walking", { id: "third" }));diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsxindex fe0d3c8..fa2faf4 100644--- a/src/components/workspace/GeneratorView.tsx+++ b/src/components/workspace/GeneratorView.tsx@@ -154,7 +154,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst animate = selected ? sceneTypeFor(selected) === "animate" : false;const selectedShots = useMemo(() => (selected ? sceneShots(selected) : []), [selected]);const shotIndex = selectedShots.findIndex((shot) => shot.id === selection.shotId);- const openShot = !animate && shotIndex >= 0 ? selectedShots[shotIndex] : null;+ const openShot = !animate && selected?.sceneType !== "single-shot" && shotIndex >= 0 ? selectedShots[shotIndex] : null;const shotEndsAt = selected && openShot? shotIndex + 1 < selectedShots.length ? selectedShots[shotIndex + 1].startSeconds : sceneDurationSeconds(selected): 0;@@ -242,6 +242,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCosetShots(job, sceneShots(job).map((shot) => shot.id === shotId ? { ...shot, ...updates } : shot));const addShot = (job: GenerationJob) => {+ if (job.sceneType === "single-shot") return;const shots = sceneShots(job);const duration = sceneDurationSeconds(job);const last = shots[shots.length - 1];@@ -363,7 +364,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoreferences already named by its shots. */const newScene = () => {const job = createDraftGenerationJob("", { steps: defaultGenerationSteps,- sceneType: selectedTemplate.mode === "animate" ? "animate" : selected?.sceneType === "long-shot" ? "long-shot" : "prompt" });+ sceneType: selectedTemplate.mode === "animate" ? "animate" : selected?.sceneType === "single-shot" ? "single-shot" : selected?.sceneType === "long-shot" ? "long-shot" : "prompt" });onChange({ ...config, generationJobs: [...jobs, job] });setSelection({ jobId: job.id, shotId: null });};@@ -427,7 +428,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCobatchScenesReady.includes(source) || ["queued", "generating", "ready"].includes(source.status));if (previousWillRender || sceneGenerationSeed(job) === RANDOM_GENERATION_SEED || job.status !== "completed"|| !job.outputRelativePath- || (!job.latentRelativePath && (job.sceneType === "long-shot" || jobs.some((candidate) => continuationSceneId(candidate, jobs) === job.id)))+ || (!job.latentRelativePath && (job.sceneType === "long-shot" || job.sceneType === "single-shot" || jobs.some((candidate) => continuationSceneId(candidate, jobs) === job.id)))|| !job.generationSnapshot|| job.generationSnapshot !== snapshotFor(job)) batchScenesReady.push(job);return true;diff --git a/src/components/workspace/SceneBoard.tsx b/src/components/workspace/SceneBoard.tsxindex 4a8632b..e0c203b 100644--- a/src/components/workspace/SceneBoard.tsx+++ b/src/components/workspace/SceneBoard.tsx@@ -148,7 +148,7 @@ export function SceneBoard({: { id: "generate", label: "Generate", icon: <Wand16 />, disabled: Boolean(blocker), onSelect: () => onGenerate(job) },{ id: "rename", label: "Rename", icon: <Rename16 />, shortcut: "F2", disabled: !onRename, onSelect: () => onRename?.({ jobId: job.id, shotId: null }) },{ id: "duplicate", label: "Duplicate", icon: <Copy16 />, disabled: !onDuplicate, onSelect: () => onDuplicate?.(job) },- { id: "add-shot", label: "Add shot", icon: <Add16 />, onSelect: () => onAddShot(job) },+ { id: "add-shot", label: "Add shot", icon: <Add16 />, disabled: job.sceneType === "single-shot", onSelect: () => onAddShot(job) },{ separator: true },{ id: "up", label: "Move up", icon: <ArrowUp16 />, disabled: jobIndex === 0, onSelect: () => onMoveScene(job.id, jobs[jobIndex - 1]?.id ?? null) },{ id: "down", label: "Move down", icon: <ArrowDown16 />, disabled: jobIndex === jobs.length - 1, onSelect: () => onMoveScene(job.id, jobs[jobIndex + 2]?.id ?? null) },@@ -392,7 +392,7 @@ export function SceneBoard({/></label>- <HeaderButton label={`Add a shot to ${job.title}`} tooltip="Add shot" onClick={() => onAddShot(job)}><Add16 /></HeaderButton>+ {job.sceneType !== "single-shot" && <HeaderButton label={`Add a shot to ${job.title}`} tooltip="Add shot" onClick={() => onAddShot(job)}><Add16 /></HeaderButton>}<HeaderButtonlabel={cancellable ? "Cancel" : "Generate"}tooltip={cancellable ? `Cancel ${job.title}` : blocker ?? `Generate ${job.title}`}diff --git a/src/components/workspace/SceneEditor.tsx b/src/components/workspace/SceneEditor.tsxindex 4a5631c..1958cd4 100644--- a/src/components/workspace/SceneEditor.tsx+++ b/src/components/workspace/SceneEditor.tsx@@ -270,6 +270,7 @@ function CharacterReplaceInputs({ shot, references, disabled, onChange }: {const SCENE_TYPES: { value: SceneType; label: string }[] = [{ value: "prompt", label: "Prompt" },+ { value: "single-shot", label: "Single Shot" },{ value: "first-last-frame", label: "First & last frame" },{ value: "backdrop", label: "Backdrop" },{ value: "long-shot", label: "Long Shot" },@@ -281,8 +282,31 @@ const SCENE_TYPES: { value: SceneType; label: string }[] = [{ value: "bridge", label: "Bridge" },];+function SingleShotPrompts({ job, shots, references, folderPath, disabled, onChange, onShots }: {+ job: GenerationJob; shots: SceneShot[]; references: ProjectReference[]; folderPath: string; disabled: boolean;+ onChange: (updates: Partial<GenerationJob>) => void; onShots: (shots: SceneShot[]) => void;+}) {+ const fields = citableReferences(references).map((reference) => ({ id: reference.id, name: reference.name,+ mediaTypes: referenceMediaTypes(reference), detail: referenceTypeLabel(reference),+ icon: <ReferenceIcon reference={reference} folderPath={folderPath} fallback={<Text16 />} /> }));+ const missingLabel = (id: string) => references.find((reference) => reference.id === id)?.name ?? "Deleted reference";+ return <>+ <div className="shot-card__action">+ <span className="shot-card__sublabel">Prompt</span>+ <PromptTextField aria-label="Single Shot prompt" rows={6} value={sceneBriefText(shots)} references={fields} missingLabel={missingLabel} disabled={disabled}+ onChange={(action) => onShots([{ ...shots[0], startSeconds: 0, action }])} />+ </div>+ <div className="shot-card__action">+ <span className="shot-card__sublabel">Ending prompt</span>+ <PromptTextField aria-label="Ending prompt" rows={4} value={job.endingPrompt ?? ""} references={fields} missingLabel={missingLabel} disabled={disabled}+ placeholder="Describe how the shot ends. Leave empty to use the main prompt." onChange={(endingPrompt) => onChange({ endingPrompt })} />+ </div>+ </>;+}+const SCENE_TYPE_DESCRIPTIONS: Record<SceneType, string> = {prompt: "Generate video from shot descriptions and optional references, without fixed start or last frames.",+ "single-shot": "Generate an ending first, then a continuous shot guided by that ending and an optional starting scene.","first-last-frame": "Generate video guided by optional start and last images, with shot descriptions controlling the action.",backdrop: "Generate subjects and action against a solid green, blue, black or white background for keying.","long-shot": "Build a longer continuous sequence by generating clips and connecting them. Generate all handles the required order.",@@ -351,6 +375,17 @@ export function SceneInspector({ job, shots, references, folderPath = "", scenesonChange={(value) => onChange({ sceneType: value as SceneType, usePreviousSceneLastFrame: undefined,...(value === "animate" ? { endFrameReferenceId: undefined } : {}) })} /></PropRow>+ {sceneType === "single-shot" && <>+ <PropRow label="Starting video" htmlFor={`${id}-single-source`} tooltip="Continue from the ending latents of another scene's full video. Generate all handles the required order.">+ <ComboBox id={`${id}-single-source`} aria-label="Single Shot starting video" disabled={disabled} value={job.continuationSceneId ?? ""}+ options={[{ value: "", label: "None" },+ ...(job.continuationSceneId && !scenes.some((scene) => scene.id === job.continuationSceneId && scene.id !== job.id)+ ? [{ 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>+ <SingleShotPrompts job={job} shots={shots} references={references} folderPath={folderPath} disabled={disabled} onChange={onChange} onShots={onShots} />+ </>}{longShot && <><p className="prop-caption">{longShot.continuation? `Continue from ${longShot.left?.title ?? "the previous scene"}. Generate all completes the preceding scenes first. Adding a following Long Shot scene turns this scene into a bridge.`diff --git a/src/lib/project.singleShot.test.ts b/src/lib/project.singleShot.test.tsnew file mode 100644index 0000000..05a847c--- /dev/null+++ b/src/lib/project.singleShot.test.ts@@ -0,0 +1,56 @@+import { expect, it } from "vitest";+import { continuationBlocker, createDraftGenerationJob, createProjectConfig, parseProjectConfig, sceneGenerationReferences, sceneGenerationSnapshot, sceneShots, type GenerationJob, type ProjectReference } from "./project";+import { sceneGenerationRequest, sendBlocker } from "./sceneGeneration";+import { duplicateScene, sceneInput } from "./sceneHistory";++const project = () => createProjectConfig({ name: "Single", prompt: "A dancer walks", resolution: "416p", aspectRatio: "16:9", targetDurationSeconds: 10 });+const shot = (id: string): GenerationJob => createDraftGenerationJob("A dancer walks", { id, sceneType: "single-shot", durationSeconds: 6 });++it("compiles both prompts with consistent reference numbering and persists ending settings in drafts and copies", () => {+ const config = project();+ config.references = ["main", "ending", "unused"].map((id): ProjectReference => ({ id, name: id, kind: "image", description: "", intendedUse: [], relativePath: `references/${id}.png`, createdAt: config.createdAt }));+ const job = { ...shot("single"), endingPrompt: "@[ref:ending] waves goodbye.",+ shots: [{ id: "one", startSeconds: 0, action: "@[ref:main] enters the room." }], startFrameReferenceId: "unused", endFrameReferenceId: "unused" };+ config.generationJobs = [job];+ const restored = parseProjectConfig(JSON.parse(JSON.stringify(config)));+ expect(restored.generationJobs[0].endingPrompt).toBe(job.endingPrompt);+ const request = sceneGenerationRequest(job, restored, "C:/Project", 8);+ expect(sceneGenerationReferences(job, config.references).map((reference) => reference.id)).toEqual(["main", "ending"]);+ expect(request.referencePaths).toEqual(["C:/Project/references/main.png", "C:/Project/references/ending.png"]);+ expect(request.prompt).toContain("<Subject 1> enters the room.");+ expect(request.singleShot?.endingPrompt).toContain("<Subject 2> waves goodbye.");+ expect(request.prompt).not.toContain("is the last frame");+ expect(request.frames).toBe(144);+ expect(sceneInput(job).endingPrompt).toBe(job.endingPrompt);+ expect(duplicateScene(config, job.id)?.config.generationJobs[1].endingPrompt).toBe(job.endingPrompt);+ expect(JSON.parse(sceneGenerationSnapshot(job, request)).singleShot).toEqual(request.singleShot);+ const changed = { ...job, endingPrompt: "@[ref:ending] sits down." };+ expect(sceneGenerationSnapshot(changed, sceneGenerationRequest(changed, restored, "C:/Project", 8))).not.toBe(sceneGenerationSnapshot(job, request));+});++it("falls back to the main prompt, collapses source shots, and rejects missing references and too-short scenes", () => {+ const config = project();+ const job = { ...shot("single"), endingPrompt: " ", shots: [+ { id: "a", startSeconds: 0, action: "Walk forward." }, { id: "b", startSeconds: 2, action: "Wave goodbye." },+ ] };+ expect(sceneShots(job)).toHaveLength(1);+ expect(sceneShots(job)[0].action).toBe("Walk forward.\n\nWave goodbye.");+ const request = sceneGenerationRequest(job, config, "C:/Project", 8);+ expect(request.singleShot?.endingPrompt).toBe(request.prompt);+ expect(sendBlocker({ ...job, endingPrompt: "@[ref:missing] leaves." }, [])).toMatch(/ending prompt/);+ expect(sendBlocker({ ...job, durationSeconds: 1 }, [])).toMatch(/at least 2 seconds/);+});++it("uses the starting video's ending latents and rejects cycles, missing sources and incompatible upscale settings", () => {+ const config = project(), source = { ...shot("start"), latentRelativePath: "latents/start.safetensors", status: "completed" as const };+ const next = { ...shot("next"), continuationSceneId: source.id, continuationFrom: "start" as const, continuationOverlapFrames: 39, continuationLockOverlap: false };+ config.generationJobs = [next, source];+ expect(continuationBlocker(next, config.generationJobs)).toBeNull();+ expect(sceneGenerationRequest(next, config, "C:/Project", 8)).toMatchObject({ previousSceneId: "start", continuationRelativePath: source.latentRelativePath,+ continuationFrom: "end", continuationOverlapFrames: 22, continuationLockOverlap: true, singleShot: { endingPrompt: expect.any(String) } });+ expect(continuationBlocker(next, [next])).toMatch(/no longer exists/);+ expect(continuationBlocker(next, [next, { ...source, sceneType: "prompt" }])).toBeNull();+ expect(continuationBlocker(next, [next, { ...source, continuationSceneId: next.id }])).toMatch(/cycle/);+ expect(continuationBlocker({ ...source, continuationSceneId: source.id }, [source])).toMatch(/cycle/);+ expect(continuationBlocker(next, [next, { ...source, latentUpscale: true }])).toMatch(/Latent upscale/);+});diff --git a/src/lib/project.ts b/src/lib/project.tsindex 01b8c20..bd179e3 100644--- a/src/lib/project.ts+++ b/src/lib/project.ts@@ -467,7 +467,7 @@ 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(["prompt", "first-last-frame", "continue", "animate", "pose", "character-replace", "extend", "bridge", "backdrop", "long-shot"]);+export const sceneTypeSchema = z.enum(["prompt", "single-shot", "first-last-frame", "continue", "animate", "pose", "character-replace", "extend", "bridge", "backdrop", "long-shot"]);export type SceneType = z.infer<typeof sceneTypeSchema>;export const DEFAULT_CONTINUATION_OVERLAP = 22;export const MAX_CONTINUATION_OVERLAP = 362;@@ -555,6 +555,7 @@ const generationJobBaseSchema = z.object({generatorTemplateId: idSchema.nullish(),id: idSchema,sceneType: sceneTypeSchema.nullish(),+ endingPrompt: z.string().max(30000).nullish(),backdropColor: z.enum(["green", "blue", "black", "white"]).nullish(),bridgeLeftMargin: z.number().int().min(0).max(340).multipleOf(17).nullish(),bridgeRightMargin: z.number().int().min(0).max(340).multipleOf(17).nullish(),@@ -1018,8 +1019,8 @@ export function audioReferenceBlocker(job: GenerationJob, bound: ProjectReferenc* order. Frame anchors use their first image, even on a multi-image reference;* the same anchor selected for both ends is sent only once. */export function sceneGenerationReferences(job: GenerationJob, references: ProjectReference[]): ProjectReference[] {- if (job.sceneType === "prompt" || job.sceneType === "backdrop" || job.sceneType === "long-shot") {- const cited = sceneShots(job).flatMap(shotReferenceIds);+ if (job.sceneType === "prompt" || job.sceneType === "backdrop" || job.sceneType === "long-shot" || job.sceneType === "single-shot") {+ const cited = [...sceneShots(job).flatMap(shotReferenceIds), ...(job.sceneType === "single-shot" ? actionReferenceIds(job.endingPrompt ?? "") : [])];return references.filter((reference) => cited.includes(reference.id));}if (job.sceneType === "pose") {@@ -1060,15 +1061,16 @@ export function sceneTypeFor(job: GenerationJob): SceneType {/** 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 === "continue" || job.sceneType === "single-shot") 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;+ if (job.sceneType === "single-shot" && !job.continuationSceneId) return null;+ if (job.sceneType !== "continue" && job.sceneType !== "single-shot" && !job.usePreviousSceneLastFrame) return null;+ if (job.sceneType && !["continue", "first-last-frame", "single-shot"].includes(job.sceneType)) return null;const seen = new Set([job.id]);let current = job;while (true) {@@ -1078,6 +1080,7 @@ export function continuationBlocker(job: GenerationJob, jobs: readonly Generatioseen.add(id);const source = jobs.find((candidate) => candidate.id === id);if (!source) return "The selected source scene no longer exists.";+ if (current.sceneType === "single-shot" && !!source.latentUpscale !== !!current.latentUpscale) return "Use the same Latent upscale setting for the Single Shot and its starting video.";if (source.sceneType !== "continue" && !continuationSceneId(source, jobs)) return null;current = source;}@@ -1105,9 +1108,9 @@ export function sceneFrameInputs(job: GenerationJob, config: ProjectConfig) {const resolved = { ...job, startFrameReferenceId: undefined, endFrameReferenceId: undefined };return { job: resolved, references: sceneGenerationReferences(resolved, config.references),previousSceneId: sourceId, continuationRelativePath: previous?.latentRelativePath ?? undefined,- continuationOverlapFrames: job.continuationOverlapFrames ?? DEFAULT_CONTINUATION_OVERLAP,- continuationFrom: job.continuationFrom ?? "end",- continuationLockOverlap: job.continuationLockOverlap ?? false,+ continuationOverlapFrames: job.sceneType === "single-shot" ? 22 : job.continuationOverlapFrames ?? DEFAULT_CONTINUATION_OVERLAP,+ continuationFrom: job.sceneType === "single-shot" ? "end" as const : job.continuationFrom ?? "end",+ continuationLockOverlap: job.sceneType === "single-shot" || (job.continuationLockOverlap ?? false),continuationSourceFrames: previous ? sceneOutputFrames(previous, config) : undefined };}@@ -1186,7 +1189,10 @@ function scenePromptTimestamp(seconds: number): string {* scenes existed becomes ONE shot holding the words and tags it already had —* no words are added and none are dropped. */export function sceneShots(job: GenerationJob): SceneShot[] {- if (job.shots && job.shots.length > 0) return normalizeSceneShots(job.shots);+ if (job.shots && job.shots.length > 0) {+ const shots = normalizeSceneShots(job.shots);+ return job.sceneType === "single-shot" ? [{ ...shots[0], startSeconds: 0, action: sceneBriefText(shots), speech: shots.map((shot) => shot.speech).filter(Boolean).join("\n") }] : shots;+ }return [{ id: `${job.id}-shot-1`, startSeconds: 0, action: job.creativeBrief.trim(), settings: job.shotTags ?? null }];}@@ -1207,6 +1213,7 @@ export function sceneGenerationSeed(job: GenerationJob): number {}export interface SceneGenerationInput {+ singleShot?: { endingPrompt: string };generationEffects?: GenerationEffects;prompt: string;latentBridge?: {@@ -1249,6 +1256,7 @@ export function sceneGenerationSnapshot(job: GenerationJob, input: SceneGeneratireturn JSON.stringify({...(job.sceneType ? { sceneType: job.sceneType } : {}),prompt: input.prompt,+ ...(input.singleShot ? { singleShot: input.singleShot, endingPrompt: job.endingPrompt ?? "" } : {}),...(input.videoTransition ? { videoTransition: input.videoTransition } : {}),...(input.latentBridge ? { latentBridge: input.latentBridge } : {}),frames: input.frames,@@ -1304,7 +1312,7 @@ export function compileMiniMaxH3PromptSegments(}export function compileGenerationJobSegments(job: GenerationJob, references: ProjectReference[] = [], defaultLook?: string | null): PromptSegment[] {- if (job.sceneType === "prompt" || job.sceneType === "long-shot") return compileScenePromptSegments({+ if (job.sceneType === "prompt" || job.sceneType === "long-shot" || job.sceneType === "single-shot") return compileScenePromptSegments({shots: sceneShots(job), soundscape: job.soundscape, music: job.music,}, sceneGenerationReferences(job, references), defaultLook);if (job.sceneType === "backdrop") return compileScenePromptSegments({diff --git a/src/lib/runtime.ts b/src/lib/runtime.tsindex 1c1308e..70f1157 100644--- a/src/lib/runtime.ts+++ b/src/lib/runtime.ts@@ -101,6 +101,7 @@ export interface AgentTurnResponse {}export interface SlopfabGenerationRequest {+ singleShot?: { endingPrompt: string };music?: import("./music").MusicSettings;jobId: string;videoTransition?: "extend" | "bridge";diff --git a/src/lib/sceneGeneration.ts b/src/lib/sceneGeneration.tsindex 1fb474a..edf386e 100644--- a/src/lib/sceneGeneration.ts+++ b/src/lib/sceneGeneration.ts@@ -6,7 +6,7 @@ import {usableAudioReferences, usableVideoReferences, referenceRefmodInputs, compileGenerationJobPrompt,danglingReferenceTokens, GENERATION_FRAME_RATE, sceneDurationSeconds, sceneFrameInputs,sceneGenerationReferences, sceneGenerationSeed, sceneGenerationSteps, sceneShots, projectItemPath,- usableReferenceImages, type GenerationJob, type ProjectConfig, type ProjectReference, type SceneType,+ usableReferenceImages, compileScenePromptSegments, type GenerationJob, type ProjectConfig, type ProjectReference, type SceneType,} from "./project";import type { SlopfabGenerationRequest } from "./runtime";import { generationSigmaShifts, templateSupportsVideo, type GeneratorTemplate } from "./settings";@@ -22,12 +22,15 @@ export function sceneGenerationRequest(job: GenerationJob, config: ProjectConfigconst longShot = longShotInputs(job, config);return {jobId: job.id,+ ...(job.sceneType === "single-shot" ? { singleShot: { endingPrompt: job.endingPrompt?.trim()+ ? compileScenePromptSegments({ shots: [{ id: `${job.id}-ending`, startSeconds: 0, action: job.endingPrompt }], soundscape: job.soundscape, music: job.music }, bound, config.settings.defaultLook).map((segment) => segment.value).join("")+ : compileGenerationJobPrompt(inputs.job, bound, config.settings.defaultLook) } } : {}),...(longShot ? { latentBridge: longShot.bridge } : {}),...(job.sceneType === "extend" || job.sceneType === "bridge" ? { videoTransition: job.sceneType } : {}),// Recompiled from current state so edits to a bound reference or a// retimed shot reach the engine, rather than sending a prompt frozen at- // draft-creation time. This is the ONE string slopfab is given, and it is- // the same string the compiled-prompt panel shows.+ // draft-creation time. This is the main prompt shown in the compiled-prompt+ // panel; Single Shot captures its separate ending prompt above.prompt: job.sceneType === "animate" ? "" : compileGenerationJobPrompt(inputs.job, bound, config.settings.defaultLook),...(inputs.previousSceneId ? { previousSceneId: inputs.previousSceneId } : {}),...(inputs.continuationRelativePath ? { continuationRelativePath: inputs.continuationRelativePath } : {}),@@ -65,6 +68,11 @@ export function sceneGenerationRequest(job: GenerationJob, config: ProjectConfig/** Validate the inputs required by the selected generator before submission. */export function sendBlocker(job: GenerationJob, references: ProjectReference[]): string | null {const shots = sceneShots(job);+ if (job.sceneType === "single-shot") {+ if (sceneDurationSeconds(job) < 2) return "Single Shot needs at least 2 seconds.";+ if (danglingReferenceTokens([{ id: "ending", startSeconds: 0, action: job.endingPrompt ?? "" }], references).length)+ return "A reference in the ending prompt can't be used. Replace it or remove it.";+ }const animate = job.sceneType === "animate";const characterReplace = job.sceneType === "character-replace";if (job.sceneType === "pose") {diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.tsindex 3850091..d79120e 100644--- a/src/lib/workQueue.test.ts+++ b/src/lib/workQueue.test.ts@@ -5,7 +5,7 @@ import { listen } from "@tauri-apps/api/event";import { invoke } from "@tauri-apps/api/core";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { releaseRendered, saveGeneratedScene } from "./generatedVideo";-import { createProjectConfig, parseProjectConfig, type ProjectRecord } from "./project";+import { createProjectConfig, parseProjectConfig, sceneGenerationSnapshot, type ProjectRecord } from "./project";import { ProjectSession } from "./projectSession";import { cancelSlopfabGeneration, enqueueSlopfabGeneration, resolveSlopfabPlan } from "./runtime";import { saveEngineSettings, saveGeneratorTemplateSettings, loadGeneratorTemplateSettings, EMPTY_ENGINE_SETTINGS, type GeneratorTemplate } from "./settings";@@ -208,6 +208,44 @@ it("resolves queued Long Shot dependencies after encoding and extends the joinedexpect(JSON.parse(saved.generationJobs[1].generationSnapshot!).latentBridge.leftMarginFrames).toBe(17);});+it("chains Single Shots from a regular generated scene while capturing prompts and joined scene ranges", async () => {+ const { queue, first } = setup();+ first.update((config) => ({ ...config, generationJobs: ["a", "b", "c"].map((id, index) => ({ ...config.generationJobs[0], id,+ sceneType: index === 0 ? "prompt" as const : "single-shot" as const, endingPrompt: `Ending ${id}`, continuationSceneId: index ? ["a", "b"][index - 1] : null })) }));+ vi.mocked(resolveSlopfabPlan).mockImplementation(async (request) => {+ const live = first.getSnapshot().config;+ const source = live.generationJobs.find((job) => job.latentRelativePath === request.continuationRelativePath);+ const tail = live.assets.find((asset) => asset.id === `asset-${source?.id}`)?.sceneSegments?.at(-1);+ return { ...plan, alignedFrames: request.continuationRelativePath ? tail!.startFrame + tail!.frameCount + Math.ceil(request.frames / 17) * 17 : 158 } as Awaited<ReturnType<typeof resolveSlopfabPlan>>;+ });+ const config = first.getSnapshot().config;+ const submissions = config.generationJobs.map((job) => {+ const request = sceneGenerationRequest(job, config, first.record.folderPath, 8);+ return { job, request, snapshot: sceneGenerationSnapshot(job, request) };+ });+ const ids = queue.enqueue(first, submissions);+ first.update((current) => ({ ...current, generationJobs: current.generationJobs.map((job) => ({ ...job, endingPrompt: "Edited later" })) }));+ for (let index = 0; index < ids.length; index++) {+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(index + 1));+ if (index > 0) {+ emit("slopfab-progress", { jobId: ids[index], stage: "singleShotEnding", step: 1, totalSteps: 14, plannedSteps: 14, elapsedSeconds: 1, timingProfile: "test" });+ expect(queue.getSnapshot().find((item) => item.id === ids[index])?.detail).toBe("Generating ending (1 of 2)");+ emit("slopfab-progress", { jobId: ids[index], stage: "singleShotFull", step: 8, totalSteps: 14, plannedSteps: 14, elapsedSeconds: 2, timingProfile: "test" });+ expect(queue.getSnapshot().find((item) => item.id === ids[index])?.detail).toBe("Generating full shot (2 of 2)");+ }+ await finish(queue, ids[index]);+ }+ const requests = vi.mocked(enqueueSlopfabGeneration).mock.calls.map(([request]) => request);+ expect(requests[0].singleShot).toBeUndefined();+ expect(requests[1].continuationRelativePath).toBe(`latents/${ids[0]}.safetensors`);+ expect(requests[2].continuationRelativePath).toBe(`latents/${ids[1]}.safetensors`);+ expect(requests[2].singleShot?.endingPrompt).toContain("Ending c");+ expect(requests[2].singleShot?.endingPrompt).not.toContain("Edited later");+ const saved = first.getSnapshot().config;+ expect(saved.assets.find((asset) => asset.id === "asset-c")?.sceneSegments?.map((part) => part.sceneId)).toEqual(["a", "b", "c"]);+ expect(saved.generationJobs.every((job) => job.generationHistory?.versions.length === 1)).toBe(true);+});+it.each(["failure", "reorder"])("refuses a queued Long Shot bridge after anchor %s", async (reason) => {const { queue, first } = setup();first.update((config) => ({ ...config, generationJobs: Array.from({ length: 3 }, (_, i) => ({ ...config.generationJobs[0], id: String(i + 1), sceneType: "long-shot" as const })) }));diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.tsindex a0cdd9b..8e34cdd 100644--- a/src/lib/workQueue.ts+++ b/src/lib/workQueue.ts@@ -20,7 +20,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, sceneOutputFrames, sceneGenerationSnapshot, type SceneInput, type GenerationJob, type ProjectRecord, type ProjectConfig } from "./project";+import { continuationBlocker, 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";@@ -544,6 +544,13 @@ export class WorkQueue {throw new Error("Generate the selected source scene successfully to save its latents before continuing it. You can also use Generate All.");}const captured = work.config.generationJobs.find((job) => job.id === work.sceneId)!;+ if (captured.sceneType === "single-shot") {+ const blocker = continuationBlocker(captured, live.generationJobs);+ if (blocker) throw new Error(blocker);+ const sourceInput = JSON.parse(previous.generationSnapshot ?? "null");+ if (sourceInput && (sourceInput.canvasWidth !== work.request.canvasWidth || sourceInput.canvasHeight !== work.request.canvasHeight || !!sourceInput.latentUpscale !== !!work.request.latentUpscale))+ throw new Error("Use the starting video's resolution and Latent upscale setting.");+ }if (captured.sceneType === "long-shot") {const current = live.generationJobs.find((job) => job.id === work.sceneId);const inputs = current && longShotContinuationInputs(current, live);@@ -680,7 +687,7 @@ export class WorkQueue {return;}const progress = Math.max(item.progress, event.totalSteps > 0 ? Math.min(0.88, 0.12 + Math.max(0, event.step) / event.totalSteps * 0.76) : event.stage === "delivering" ? 0.88 : 0.08);- this.patch(work.id, { status: "generating", progress, completionAt: this.timing.update(event), detail: item.cancelling ? "Cancelling generation" : event.stage === "upscaling" ? "Upscaling video latents" : work.request.imageEdit ? `Applying image edits (${Math.min(work.request.imageEdit.edits.length, Math.floor(event.step / Math.max(1, event.totalSteps) * work.request.imageEdit.edits.length) + 1)} of ${work.request.imageEdit.edits.length})` : work.music ? "Generating music" : event.stage === "starting" || event.stage === "transformerLoad" ? "Loading MiniMax H3" : work.image ? "Generating image" : "Generating video" });+ this.patch(work.id, { status: "generating", progress, completionAt: this.timing.update(event), detail: item.cancelling ? "Cancelling generation" : event.stage === "singleShotEnding" ? "Generating ending (1 of 2)" : event.stage === "singleShotFull" ? "Generating full shot (2 of 2)" : event.stage === "upscaling" ? "Upscaling video latents" : work.request.imageEdit ? `Applying image edits (${Math.min(work.request.imageEdit.edits.length, Math.floor(event.step / Math.max(1, event.totalSteps) * work.request.imageEdit.edits.length) + 1)} of ${work.request.imageEdit.edits.length})` : work.music ? "Generating music" : event.stage === "starting" || event.stage === "transformerLoad" ? "Loading MiniMax H3" : work.image ? "Generating image" : "Generating video" });this.updateScene(work, { status: "generating", stage: event.stage === "starting" || event.stage === "transformerLoad" ? "preparing" : "generating", progress }, false);}private event(event: JobEvent) {