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: a half-written project is refused, a panicking decode job is survived, a closed project's results are dropped
Jareerfa69d49d815e
diff --git a/src/crates/concat-api/src/lib.rs b/src/crates/concat-api/src/lib.rsindex d3b7f843..38e5e886 100644--- a/src/crates/concat-api/src/lib.rs+++ b/src/crates/concat-api/src/lib.rs@@ -1018,7 +1018,12 @@ mod tests {path: path.clone(),name: None,}));- assert_eq!(projects::read_document(&path).expect("saved"), document);+ assert_eq!(+ projects::read_document(&path)+ .expect("saved")+ .expect("a document"),+ document+ );}#[test]diff --git a/src/crates/concat-host/src/projects.rs b/src/crates/concat-host/src/projects.rsindex d8571f38..a0d0ff98 100644--- a/src/crates/concat-host/src/projects.rs+++ b/src/crates/concat-host/src/projects.rs@@ -205,13 +205,20 @@ pub fn is_settings_only(document: &serde_json::Value) -> bool {.all(|key| document.get(key).is_none())}-/// Reads the whole project document back.-pub fn read_document(path: &str) -> Result<serde_json::Value, String> {+/// Reads the whole project document back: `None` when the folder has no+/// document yet, an error for one that is there and cannot be read or+/// parsed. The two are kept apart because a caller that treats them alike+/// opens a half-written document as an empty project and saves over it+/// (audit 2026-09-23, #1).+pub fn read_document(path: &str) -> Result<Option<serde_json::Value>, String> {let manifest = manifest_path(Path::new(path));- let bytes = std::fs::read(&manifest)- .map_err(|error| format!("could not read {}: {error}", manifest.display()))?;-+ let bytes = match std::fs::read(&manifest) {+ Ok(bytes) => bytes,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(format!("could not read {}: {error}", manifest.display())),+ };serde_json::from_slice(&bytes)+ .map(Some).map_err(|error| format!("{} is not a Concat project: {error}", manifest.display()))}diff --git a/src/crates/concat-host/src/session.rs b/src/crates/concat-host/src/session.rsindex 6031a60f..2256d2d9 100644--- a/src/crates/concat-host/src/session.rs+++ b/src/crates/concat-host/src/session.rs@@ -63,16 +63,16 @@ pub struct SettingsView {impl Session {/// Opens a project folder as the editing session.///- /// A folder whose document is missing or unreadable opens as an empty- /// project rather than failing, but a *corrupt* document is an error,- /// because silently replacing an edit with emptiness is how projects get- /// lost. `settings` come from the manifest and seed the first timeline+ /// A folder with no document yet opens as an empty project rather than+ /// failing, but a document that is there and cannot be read or parsed+ /// is an error, because silently replacing an edit with emptiness is+ /// how projects get lost. `settings` come from the manifest and seed the first timeline/// of a project that has no document yet; a document that loads brings/// every timeline's own frame with it, and those win, because that is/// where an edited frame was saved.pub fn open(path: &str, settings: DocumentSettings) -> Result<Session, String> {let editor = match projects::read_document(path) {- Ok(document) => match Editor::from_document(&document) {+ Ok(Some(document)) => match Editor::from_document(&document) {Some(editor) => editor,// The settings-only manifest `create` writes: a project// closed before its first edit reopens empty, it is not@@ -92,7 +92,11 @@ impl Session {}},// No document yet - a project created moments ago.- Err(_) => Editor::with_video(settings.video()),+ Ok(None) => Editor::with_video(settings.video()),+ // Unreadable or not JSON: a save cut short, a disk in trouble.+ // The one thing open must not do is answer with an empty+ // project, since the next save would replace what was edited.+ Err(error) => return Err(error),};Ok(Session {path: path.to_owned(),@@ -338,4 +342,23 @@ mod tests {assert!(Session::open(&scratch.to_string_lossy(), settings()).is_err());let _ = std::fs::remove_dir_all(&scratch);}++ #[test]+ fn a_truncated_document_is_refused_rather_than_replaced() {+ let scratch =+ std::env::temp_dir().join(format!("concat-truncated-test-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&scratch);+ std::fs::create_dir_all(&scratch).expect("scratch dir");+ // A save cut short by a power cut or an outside tool: the file is+ // there, and it is not JSON. Opening it as an empty project would+ // let the next save replace whatever was edited.+ std::fs::write(+ scratch.join("concat.json"),+ br#"{"version": 1, "timelines": ["#,+ )+ .expect("writes");+ let opened = Session::open(&scratch.to_string_lossy(), settings());+ assert!(opened.is_err(), "a half document is not an empty project");+ let _ = std::fs::remove_dir_all(&scratch);+ }}diff --git a/src/crates/concat-host/src/templates.rs b/src/crates/concat-host/src/templates.rsindex 04d6df45..6052c1df 100644--- a/src/crates/concat-host/src/templates.rs+++ b/src/crates/concat-host/src/templates.rs@@ -540,7 +540,9 @@ mod tests {).expect("instantiates");- let opened = projects::read_document(&made.path).expect("reads back");+ let opened = projects::read_document(&made.path)+ .expect("reads back")+ .expect("a document");let media = opened["media"].as_array().expect("media");let sound = media[1]["path"].as_str().expect("path");assert!(@@ -588,7 +590,9 @@ mod tests {.expect("instantiates");assert_eq!((project.width, project.height), (1920, 1080));- let document = projects::read_document(&project.path).expect("reads back");+ let document = projects::read_document(&project.path)+ .expect("reads back")+ .expect("a document");let media = document["media"].as_array().expect("media");assert!(media.iter().all(|item| {!itemdiff --git a/src/crates/concat-media/src/prefetch.rs b/src/crates/concat-media/src/prefetch.rsindex 3792cc23..29017169 100644--- a/src/crates/concat-media/src/prefetch.rs+++ b/src/crates/concat-media/src/prefetch.rs@@ -191,9 +191,12 @@ impl Prefetcher {});for index in 0..workers {let lane = Arc::clone(&lane);- let _ = std::thread::Builder::new()+ if let Err(error) = std::thread::Builder::new().name(format!("concat-decode-{index}"))- .spawn(move || work(&lane));+ .spawn(move || work(&lane))+ {+ log::error!("decode worker {index} could not start: {error}");+ }}Self {shared: Arc::new(Shared {@@ -352,20 +355,40 @@ fn work(lane: &Lane) {.unwrap_or_else(|poisoned| poisoned.into_inner());}};- job();- let mut queue = lock(&lane.queue);+ let finished = Finished { lane, priority };+ // A job that panics must not take the counters with it: `running`+ // would never come down, `drain` would wait forever and the reserve+ // would stay spent for the life of the process. The guard counts+ // the job as finished whatever it did (audit 2026-09-23, #2).+ if std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)).is_err() {+ log::error!("a {priority:?} job panicked; the worker carries on");+ }+ drop(finished);+ }+}++/// A running job's place in the counters, given back when dropped, so it+/// is given back on a panic too.+struct Finished<'a> {+ lane: &'a Lane,+ priority: Priority,+}++impl Drop for Finished<'_> {+ fn drop(&mut self) {+ let mut queue = lock(&self.lane.queue);queue.running -= 1;- if priority.background() {+ if self.priority.background() {queue.background_running -= 1;}- if priority == Priority::Proxy {+ if self.priority == Priority::Proxy {queue.proxy_running -= 1;}drop(queue);// A finished job frees a worker for a job the reserve was holding// back, and is what a drain waits for.- lane.ready.notify_all();- lane.done.notify_all();+ self.lane.ready.notify_all();+ self.lane.done.notify_all();}}@@ -381,6 +404,29 @@ mod tests {use concat_core::time::FrameRate;use std::sync::atomic::AtomicUsize;+ /// A job that panics is counted as finished: the worker carries on,+ /// the next job runs, and a drain returns rather than waiting on a+ /// counter nothing will ever bring down.+ #[test]+ fn a_panicking_job_does_not_take_the_worker_with_it() {+ let pool = Arc::new(ReaderPool::new(1024, 1));+ let prefetcher = Prefetcher::new(pool, 1);+ prefetcher.submit(Priority::Artwork, || panic!("a bad job"));+ let ran = Arc::new(AtomicUsize::new(0));+ let mark = Arc::clone(&ran);+ prefetcher.submit(Priority::Artwork, move || {+ mark.fetch_add(1, Ordering::SeqCst);+ });+ prefetcher.drain();+ assert_eq!(ran.load(Ordering::SeqCst), 1, "the job after the panic ran");+ let queue = lock(&prefetcher.lane.queue);+ assert_eq!(+ (queue.running, queue.background_running, queue.proxy_running),+ (0, 0, 0),+ "the counters came back down"+ );+ }+/// Jobs run most urgent first, and a background job never takes the/// last worker: with one worker and a reserve of none, everything/// runs; the order is by priority, then by arrival.diff --git a/src/crates/concat/src/host.rs b/src/crates/concat/src/host.rsindex c864d720..51ddfce2 100644--- a/src/crates/concat/src/host.rs+++ b/src/crates/concat/src/host.rs@@ -179,17 +179,56 @@ pub fn spawn<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static,then: impl FnOnce(&mut Studio, &App, &Models, T) + Send + 'static,) {- spawn_detached(move || deliver(work(), then));+ spawn_detached(move || deliver(None, work(), then));+}++/// The project the window is on, counted up at every open and close. A+/// worker's result made for an earlier project is told apart by it and+/// dropped in [`deliver`], in one place, rather than guarded against in+/// every closure: a probe, a caption run or a spoken line started in one+/// project must not land in the next (audit 2026-09-23, #3).+static PROJECT_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);++/// The project epoch now; see [`spawn_in_project`].+pub fn project_epoch() -> u64 {+ PROJECT_EPOCH.load(std::sync::atomic::Ordering::Acquire)+}++/// Starts the next project epoch: a project opened or closed.+pub fn next_project_epoch() {+ PROJECT_EPOCH.fetch_add(1, std::sync::atomic::Ordering::AcqRel);+}++/// Whether a result made in `epoch` concerns a project no longer open.+fn stale(epoch: Option<u64>) -> bool {+ epoch.is_some_and(|epoch| epoch != project_epoch())+}++/// [`spawn`] for work that belongs to the open project: `then` runs only+/// while that project is still the open one, and is dropped otherwise.+/// Work that is not a project's - a poster for the launch screen, a model+/// download - goes through [`spawn`] and is always delivered.+pub fn spawn_in_project<T: Send + 'static>(+ work: impl FnOnce() -> T + Send + 'static,+ then: impl FnOnce(&mut Studio, &App, &Models, T) + Send + 'static,+) {+ let epoch = project_epoch();+ spawn_detached(move || deliver(Some(epoch), work(), then));}/// Hands a worker's result to the event-loop thread: `then` with the state-/// and the window, and a full publish after it.+/// and the window, and a full publish after it. A result made in a project+/// epoch that has passed is dropped here.fn deliver<T: Send + 'static>(+ epoch: Option<u64>,result: T,then: impl FnOnce(&mut Studio, &App, &Models, T) + Send + 'static,) {let _ = slint::invoke_from_event_loop(move || {Shell::with(|shell, app| {+ if stale(epoch) {+ return;+ }{let mut studio = shell.studio.borrow_mut();then(&mut studio, &app, &shell.models, result);@@ -225,14 +264,31 @@ fn spawn_at<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static,then: impl FnOnce(&mut Studio, &App, &Models, T) + Send + 'static,) {- concat_host::scheduler().submit(priority, move || deliver(work(), then));+ concat_host::scheduler().submit(priority, move || deliver(None, work(), then));}/// Runs `body` on the event-loop thread from anywhere, with a full publish/// after. For progress reports from a worker.pub fn on_ui(body: impl FnOnce(&mut Studio, &App, &Models) + Send + 'static) {+ on_ui_gated(None, body);+}++/// [`on_ui`] for a report about the open project - a job's progress -+/// made in `epoch` (see [`project_epoch`]): dropped once that project has+/// closed, like a [`spawn_in_project`] result.+pub fn on_ui_in_project(+ epoch: u64,+ body: impl FnOnce(&mut Studio, &App, &Models) + Send + 'static,+) {+ on_ui_gated(Some(epoch), body);+}++fn on_ui_gated(epoch: Option<u64>, body: impl FnOnce(&mut Studio, &App, &Models) + Send + 'static) {let _ = slint::invoke_from_event_loop(move || {Shell::with(|shell, app| {+ if stale(epoch) {+ return;+ }{let mut studio = shell.studio.borrow_mut();body(&mut studio, &app, &shell.models);@@ -621,3 +677,22 @@ pub fn media_art(strip,}}++#[cfg(test)]+mod epoch_tests {+ #[test]+ fn a_result_from_an_earlier_project_is_stale() {+ let then = super::project_epoch();+ assert!(+ !super::stale(None),+ "work that is nobody's project is never stale"+ );+ assert!(!super::stale(Some(then)));+ super::next_project_epoch();+ assert!(+ super::stale(Some(then)),+ "the project it was made in has closed"+ );+ assert!(!super::stale(Some(super::project_epoch())));+ }+}diff --git a/src/crates/concat/src/panes/captions.rs b/src/crates/concat/src/panes/captions.rsindex 1eed4ab6..523e2af1 100644--- a/src/crates/concat/src/panes/captions.rs+++ b/src/crates/concat/src/panes/captions.rs@@ -17,7 +17,7 @@ use concat_project::model::TextStyle;use concat_speech::transcribe::Segment;use slint::SharedString;-use crate::host::{on_ui, spawn};+use crate::host::{on_ui_in_project, spawn_in_project};use crate::i18n::{t, tf};use crate::panes::Msg;use crate::panes::settings::installed;@@ -235,10 +235,11 @@ impl CaptionsPane {self.running = true;self.progress = 0.0;self.message.clear();- spawn(+ let epoch = crate::host::project_epoch();+ spawn_in_project(move || {- transcriber.transcribe(&dirs, &request, |percent| {- on_ui(move |studio, _, _| {+ transcriber.transcribe(&dirs, &request, move |percent| {+ on_ui_in_project(epoch, move |studio, _, _| {studio.handle(Msg::Captions(CaptionsMsg::Progress(percent)));});})diff --git a/src/crates/concat/src/panes/media_bin.rs b/src/crates/concat/src/panes/media_bin.rsindex 518fd1c2..4b55a47d 100644--- a/src/crates/concat/src/panes/media_bin.rs+++ b/src/crates/concat/src/panes/media_bin.rs@@ -19,7 +19,7 @@ use concat_project::Command;use concat_project::model::{self, MediaItem, MediaOrigin, Project};use crate::format::wave_path;-use crate::host::{probe_error, spawn};+use crate::host::{probe_error, spawn_in_project};use crate::i18n::{t, tf};use crate::panes::Msg;use crate::studio::Studio;@@ -140,7 +140,7 @@ impl MediaBin {if paths.is_empty() || studio.session.is_none() {return;}- spawn(+ spawn_in_project(move || {paths.iter()diff --git a/src/crates/concat/src/panes/mod.rs b/src/crates/concat/src/panes/mod.rsindex a3d05873..0e57ecc2 100644--- a/src/crates/concat/src/panes/mod.rs+++ b/src/crates/concat/src/panes/mod.rs@@ -6,8 +6,9 @@//! Each pane owns its state and is changed only by its own messages: a//! Slint callback and a worker's report are the same thing, one [`Msg`]//! posted to [`crate::studio::Studio::handle`], which routes it to the pane-//! and publishes. A message that arrives after the project it concerns-//! has closed is dropped there, in one place, rather than guarded against+//! and publishes. A worker's result for a project that has since closed+//! is dropped in one place, `host::deliver`, by the project epoch the work+//! was started in (`host::spawn_in_project`), rather than guarded against//! in every closure.//!//! The panes move here one at a time from the window's controller; thediff --git a/src/crates/concat/src/panes/monitor.rs b/src/crates/concat/src/panes/monitor.rsindex 1b990022..d3080470 100644--- a/src/crates/concat/src/panes/monitor.rs+++ b/src/crates/concat/src/panes/monitor.rs@@ -22,7 +22,7 @@ use std::sync::Arc;use concat_host::preview::FrameSpec;use concat_project::model::Project;-use crate::host::{spawn, spawn_detached};+use crate::host::{spawn_detached, spawn_in_project};use crate::i18n::tf;use crate::panes::Msg;use crate::studio::Studio;@@ -188,7 +188,7 @@ impl MonitorPane {let monitor = studio.host.monitor.clone();self.busy = true;self.wanted = false;- spawn(+ spawn_in_project(move || {// On the window's device the frame stays a texture; without// one it comes back as pixels and is uploaded here.diff --git a/src/crates/concat/src/panes/speech.rs b/src/crates/concat/src/panes/speech.rsindex 51f6ce56..1991fb7f 100644--- a/src/crates/concat/src/panes/speech.rs+++ b/src/crates/concat/src/panes/speech.rs@@ -31,7 +31,7 @@ use concat_speech::tts::{use slint::SharedString;use crate::format::wave_path;-use crate::host::{on_ui, spawn};+use crate::host::{on_ui_in_project, spawn_in_project};use crate::i18n::{t, tf};use crate::panes::Msg;use crate::panes::captions::CHARS_PER_SECOND;@@ -336,10 +336,11 @@ impl SpeechPane {self.running = true;self.progress = 0.0;self.message.clear();- spawn(+ let epoch = crate::host::project_epoch();+ spawn_in_project(move || {- let spoken = speech.speak(&dirs, &request, |fraction| {- on_ui(move |studio, _, _| {+ let spoken = speech.speak(&dirs, &request, move |fraction| {+ on_ui_in_project(epoch, move |studio, _, _| {studio.handle(Msg::Speech(SpeechMsg::Progress(fraction)));});})?;diff --git a/src/crates/concat/src/studio.rs b/src/crates/concat/src/studio.rsindex acc97308..fbdfa4c3 100644--- a/src/crates/concat/src/studio.rs+++ b/src/crates/concat/src/studio.rs@@ -53,8 +53,8 @@ use crate::format::{};use crate::host::{CachedStrip, Host, MediaArt, WindowArt, cached_media_art, cached_window_art, image_at,- image_of, media_art, on_ui, spawn, spawn_art, spawn_strip, strip_window, window_art,- window_span, window_start,+ image_of, media_art, on_ui_in_project, spawn, spawn_art, spawn_in_project, spawn_strip,+ strip_window, window_art, window_span, window_start,};use crate::i18n::{self, t, tf};use crate::panes::settings::installed;@@ -4474,7 +4474,8 @@ impl Studio {};self.cutout_jobs.insert(id.clone(), (false, 0.0));let cutouts = Arc::clone(&self.host.cutouts);- spawn(+ let epoch = crate::host::project_epoch();+ spawn_in_project(move || {let mut last = (false, -1.0f32);let reporting = id.clone();@@ -4490,7 +4491,7 @@ impl Studio {if now.0 != last.0 || now.1 - last.1 >= 0.01 {last = now;let id = reporting.clone();- on_ui(move |studio, _, _| {+ on_ui_in_project(epoch, move |studio, _, _| {if let Some(held) = studio.cutout_jobs.get_mut(&id) {*held = now;}@@ -4586,7 +4587,7 @@ impl Studio {file.display());self.notify(&t("Rendering the sound…"), false);- spawn(+ spawn_in_project(move || -> Result<concat_host::media::MediaSummary, String> {std::fs::create_dir_all(&out_dir).map_err(|error| format!("could not create {}: {error}", out_dir.display()))?;@@ -4662,7 +4663,8 @@ impl Studio {false,);let enhancers = Arc::clone(&self.host.enhancers);- spawn(+ let epoch = crate::host::project_epoch();+ spawn_in_project(move || {let mut last = (false, -1.0f32);let reporting = clip_id.clone();@@ -4676,7 +4678,7 @@ impl Studio {if now.0 != last.0 || now.1 - last.1 >= 0.01 {last = now;let id = reporting.clone();- on_ui(move |studio, _, _| {+ on_ui_in_project(epoch, move |studio, _, _| {if let Some(held) = studio.enhance_jobs.get_mut(&id) {*held = now;}@@ -5236,6 +5238,7 @@ impl Studio {}self.pause();self.session = Some(session);+ crate::host::next_project_epoch();self.echo = None;self.dirty = false;self.project_name = info.name.clone();@@ -5323,6 +5326,13 @@ impl Studio {}self.autosave.stop();self.session = None;+ // Whatever a worker still brings back for this project is dropped+ // at delivery; the sheets that were waiting on one stop waiting.+ crate::host::next_project_epoch();+ self.captions.running = false;+ self.captions.progress = 0.0;+ self.speech.running = false;+ self.speech.progress = 0.0;self.echo = None;self.dirty = false;self.selection.clear();@@ -6366,7 +6376,8 @@ impl Studio {self.region_job = Some(key.clone());self.cutout_jobs.entry(key.clone()).or_insert((false, 0.0));let brushes = Arc::clone(&self.host.brushes);- spawn(+ let epoch = crate::host::project_epoch();+ spawn_in_project(move || {let reporting = key.clone();let result = brushes.read(&request, &mut |progress| {@@ -6377,7 +6388,7 @@ impl Studio {concat_host::cutout::Progress::Analysing(fraction) => (false, fraction),};let key = reporting.clone();- on_ui(move |studio, _, _| {+ on_ui_in_project(epoch, move |studio, _, _| {if let Some(held) = studio.cutout_jobs.get_mut(&key) {*held = now;}