The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
fix: preserve project saves across concurrent writes and failed closes
Rafael Fernandese75af9b85b5a
diff --git a/src/crates/concat-host/src/projects.rs b/src/crates/concat-host/src/projects.rsindex 46817590..98dc51db 100644--- a/src/crates/concat-host/src/projects.rs+++ b/src/crates/concat-host/src/projects.rs@@ -11,7 +11,10 @@//! It describes this machine's history, and copying a project folder to//! another machine should not drag one person's recent files along with it.+use std::collections::HashMap;use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex, OnceLock};use std::time::{SystemTime, UNIX_EPOCH};use serde::{Deserialize, Serialize};@@ -158,40 +161,227 @@ pub fn create(})}-/// Writes the whole project document to the project's manifest.+/// A snapshot's place in this process's write order.+///+/// Minted by [`ticket`] where a document is captured - on the thread that+/// captures it, before the write is handed to a worker - and carried to+/// [`save_ordered`], where the write happens. Two snapshots of one project+/// are written in ticket order, so a worker that finishes late cannot put an+/// older document back on disk after a newer one.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub struct Ticket(u64);++/// Mints the next ticket; see [`Ticket`].+///+/// The counter is process-wide, so tickets are monotonic for every project,+/// and therefore for each project on its own. It is not shared with another+/// process; see [`save_ordered`] for what that leaves unordered.+pub fn ticket() -> Ticket {+ Ticket(NEXT_TICKET.fetch_add(1, Ordering::Relaxed))+}++static NEXT_TICKET: AtomicU64 = AtomicU64::new(1);++/// What an ordered save did.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Saved {+ /// The document is on disk.+ Written,+ /// A snapshot minted after this one was already written, so this older+ /// document was left alone rather than put back on disk. Nothing went+ /// wrong: the project is saved, to the newer document.+ Superseded,+}++/// One project's writes: the lock that runs them one at a time, and the+/// highest ticket already on disk.+struct Writes {+ /// Held for a whole write - the temporary file, its flush and the+ /// rename - so two workers never write one manifest at once.+ writing: Mutex<()>,+ /// The highest ticket whose document reached the manifest. Read and+ /// written under `writing`, so the check that skips an older snapshot+ /// and the write that follows it cannot be split by another writer.+ written: AtomicU64,+}++/// The per-project write state, keyed by the folder as the filesystem+/// spells it; see [`project_key`].+fn writes() -> &'static Mutex<HashMap<PathBuf, Arc<Writes>>> {+ static WRITES: OnceLock<Mutex<HashMap<PathBuf, Arc<Writes>>>> = OnceLock::new();+ WRITES.get_or_init(|| Mutex::new(HashMap::new()))+}++/// One key per project folder: the real path where the filesystem will say+/// it, so `/var` and `/private/var`, a trailing slash, a symlinked parent+/// and a different case on a case-insensitive volume all name one project.+/// The path as it was given when it cannot be resolved, which still names+/// the folder it was given.+fn project_key(root: &Path) -> PathBuf {+ std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf())+}++/// The write state for one project folder.+fn write_state(key: &Path) -> Arc<Writes> {+ let mut all = writes()+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ Arc::clone(all.entry(key.to_path_buf()).or_insert_with(|| {+ Arc::new(Writes {+ writing: Mutex::new(()),+ written: AtomicU64::new(0),+ })+ }))+}++/// Writes the whole project document to the project's manifest, now.////// The document is passed through as opaque JSON rather than being mirrored/// into Rust types: the engine (`concat-project`) owns the canonical model and/// produced this document, and the host has no decisions to make about its/// contents beyond writing it safely.///-/// Written to a temporary file and renamed into place, because a save-/// interrupted halfway is worse than no save at all - a truncated manifest-/// loses the project, while a failed rename leaves the previous one intact.+/// The write is ordered like [`save_ordered`], with its ticket minted here: a+/// caller that captured the document and writes it at once - the API, a+/// template - is in call order already. A caller that captures a document on+/// one thread and writes it on another (the window's autosave) mints the+/// ticket where it captures the document and calls [`save_ordered`] instead.pub fn save(path: &str, document: &serde_json::Value) -> Result<(), String> {- let root = PathBuf::from(path);- let manifest = manifest_path(&root);- let temporary = root.join(format!("{MANIFEST}.saving"));+ save_ordered(path, document, ticket()).map(|_| ())+}+/// Writes a document captured at `ticket`, in this process's write order.+///+/// A snapshot older than the one already on disk is skipped whole - see+/// [`Saved`] - so a worker that finishes late cannot put an older document+/// back over a newer one, whatever order the two are scheduled in. A write+/// that fails is always a failure: a document that should have been written+/// and could not returns the error, never [`Saved::Superseded`].+///+/// The temporary file is this call's own (`create_new`), so two saves -+/// including ones in different processes on the same folder - never write one+/// another's bytes, and the rename over the manifest is atomic on every+/// platform. What a folder shared between processes does not get is the+/// order: each process counts tickets on its own, so a stale snapshot in one+/// process can still land after a newer document written by another.+/// Ordering across processes would need a lock both honour, and a project+/// folder has none today.+pub fn save_ordered(+ path: &str,+ document: &serde_json::Value,+ ticket: Ticket,+) -> Result<Saved, String> {+ let root = PathBuf::from(path);std::fs::create_dir_all(&root).map_err(|error| format!("could not create {}: {error}", root.display()))?;+ let state = write_state(&project_key(&root));+ // Held across the write: the check below and the write it decides are+ // one step, so two saves cannot both decide to write and have the older+ // one land second.+ let _writing = state+ .writing+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ if ticket.0 < state.written.load(Ordering::Acquire) {+ return Ok(Saved::Superseded);+ }+let encoded = serde_json::to_vec_pretty(document).map_err(|error| format!("could not encode the project: {error}"))?;+ write_manifest(&root, &encoded)?;+ state.written.store(ticket.0, Ordering::Release);+ Ok(Saved::Written)+}++/// The temporary file a save writes: flushed and renamed into place on the+/// way through, removed on every other way out, so a failure leaves no+/// `.saving` file behind. The name is this call's own - process id and a+/// counter - so no two saves share it.+struct Temporary {+ path: PathBuf,+ file: Option<std::fs::File>,+ renamed: bool,+}++impl Temporary {+ /// Creates a fresh temporary beside the manifest. `create_new` never+ /// reuses or follows a name already there, so it cannot write through a+ /// symlink someone planted and fails rather than sharing a temporary+ /// with another save; a leftover from a crashed run makes it try another+ /// name.+ fn open(root: &Path) -> Result<Temporary, String> {+ let mut attempts = 0;+ loop {+ let nonce = NEXT_TEMPORARY.fetch_add(1, Ordering::Relaxed);+ let path = root.join(format!("{MANIFEST}.saving.{}.{nonce}", std::process::id()));+ match std::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(&path)+ {+ Ok(file) => {+ return Ok(Temporary {+ path,+ file: Some(file),+ renamed: false,+ });+ }+ Err(error)+ if error.kind() == std::io::ErrorKind::AlreadyExists && attempts < 16 =>+ {+ attempts += 1;+ }+ Err(error) => return Err(format!("could not write {}: {error}", path.display())),+ }+ }+ }- // Written, then flushed to the disk, then renamed: a rename is only- // atomic over bytes that have reached the platter. Without the sync a- // power cut after the rename can leave a zero-length manifest.- let mut file = std::fs::File::create(&temporary)- .map_err(|error| format!("could not write {}: {error}", temporary.display()))?;- std::io::Write::write_all(&mut file, &encoded)- .map_err(|error| format!("could not write {}: {error}", temporary.display()))?;- file.sync_all()- .map_err(|error| format!("could not flush {}: {error}", temporary.display()))?;- drop(file);+ /// Writes `encoded` and flushes its contents before the atomic rename.+ /// Atomic replacement and durability are distinct: flushing the file+ /// reduces power-loss risk, but does not also sync the parent directory.+ fn write(&mut self, encoded: &[u8]) -> Result<(), String> {+ let file = self.file.as_mut().expect("a fresh temporary");+ std::io::Write::write_all(file, encoded)+ .map_err(|error| format!("could not write {}: {error}", self.path.display()))?;+ file.sync_all()+ .map_err(|error| format!("could not flush {}: {error}", self.path.display()))+ }- std::fs::rename(&temporary, &manifest)- .map_err(|error| format!("could not replace {}: {error}", manifest.display()))+ /// Closes the file and renames it over the manifest. Every path out but+ /// this one removes the temporary when the value drops.+ fn commit(&mut self, manifest: &Path) -> Result<(), String> {+ // Closed first, so the name is free for Windows to replace.+ self.file.take();+ std::fs::rename(&self.path, manifest)+ .map_err(|error| format!("could not replace {}: {error}", manifest.display()))?;+ self.renamed = true;+ Ok(())+ }+}++impl Drop for Temporary {+ fn drop(&mut self) {+ // The handle goes first: Windows will not take a file back while it+ // is open.+ self.file.take();+ if !self.renamed {+ let _ = std::fs::remove_file(&self.path);+ }+ }+}++static NEXT_TEMPORARY: AtomicU64 = AtomicU64::new(0);++/// Writes `encoded` to the project's manifest: a temporary of its own,+/// flushed to the disk, then renamed over the manifest, because a save+/// interrupted halfway is worse than no save at all - a truncated manifest+/// loses the project, while a failed rename leaves the previous one intact.+fn write_manifest(root: &Path, encoded: &[u8]) -> Result<(), String> {+ let manifest = manifest_path(root);+ let mut temporary = Temporary::open(root)?;+ temporary.write(encoded)?;+ temporary.commit(&manifest)}/// True when a document carries no edit state at all - the settings-only@@ -449,4 +639,160 @@ mod tests {));assert!(same_path("C:/Work/Film/", "c:\\work\\film"));}++ /// A project folder of this test's own, swept if it is already there.+ fn scratch(name: &str) -> String {+ let root =+ std::env::temp_dir().join(format!("concat-projects-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(&root).expect("scratch dir");+ root.to_string_lossy().into_owned()+ }++ /// A whole document, as a save writes one.+ fn document(marker: &str) -> serde_json::Value {+ serde_json::json!({ "marker": marker, "tracks": [] })+ }++ /// How many temporary files a folder holds: none, after any save.+ fn temporaries(root: &str) -> usize {+ std::fs::read_dir(root)+ .expect("reads the scratch")+ .filter_map(Result::ok)+ .filter(|entry| {+ entry+ .file_name()+ .to_string_lossy()+ .starts_with(&format!("{MANIFEST}.saving"))+ })+ .count()+ }++ #[test]+ fn a_late_snapshot_never_lands_after_a_newer_one() {+ let root = scratch("late-snapshot");+ let older = document("older");+ let newer = document("newer");+ // Minted where each document is captured: the older one first.+ let older_ticket = ticket();+ let newer_ticket = ticket();+ // The newer worker finishes first, the older one arrives after it -+ // the order two workers on the pool can take.+ assert_eq!(+ save_ordered(&root, &newer, newer_ticket).expect("writes"),+ Saved::Written+ );+ assert_eq!(+ save_ordered(&root, &older, older_ticket).expect("skips, it does not fail"),+ Saved::Superseded+ );+ assert_eq!(+ read_document(&root).expect("reads"),+ Some(newer),+ "the newer document stands"+ );+ assert_eq!(temporaries(&root), 0, "no temporary is left behind");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn concurrent_saves_keep_the_document_readable() {+ let root = scratch("concurrent");+ const SAVES: usize = 8;+ let documents: Vec<serde_json::Value> = (0..SAVES)+ .map(|index| document(&format!("doc-{index}")))+ .collect();+ let tickets: Vec<Ticket> = (0..SAVES).map(|_| ticket()).collect();+ std::thread::scope(|scope| {+ for (document, ticket) in documents.iter().zip(&tickets) {+ let root = root.clone();+ scope.spawn(move || {+ save_ordered(&root, document, *ticket).expect("a save that cannot fail here");+ });+ }+ });+ assert_eq!(+ read_document(&root).expect("reads"),+ Some(documents[SAVES - 1].clone()),+ "the last ticket's document stands, whatever order the workers took"+ );+ assert_eq!(temporaries(&root), 0, "no temporary is left behind");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn an_older_ticket_is_skipped_and_a_real_failure_is_not() {+ let root = scratch("skip-or-fail");+ let first = ticket();+ let second = ticket();+ save_ordered(&root, &document("one"), first).expect("writes");+ save_ordered(&root, &document("two"), second).expect("writes");+ // An older ticket is a skip, told apart from a failure.+ assert_eq!(+ save_ordered(&root, &document("stale"), Ticket(first.0)).expect("not an error"),+ Saved::Superseded+ );+ assert_eq!(read_document(&root).expect("reads"), Some(document("two")));++ // A write that truly cannot happen is an error, never a skip.+ let blocked = scratch("skip-or-fail-blocked");+ let manifest = Path::new(&blocked).join(MANIFEST);+ std::fs::create_dir(&manifest).expect("the manifest spot");+ std::fs::write(manifest.join("kept"), b"kept").expect("something worth keeping");+ let error = save_ordered(&blocked, &document("three"), ticket())+ .expect_err("cannot replace a directory");+ assert!(!error.is_empty());+ assert!(+ manifest.join("kept").exists(),+ "what was there is untouched"+ );+ assert_eq!(+ temporaries(&blocked),+ 0,+ "the temporary is cleaned up on failure"+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&blocked);+ }++ #[cfg(unix)]+ #[test]+ fn a_failed_save_keeps_the_document_it_had() {+ use std::os::unix::fs::PermissionsExt;++ let root = scratch("keeps-document");+ let saved = document("saved");+ save(&root, &saved).expect("first save");+ let manifest = Path::new(&root).join(MANIFEST);+ let before = std::fs::read(&manifest).expect("reads");++ // A folder that refuses new files: the temporary cannot be created.+ std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o555))+ .expect("read-only folder");+ let probe = Path::new(&root).join("probe");+ if std::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(&probe)+ .is_ok()+ {+ // A privileged account ignores the permission; nothing to test.+ let _ = std::fs::remove_file(&probe);+ let _ = std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o755));+ let _ = std::fs::remove_dir_all(&root);+ return;+ }++ let error = save(&root, &document("next")).expect_err("the folder refuses a temporary");+ assert!(!error.is_empty());+ assert_eq!(+ std::fs::read(&manifest).expect("reads"),+ before,+ "the document that was saved stands"+ );+ assert_eq!(temporaries(&root), 0, "no temporary is left behind");++ let _ = std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o755));+ let _ = std::fs::remove_dir_all(&root);+ }}diff --git a/src/crates/concat/src/lib.rs b/src/crates/concat/src/lib.rsindex dbf21d55..f5b6e08b 100644--- a/src/crates/concat/src/lib.rs+++ b/src/crates/concat/src/lib.rs@@ -158,6 +158,27 @@ pub fn smoke() -> Result<(), slint::PlatformError> {start(None, true)}+/// Runs one way out of the open project, in the order that keeps the work+/// safe: `close` writes the project and lets its session go, and `leave` -+/// hiding the window, quitting the loop, starting a replacement build - runs+/// only when that write landed.+///+/// Every path out goes through this: the title bar's X, the system's close+/// request, File › Close Window and a version switch. Before it existed, a+/// save that failed still hid the window and quit, taking whatever the+/// project held with it; a failure here leaves the session, its running jobs+/// and the window exactly as they were, and returns the reason.+pub(crate) fn close_window(+ close: impl FnOnce() -> Result<(), String>,+ leave: impl FnOnce(),+) -> Result<(), String> {+ let result = close();+ if result.is_ok() {+ leave();+ }+ result+}+/// [`run_with_project`], or [`smoke`] when `smoke` is set.fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::PlatformError> {// The interface scale is read by Slint's window backend when the window@@ -465,21 +486,49 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::app.on_titlebar_close(|| {log::info!("close: titlebar X pressed");Shell::with(|shell, app| {- shell.studio.borrow_mut().close_project();- log::info!("close: project closed, hiding window");- app.window().hide().ok();- slint::quit_event_loop().ok();- log::info!("close: quit_event_loop called");+ let outcome = close_window(+ || shell.studio.borrow_mut().close_project(),+ || {+ log::info!("close: project closed, hiding window");+ app.window().hide().ok();+ slint::quit_event_loop().ok();+ log::info!("close: quit_event_loop called");+ },+ );+ if let Err(error) = outcome {+ // The save failed and `close_project` left the session+ // open, so the window stays up. Its notice is published+ // here or nobody would see it.+ log::warn!("close: not closing, project could not be saved: {error}");+ shell.studio.borrow_mut().refresh_art();+ shell.studio.borrow().publish(&app, &shell.models);+ }});});- // System-driven close (Alt+F4, taskbar close): the same road out.+ // System-driven close (Alt+F4, taskbar close): the same road out, and+ // refused the same way when the project cannot be saved.app.window().on_close_requested(|| {log::info!("close: system close request (Alt+F4 / taskbar)");- Shell::with(|shell, _app| {- shell.studio.borrow_mut().close_project();+ let saved = std::cell::Cell::new(true);+ Shell::with(|shell, app| {+ let outcome = close_window(+ || shell.studio.borrow_mut().close_project(),+ || {+ slint::quit_event_loop().ok();+ },+ );+ if let Err(error) = outcome {+ saved.set(false);+ log::warn!("close: not closing, project could not be saved: {error}");+ shell.studio.borrow_mut().refresh_art();+ shell.studio.borrow().publish(&app, &shell.models);+ }});- slint::quit_event_loop().ok();- slint::CloseRequestResponse::HideWindow+ if saved.get() {+ slint::CloseRequestResponse::HideWindow+ } else {+ slint::CloseRequestResponse::KeepWindowShown+ }});// Maximised or not is read back on every resize rather than tracked:// the platform can maximise the window without us - a drag to the top@@ -1758,7 +1807,12 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::"speech" => state.handle(Msg::Speech(SpeechMsg::Open)),"clear-cache" => state.clear_project_cache(),"settings" => state.handle(Msg::Settings(SettingsMsg::Open)),- "close-project" => state.close_project(),+ "close-project" => {+ // Back to the launch screen, not out of the+ // app: a failed save keeps the project open and+ // the notice below lands it on screen.+ let _ = state.close_project();+ }"undo" => state.undo(),"redo" => state.redo(),"snap" => state.handle(Msg::Timeline(TimelineMsg::SnapToggled)),@@ -1796,9 +1850,21 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::}if action == "close-window" {log::info!("close: File > Close Window");- shell.studio.borrow_mut().close_project();- app.window().hide().ok();- slint::quit_event_loop().ok();+ let outcome = close_window(+ || shell.studio.borrow_mut().close_project(),+ || {+ app.window().hide().ok();+ slint::quit_event_loop().ok();+ },+ );+ if let Err(error) = outcome {+ // Unsaved work is worth more than the window: the+ // project stays open and the reason is shown.+ log::warn!("close: not closing, project could not be saved: {error}");+ shell.studio.borrow_mut().refresh_art();+ shell.studio.borrow().publish(&app, &shell.models);+ return;+ }log::info!("close: quit_event_loop called (menu)");return;}@@ -2042,3 +2108,203 @@ fn leave(code: i32) -> ! {#[cfg(not(target_os = "linux"))]std::process::exit(code);}++#[cfg(test)]+mod tests {+ use super::close_window;+ use std::cell::{Cell, RefCell};+ use std::path::Path;++ use concat_host::{Session, projects};++ /// A scratch folder that removes itself when the test ends, pass, fail or+ /// panic. Its name carries the process id and the thread's so two tests+ /// running at once never share one, and it sits under `temp_dir`, which+ /// the isolated run points into the approved directory.+ struct Scratch(std::path::PathBuf);++ impl Scratch {+ fn new(tag: &str) -> Self {+ let path = std::env::temp_dir().join(format!(+ "concat-close-{tag}-{}-{:?}",+ std::process::id(),+ std::thread::current().id()+ ));+ let _ = std::fs::remove_dir_all(&path);+ std::fs::create_dir_all(&path).expect("a scratch folder");+ Self(path)+ }++ fn location(&self) -> String {+ self.0.to_string_lossy().into_owned()+ }+ }++ impl Drop for Scratch {+ fn drop(&mut self) {+ // Best effort: a leftover scratch must not fail a run that its+ // test already decided.+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }++ /// Saves the session the slot holds and, only when the write lands, lets+ /// it go - the contract `Studio::close_project` keeps for every way out.+ /// The write is `concat_host`'s own, so nothing here fabricates a+ /// failure or a success.+ fn save_then_release(slot: &RefCell<Option<Session>>) -> Result<(), String> {+ let mut slot = slot.borrow_mut();+ let result = match slot.as_mut() {+ Some(session) => session.save(None),+ None => Ok(()),+ };+ if result.is_ok() {+ *slot = None;+ }+ result+ }++ fn tracks(session: &Session) -> usize {+ session.project().active().tracks.len()+ }++ /// The regression this gate exists for, over a real project on disk: a+ /// close used to hide the window and quit whatever the save did. The+ /// write here is `concat_host`'s own - a real [`Session`] through+ /// `projects::save` - and it is made to fail by a directory standing+ /// where the manifest must go, a block at the destination the save+ /// renames onto, so the failure holds whatever the save calls its+ /// temporary file (the old `.saving` or the current per-call name). A+ /// failed write must leave the session open, keep the edit it holds and+ /// never leave; the retry, unblocked, must land the edit and then leave.+ ///+ /// The gate is what is under test, not a Slint handler: there is no+ /// window, no event loop and no `Studio` here, only the real session and+ /// the real filesystem.+ #[test]+ fn a_failed_save_keeps_the_real_session_and_its_edit() {+ let scratch = Scratch::new("session");+ let info = projects::create(&scratch.location(), "Closing", 1920, 1080, 30, 1)+ .expect("creates the project");+ let manifest = projects::manifest_path(Path::new(&info.path));++ // A real session, saved once; then an edit that lives in memory+ // only, so the disk holds the project without it.+ let mut session = Session::open_info(&info).expect("opens the session");+ let unedited = tracks(&session);+ session.save(None).expect("the baseline write lands");+ let baseline = std::fs::read(&manifest).expect("reads the baseline manifest");+ session+ .apply(concat_project::Command::AddTrack { bottom: false })+ .expect("adds a track");+ let edited = tracks(&session);+ assert_eq!(edited, unedited + 1, "the edit really changed the project");++ // Block the destination: a directory where the manifest must go. The+ // save writes its temporary, flushes it, and cannot rename it over a+ // directory, so it fails for real and leaves no partial manifest.+ std::fs::remove_file(&manifest).expect("removes the manifest");+ std::fs::create_dir(&manifest).expect("blocks the manifest path");++ let slot = RefCell::new(Some(session));+ let left = Cell::new(false);+ let outcome = close_window(|| save_then_release(&slot), || left.set(true));++ let failed_at = manifest.display().to_string();+ assert!(outcome.is_err(), "a blocked write is a failure");+ assert!(+ outcome.as_ref().unwrap_err().contains(failed_at.as_str()),+ "the failure is the real one from the blocked destination: {outcome:?}"+ );+ assert!(manifest.is_dir(), "the block is untouched, nothing landed");+ {+ let held = slot.borrow();+ let session = held.as_ref().expect("the session is kept");+ assert_eq!(+ tracks(session),+ edited,+ "the kept session still holds the edit"+ );+ }+ assert!(!left.get(), "nothing leaves on a failed save");++ // Restore the baseline that the test removed to install its block.+ // This checks recovery; it does not claim that a manifest deleted+ // by the test itself was preserved by the failed write.+ std::fs::remove_dir(&manifest).expect("clears the block");+ std::fs::write(&manifest, &baseline).expect("restores the manifest");+ let reopened = Session::open_info(&info).expect("reopens the old document");+ assert_eq!(+ tracks(&reopened),+ unedited,+ "the failed write saved nothing over the old one"+ );+ drop(reopened);++ // The retry, unblocked: the same gate, now landing. Only a landed+ // save lets the session go and leaves, and the edit is on disk for+ // the next open.+ let outcome = close_window(|| save_then_release(&slot), || left.set(true));+ assert!(outcome.is_ok(), "the retry lands: {outcome:?}");+ assert!(slot.borrow().is_none(), "a landed save lets the session go");+ assert!(left.get(), "and only then leaves");+ let reopened = Session::open_info(&info).expect("reopens the saved project");+ assert_eq!(+ tracks(&reopened),+ edited,+ "the edit is on disk after the retry"+ );+ }++ /// Exercise the capture-before-dispatch contract with real session+ /// snapshots: a queued autosave must not replace the newer close save,+ /// even if its worker only starts writing after close has succeeded.+ #[test]+ fn a_delayed_autosave_cannot_replace_the_close_snapshot() {+ let scratch = Scratch::new("ordered-close");+ let info = projects::create(&scratch.location(), "Ordered", 1920, 1080, 30, 1)+ .expect("creates the project");+ let mut session = Session::open_info(&info).expect("opens the session");+ let (old_path, old_document) = session.prepare_save(None);+ let old_ticket = projects::ticket();+ session+ .apply(concat_project::Command::AddTrack { bottom: false })+ .expect("adds the unsaved track");+ let edited = tracks(&session);+ let (new_path, new_document) = session.prepare_save(None);+ let new_ticket = projects::ticket();++ let (release, delayed) = std::sync::mpsc::channel();+ let worker = std::thread::spawn(move || {+ delayed.recv().expect("releases the delayed autosave");+ projects::save_ordered(&old_path, &old_document, old_ticket)+ });+ let left = Cell::new(false);+ let outcome = close_window(+ || projects::save_ordered(&new_path, &new_document, new_ticket).map(|_| ()),+ || left.set(true),+ );+ // Always release and join the worker before asserting, including+ // when the close write unexpectedly fails.+ release.send(()).expect("releases the worker");+ let late = worker.join().expect("the worker completes");+ assert!(outcome.is_ok(), "the close save succeeds: {outcome:?}");+ assert!(left.get());+ assert_eq!(late, Ok(projects::Saved::Superseded));+ let reopened = Session::open_info(&info).expect("reopens the latest snapshot");+ assert_eq!(tracks(&reopened), edited, "the last edit survives close");+ }++ /// The version switch schedules its relaunch inside the leave, so a+ /// failed save starts no replacement build over the running one.+ #[test]+ fn a_failed_save_does_not_schedule_the_relaunch() {+ let relaunched = Cell::new(false);+ let outcome = close_window(+ || Err("could not write the project".to_owned()),+ || relaunched.set(true),+ );+ assert!(outcome.is_err());+ assert!(!relaunched.get(), "nothing is relaunched on a failed save");+ }+}diff --git a/src/crates/concat/src/panes/settings.rs b/src/crates/concat/src/panes/settings.rsindex c1029b9c..db1a162c 100644--- a/src/crates/concat/src/panes/settings.rs+++ b/src/crates/concat/src/panes/settings.rs@@ -20,6 +20,7 @@ use concat_host::models::SourcePreference;use concat_host::updates::{self, Fixed, Installed, Release, Standing, Version};use slint::SharedString;+use crate::close_window;use crate::host::{on_ui, spawn};use crate::i18n::{self, t, tf};use crate::panes::Msg;@@ -426,15 +427,19 @@ impl SettingsPane {Ok(Installed::InstallerRunning) => {log::info!("update: the installer for {version} is running; closing");studio.notify(&tf("settings.installerOpened", &[&version]), false);- quit_for_switch();+ quit_for_switch(|| {});}Ok(Installed::Replaced) => {+ // The bundle on disk is already the new build; what+ // is left is to start it, and that waits on the+ // project being saved.log::info!("update: {version} is in place; starting it");- if let Err(error) = updates::relaunch() {- log::warn!("update: could not arrange the start: {error}");- }studio.notify(&tf("settings.versionInstalled", &[&version]), false);- quit_for_switch();+ quit_for_switch(|| {+ if let Err(error) = updates::relaunch() {+ log::warn!("update: could not arrange the start: {error}");+ }+ });}Ok(Installed::Opened) => {studio.notify(&tf("settings.packageOpened", &[&version]), false);@@ -838,15 +843,31 @@ fn fixed_note(why: Fixed) -> String {}}-/// Closes the app on the event loop's next turn, the way File › Close-/// Window does, so an installer can replace its files or the build put in-/// place can start.-fn quit_for_switch() {- on_ui(|studio, app, _| {+/// Saves and closes the project, then quits - running `after`, the start of+/// a build already replaced on disk, only once the project has been written.+///+/// A switch is only worth making if the save lands first. The relaunch of a+/// replaced build used to be scheduled before the save, so a save that then+/// failed started the new build over a window that still held the old+/// session. Now a failed save starts nothing and quits nothing: the window+/// stays up with `close_project`'s reason, and the bundle already on disk+/// can be started by hand.+fn quit_for_switch(after: impl FnOnce() + Send + 'static) {+ on_ui(move |studio, app, models| {log::info!("close: quitting for a version switch");- studio.close_project();- slint::ComponentHandle::window(app).hide().ok();- slint::quit_event_loop().ok();+ let outcome = close_window(+ || studio.close_project(),+ || {+ after();+ slint::ComponentHandle::window(app).hide().ok();+ slint::quit_event_loop().ok();+ },+ );+ if let Err(error) = outcome {+ log::warn!("close: not switching, project could not be saved: {error}");+ studio.refresh_art();+ studio.publish(app, models);+ }});}diff --git a/src/crates/concat/src/studio.rs b/src/crates/concat/src/studio.rsindex 20006854..6e9418cf 100644--- a/src/crates/concat/src/studio.rs+++ b/src/crates/concat/src/studio.rs@@ -2594,12 +2594,15 @@ impl Studio {};self.autosave.stop();let (path, document) = session.prepare_save(None);+ // Capture the write order with the snapshot, not later when a+ // worker happens to pick it up.+ let ticket = projects::ticket();self.dirty = false;- spawn(- move || projects::save(&path, &document),+ spawn_in_project(+ move || projects::save_ordered(&path, &document, ticket),move |studio, _, _, result| match result {- Ok(()) if announce => studio.notify(&t("studio.projectSaved"), false),- Ok(()) => {}+ Ok(_) if announce => studio.notify(&t("studio.projectSaved"), false),+ Ok(_) => {}Err(error) => {studio.dirty = true;studio.notify(&tf("studio.couldNotSave", &[&error]), true);@@ -7220,11 +7223,32 @@ impl Studio {}/// Saves, then closes the session and returns to the launch screen.- pub fn close_project(&mut self) {+ ///+ /// A save that fails returns its reason and stops short of the close:+ /// the session, its running jobs and the autosave timer are left as they+ /// were, so a caller that was about to hide the window or quit can keep+ /// it up rather than drop unsaved work on the floor. Not untouched, to be+ /// exact - the close flushes a half-typed commit and pauses playback+ /// before it saves, and a failed save leaves those two as done. What a+ /// failure does not reach is the teardown: the worker cancellations, the+ /// job lists, the autosave timer and the session itself.+ pub fn close_project(&mut self) -> Result<(), String> {log::info!("project: closing {}", self.project_name);// Words still being typed land in the save, not on the floor.self.flush_commit();self.pause();+ // Saved before the workers are cancelled: a close that cannot be+ // written is not a close, and the jobs it would have stopped are+ // not ours to throw away.+ if let Some(session) = self.session.as_mut() {+ let (path, document) = session.prepare_save(None);+ let ticket = projects::ticket();+ if let Err(error) = projects::save_ordered(&path, &document, ticket) {+ log::warn!("project: could not be saved, not closing: {error}");+ self.notify(&tf("studio.couldNotSave", &[&error]), true);+ return Err(error);+ }+ }self.host.cutouts.cancel();self.host.enhancers.cancel();self.host.reversers.cancel();@@ -7233,13 +7257,6 @@ impl Studio {self.cancel_merge();self.cutout_jobs.clear();self.region_job = None;- if let Some(session) = self.session.as_mut() {- let (path, document) = session.prepare_save(None);- if let Err(error) = projects::save(&path, &document) {- self.notify(&tf("studio.couldNotSave", &[&error]), true);- return;- }- }self.autosave.stop();if let Some(session) = self.session.as_ref() {self.host.open_projects.release(session.path());@@ -7278,6 +7295,7 @@ impl Studio {.set_clips(std::path::PathBuf::new(), Vec::new());self.on_start = true;self.recents = projects::list(&self.host.dirs.config);+ Ok(())}/// Posters for the recents that have none yet, decoded on a worker.