AI media harness for planning, generating, and editing locally
TypeScript
Clean up removed generation files
Bitti4099a97f8c1a
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.mdindex 842c64f..fec491a 100644--- a/RELEASE_NOTES.md+++ b/RELEASE_NOTES.md@@ -21,6 +21,7 @@ Changes since 0.3.2.## Fixes and improvements+- Saving now deletes unused files from replaced video takes and removed video, image and music generations, including latents and derived caches. Files still used by timeline clips, references or other generations are preserved; saved deletions cannot be undone.- Fixed a Windows file-sharing error when Minimax reads a cropped image-edit reference.- Local image edits now generate only the selected bounding box or lasso bounds, padded to multiples of 32, and merge into the original image without changing surrounding pixels.- Generate's dropdown arrow now shares its neutral disabled colors while keeping available upscale actions accessible.diff --git a/src-tauri/src/commands/generation.rs b/src-tauri/src/commands/generation.rsindex 48220f7..165bcf6 100644--- a/src-tauri/src/commands/generation.rs+++ b/src-tauri/src/commands/generation.rs@@ -368,7 +368,8 @@ fn prepare_image_edit_path(request: &mut slopfab::GenerationRequest, folder_pathuse std::hash::{Hash, Hasher};let mut hash = std::collections::hash_map::DefaultHasher::new();(&request.job_id, &path, request.canvas_width, request.canvas_height).hash(&mut hash);- let directory = root.directory("cache/image-edits")?;+ let stem = generated_file_stem(&request.job_id)?;+ let directory = root.directory(&format!("cache/image-edits/{stem}"))?;let destination = directory.join(format!("{:016x}.png", hash.finish()));let resized = ::image::open(&path).map_err(|error| format!("Could not read source image: {error}"))?.resize_exact(request.canvas_width as u32, request.canvas_height as u32, ::image::imageops::FilterType::Lanczos3);diff --git a/src-tauri/src/commands/project.rs b/src-tauri/src/commands/project.rsindex ee78e95..da7e902 100644--- a/src-tauri/src/commands/project.rs+++ b/src-tauri/src/commands/project.rs@@ -80,9 +80,9 @@ pub(crate) fn create_project(}#[tauri::command]-pub(crate) fn save_project(folder_path: String, config: ProjectConfig) -> Result<(), String> {+pub(crate) fn save_project(folder_path: String, config: ProjectConfig, protected_paths: Option<Vec<String>>) -> Result<(), String> {let folder = PathBuf::from(folder_path).canonicalize().map_err(|error| format!("Could not resolve project folder: {error}"))?;- write_project(&folder, &config)+ crate::project::storage::write_project_protected(&folder, &config, &protected_paths.unwrap_or_default())}diff --git a/src-tauri/src/project/cleanup.rs b/src-tauri/src/project/cleanup.rsnew file mode 100644index 0000000..b34b5c8--- /dev/null+++ b/src-tauri/src/project/cleanup.rs@@ -0,0 +1,320 @@+//! Delete only previously tracked generated files, after the new document is+//! durable. Never sweep the output directory: it may contain an in-flight render.+use super::{paths::{normalize_project_path, ProjectRoot}, ProjectConfig};+use serde_json::Value;+use std::{collections::BTreeSet, fs, path::Path};++const JOURNAL: &str = ".generated-cleanup.json";++fn path_key(path: &str) -> Option<String> {+ let path = normalize_project_path(path).ok()?;+ #[cfg(windows)]+ let path = path.to_lowercase();+ Some(path)+}++fn managed(path: &str) -> bool {+ ["media/generated/", "latents/", "cache/scene-last/", "cache/image-edits/", "thumbnails/timeline/"]+ .iter().any(|prefix| path.starts_with(prefix) && path.len() > prefix.len())+}++fn collect(value: &Value, root: &ProjectRoot, paths: &mut BTreeSet<String>) {+ match value {+ Value::Array(items) => for item in items { collect(item, root, paths); },+ Value::Object(fields) => for (key, value) in fields {+ if let Some(path) = value.as_str() {+ let relative = if key == "sourcePath" {+ Path::new(path).canonicalize().ok().and_then(|path| path.strip_prefix(root.path()).ok()+ .map(|relative| relative.to_string_lossy().replace('\\', "/")))+ } else if key == "relativePath" || key.ends_with("RelativePath") || key == "thumbnail" {+ path_key(path)+ } else { None };+ if let Some(relative) = relative.and_then(|path| path_key(&path)).filter(|path| managed(path)) {+ if relative.starts_with("media/generated/") && relative.ends_with(".mp4") {+ if let Some(stem) = Path::new(&relative).file_stem().and_then(|s| s.to_str()) {+ paths.insert(format!("cache/scene-last/{stem}.png"));+ }+ }+ if relative.starts_with("media/generated/") && (relative.ends_with(".png") || relative.ends_with(".jpg")) {+ if let Some(stem) = Path::new(&relative).file_stem().and_then(|s| s.to_str()) {+ paths.insert(format!("cache/image-edits/{stem}"));+ }+ }+ paths.insert(relative);+ }+ } else { collect(value, root, paths); }+ },+ _ => {}+ }+}++fn files(config: &ProjectConfig, root: &ProjectRoot) -> Result<BTreeSet<String>, String> {+ let mut paths = BTreeSet::new();+ collect(&serde_json::to_value(config).map_err(|error| error.to_string())?, root, &mut paths);+ let mut thumbnail = |id: &str| {+ if let Ok(stem) = slopus_core::names::generated_file_stem(id) {+ paths.insert(path_key(&format!("thumbnails/timeline/{stem}")).unwrap());+ }+ };+ for job in &config.generation_jobs {+ if job.output_relative_path.is_some() { thumbnail(&job.id); }+ }+ for asset in &config.assets {+ if asset.kind == "generated" && asset.relative_path.is_some() {+ if let Some(id) = asset.id.strip_prefix("asset-") { thumbnail(id); }+ }+ }+ Ok(paths)+}++pub(super) struct Cleanup {+ root: ProjectRoot,+ pending: BTreeSet<String>,+}++impl Cleanup {+ pub(super) fn prepare(folder: &Path, previous: Option<&ProjectConfig>, next: &ProjectConfig) -> Result<Self, String> {+ let root = ProjectRoot::from_directory(folder)?;+ let journal = root.path().join(JOURNAL);+ let mut pending: BTreeSet<String> = if journal.exists() {+ serde_json::from_slice(&fs::read(root.existing(JOURNAL)?).map_err(|error| error.to_string())?)+ .map_err(|error| format!("Could not read generated-file cleanup journal: {error}"))?+ } else { BTreeSet::new() };+ if let Some(previous) = previous { pending.extend(files(previous, &root)?); }+ let retained = files(next, &root)?;+ pending = pending.into_iter().filter_map(|path| path_key(&path)).collect();+ pending.retain(|path| managed(path)+ && !retained.iter().any(|keep| keep == path || keep.starts_with(&format!("{path}/"))));+ let cleanup = Self { root, pending };+ // Persist the retry list before committing the project. If that commit+ // fails, a subsequent save subtracts the still-live references again.+ if !cleanup.pending.is_empty() || journal.exists() { cleanup.persist()?; }+ Ok(cleanup)+ }++ fn persist(&self) -> Result<(), String> {+ crate::storage::atomic::write_atomically(&self.root.path().join(JOURNAL),+ &serde_json::to_vec(&self.pending).map_err(|error| error.to_string())?)+ }++ pub(super) fn finish(mut self, protected_paths: &[String]) {+ self.pending.retain(|relative| {+ if protected_paths.iter().filter_map(|path| path_key(path))+ .any(|path| path == *relative || path.starts_with(&format!("{relative}/"))) { return true; }+ match remove(&self.root, relative) {+ Ok(()) => false,+ Err(error) => {+ crate::diagnostics::warn("project", "cleanup.failed", &error,+ serde_json::json!({"path": relative, "folder": self.root.path()}));+ true+ }+ }+ });+ // Cleanup failure must not report a failed document save: callers could+ // otherwise restore the old document after some files were deleted.+ // Locked files remain journaled and are retried on the next save.+ if self.root.path().join(JOURNAL).exists() || !self.pending.is_empty() {+ if let Err(error) = self.persist() {+ crate::diagnostics::warn("project", "cleanup.journal_failed", &error, serde_json::json!({"folder": self.root.path()}));+ }+ }+ }+}++fn remove(root: &ProjectRoot, relative: &str) -> Result<(), String> {+ let expected = root.path().join(relative);+ match fs::symlink_metadata(&expected) {+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(format!("Could not inspect {relative}: {error}")),+ Ok(_) => {}+ }+ let target = root.existing(relative)?;+ // Refuse redirected ancestors even when their destination is inside the+ // project: it might be another generation's live file.+ #[cfg(windows)]+ let redirected = !target.to_string_lossy().eq_ignore_ascii_case(&expected.to_string_lossy());+ #[cfg(not(windows))]+ let redirected = target != expected;+ if redirected { return Err(format!("Refusing to remove redirected generated path: {relative}")); }+ if target.is_dir() {+ if !relative.starts_with("thumbnails/timeline/") && !relative.starts_with("cache/image-edits/") {+ return Err(format!("Expected a generated file, found a directory: {relative}"));+ }+ for entry in fs::read_dir(&target).map_err(|error| error.to_string())? {+ let entry = entry.map_err(|error| error.to_string())?;+ remove(root, &format!("{relative}/{}", entry.file_name().to_string_lossy()))?;+ }+ fs::remove_dir(&target)+ } else { fs::remove_file(&target) }+ .map_err(|error| format!("Could not remove {relative}: {error}"))+}++#[cfg(test)]+mod tests {+ use super::*;+ use super::super::{storage::{write_project, write_project_protected, write_project_with_replacer}, SceneGenerationHistory, SceneGenerationVersion};++ fn touch(root: &Path, path: &str) {+ let file = root.join(path);+ fs::create_dir_all(file.parent().unwrap()).unwrap();+ fs::write(file, b"generated").unwrap();+ }++ fn asset(id: &str, path: &str, kind: &str) -> super::super::ProjectAsset {+ serde_json::from_value(serde_json::json!({"id": id, "kind": kind, "name": id, "relativePath": path,+ "mimeType": if kind == "audio" { "audio/wav" } else if kind == "image" { "image/png" } else { "video/mp4" },+ "createdAt": "2026-01-01T00:00:00.000Z"})).unwrap()+ }++ #[test]+ fn fifth_take_removes_evicted_video_latents_and_last_frame_only() {+ let root = tempfile::tempdir().unwrap();+ let mut config = crate::tests::created_fixture();+ let mut input = serde_json::to_value(&config.generation_jobs[0]).unwrap();+ for key in ["id", "status", "stage", "progress", "compiledPrompt", "generationSnapshot", "clipId", "outputRelativePath", "latentRelativePath", "error", "createdAt", "updatedAt"] {+ input.as_object_mut().unwrap().remove(key);+ }+ let version = |n| SceneGenerationVersion { id: format!("take-{n}"), created_at: config.created_at.clone(), scene: input.clone(),+ media: asset(&format!("take-{n}"), &format!("media/generated/take-{n}.mp4"), "generated"),+ latent_relative_path: Some(format!("latents/take-{n}.safetensors")), original_latent_relative_path: None,+ generation_snapshot: None, generator_name: None, upscale_factor: None };+ let fifth = version(5);+ config.generation_jobs[0].generation_history = Some(SceneGenerationHistory {+ versions: (1..=4).map(version).collect(), primary_id: Some("take-4".into()), selected_id: Some("take-4".into()), draft: None });+ write_project(root.path(), &config).unwrap();+ for n in 1..=5 {+ for path in [format!("media/generated/take-{n}.mp4"), format!("latents/take-{n}.safetensors"), format!("cache/scene-last/take-{n}.png")] { touch(root.path(), &path); }+ }+ touch(root.path(), "media/generated/in-flight.mp4");+ let history = config.generation_jobs[0].generation_history.as_mut().unwrap();+ history.versions.remove(0); history.versions.push(fifth);+ history.primary_id = Some("take-5".into()); history.selected_id = Some("take-5".into());+ write_project(root.path(), &config).unwrap();+ for path in ["media/generated/take-1.mp4", "latents/take-1.safetensors", "cache/scene-last/take-1.png"] { assert!(!root.path().join(path).exists(), "{path}"); }+ for path in ["media/generated/take-2.mp4", "latents/take-5.safetensors", "media/generated/in-flight.mp4"] { assert!(root.path().join(path).exists(), "{path}"); }+ }++ #[test]+ fn deleting_generations_clears_media_covers_and_thumbnails_but_keeps_shared_files() {+ let root = tempfile::tempdir().unwrap();+ let mut config = crate::tests::created_fixture();+ config.generation_jobs.clear();+ config.assets = vec![asset("asset-scene", "media/generated/video.mp4", "generated"), asset("picture", "media/generated/picture.png", "image"), asset("song", "media/generated/song.wav", "audio")];+ config.thumbnail = Some("media/generated/cover.jpg".into());+ // A retained media segment keeps shared latents.+ config.assets[0].scene_segments = Some(vec![super::super::SceneMediaSegment { scene_id: "scene".into(), latent_relative_path: "latents/shared.safetensors".into(), start_frame: 0, frame_count: 24 }]);+ write_project(root.path(), &config).unwrap();+ let removed = ["media/generated/picture.png", "media/generated/song.wav", "media/generated/cover.jpg", "cache/image-edits/picture/resized.png"];+ let retained = ["media/generated/video.mp4", "latents/shared.safetensors", "thumbnails/timeline/scene/00000000.jpg"];+ for path in removed.iter().chain(retained.iter()) { touch(root.path(), path); }+ config.assets.truncate(1); config.thumbnail = None;+ write_project(root.path(), &config).unwrap();+ for path in removed { assert!(!root.path().join(path).exists()); }+ for path in retained { assert!(root.path().join(path).exists()); }+ config.assets.clear();+ write_project(root.path(), &config).unwrap();+ for path in retained { assert!(!root.path().join(path).exists()); }+ assert!(!root.path().join("thumbnails/timeline/scene").exists());+ }++ #[test]+ fn failed_save_does_not_delete_and_protected_inputs_are_retried_after_reopen() {+ let root = tempfile::tempdir().unwrap();+ let mut config = crate::tests::created_fixture();+ let path = "media/generated/image.png";+ config.assets.push(asset("image", path, "image"));+ write_project(root.path(), &config).unwrap(); touch(root.path(), path);+ let mut removed = config.clone(); removed.assets.clear();+ assert!(write_project_with_replacer(root.path(), &removed, |_, _| Err(std::io::Error::other("save failed"))).is_err());+ assert!(root.path().join(path).exists());+ write_project(root.path(), &config).unwrap();+ assert!(root.path().join(path).exists());+ write_project_protected(root.path(), &removed, &[path.into()]).unwrap();+ assert!(root.path().join(path).exists());+ let reopened = super::super::storage::read_project(root.path()).unwrap();+ write_project(root.path(), &reopened.config).unwrap();+ assert!(!root.path().join(path).exists());+ }++ #[test]+ fn never_deletes_imports_external_files_or_traversal_from_a_journal() {+ let root = tempfile::tempdir().unwrap();+ let outside = tempfile::tempdir().unwrap();+ let config = crate::tests::created_fixture();+ write_project(root.path(), &config).unwrap();+ touch(root.path(), "media/imported/original.png"); touch(outside.path(), "original.wav");+ fs::write(root.path().join(JOURNAL), serde_json::to_vec(&vec!["media/imported/original.png".into(), "latents/../../outside".into(), outside.path().join("original.wav").to_string_lossy().into_owned()]).unwrap()).unwrap();+ write_project(root.path(), &config).unwrap();+ assert!(root.path().join("media/imported/original.png").exists());+ assert!(outside.path().join("original.wav").exists());+ }++ #[test]+ fn retained_image_recipe_and_absolute_reference_keep_shared_generated_files() {+ let root = tempfile::tempdir().unwrap();+ let path = "media/generated/source.png";+ let mut config = crate::tests::created_fixture();+ let mut output = asset("edited", "media/generated/edited.png", "image");+ let mut snapshot: Value = serde_json::from_str(include_str!("../../../fixtures/image-generation-snapshot.json")).unwrap();+ snapshot["scene"]["rootType"] = "image".into();+ snapshot["scene"]["sourceImage"] = serde_json::json!({"relativePath": path, "name": "Source", "width": 640, "height": 480});+ output.image_generation = Some(serde_json::from_value(snapshot).unwrap());+ config.assets = vec![asset("source", path, "image"), output];+ write_project(root.path(), &config).unwrap(); touch(root.path(), path);+ config.assets.remove(0);+ write_project(root.path(), &config).unwrap();+ assert!(root.path().join(path).exists());+ let external = serde_json::json!({"relativePath": null, "sourcePath": root.path().join(path).to_string_lossy()});+ let mut references = BTreeSet::new();+ collect(&external, &ProjectRoot::from_directory(root.path()).unwrap(), &mut references);+ assert!(references.contains(path));+ config.assets.clear();+ write_project(root.path(), &config).unwrap();+ assert!(!root.path().join(path).exists());+ }++ #[test]+ fn redirected_generation_directory_is_never_followed_for_deletion() {+ let root = tempfile::tempdir().unwrap();+ let outside = tempfile::tempdir().unwrap();+ let mut config = crate::tests::created_fixture();+ config.assets = vec![asset("image", "media/generated/image.png", "image")];+ write_project(root.path(), &config).unwrap();+ fs::create_dir(root.path().join("media")).unwrap();+ let link = root.path().join("media/generated");+ #[cfg(unix)]+ std::os::unix::fs::symlink(outside.path(), &link).unwrap();+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ assert!(std::process::Command::new("powershell.exe")+ .args(["-NoProfile", "-NonInteractive", "-Command", "$ErrorActionPreference = 'Stop'; New-Item -ItemType Junction -Path $env:SLOPUS_TEST_LINK -Target $env:SLOPUS_TEST_TARGET | Out-Null"])+ .env("SLOPUS_TEST_LINK", &link).env("SLOPUS_TEST_TARGET", outside.path())+ .creation_flags(0x0800_0000).status().unwrap().success());+ }+ touch(outside.path(), "image.png");+ config.assets.clear();+ write_project(root.path(), &config).unwrap();+ assert!(outside.path().join("image.png").exists());+ assert!(fs::read_to_string(root.path().join(JOURNAL)).unwrap().contains("media/generated/image.png"));+ }++ #[cfg(windows)]+ #[test]+ fn a_locked_output_is_retried_without_failing_the_saved_deletion() {+ use std::os::windows::fs::OpenOptionsExt;+ let root = tempfile::tempdir().unwrap();+ let mut config = crate::tests::created_fixture();+ let path = "media/generated/song.wav";+ config.assets = vec![asset("song", path, "audio")];+ write_project(root.path(), &config).unwrap(); touch(root.path(), path);+ let locked = fs::OpenOptions::new().read(true).share_mode(0).open(root.path().join(path)).unwrap();+ config.assets.clear();+ write_project(root.path(), &config).unwrap();+ assert!(root.path().join(path).exists());+ assert!(super::super::storage::read_project(root.path()).unwrap().config.assets.is_empty());+ drop(locked);+ write_project(root.path(), &config).unwrap();+ assert!(!root.path().join(path).exists());+ }+}diff --git a/src-tauri/src/project/mod.rs b/src-tauri/src/project/mod.rsindex 7c58753..eb35252 100644--- a/src-tauri/src/project/mod.rs+++ b/src-tauri/src/project/mod.rs@@ -7,6 +7,7 @@ pub(crate) mod paths;pub(crate) mod references;pub(crate) mod scenes;pub(crate) mod storage;+mod cleanup;pub(crate) mod timeline;pub(crate) mod validation;pub(crate) use model::*;diff --git a/src-tauri/src/project/storage.rs b/src-tauri/src/project/storage.rsindex c790dbe..5f8c1f8 100644--- a/src-tauri/src/project/storage.rs+++ b/src-tauri/src/project/storage.rs@@ -53,6 +53,10 @@ pub(crate) fn write_project(folder: &Path, config: &ProjectConfig) -> Result<(),write_project_with_replacer(folder, config, atomic_replace)}+pub(crate) fn write_project_protected(folder: &Path, config: &ProjectConfig, protected_paths: &[String]) -> Result<(), String> {+ write_project_impl(folder, config, protected_paths, atomic_replace)+}+pub(crate) fn write_project_with_replacer<F>(folder: &Path,config: &ProjectConfig,@@ -61,10 +65,21 @@ pub(crate) fn write_project_with_replacer<F>(whereF: FnOnce(&Path, &Path) -> io::Result<()>,{+ write_project_impl(folder, config, &[], replacer)+}++fn write_project_impl<F>(folder: &Path, config: &ProjectConfig, protected_paths: &[String], replacer: F) -> Result<(), String>+where F: FnOnce(&Path, &Path) -> io::Result<()> {+ // Keep the old-document comparison, commit and cleanup in one ordered+ // operation even when desktop commands save different sessions concurrently.+ static WRITES: std::sync::Mutex<()> = std::sync::Mutex::new(());+ let _write = WRITES.lock().map_err(|_| "Project save lock was poisoned.".to_string())?;let config = validate_and_normalize_config(config.clone())?;if !folder.is_dir() {return Err("Project folder does not exist.".into());}+ let previous = if project_file_in(folder).exists() { Some(read_project(folder)?.config) } else { None };+ let cleanup = super::cleanup::Cleanup::prepare(folder, previous.as_ref(), &config)?;let json = serde_json::to_string_pretty(&config).map_err(|error| format!("Could not serialize project: {error}"))?;let destination = folder.join(PROJECT_FILE_NAME);@@ -73,5 +88,7 @@ whereformat!("{json}\n").as_bytes(),replacer,)- .map_err(|error| format!("Could not write project config: {error}"))+ .map_err(|error| format!("Could not write project config: {error}"))?;+ cleanup.finish(protected_paths);+ Ok(())}diff --git a/src/components/workspace/ImageEditor.test.tsx b/src/components/workspace/ImageEditor.test.tsxindex 243c6e1..57e02c0 100644--- a/src/components/workspace/ImageEditor.test.tsx+++ b/src/components/workspace/ImageEditor.test.tsx@@ -673,12 +673,25 @@ it("removes generated images through their context menu and keeps the preview anfireEvent.click(screen.getByRole("menuitem", { name: "Remove" }));expect(current().assets).toHaveLength(0);expect(current().imageScene!.outputAssetId).toBeNull();+ expect(current().imageScene!.sourceImage).toBeFalsy();expect(current().thumbnail).toBeNull();expect(within(screen.getByLabelText("Generated images")).queryByRole("button")).not.toBeInTheDocument();expect(screen.getByText("Compose your image")).toBeInTheDocument();expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).imageScene).toEqual(current().imageScene);});+it("clears the source when removing the last image opened for editing", () => {+ const initial = parseProjectConfig(fixture);+ initial.assets = [{ id: "only", kind: "image", name: "Only", relativePath: "media/generated/only.png", mimeType: "image/png", width: 640, height: 480, createdAt: initial.createdAt }];+ const current = setup(restoreGeneratedImage(initial, "only"));+ expect(current().imageScene?.sourceImage?.relativePath).toBe("media/generated/only.png");+ fireEvent.contextMenu(screen.getByRole("button", { name: "View Only" }));+ fireEvent.click(screen.getByRole("menuitem", { name: "Remove" }));+ expect(current().assets).toHaveLength(0);+ expect(current().imageScene?.sourceImage).toBeNull();+ expect(saveImageDraft(current()).assets).toHaveLength(0);+});+it("creates a blank draft from the image bar and preserves it while browsing", () => {const initial = parseProjectConfig(fixture);initial.assets = [{ id: "saved", name: "Saved", kind: "image", relativePath: "media/generated/saved.jpg", mimeType: "image/jpeg", width: 101, height: 77, createdAt: initial.createdAt }];diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsxindex dc405a1..9bf086d 100644--- a/src/components/workspace/ImageEditor.tsx+++ b/src/components/workspace/ImageEditor.tsx@@ -323,7 +323,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene: remaining[Math.min(currentImages.findIndex((asset) => asset.id === id), remaining.length - 1)];const updated = { ...current,assets: removeImageAsset(current.assets, id),- imageScene: removingSelected && removed.imageDraft && !next ? currentScene.rootType === "image" ? createImageEditScene(null, currentScene) : { ...createImageScene(), steps: template?.defaultSteps ?? 20 } : { ...currentScene, outputAssetId: removingSelected ? next?.id ?? null : currentScene.outputAssetId },+ imageScene: removingSelected && !next ? currentScene.rootType === "image" ? createImageEditScene(null, currentScene) : { ...createImageScene(), steps: template?.defaultSteps ?? 20 } : { ...currentScene, outputAssetId: removingSelected ? next?.id ?? null : currentScene.outputAssetId },thumbnail: removingSelected || current.thumbnail === removed.relativePath ? next?.relativePath ?? null : current.thumbnail,timeline: { ...current.timeline, tracks: current.timeline.tracks.map((track) => ({ ...track, clips: track.clips.filter((clip) => clip.assetId !== id) })) },};diff --git a/src/components/workspace/VideoLibraryView.tsx b/src/components/workspace/VideoLibraryView.tsxindex e412a88..4e132fd 100644--- a/src/components/workspace/VideoLibraryView.tsx+++ b/src/components/workspace/VideoLibraryView.tsx@@ -81,7 +81,7 @@ export function VideoLibraryView(props: ComponentProps<typeof GeneratorView> & {{ label: "New folder", icon: <FolderAdd16 />, onSelect: () => { setFolderName(""); setCreatingFolder(true); } },];const remove = async (video: ProjectVideo) => {- if (!await askNative({ message: `Remove ${video.title} and its scenes? Existing timeline clips and media will be kept.`, title: "Remove video", kind: "warning" })) return;+ if (!await askNative({ message: `Remove ${video.title} and its scenes? Unused generated files will be deleted when saved. Media used by timeline clips or references will be kept.`, title: "Remove video", kind: "warning" })) return;update((current) => ({ ...current, videos: current.videos!.filter((item) => item.id !== video.id), generationJobs: current.generationJobs.filter((scene) => !video.sceneIds.includes(scene.id)) }));setPlayback(undefined);};diff --git a/src/lib/generationCleanup.test.ts b/src/lib/generationCleanup.test.tsnew file mode 100644index 0000000..795bfda--- /dev/null+++ b/src/lib/generationCleanup.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it, vi } from "vitest";+import { createProjectConfig, generationAssetId, type ProjectAsset } from "./project";+import { generatedFilePaths, removeUnusedGenerationAssets } from "./generationCleanup";+import { ProjectSession } from "./projectSession";+import { newSong } from "./music";++vi.mock("./diagnostics", async importOriginal => ({ ...await importOriginal<typeof import("./diagnostics")>(), writeDiagnostic: vi.fn() }));++const config = () => createProjectConfig({ name: "Cleanup", prompt: "A scene", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 10 });+const asset = (id: string, kind: ProjectAsset["kind"] = "generated"): ProjectAsset => ({ id, kind, name: id, mimeType: kind === "audio" ? "audio/wav" : "video/mp4",+ relativePath: `media/generated/${id}.${kind === "audio" ? "wav" : "mp4"}`, createdAt: new Date().toISOString() });++describe("generated file cleanup", () => {+ it("removes unneeded scene and song assets but preserves timeline and video source uses", () => {+ const previous = config(), id = generationAssetId(previous.generationJobs[0].id);+ previous.assets = [asset(id), asset("song", "audio")];+ previous.musicSongs = [{ ...newSong(), assetId: "song" }];+ const next = { ...previous, generationJobs: [], musicSongs: [] };+ expect(removeUnusedGenerationAssets(next, previous).assets).toEqual([]);+ const clip = { id: "clip", trackId: next.timeline.tracks[0].id, assetId: id, startMs: 0, durationMs: 1000, sourceStartMs: 0, label: "Scene", status: "generated" as const };+ next.timeline.tracks[0].clips = [clip];+ next.videos = [{ id: "video", title: "Video", sceneIds: [], prompt: "", createdAt: previous.createdAt, musicSource: { kind: "asset", id: "song" } }];+ expect(removeUnusedGenerationAssets(next, previous).assets).toEqual(previous.assets);+ });++ it("collects nested image sources, take latents, shared segments and album covers", () => {+ expect([...generatedFilePaths({ assets: [{ relativePath: "media/generated/a.png", imageGeneration: { scene: { sourceImage: { relativePath: "media/generated/source.png" } } } }],+ generationJobs: [{ generationHistory: { versions: [{ originalLatentRelativePath: "latents/base.safetensors", media: { sceneSegments: [{ latentRelativePath: "latents/shared.safetensors" }] } }] } }],+ musicSongs: [{ coverRelativePath: "media/generated/cover.jpg" }], sourcePath: "C:/external.wav", relativePath: "media/imported/source.png" })].sort())+ .toEqual(["latents/base.safetensors", "latents/shared.safetensors", "media/generated/a.png", "media/generated/cover.jpg", "media/generated/source.png"]);+ });++ it("makes deletion permanent at save, including while the write is pending", async () => {+ const initial = config(); initial.assets = [asset("song", "audio")];+ let finish!: () => void;+ const writer = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));+ const session = new ProjectSession({ folderPath: "C:/cleanup", config: initial }, writer);+ session.edit(current => ({ ...current, assets: [] }));+ expect(session.undo()).toBe(true);+ expect(session.redo()).toBe(true);+ const saving = session.save();+ expect(session.undo()).toBe(false);+ session.edit(current => ({ ...current, name: "New name" }));+ await vi.waitFor(() => expect(writer).toHaveBeenCalledOnce());+ finish(); await saving;+ expect(session.undo()).toBe(true);+ expect(session.getSnapshot().config.assets).toEqual([]);+ await session.discard();+ expect(session.getSnapshot().config.assets).toEqual([]);+ });++ it("retries deferred cleanup after queued work releases its input files", async () => {+ const initial = config(); initial.assets = [asset("song", "audio")];+ let protectedPaths = [initial.assets[0].relativePath!];+ const writer = vi.fn(async () => undefined);+ const session = new ProjectSession({ folderPath: "C:/cleanup", config: initial }, writer, () => protectedPaths);+ session.edit(current => ({ ...current, assets: [] }));+ await session.save();+ expect(writer).toHaveBeenLastCalledWith(expect.anything(), protectedPaths);+ await session.flushGeneratedCleanup();+ expect(writer).toHaveBeenCalledTimes(1);+ protectedPaths = [];+ await session.flushGeneratedCleanup();+ expect(writer).toHaveBeenCalledTimes(2);+ });++ it("keeps files recoverable after a failed save but cannot undo a later successful deletion", async () => {+ const initial = config(); initial.assets = [asset("song", "audio")];+ const writer = vi.fn().mockRejectedValueOnce(new Error("Disk full")).mockResolvedValue(undefined);+ const session = new ProjectSession({ folderPath: "C:/cleanup", config: initial }, writer);+ session.edit(current => ({ ...current, assets: [] }));+ await expect(session.save()).rejects.toThrow("Disk full");+ await session.discard();+ expect(session.getSnapshot().config.assets).toEqual(initial.assets);+ session.edit(current => ({ ...current, assets: [] }));+ await session.save();+ expect(session.undo()).toBe(false);+ });+});diff --git a/src/lib/generationCleanup.ts b/src/lib/generationCleanup.tsnew file mode 100644index 0000000..300ac8a--- /dev/null+++ b/src/lib/generationCleanup.ts@@ -0,0 +1,49 @@+import { generationAssetId, type ProjectConfig } from "./project";++/** Drop a removed scene/song's library asset unless something still uses it. */+export function removeUnusedGenerationAssets(config: ProjectConfig, previous: ProjectConfig): ProjectConfig {+ const removed = new Set<string>();+ for (const job of previous.generationJobs) {+ if (config.generationJobs.some(item => item.id === job.id)) continue;+ removed.add(generationAssetId(job.id));+ for (const asset of previous.assets) {+ if (job.outputRelativePath && asset.kind === "generated" && asset.relativePath === job.outputRelativePath) removed.add(asset.id);+ }+ }+ for (const song of previous.musicSongs ?? []) {+ if (song.assetId && !config.musicSongs?.some(item => item.id === song.id && item.assetId === song.assetId)) removed.add(song.assetId);+ }+ for (const track of config.timeline.tracks) for (const clip of track.clips) removed.delete(clip.assetId);+ for (const song of config.musicSongs ?? []) if (song.assetId) removed.delete(song.assetId);+ for (const job of config.generationJobs) removed.delete(generationAssetId(job.id));+ for (const video of config.videos ?? []) {+ for (const source of [video.musicSource, video.videoSource]) if (source?.kind === "asset") removed.delete(source.id);+ }+ const assets = config.assets.filter(asset => !removed.has(asset.id));+ if (assets.length === config.assets.length) return config;+ const removedPaths = new Set(config.assets.filter(asset => removed.has(asset.id)).map(asset => asset.relativePath));+ return { ...config, assets, thumbnail: config.thumbnail && removedPaths.has(config.thumbnail) ? null : config.thumbnail };+}++/** Mirrors the managed path fields collected by project/cleanup.rs. */+export function generatedFilePaths(value: unknown, paths = new Set<string>(), folderPath?: string): Set<string> {+ if (Array.isArray(value)) for (const item of value) generatedFilePaths(item, paths, folderPath);+ else if (value && typeof value === "object") for (const [key, item] of Object.entries(value)) {+ if (typeof item === "string" && (key.endsWith("RelativePath") || key === "relativePath" || key === "thumbnail" || key === "sourcePath")) {+ let path = item.replaceAll("\\", "/").replace(/^(\.\/)+/, "");+ if (key === "sourcePath") {+ if (!folderPath) continue;+ const root = folderPath.replaceAll("\\", "/").replace(/\/$/, "") + "/";+ if (!path.toLowerCase().startsWith(root.toLowerCase())) continue;+ path = path.slice(root.length);+ }+ if (/^(media\/generated|latents|cache\/(scene-last|image-edits)|thumbnails\/timeline)\//i.test(path)) paths.add(path);+ } else if (typeof item === "object") generatedFilePaths(item, paths, folderPath);+ }+ return paths;+}++export function removesGeneratedFiles(previous: ProjectConfig, next: ProjectConfig, folderPath?: string): boolean {+ const retained = generatedFilePaths(next, new Set(), folderPath);+ return [...generatedFilePaths(previous, new Set(), folderPath)].some(path => !retained.has(path));+}diff --git a/src/lib/persistence.ts b/src/lib/persistence.tsindex 1e417cd..bef5616 100644--- a/src/lib/persistence.ts+++ b/src/lib/persistence.ts@@ -260,13 +260,13 @@ export async function createProject(input: CreateProjectInput): Promise<ProjectRreturn record;}-export async function saveProject(record: ProjectRecord): Promise<ProjectRecord> {+export async function saveProject(record: ProjectRecord, protectedPaths: string[] = []): Promise<ProjectRecord> {const next: ProjectRecord = {...record,config: parseProjectConfig({ ...record.config, updatedAt: new Date().toISOString() }),};if (isTauri()) {- await invoke("save_project", { folderPath: next.folderPath, config: next.config });+ await invoke("save_project", { folderPath: next.folderPath, config: next.config, ...(protectedPaths.length ? { protectedPaths } : {}) });} else {const projects = getWebProjects().projects.filter((project) => project.config.id !== next.config.id);localStorage.setItem(WEB_PROJECTS_KEY, JSON.stringify([next, ...projects]));diff --git a/src/lib/projectSession.ts b/src/lib/projectSession.tsindex c004592..a36bf70 100644--- a/src/lib/projectSession.ts+++ b/src/lib/projectSession.ts@@ -4,9 +4,10 @@ import type { ProjectConfig, ProjectRecord } from "./project";import { saveImageDraft } from "./imageHistory";import { addReferenceImageAssets } from "./referenceImageAssets";import { createUndoStack, type UndoStack } from "./undo";+import { removeUnusedGenerationAssets, removesGeneratedFiles } from "./generationCleanup";export type ProjectUpdate = ProjectConfig | ((current: ProjectConfig) => ProjectConfig);-export type ProjectWriter = (record: ProjectRecord) => Promise<ProjectRecord | void>;+export type ProjectWriter = (record: ProjectRecord, protectedPaths?: string[]) => Promise<ProjectRecord | void>;export interface ProjectSessionState {config: ProjectConfig;@@ -65,11 +66,14 @@ export class ProjectSession {private revision = 0;private pending = 0;private savedConfig: ProjectConfig;+ private queuedConfig: ProjectConfig;+ private cleanupDeferred = false;private history: UndoStack<HistoryEntry> = createUndoStack<HistoryEntry>({ limit: 100, mergeWindowMs: 500 });private background: BackgroundChange[] = [];private backgroundSeq = 0;- constructor(readonly record: ProjectRecord, private writer: ProjectWriter) {+ constructor(readonly record: ProjectRecord, private writer: ProjectWriter, private cleanupProtection: () => string[] = () => []) {this.savedConfig = record.config;+ this.queuedConfig = record.config;const config = saveImageDraft(record.config);const stamped = Date.parse(record.config.updatedAt);this.state = { config, dirty: config !== record.config, saving: false, saveError: null, canUndo: false, canRedo: false, savedAt: Number.isFinite(stamped) ? stamped : null };@@ -92,7 +96,7 @@ export class ProjectSession {/** A change the app makes on its own. Never an undo step (see above). */update = (next: ProjectUpdate, dirty = true) => {- const config = saveSceneDrafts(saveImageDraft(typeof next === "function" ? next(this.state.config) : next), this.state.config);+ const config = saveSceneDrafts(saveImageDraft(removeUnusedGenerationAssets(typeof next === "function" ? next(this.state.config) : next, this.state.config)), this.state.config);if (config === this.state.config) return;if (typeof next === "function") {this.backgroundSeq += 1;@@ -104,7 +108,7 @@ export class ProjectSession {/** A change the person made: recorded for undo. Same `key` within 500ms = one step. */edit = (next: ProjectUpdate, key = "edit") => {- const config = saveSceneDrafts(saveImageDraft(addReferenceImageAssets(typeof next === "function" ? next(this.state.config) : next, this.state.config.references)), this.state.config);+ const config = saveSceneDrafts(saveImageDraft(addReferenceImageAssets(removeUnusedGenerationAssets(typeof next === "function" ? next(this.state.config) : next, this.state.config), this.state.config.references)), this.state.config);if (config === this.state.config) return;this.history.record({ config: this.state.config, mark: this.backgroundSeq }, key);this.apply(config, true);@@ -118,7 +122,7 @@ export class ProjectSession {let config = entry.config;for (const change of this.background) {if (change.seq <= entry.mark) continue;- try { config = change.apply(config); } catch { /* A patch whose target is gone is simply skipped. */ }+ try { config = removeUnusedGenerationAssets(change.apply(config), config); } catch { /* A patch whose target is gone is simply skipped. */ }}return saveSceneDrafts(saveImageDraft(config));}@@ -138,19 +142,38 @@ export class ProjectSession {};dismissError = () => this.publish({ saveError: null });+ /** Retry removals held back while queued generations still needed their inputs. */+ flushGeneratedCleanup = async () => {+ if (!this.cleanupDeferred || this.cleanupProtection().length) return;+ this.cleanupDeferred = false;+ try { await this.save(); } catch (error) { this.cleanupDeferred = true; throw error; }+ };discard = async (): Promise<void> => {await this.writes;this.revision += 1;this.history.clear();this.background = [];+ this.queuedConfig = this.savedConfig;this.publish({ config: this.savedConfig, dirty: false, saveError: null });};save = (): Promise<void> => {const revision = this.revision;const record = { ...this.record, config: this.state.config };+ // Saving commits physical deletions. Older snapshots must not bring back+ // entries pointing to those files, including while this write is pending.+ if (removesGeneratedFiles(this.queuedConfig, record.config, this.record.folderPath)+ || removesGeneratedFiles(this.savedConfig, record.config, this.record.folderPath)) {+ this.history.clear();+ this.background = [];+ if (this.cleanupProtection().length) this.cleanupDeferred = true;+ }+ this.queuedConfig = record.config;this.pending += 1;this.publish({ saving: true, saveError: null });- const write = this.writes.catch(() => undefined).then(() => this.writer(record));+ const write = this.writes.catch(() => undefined).then(() => {+ const protectedPaths = this.cleanupProtection();+ return protectedPaths.length ? this.writer(record, protectedPaths) : this.writer(record);+ });this.writes = write.then(() => undefined, () => undefined);return write.then(() => {this.savedConfig = record.config;diff --git a/src/lib/sceneHistory.ts b/src/lib/sceneHistory.tsindex 533138d..a5cb06e 100644--- a/src/lib/sceneHistory.ts+++ b/src/lib/sceneHistory.ts@@ -114,7 +114,7 @@ export function makeSceneGenerationPrimary(config: ProjectConfig, sceneId: strin};}-/** Remove history metadata, keeping media files available to Undo and references. */+/** Remove a take. Saving deletes its files once no remaining entry uses them. */export function removeSceneGeneration(config: ProjectConfig, sceneId: string, versionId: string): ProjectConfig {const current = config.generationJobs.find(job => job.id === sceneId);if (!current) return config;diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.tsindex bcc3411..83fa58a 100644--- a/src/lib/workQueue.ts+++ b/src/lib/workQueue.ts@@ -1,5 +1,6 @@import { effectiveLoras, loraSnapshot } from "./loras";import { completeSceneGeneration, sceneInput } from "./sceneHistory";+import { generatedFilePaths } from "./generationCleanup";import { albumCoverPrompt, musicSongSchema, musicSettingsForModel, newSongVariation, updateSong, type MusicSong } from "./music";import { albumCoverGenerator } from "./referenceIconSettings";import { templateSupportsMusic } from "./settings";@@ -169,7 +170,13 @@ export class WorkQueue {const config = isTauri() ? { ...record.config, musicSongs: (record.config.musicSongs ?? []).map((song) =>["queued", "generating"].includes(song.status) ? { ...song, status: "failed" as const, error: "Generation was interrupted when Slopus closed. Generate again to restart." } : song), generationJobs: record.config.generationJobs.map((job) =>["queued", "generating", "ready"].includes(job.status) ? { ...job, status: "failed" as const, stage: "failed" as const, error: "Generation was interrupted when Slopus closed. Generate again to restart." } : job) } : record.config;- session = new ProjectSession({ ...record, config }, this.writer);+ session = new ProjectSession({ ...record, config }, this.writer, () => {+ const paths = new Set<string>();+ for (const work of this.work.values()) {+ if (projectQueueKey(work.session.record) === key && this.items.some(item => item.id === work.id && isWorkActive(item))) generatedFilePaths(work.config, paths, record.folderPath);+ }+ return [...paths];+ });this.projects.set(key, session);}this.icons.watch(session);@@ -669,6 +676,7 @@ export class WorkQueue {// Queue history only needs WorkItem; finished runs must not keep a// deep copy of the entire project and its image history alive.this.work.delete(work.id);+ await work.session.flushGeneratedCleanup().catch(() => undefined);}}} finally { this.pumping = false; }