Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Continue scenes from saved latents

Bitti430e82f06378
diff --git a/docs/architecture.md b/docs/architecture.md
index 5046b2a..3647068 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -57,6 +57,10 @@ The slopfab C API is loaded dynamically by the Rust backend. It resolves request
The application must fail gracefully when the DLL, model files, WebCodecs, or WebGPU are unavailable. A missing runtime disables generation, never project editing.
+Every queued generation saves a unique `latents/<generation-id>.safetensors` archive inside its project using SlopFab C API 1.9's automatic save before VAE decoding. Completed scenes record `latentRelativePath` in `slopus.json`. Archives from earlier runs are retained. The “Previous scene's last frame” option continues the previous scene's saved audio/video latents with 22 overlapping frames; it no longer extracts an image. Generate All waits for the preceding scene and uses its newly saved archive. Older scenes without latents must be regenerated.
+
+Continuation archives contain the full cumulative sequence. Slopus streams only the newly added video frames and the corresponding audio suffix to WebCodecs, so separate scenes do not repeat their predecessors on the timeline. The requested scene length denotes new frames, rounded up to a multiple of 17 by SlopFab. Continuations must use the source canvas size and compatible H3 weights/VAEs; SlopFab validates the archive and canvas during planning.
+
## Independently judged slices
1. Foundation: desktop shell, library, portable project persistence, schema, and always-visible agent prompt.
diff --git a/src-tauri/src/agent.rs b/src-tauri/src/agent.rs
index 9a15674..399ff51 100644
--- a/src-tauri/src/agent.rs
+++ b/src-tauri/src/agent.rs
@@ -54,6 +54,8 @@ For edits, return JSONL only: one compact JSON object per line, followed by one
Use existing stable IDs for updates and concise descriptive IDs for additions. Order dependent commands so their targets exist before use. Omit unchanged fields. The executor derives prompt mirrors, reference bindings, timestamps, and draft state. There are deliberately no commands for file paths, assets, provider settings, generated output, progress, project identity, or schema version. Never claim media was generated or an MP4 exists.
+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.
+
Use project.set to change the open project's video settings, just like the Project settings popup opened by clicking its name:
- aspectRatio: "16:9", "9:16", "1:1", or "4:5".
- resolution: "416p", "544p", "640p", "768p", "1088p", or "1344p". These are stored resolution keys; the pixel dimensions depend on aspectRatio.
diff --git a/src-tauri/src/agent_commands.rs b/src-tauri/src/agent_commands.rs
index 1de7f28..5143742 100644
--- a/src-tauri/src/agent_commands.rs
+++ b/src-tauri/src/agent_commands.rs
@@ -558,6 +558,7 @@ fn apply_command(
music: music.clone(),
clip_id: None,
output_relative_path: None,
+ latent_relative_path: None,
error: None,
created_at: now.clone(),
updated_at: now,
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 9ca2274..fd3a555 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -383,6 +383,8 @@ struct GenerationJob {
clip_id: Option<String>,
#[serde(default)]
output_relative_path: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ latent_relative_path: Option<String>,
#[serde(default)]
error: Option<String>,
created_at: String,
@@ -1205,6 +1207,8 @@ fn validate_and_normalize_config(mut config: ProjectConfig) -> Result<ProjectCon
.as_deref()
.map(normalize_project_path)
.transpose()?;
+ job.latent_relative_path = job.latent_relative_path.as_deref()
+ .map(normalize_project_path).transpose()?;
}
for message in &config.agent_conversation.messages {
if message.id.trim().is_empty() || message.content.trim().is_empty() {
@@ -2460,9 +2464,11 @@ fn release_reference_videos(ids: Vec<String>) -> Result<(), String> {
#[tauri::command]
fn resolve_slopfab_plan(
- request: slopfab::GenerationRequest,
+ mut request: slopfab::GenerationRequest,
config: ProjectConfig,
+ folder_path: Option<String>,
) -> Result<slopfab::ResolvedPlan, String> {
+ prepare_continuation_path(&mut request, folder_path.as_deref())?;
let context = serde_json::json!({
"jobId": request.job_id, "frames": request.frames, "steps": request.steps,
"canvasWidth": request.canvas_width, "canvasHeight": request.canvas_height,
@@ -2496,9 +2502,12 @@ fn resolve_slopfab_plan(
fn enqueue_slopfab_generation(
app: AppHandle,
state: tauri::State<'_, slopfab::SlopfabRuntime>,
- request: slopfab::GenerationRequest,
+ mut request: slopfab::GenerationRequest,
config: ProjectConfig,
+ folder_path: String,
) -> Result<(), String> {
+ prepare_continuation_path(&mut request, Some(&folder_path))?;
+ request.save_latents_path = Some(generated_latent_destination(&folder_path, &request.job_id)?);
let job_id = request.job_id.clone();
let result = validate_and_normalize_config(config)
.and_then(|config| state.enqueue(app, request, &config.provider_settings));
@@ -2769,6 +2778,37 @@ fn save_reference_icon(folder_path: String, job_id: String) -> Result<String, St
write_reference_icon_frame(&folder_path, &job_id, &reference_icon_pixels(&job_id)?)
}
+fn generated_latent_destination(folder_path: &str, job_id: &str) -> Result<PathBuf, String> {
+ let root = project_root(folder_path)?;
+ let stem = generated_file_stem(job_id)?;
+ let directory = root.join("latents");
+ fs::create_dir_all(&directory).map_err(|error| format!("Could not create the project latents folder: {error}"))?;
+ let directory = directory.canonicalize().map_err(|error| error.to_string())?;
+ if !directory.starts_with(&root) {
+ return Err("The latents folder must be inside this project.".into());
+ }
+ let destination = directory.join(format!("{stem}.safetensors"));
+ if destination.exists() {
+ return Err("Latents already exist for this generation. Start a new generation to preserve them.".into());
+ }
+ Ok(destination)
+}
+
+fn prepare_continuation_path(request: &mut slopfab::GenerationRequest, folder_path: Option<&str>) -> Result<(), String> {
+ request.continuation_path = None;
+ if let Some(relative) = &request.continuation_relative_path {
+ let root = project_root(folder_path.ok_or("A project folder is required to continue a scene.")?)?;
+ let relative = normalize_project_path(relative)?;
+ let path = root.join(&relative).canonicalize()
+ .map_err(|error| format!("Could not open previous scene latents. Generate that scene again: {error}"))?;
+ if !path.starts_with(&root) || !path.is_file() {
+ return Err("Previous scene latents must be a file inside this project.".into());
+ }
+ request.continuation_path = Some(path);
+ }
+ Ok(())
+}
+
fn reference_icon_pixels(job_id: &str) -> Result<Vec<u8>, String> {
let summary = rendered::summary(&job_id).ok_or("The reference icon is no longer available.")?;
if summary.width != reference_icons::RENDER_SIZE || summary.height != reference_icons::RENDER_SIZE || summary.frame_count != 1 {
@@ -5213,6 +5253,37 @@ mod tests {
assert!(destination.starts_with(folder.path().canonicalize().unwrap()));
}
+ #[test]
+ fn latent_archives_are_unique_and_confined_to_the_project() {
+ let folder = project_folder();
+ let root = folder.path().to_string_lossy();
+ let destination = generated_latent_destination(&root, "work-one").unwrap();
+ assert!(destination.ends_with("latents/work-one.safetensors"));
+ fs::write(&destination, b"archive").unwrap();
+ assert!(generated_latent_destination(&root, "work-one").is_err());
+ assert!(generated_latent_destination(&root, "../escape").is_err());
+ let mut request: slopfab::GenerationRequest = serde_json::from_value(serde_json::json!({
+ "jobId": "next", "prompt": "Continue", "frames": 119, "steps": 4, "seed": 1,
+ "canvasWidth": 736, "canvasHeight": 416,
+ "continuationRelativePath": "latents/work-one.safetensors",
+ "saveLatentsPath": "C:/outside.safetensors", "continuationPath": "C:/outside.safetensors",
+ })).unwrap();
+ assert!(request.save_latents_path.is_none());
+ assert!(request.continuation_path.is_none());
+ assert!(prepare_continuation_path(&mut request, None).is_err());
+ prepare_continuation_path(&mut request, Some(&root)).unwrap();
+ assert_eq!(request.continuation_path, Some(destination));
+ for invalid in ["../outside.safetensors", "C:/outside.safetensors", "latents/missing.safetensors"] {
+ request.continuation_relative_path = Some(invalid.into());
+ assert!(prepare_continuation_path(&mut request, Some(&root)).is_err());
+ }
+ let mut config = created_fixture();
+ config.generation_jobs[0].latent_relative_path = Some("latents/work-one.safetensors".into());
+ assert!(validate_and_normalize_config(config.clone()).is_ok());
+ config.generation_jobs[0].latent_relative_path = Some("../outside.safetensors".into());
+ assert!(validate_and_normalize_config(config).is_err());
+ }
+
#[test]
fn purging_timeline_thumbnails_removes_only_the_named_scene() {
let folder = project_folder();
diff --git a/src-tauri/src/slopfab.rs b/src-tauri/src/slopfab.rs
index 5487b6e..039a92c 100644
--- a/src-tauri/src/slopfab.rs
+++ b/src-tauri/src/slopfab.rs
@@ -110,7 +110,7 @@ pub struct GpuDevice {
pub fn gpu_devices() -> Vec<GpuDevice> { ffi::gpu_devices() }
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GenerationRequest {
pub job_id: String,
@@ -129,6 +129,13 @@ pub struct GenerationRequest {
pub reference_video_ids: Vec<String>,
#[serde(default)]
pub refmods: Vec<RefmodInput>,
+ #[serde(default)]
+ pub continuation_relative_path: Option<String>,
+ // Only the project commands resolve paths; IPC cannot supply save targets.
+ #[serde(skip)]
+ pub continuation_path: Option<PathBuf>,
+ #[serde(skip)]
+ pub save_latents_path: Option<PathBuf>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -632,11 +639,12 @@ pub fn resolve_plan(
configure_request(&api, handle.0, request, &configuration, platform, false)?;
let plan = api.resolve(handle.0)?;
let description = api.describe(handle.0)?;
+ let (_, frames) = scene_frame_window(request, plan.aligned_frames)?;
Ok(ResolvedPlan {
canvas_width: plan.canvas_width,
canvas_height: plan.canvas_height,
- aligned_frames: plan.aligned_frames,
- duration_seconds: plan.duration_seconds,
+ aligned_frames: frames,
+ duration_seconds: plan.duration_seconds * frames as f64 / plan.aligned_frames as f64,
model_evaluations: plan.num_model_evaluations,
sequence_rows_without_text: plan.sequence_rows_without_text,
latent_frames: plan.latent_frames,
@@ -696,6 +704,14 @@ fn configure_request(
api.set_inference_backend(handle, platform.backend())?;
api.set_attention(handle, configuration.attention)?;
api.set_verbose(handle, false)?;
+ if let Some(path) = &request.continuation_path {
+ api.set_continuation_file(handle, path, 22)?;
+ }
+ if include_models {
+ if let Some(path) = &request.save_latents_path {
+ api.set_save_latents(handle, path)?;
+ }
+ }
for lora in configuration.loras.as_ref().map_err(Clone::clone)? {
if lora.path.trim().is_empty() || !lora.strength.is_finite() {
return Err("LoRA paths must be nonempty and strengths finite.".into());
@@ -738,11 +754,35 @@ fn configure_request(
Ok(())
}
+/// Continuation output is cumulative. Expose only the new scene to the editor,
+/// while the DLL saves the full archive for the next continuation.
+fn scene_frame_window(request: &GenerationRequest, total: i32) -> Result<(i32, i32), String> {
+ if total <= 0 { return Err("Slopfab returned no video frames.".into()); }
+ if request.continuation_path.is_none() { return Ok((0, total)); }
+ if request.frames <= 0 { return Err("Continuation needs a positive frame count.".into()); }
+ let frames = request.frames.checked_add(16).ok_or("Continuation frame count overflow.")? / 17 * 17;
+ let offset = total.checked_sub(frames).filter(|offset| *offset >= 22)
+ .ok_or("Slopfab continuation output is missing its source frames.".to_string())?;
+ Ok((offset, frames))
+}
+
+fn scene_audio_offset(frame_offset: i32, fps: f64, channels: i32, sample_rate: i32, total: usize) -> Result<usize, String> {
+ if total == 0 || frame_offset == 0 { return Ok(0); }
+ if !fps.is_finite() || fps <= 0.0 || channels <= 0 || sample_rate <= 0 {
+ return Err("Slopfab returned invalid continuation audio timing.".into());
+ }
+ let samples = (frame_offset as f64 * sample_rate as f64 / fps).round();
+ let offset = (samples as usize).checked_mul(channels as usize)
+ .filter(|offset| *offset <= total).ok_or("Slopfab continuation audio is shorter than its source scene.")?;
+ Ok(offset)
+}
+
/// Runs one generation and retains its terminal handle for frame streaming.
/// Audio is copied once; video stays owned by slopfab until encoding completes.
struct FinishedGeneration {
api: ffi::Api,
generation: *mut ffi::Generation,
+ frame_offset: u32,
}
// Created by the serial worker and moved into a mutex-protected render store
@@ -751,6 +791,7 @@ unsafe impl Send for FinishedGeneration {}
impl rendered::FrameSource for FinishedGeneration {
fn frame_rgba(&self, index: u32, width: u32, height: u32) -> Result<Vec<u8>, String> {
+ let index = index.checked_add(self.frame_offset).ok_or("Continuation frame index overflow.")?;
self.api.frame_rgba8(self.generation, index, width, height)
}
}
@@ -856,22 +897,26 @@ fn run_generation(item: &QueueItem) -> Result<(OutputMetadata, rendered::Rendere
return Err(error);
}
};
+ unsafe { drop(Box::from_raw(context_ptr)) };
+ drop(request);
+ let mut source = Box::new(FinishedGeneration { api, generation, frame_offset: 0 });
+ let (frame_offset, frames) = scene_frame_window(&item.request, output.frames)?;
+ source.frame_offset = frame_offset as u32;
if output.audio.is_null() && output.audio_float_count != 0 {
- api.destroy_generation(generation);
- unsafe { drop(Box::from_raw(context_ptr)) };
return Err("Slopfab returned a null audio buffer with a non-zero size.".into());
}
// Audio is small enough to own directly. Video remains in the generation
// and is converted through frame_rgba8 only as WebCodecs asks for it.
+ let audio_offset = scene_audio_offset(frame_offset, output.fps, output.audio_channels, output.audio_sample_rate, output.audio_float_count)?;
let audio = if output.audio.is_null() {
- Vec::new()
+ &[][..]
} else {
- unsafe { std::slice::from_raw_parts(output.audio, output.audio_float_count) }.to_vec()
+ &(unsafe { std::slice::from_raw_parts(output.audio, output.audio_float_count) })[audio_offset..]
};
let metadata = OutputMetadata {
- frames: output.frames, width: output.width, height: output.height, fps: output.fps,
+ frames, width: output.width, height: output.height, fps: output.fps,
audio_channels: output.audio_channels, audio_sample_rate: output.audio_sample_rate,
- audio_samples: output.audio_float_count,
+ audio_samples: audio.len(),
reference_count: item.request.reference_count(),
timing_profile,
seconds_conditioning: output.seconds_conditioning,
@@ -882,22 +927,17 @@ fn run_generation(item: &QueueItem) -> Result<(OutputMetadata, rendered::Rendere
steps_computed: output.steps_computed,
steps_skipped: output.steps_skipped,
duration_seconds: if output.fps > 0.0 {
- output.frames as f64 / output.fps
+ frames as f64 / output.fps
} else {
0.0
},
- boundary: "Decoded buffers remain owned by slopfab and frames are converted on demand. The webview encodes them; slopfab wrote no file.",
+ boundary: "Latents are saved in the project. Decoded buffers remain owned by slopfab; the webview encodes the new scene's frames on demand.",
};
- unsafe {
- drop(Box::from_raw(context_ptr));
- }
- drop(request);
- let source = Box::new(FinishedGeneration { api, generation });
let pictures = rendered::from_source(
&item.request.job_id,
source,
- &audio,
- output.frames.max(0) as u32,
+ audio,
+ frames as u32,
output.width.max(0) as u32,
output.height.max(0) as u32,
output.channels.max(0) as u32,
@@ -965,6 +1005,7 @@ fn write_reference_icon(
reference_paths: Vec::new(),
refmods: Vec::new(),
reference_video_ids: Vec::new(),
+ ..Default::default()
};
let handle = RequestHandle::new(api)?;
configure_request(api, handle.0, &request, configuration, platform, true)?;
@@ -1301,6 +1342,8 @@ mod ffi {
set_resolution: unsafe extern "C" fn(*mut Request, i32, i32) -> i32,
set_frames: unsafe extern "C" fn(*mut Request, i32) -> i32,
set_still_image: 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_steps: unsafe extern "C" fn(*mut Request, i32) -> i32,
set_seed: unsafe extern "C" fn(*mut Request, u64) -> i32,
set_model: unsafe extern "C" fn(*mut Request, i32, *const c_char) -> i32,
@@ -1403,6 +1446,12 @@ mod ffi {
add_lora: library
.get::<unsafe extern "C" fn(*mut Request, *const c_char, f32) -> i32>(b"slopfab_request_add_lora\0")
.ok().map(|symbol| *symbol),
+ set_save_latents: library
+ .get::<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>(b"slopfab_request_set_save_latents\0")
+ .ok().map(|symbol| *symbol),
+ set_continuation_file: library
+ .get::<unsafe extern "C" fn(*mut Request, *const c_char, i32) -> i32>(b"slopfab_request_set_continuation_file\0")
+ .ok().map(|symbol| *symbol),
add_refmod: library
.get::<unsafe extern "C" fn(*mut Request, *const c_char, f32, i32) -> i32>(b"slopfab_request_add_refmod\0")
.ok().map(|symbol| *symbol),
@@ -1531,6 +1580,16 @@ mod ffi {
let set = self.set_still_image.ok_or("This slopfab.dll does not support still-image generation. Update the runtime to generate reference icons.")?;
self.error(unsafe { set(r, 1) })
}
+ pub fn set_save_latents(&self, r: *mut Request, path: &Path) -> Result<(), String> {
+ let set = self.set_save_latents.ok_or("Saving generation latents requires slopfab.dll API 1.9 or later. Update the runtime.")?;
+ let path = path_cstring(path)?;
+ self.error(unsafe { set(r, path.as_ptr()) })
+ }
+ pub fn set_continuation_file(&self, r: *mut Request, path: &Path, overlap: i32) -> Result<(), String> {
+ let set = self.set_continuation_file.ok_or("Scene continuation requires slopfab.dll API 1.9 or later. Update the runtime.")?;
+ let path = path_cstring(path)?;
+ self.error(unsafe { set(r, path.as_ptr(), overlap) })
+ }
pub fn set_steps(&self, r: *mut Request, v: i32) -> Result<(), String> {
self.error(unsafe { (self.set_steps)(r, v) })
}
@@ -1700,6 +1759,68 @@ mod ffi {
#[cfg(test)]
mod tests {
use super::*;
+
+ #[test]
+ fn continuation_uses_22_frames_and_plans_only_the_new_scene() {
+ // An independent 39-frame, 64x32 archive exercises the real DLL without
+ // loading model weights. Its sampling window should be 22 + 34 frames.
+ let root = tempfile::tempdir().unwrap();
+ let path = root.path().join("previous.safetensors");
+ let video_bytes = 24 * 96 * 4;
+ let audio_bytes = 130 * 32 * 4;
+ let mut header = serde_json::json!({
+ "__metadata__": { "slopfab_latents": "h3-av-v1", "width": "64", "height": "32", "frames": "39", "fps": "24", "sampled": "1" },
+ "video_rows": { "dtype": "F32", "shape": [24, 96], "data_offsets": [0, video_bytes] },
+ "audio_rows": { "dtype": "F32", "shape": [130, 32], "data_offsets": [video_bytes, video_bytes + audio_bytes] },
+ }).to_string();
+ while header.len() % 8 != 0 { header.push(' '); }
+ let mut bytes = (header.len() as u64).to_le_bytes().to_vec();
+ bytes.extend_from_slice(header.as_bytes());
+ bytes.resize(bytes.len() + video_bytes + audio_bytes, 0);
+ std::fs::write(&path, bytes).unwrap();
+ let mut request = GenerationRequest {
+ job_id: "continued".into(), prompt: "The camera keeps moving.".into(),
+ frames: 18, steps: 4, seed: 1, canvas_width: 64, canvas_height: 32,
+ continuation_path: Some(path.clone()), save_latents_path: Some(root.path().join("next.safetensors")),
+ ..Default::default()
+ };
+ let settings = BTreeMap::new();
+ let configuration = Configuration::from_settings(&settings);
+ let api = ffi::Api::load(&configuration.dll_path).unwrap();
+ for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {
+ let handle = RequestHandle::new(&api).unwrap();
+ configure_request(&api, handle.0, &request, &configuration, platform, true).unwrap();
+ let raw = api.resolve(handle.0).unwrap();
+ assert_eq!(raw.aligned_frames, 73);
+ assert_eq!(raw.latent_frames, 17); // 56-frame window, including 22 overlap.
+ assert_eq!(scene_frame_window(&request, raw.aligned_frames).unwrap(), (39, 34));
+ }
+ let plan = resolve_plan(&request, &settings).unwrap();
+ assert_eq!(plan.aligned_frames, 34);
+ assert!((plan.duration_seconds - 34.0 / 24.0).abs() < 1e-6);
+ assert!(!request.save_latents_path.as_ref().unwrap().exists()); // Planning never writes.
+ request.canvas_width = 128;
+ assert!(resolve_plan(&request, &settings).is_err());
+ request.canvas_width = 64;
+ std::fs::write(&path, b"invalid archive").unwrap();
+ assert!(resolve_plan(&request, &settings).is_err());
+ }
+
+ #[test]
+ fn continuation_video_and_audio_skip_the_cumulative_source() {
+ let mut request = GenerationRequest { frames: 119, continuation_path: Some("source".into()), ..Default::default() };
+ assert_eq!(scene_frame_window(&request, 243).unwrap(), (124, 119));
+ // A further continuation skips the full joined source, not just its last scene.
+ assert_eq!(scene_frame_window(&request, 362).unwrap(), (243, 119));
+ assert_eq!(scene_audio_offset(124, 24.0, 2, 48_000, 972_000).unwrap(), 496_000);
+ assert_eq!(scene_audio_offset(243, 24.0, 2, 44_100, 2_000_000).unwrap(), 893_026);
+ assert_eq!(scene_audio_offset(124, 24.0, 0, 0, 0).unwrap(), 0);
+ assert!(scene_audio_offset(124, 24.0, 2, 48_000, 100).is_err());
+ assert!(scene_frame_window(&request, 120).is_err());
+ request.continuation_path = None;
+ assert_eq!(scene_frame_window(&request, 124).unwrap(), (0, 124));
+ }
+
#[test]
fn refmods_attach_for_plans_and_icons_or_report_an_older_dll() {
let configuration = Configuration::from_settings(&BTreeMap::new());
@@ -1719,6 +1840,7 @@ mod tests {
steps: 20, seed: 1, canvas_width: 768, canvas_height: 768,
reference_paths: Vec::new(), reference_video_ids: Vec::new(),
refmods: vec![RefmodInput { path: file.to_string_lossy().into_owned(), strength: 0.7, copies: 2 }],
+ ..Default::default()
};
let probe = RequestHandle::new(&api).unwrap();
let added = api.add_refmod(probe.0, &file, 0.7, 2);
@@ -1771,6 +1893,7 @@ mod tests {
canvas_width: 736, canvas_height: 416,
reference_paths: Vec::new(), reference_video_ids: Vec::new(),
refmods: Vec::new(),
+ ..Default::default()
};
for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {
for include_models in [false, true] {
@@ -1810,6 +1933,7 @@ mod tests {
canvas_width: 736, canvas_height: 416,
reference_paths: Vec::new(), reference_video_ids: vec![id.clone()],
refmods: Vec::new(),
+ ..Default::default()
};
let configuration = Configuration::from_settings(&settings);
let api = ffi::Api::load(&configuration.dll_path)?;
diff --git a/src/components/workspace/GeneratorView.test.tsx b/src/components/workspace/GeneratorView.test.tsx
index 3bdac3e..5c9fc6e 100644
--- a/src/components/workspace/GeneratorView.test.tsx
+++ b/src/components/workspace/GeneratorView.test.tsx
@@ -215,7 +215,7 @@ describe("Generator scene controls", () => {
it("marks a linked scene yellow when its previous scene regenerates and clears it after regeneration", () => {
const initial = project();
- initial.generationJobs[0] = { ...initial.generationJobs[0], status: "completed", outputRelativePath: "media/generated/work-original.mp4" };
+ initial.generationJobs[0] = { ...initial.generationJobs[0], status: "completed", outputRelativePath: "media/generated/work-original.mp4", latentRelativePath: "latents/work-original.safetensors" };
const state = setup(initial);
expect(screen.getByRole("option", { name: "Previous scene's last frame" })).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Select scene Second scene" }));
@@ -226,27 +226,27 @@ describe("Generator scene controls", () => {
generateSecond();
const snapshot = JSON.parse(state.latest().generationJobs[1].generationSnapshot!);
expect(snapshot.previousSceneId).toBe("scene-first");
- expect(snapshot.referencePaths[0]).toContain("work-original.png");
+ expect(snapshot.continuationRelativePath).toBe("latents/work-original.safetensors");
finishSecond();
const second = () => screen.getByRole("region", { name: "Second scene" });
expect(within(second()).getByText("FINISHED")).toBeInTheDocument();
state.replace({ ...state.latest(), generationJobs: state.latest().generationJobs.map((job, index) => index === 0 ? { ...job, status: "generating" } : job) });
expect(within(second()).getByText("CHANGED")).toBeInTheDocument();
expect(second().querySelector(".scene-rule__status--changed")).not.toBeNull();
- state.replace({ ...state.latest(), generationJobs: state.latest().generationJobs.map((job, index) => index === 0 ? { ...job, status: "completed", outputRelativePath: "media/generated/work-new.mp4" } : job) });
+ state.replace({ ...state.latest(), generationJobs: state.latest().generationJobs.map((job, index) => index === 0 ? { ...job, status: "completed", outputRelativePath: "media/generated/work-new.mp4", latentRelativePath: "latents/work-new.safetensors" } : job) });
expect(within(second()).getByText("CHANGED")).toBeInTheDocument();
// Opening a saved project retains the dependency's recorded renderer inputs.
state.replace(parseProjectConfig(JSON.parse(JSON.stringify(state.latest()))));
expect(within(second()).getByText("CHANGED")).toBeInTheDocument();
generateSecond();
- expect(JSON.parse(state.latest().generationJobs[1].generationSnapshot!).referencePaths[0]).toContain("work-new.png");
+ expect(JSON.parse(state.latest().generationJobs[1].generationSnapshot!).continuationRelativePath).toBe("latents/work-new.safetensors");
finishSecond();
expect(within(second()).getByText("FINISHED")).toBeInTheDocument();
});
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`, usePreviousSceneLastFrame: index === 1 }));
+ initial.generationJobs = initial.generationJobs.map((job, index) => ({ ...job, seed: 42, outputRelativePath: `media/generated/work-${index}.mp4`, latentRelativePath: `latents/work-${index}.safetensors`, usePreviousSceneLastFrame: index === 1 }));
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" })) });
@@ -256,6 +256,18 @@ describe("Generator scene controls", () => {
expect(state.latest().generationJobs.map((job) => job.status)).toEqual(["queued", "queued"]);
});
+ it("regenerates a completed source without latents when Generate All continues it", () => {
+ const initial = project();
+ initial.generationJobs = initial.generationJobs.map((job, index) => ({ ...job, seed: 42,
+ outputRelativePath: `media/generated/work-${index}.mp4`, usePreviousSceneLastFrame: index === 1 }));
+ const state = setup(initial);
+ fireEvent.click(screen.getByRole("button", { name: "Generate All" }));
+ // Simulate an older completed project: matching snapshots, but no archives.
+ state.replace({ ...state.latest(), generationJobs: state.latest().generationJobs.map((job) => ({ ...job, status: "completed" })) });
+ fireEvent.click(screen.getByRole("button", { name: "Generate All" }));
+ expect(state.latest().generationJobs.map((job) => job.status)).toEqual(["queued", "queued"]);
+ });
+
it("shows scene generation controls and sends their values in the render snapshot", async () => {
const initial = project();
initial.settings = { ...initial.settings, resolution: "416p", frameRate: 60 };
diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsx
index c8a6dda..ce98701 100644
--- a/src/components/workspace/GeneratorView.tsx
+++ b/src/components/workspace/GeneratorView.tsx
@@ -303,6 +303,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo
// the same string the compiled-prompt panel shows.
prompt: compileGenerationJobPrompt(inputs.job, bound),
...(inputs.previousSceneId ? { previousSceneId: inputs.previousSceneId } : {}),
+ ...(inputs.continuationRelativePath ? { continuationRelativePath: inputs.continuationRelativePath } : {}),
// The scene's own length, not a fixed six seconds.
frames: Math.round(sceneDurationSeconds(job) * GENERATION_FRAME_RATE),
steps: sceneGenerationSteps(job, defaultGenerationSteps),
@@ -390,6 +391,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo
(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.generationSnapshot
|| job.generationSnapshot !== snapshotFor(job)) batchScenesReady.push(job);
}
@@ -399,7 +401,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo
const generationBlocker = (job: GenerationJob): string | null => {
if (!runtimeReady) return runtimeError ?? generatorRuntime?.detail ?? "The video generator is not ready.";
if (job.status === "ready") return "This scene is being saved now.";
- if (job.usePreviousSceneLastFrame && jobs[0]?.id === job.id) return "This scene needs a previous scene to supply its first frame.";
+ if (job.usePreviousSceneLastFrame && jobs[0]?.id === job.id) return "This scene needs a previous scene to continue.";
return sendBlocker(job, config.references);
};
diff --git a/src/components/workspace/SceneEditor.tsx b/src/components/workspace/SceneEditor.tsx
index 191ee40..f5df98b 100644
--- a/src/components/workspace/SceneEditor.tsx
+++ b/src/components/workspace/SceneEditor.tsx
@@ -337,7 +337,7 @@ export function SceneInspector({ job, shots, references, previousScene, defaultS
><ImagePlus size={15} /> Add image</button>
</div>
<small>{job.usePreviousSceneLastFrame
- ? previousScene ? `Starts from the last rendered frame of “${previousScene.title}”. Generate that scene first, or use Generate All.` : "Move this scene after another scene to use its last frame."
+ ? previousScene ? `Continues “${previousScene.title}” using its saved latents with 22 overlapping frames. Generate that scene first, or use Generate All.` : "Move this scene after another scene to continue it."
: "The selected image anchors the opening frame."}</small>
</div>
<div className="scene-settings__field">
diff --git a/src/lib/project.test.ts b/src/lib/project.test.ts
index b73a911..a6982cd 100644
--- a/src/lib/project.test.ts
+++ b/src/lib/project.test.ts
@@ -535,17 +535,18 @@ describe("project schema", () => {
expect(compileGenerationJobPrompt(same, sceneGenerationReferences(same, references))).toContain("<Picture 1> is the last frame of the video.");
});
- it("resolves scene continuity from board order and the current rendered file", () => {
+ it("resolves scene continuity from board order and the current latent archive", () => {
const config = parseProjectConfig(createdFixture);
- const first = { ...config.generationJobs[0], outputRelativePath: "media/generated/work-first.mp4" };
+ const first = { ...config.generationJobs[0], latentRelativePath: "latents/work-first.safetensors" };
const second = createDraftGenerationJob("Continue", { usePreviousSceneLastFrame: true });
config.generationJobs = [first, second];
const inputs = sceneFrameInputs(second, config);
expect(inputs.previousSceneId).toBe(first.id);
- expect(usableReferenceImages(inputs.references)[0].relativePath).toBe("cache/scene-last/work-first.png");
- expect(compileGenerationJobPrompt(inputs.job, inputs.references)).toContain("<Picture 1> is the first frame of the video.");
- first.outputRelativePath = "media/generated/work-rerendered.mp4";
- expect(usableReferenceImages(sceneFrameInputs(second, config).references)[0].relativePath).toBe("cache/scene-last/work-rerendered.png");
+ expect(inputs.continuationRelativePath).toBe("latents/work-first.safetensors");
+ expect(usableReferenceImages(inputs.references)).toHaveLength(0);
+ expect(compileGenerationJobPrompt(inputs.job, inputs.references)).not.toContain("is the first frame of the video.");
+ first.latentRelativePath = "latents/work-rerendered.safetensors";
+ expect(sceneFrameInputs(second, config).continuationRelativePath).toBe("latents/work-rerendered.safetensors");
config.generationJobs.reverse();
expect(sceneFrameInputs(second, config).previousSceneId).toBeUndefined();
});
@@ -571,8 +572,8 @@ describe("project schema", () => {
});
it("resolves project-relative reference paths to absolute for the engine", () => {
- // enqueue_slopfab_generation never receives the project folder and slopfab.rs
- // uses the string verbatim, so the frontend must send an absolute path.
+ // Image references reach slopfab.rs verbatim, so the frontend resolves
+ // these paths even though latents are resolved separately in the backend.
expect(projectFilePath("C:\\Projects\\Lighthouse", "references/a.jpg")).toBe("C:\\Projects\\Lighthouse\\references\\a.jpg");
expect(projectFilePath("/home/nn/lighthouse", "references/a.jpg")).toBe("/home/nn/lighthouse/references/a.jpg");
expect(projectFilePath("/home/nn/lighthouse/", "references/a.jpg")).toBe("/home/nn/lighthouse/references/a.jpg");
diff --git a/src/lib/project.ts b/src/lib/project.ts
index 9ed44fe..058e2a8 100644
--- a/src/lib/project.ts
+++ b/src/lib/project.ts
@@ -448,6 +448,7 @@ export const generationJobSchema = z.object({
startFrameReferenceId: idSchema.nullish(),
endFrameReferenceId: idSchema.nullish(),
usePreviousSceneLastFrame: z.boolean().nullish(),
+ latentRelativePath: projectRelativePathSchema.nullish(),
// `.nullish()` because Rust holds it as an Option — see the note on
// projectAssetSchema.durationMs. Every project written before shot tags
// existed has no key here at all, and must keep opening.
@@ -804,13 +805,13 @@ export function sceneGenerationReferences(job: GenerationJob, references: Projec
export function sceneFrameInputs(job: GenerationJob, config: ProjectConfig) {
if (!job.usePreviousSceneLastFrame) return { job, references: sceneGenerationReferences(job, config.references) };
const previous = config.generationJobs[config.generationJobs.findIndex((candidate) => candidate.id === job.id) - 1];
- const id = `previous-frame-${job.id}`;
- const resolved = { ...job, startFrameReferenceId: id };
- const reference: ProjectReference = {
- id, kind: "image", name: "Previous scene's last frame", description: "", intendedUse: [], createdAt: job.createdAt,
- relativePath: previous?.outputRelativePath ? sceneLastFramePath(previous.outputRelativePath) : `cache/scene-last/pending-${job.id}.png`,
- };
- return { job: resolved, references: sceneGenerationReferences(resolved, [reference, ...config.references]), previousSceneId: previous?.id };
+ const resolved = { ...job, startFrameReferenceId: undefined };
+ return { job: resolved, references: sceneGenerationReferences(resolved, config.references),
+ previousSceneId: previous?.id, continuationRelativePath: previous?.latentRelativePath ?? undefined };
+}
+
+export function generationLatentPath(jobId: string): string {
+ return `latents/${jobId}.safetensors`;
}
export function sceneLastFramePath(outputRelativePath: string): string {
@@ -904,6 +905,7 @@ export interface SceneGenerationInput {
referenceVideos?: readonly { name: string; relativePath?: string | null; sourcePath?: string | null; startSeconds: number; durationSeconds?: number; includeAudio: boolean }[];
refmods?: readonly { path: string; strength: number; copies: number }[];
previousSceneId?: string;
+ continuationRelativePath?: string;
}
/** A stable record of everything sent to the renderer. Shot ids are retained
@@ -926,6 +928,7 @@ export function sceneGenerationSnapshot(job: GenerationJob, input: SceneGenerati
...(input.referenceVideos?.length ? { referenceVideos: input.referenceVideos } : {}),
...(input.refmods?.length ? { refmods: input.refmods } : {}),
...(input.previousSceneId ? { previousSceneId: input.previousSceneId } : {}),
+ ...(input.continuationRelativePath ? { continuationRelativePath: input.continuationRelativePath } : {}),
shots,
});
}
diff --git a/src/lib/referenceIconWork.ts b/src/lib/referenceIconWork.ts
index 6415a4b..90871a6 100644
--- a/src/lib/referenceIconWork.ts
+++ b/src/lib/referenceIconWork.ts
@@ -260,7 +260,7 @@ export class ReferenceIconWork {
jobId: task.nativeId, prompt: task.prompt, stillImage: true, frames: 1,
steps: REFERENCE_ICON_STEPS, seed: -1, canvasWidth: REFERENCE_ICON_RENDER_SIZE, canvasHeight: REFERENCE_ICON_RENDER_SIZE, referencePaths: [],
...(activeReferenceRefmods(reference).length ? { refmods: referenceRefmodInputs(task.session.record.folderPath, [reference]) } : {}),
- }, withEngineSettings(task.session.getSnapshot().config));
+ }, withEngineSettings(task.session.getSnapshot().config), task.session.record.folderPath);
task.submitted = true;
if (task.cancelled) await this.cancelNative(task);
else if (task.yielded) await this.cancelForVideo(task);
diff --git a/src/lib/runtime.ts b/src/lib/runtime.ts
index a8af201..4c4bedc 100644
--- a/src/lib/runtime.ts
+++ b/src/lib/runtime.ts
@@ -95,6 +95,7 @@ export interface SlopfabGenerationRequest {
referenceVideoIds?: string[];
/** Resolved by the app queue before native submission. */
previousSceneId?: string;
+ continuationRelativePath?: string;
}
export interface ResolvedPlan {
@@ -221,10 +222,11 @@ export async function cancelAgentTurn(requestId: string): Promise<boolean> {
return isTauri() ? invoke<boolean>("cancel_agent_turn", { requestId }) : true;
}
-export async function resolveSlopfabPlan(request: SlopfabGenerationRequest, config: ProjectConfig): Promise<ResolvedPlan> {
+export async function resolveSlopfabPlan(request: SlopfabGenerationRequest, config: ProjectConfig, folderPath?: string): Promise<ResolvedPlan> {
request = { ...request, steps: generationStepsWithLoras(request.steps, config) };
- if (isTauri()) return invoke<ResolvedPlan>("resolve_slopfab_plan", { request, config });
- const alignedFrames = Math.ceil(Math.max(5, request.frames - 5) / 17) * 17 + 5;
+ if (isTauri()) return invoke<ResolvedPlan>("resolve_slopfab_plan", { request, config, folderPath });
+ const alignedFrames = request.continuationRelativePath ? Math.ceil(request.frames / 17) * 17
+ : Math.ceil(Math.max(5, request.frames - 5) / 17) * 17 + 5;
return {
canvasWidth: request.canvasWidth,
canvasHeight: request.canvasHeight,
@@ -238,9 +240,9 @@ export async function resolveSlopfabPlan(request: SlopfabGenerationRequest, conf
};
}
-export async function enqueueSlopfabGeneration(request: SlopfabGenerationRequest, config: ProjectConfig): Promise<void> {
+export async function enqueueSlopfabGeneration(request: SlopfabGenerationRequest, config: ProjectConfig, folderPath: string): Promise<void> {
request = { ...request, steps: generationStepsWithLoras(request.steps, config) };
- if (isTauri()) await invoke("enqueue_slopfab_generation", { request, config });
+ if (isTauri()) await invoke("enqueue_slopfab_generation", { request, config, folderPath });
}
export async function cancelSlopfabGeneration(jobId: string): Promise<boolean> {
diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.ts
index 8e5cebe..2422855 100644
--- a/src/lib/workQueue.test.ts
+++ b/src/lib/workQueue.test.ts
@@ -77,22 +77,39 @@ describe("application work queue", () => {
expect(enqueueSlopfabGeneration).not.toHaveBeenCalled();
});
- it("resolves a linked first frame after the previous scene finishes encoding and saving", async () => {
+ it("continues from the newly saved latents after the previous scene finishes", async () => {
const { queue, first } = setup();
first.update((config) => ({ ...config, generationJobs: [config.generationJobs[0], { ...config.generationJobs[0], id: "linked", usePreviousSceneLastFrame: true }] }));
const source = submission(first);
- const linked = { ...submission(first), job: first.getSnapshot().config.generationJobs[1], request: { ...source.request, previousSceneId: source.job.id, referencePaths: ["pending.png", "subject.png"] } };
+ const linked = { ...submission(first), job: first.getSnapshot().config.generationJobs[1], request: { ...source.request, previousSceneId: source.job.id, referencePaths: ["subject.png"] } };
queue.enqueue(first, [source, linked]);
await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1));
expect(saveSceneLastFrame).not.toHaveBeenCalled();
await finish(queue, queue.getSnapshot()[0].id);
await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(2));
- expect(saveSceneLastFrame).toHaveBeenCalledWith("C:/First", "media/generated/result.mp4");
- expect(vi.mocked(enqueueSlopfabGeneration).mock.calls[1][0].referencePaths).toEqual(["C:/First/cache/scene-last/work-new.png", "subject.png"]);
+ 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][2]).toBe("C:/First");
await finish(queue, queue.getSnapshot()[1].id);
const snapshot = JSON.parse(first.getSnapshot().config.generationJobs[1].generationSnapshot!);
expect(snapshot.previousSceneId).toBe(source.job.id);
- expect(snapshot.referencePaths[0]).toBe("C:/First/cache/scene-last/work-new.png");
+ expect(snapshot.continuationRelativePath).toBe(latentPath);
+ expect(parseProjectConfig(JSON.parse(JSON.stringify(first.getSnapshot().config))).generationJobs[1].latentRelativePath)
+ .toBe(`latents/${queue.getSnapshot()[1].id}.safetensors`);
+ });
+
+ it("asks for regeneration when an older completed scene has no latent archive", async () => {
+ const { queue, first } = setup();
+ first.update((config) => ({ ...config, generationJobs: [
+ { ...config.generationJobs[0], status: "completed", outputRelativePath: "media/generated/old.mp4" },
+ { ...config.generationJobs[0], id: "linked", usePreviousSceneLastFrame: true },
+ ] }));
+ const source = submission(first);
+ queue.enqueue(first, [{ ...source, job: first.getSnapshot().config.generationJobs[1], request: { ...source.request, previousSceneId: source.job.id } }]);
+ await waitFor(() => expect(queue.getSnapshot()[0].status).toBe("failed"));
+ expect(queue.getSnapshot()[0].error).toContain("save its latents");
+ expect(enqueueSlopfabGeneration).not.toHaveBeenCalled();
});
it("fails a dependent scene if the previous generation fails, even when an older video exists", async () => {
diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.ts
index aa9699b..bfde7e1 100644
--- a/src/lib/workQueue.ts
+++ b/src/lib/workQueue.ts
@@ -3,8 +3,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, GENERATION_FRAME_RATE, projectItemPath, sceneGenerationSnapshot, type GenerationJob, type ProjectRecord, type ProjectConfig } from "./project";
-import { saveSceneLastFrame } from "./sceneLastFrame";
+import { generationAssetId, generationLatentPath, GENERATION_FRAME_RATE, 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";
@@ -214,12 +213,10 @@ export class WorkQueue {
if (work.cancelled) continue;
if (work.request.previousSceneId) {
const previous = work.session.getSnapshot().config.generationJobs.find((job) => job.id === work.request.previousSceneId);
- if (!previous?.outputRelativePath || previous.status !== "completed") {
- throw new Error("Generate the previous scene successfully before using its last frame.");
+ 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.");
}
- const relativePath = await saveSceneLastFrame(next.folderPath, previous.outputRelativePath);
- if (work.cancelled) continue;
- work.request.referencePaths[0] = projectItemPath(next.folderPath, { relativePath })!;
+ work.request.continuationRelativePath = previous.latentRelativePath;
const captured = work.config.generationJobs.find((job) => job.id === work.sceneId)!;
work.snapshot = sceneGenerationSnapshot(captured, work.request);
this.updateScene(work, { generationSnapshot: work.snapshot });
@@ -231,11 +228,11 @@ export class WorkQueue {
() => work.cancelled, (detail) => this.patch(work.id, { detail }));
}
if (work.cancelled) continue;
- const plan = await resolveSlopfabPlan(work.request, work.config);
+ const plan = await resolveSlopfabPlan(work.request, work.config, next.folderPath);
if (work.cancelled) continue;
this.patch(work.id, { status: "generating", detail: `Generating ${plan.alignedFrames} frames at ${plan.canvasWidth} × ${plan.canvasHeight}` });
this.updateScene(work, { status: "generating", stage: "preparing" }, false);
- await enqueueSlopfabGeneration(work.request, work.config);
+ await enqueueSlopfabGeneration(work.request, work.config, next.folderPath);
work.submitted = true;
if (work.cancelled) await this.requestNativeCancellation(work);
await work.done;
@@ -334,7 +331,7 @@ export class WorkQueue {
const media = { kind: "generated" as const, relativePath: saved.relativePath, sourcePath: null, mimeType: "video/mp4", hasAudio: saved.hasAudio ?? null, width: saved.width ?? work.request.canvasWidth, height: saved.height ?? work.request.canvasHeight, durationMs: saved.durationMs ?? Math.round(work.request.frames / GENERATION_FRAME_RATE * 1000) };
work.session.update((current) => ({
...current,
- generationJobs: current.generationJobs.map((job) => job.id === work.sceneId ? { ...job, status: "completed", stage: "completed", progress: 1, generationSnapshot: work.snapshot, outputRelativePath: saved.relativePath, error: saved.note, updatedAt: new Date().toISOString() } : job),
+ generationJobs: current.generationJobs.map((job) => job.id === work.sceneId ? { ...job, status: "completed", stage: "completed", progress: 1, generationSnapshot: work.snapshot, outputRelativePath: saved.relativePath, latentRelativePath: generationLatentPath(work.id), error: saved.note, updatedAt: new Date().toISOString() } : job),
assets: current.assets.some((asset) => asset.id === assetId)
? current.assets.map((asset) => asset.id === assetId ? { ...asset, ...media } : asset)
: current.generationJobs.some((job) => job.id === work.sceneId)