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(host): enforce one-at-a-time jobs and get I/O commands off the main thread
Jareer310c80817262
diff --git a/desktop/desktop/src-tauri/whisper/whisper-cli b/desktop/desktop/src-tauri/whisper/whisper-clideleted file mode 100755index 93a3394b..00000000Binary files a/desktop/desktop/src-tauri/whisper/whisper-cli and /dev/null differdiff --git a/desktop/src-tauri/src/editor_api.rs b/desktop/src-tauri/src/editor_api.rsindex 5a7e623e..ffd5074d 100644--- a/desktop/src-tauri/src/editor_api.rs+++ b/desktop/src-tauri/src/editor_api.rs@@ -101,7 +101,7 @@ fn with_session<T>(/// but a *corrupt* document is an error, because silently replacing an/// edit with emptiness is how projects get lost.#[tauri::command]-pub fn editor_open(+pub async fn editor_open(state: tauri::State<'_, EditorState>,path: String,name: String,@@ -110,28 +110,36 @@ pub fn editor_open(rate_num: i64,rate_den: i64,) -> Result<EditorView, String> {- let mut settings = DocumentSettings { name, width, height, rate_num, rate_den };- let editor = match projects::read_document(&path) {- Ok(document) => {- // The document's frame wins over the manifest: it is where an- // edited output size was saved.- if let Some(video) = document.get("video") {- if let (Some(width), Some(height)) = (- video.get("width").and_then(|value| value.as_u64()),- video.get("height").and_then(|value| value.as_u64()),- ) {- if width > 0 && height > 0 {- settings.width = width as u32;- settings.height = height as u32;+ // Reading and parsing the document is the slow part and needs no state,+ // so it runs on a blocking thread; the session lock is taken only for the+ // in-memory install below.+ let (path, settings, editor) = tauri::async_runtime::spawn_blocking(move || {+ let mut settings = DocumentSettings { name, width, height, rate_num, rate_den };+ let editor = match projects::read_document(&path) {+ Ok(document) => {+ // The document's frame wins over the manifest: it is where an+ // edited output size was saved.+ if let Some(video) = document.get("video") {+ if let (Some(width), Some(height)) = (+ video.get("width").and_then(|value| value.as_u64()),+ video.get("height").and_then(|value| value.as_u64()),+ ) {+ if width > 0 && height > 0 {+ settings.width = width as u32;+ settings.height = height as u32;+ }}}+ Editor::from_document(&document)+ .ok_or_else(|| format!("{path} holds a document this build cannot read"))?}- Editor::from_document(&document)- .ok_or_else(|| format!("{path} holds a document this build cannot read"))?- }- // No document yet - a project created moments ago.- Err(_) => Editor::new(),- };+ // No document yet - a project created moments ago.+ Err(_) => Editor::new(),+ };+ Ok::<_, String>((path, settings, editor))+ })+ .await+ .map_err(|error| format!("open task failed: {error}"))??;let mut guard = state.0.lock().map_err(|_| "editor state poisoned".to_owned())?;*guard = Some(Session { path, settings, editor });@@ -177,28 +185,35 @@ pub fn editor_state(state: tauri::State<'_, EditorState>) -> Result<EditorView,/// have been edited in the preview footer and the name in the project/// details dialog, so both ride along here.#[tauri::command]-pub fn editor_save(+pub async fn editor_save(state: tauri::State<'_, EditorState>,name: Option<String>,width: Option<u32>,height: Option<u32>,) -> Result<(), String> {- with_session(&state, |session| {+ // Settings mutation and serialisation happen under the lock; the disk+ // write - the slow, blockable part - happens off the main thread with the+ // lock released.+ let (path, document) = with_session(&state, |session| {if let Some(name) = name {let trimmed = name.trim();if !trimmed.is_empty() {session.settings.name = trimmed.to_owned();}}- if let Some(width) = width {+ // A zero dimension is never a real output size, only a caller bug -+ // saving it would poison the document until the next open.+ if let Some(width) = width.filter(|width| *width > 0) {session.settings.width = width;}- if let Some(height) = height {+ if let Some(height) = height.filter(|height| *height > 0) {session.settings.height = height;}- let document = session.editor.to_document(&session.settings);- projects::save(&session.path, &document)- })+ Ok((session.path.clone(), session.editor.to_document(&session.settings)))+ })?;+ tauri::async_runtime::spawn_blocking(move || projects::save(&path, &document))+ .await+ .map_err(|error| format!("save task failed: {error}"))?}/// Closes the session, dropping its undo history.diff --git a/desktop/src-tauri/src/jobs.rs b/desktop/src-tauri/src/jobs.rsnew file mode 100644index 00000000..fae74638--- /dev/null+++ b/desktop/src-tauri/src/jobs.rs@@ -0,0 +1,110 @@+//! One-at-a-time job slots for the host's long-running work.+//!+//! Export, transcription and model downloads are all "one at a time", and+//! that invariant used to live in doc comments while the commands happily+//! accepted a second run: two exports would race each other's temp files, and+//! starting a second job *cleared* the shared cancel flag out from under the+//! first. `SingleFlight` makes the invariant code: `begin` refuses a second+//! concurrent job, and every run gets its own cancel flag, so a cancel can+//! only ever stop the job that is actually running and a new job can never be+//! un-cancelled by a stale start or stopped by a stale cancel.++use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};++/// The slot: at most one running job, identified by its own cancel flag.+pub struct SingleFlight {+ slot: Mutex<Option<Arc<AtomicBool>>>,+}++impl SingleFlight {+ pub fn new() -> Self {+ Self { slot: Mutex::new(None) }+ }++ /// Claims the slot for a new job, or reports the one already running.+ ///+ /// `what` is the user-facing job name ("export", "transcription", ...).+ pub fn begin(self: &Arc<Self>, what: &str) -> Result<Job, String> {+ let mut slot = self.slot.lock().map_err(|_| format!("{what} state poisoned"))?;+ if slot.is_some() {+ return Err(format!("a {what} is already running - wait for it or cancel it first"));+ }+ let cancel = Arc::new(AtomicBool::new(false));+ *slot = Some(Arc::clone(&cancel));+ Ok(Job { owner: Arc::clone(self), cancel })+ }++ /// Cancels the running job. Idle is a harmless no-op.+ pub fn cancel(&self) {+ if let Ok(slot) = self.slot.lock() {+ if let Some(cancel) = slot.as_ref() {+ cancel.store(true, Ordering::Relaxed);+ }+ }+ }+}++/// A claim on the slot, released on drop - however the job ended, panic+/// included, the slot frees and the next `begin` succeeds.+pub struct Job {+ owner: Arc<SingleFlight>,+ cancel: Arc<AtomicBool>,+}++impl Job {+ /// This run's stop flag, for the worker to poll.+ pub fn cancel_flag(&self) -> &AtomicBool {+ &self.cancel+ }+}++impl Drop for Job {+ fn drop(&mut self) {+ if let Ok(mut slot) = self.owner.slot.lock() {+ // Release only our own claim. Guards are one-per-begin so the+ // check is belt and braces, but it makes a stale drop harmless.+ if slot.as_ref().is_some_and(|flag| Arc::ptr_eq(flag, &self.cancel)) {+ *slot = None;+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn refuses_a_second_concurrent_job() {+ let flight = Arc::new(SingleFlight::new());+ let job = flight.begin("export").expect("first begin");+ match flight.begin("export") {+ Err(error) => assert!(error.contains("already running")),+ Ok(_) => panic!("second begin must be refused"),+ }+ drop(job);+ assert!(flight.begin("export").is_ok(), "slot frees on drop");+ }++ #[test]+ fn cancel_reaches_only_the_running_job() {+ let flight = Arc::new(SingleFlight::new());+ let first = flight.begin("export").expect("begin");+ flight.cancel();+ assert!(first.cancel_flag().load(Ordering::Relaxed));++ drop(first);+ // A new job starts with a fresh, uncancelled flag: the earlier cancel+ // cannot leak forward, and starting fresh cannot un-cancel anyone.+ let second = flight.begin("export").expect("begin again");+ assert!(!second.cancel_flag().load(Ordering::Relaxed));+ }++ #[test]+ fn cancel_when_idle_is_a_no_op() {+ let flight = Arc::new(SingleFlight::new());+ flight.cancel();+ assert!(flight.begin("export").is_ok());+ }+}diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex a8fe9ce5..211f8423 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -9,6 +9,7 @@// Public so the integration tests can drive a real export; see tests/.pub mod export;mod editor_api;+mod jobs;mod playback;mod projects;mod templates;@@ -117,9 +118,17 @@ impl From<wolfcut_media::MediaInfo> for MediaSummary {}/// Reports what is inside a media file.+///+/// Async because ffprobe on a slow or network volume takes real time, and a+/// synchronous command runs on the main thread - the one place a stall is a+/// frozen window.#[tauri::command]-fn probe_media(path: String) -> Result<MediaSummary, String> {- wolfcut_media::probe(&path).map(MediaSummary::from).map_err(describe)+async fn probe_media(path: String) -> Result<MediaSummary, String> {+ tauri::async_runtime::spawn_blocking(move || {+ wolfcut_media::probe(&path).map(MediaSummary::from).map_err(describe)+ })+ .await+ .map_err(|error| format!("probe task failed: {error}"))?}/// The version of the app the UI is talking to. Also a liveness check on the@@ -139,10 +148,13 @@ fn engine_version() -> &'static str {/// It loads the entire file into memory, so it is not a general-purpose/// reader and must not become one.#[tauri::command]-fn read_media_bytes(path: String) -> Result<tauri::ipc::Response, String> {- std::fs::read(&path)- .map(tauri::ipc::Response::new)- .map_err(|error| format!("could not read {path}: {error}"))+async fn read_media_bytes(path: String) -> Result<tauri::ipc::Response, String> {+ tauri::async_runtime::spawn_blocking(move || {+ std::fs::read(&path).map_err(|error| format!("could not read {path}: {error}"))+ })+ .await+ .map_err(|error| format!("read task failed: {error}"))?+ .map(tauri::ipc::Response::new)}/// Where one artwork file lives inside a project's cache.@@ -169,23 +181,30 @@ fn artwork_file(project: &str, key: &str) -> Result<std::path::PathBuf, String>/// Returns one cached artwork file, or an error the frontend treats as a miss.#[tauri::command]-fn read_artwork(project: String, key: String) -> Result<tauri::ipc::Response, String> {+async fn read_artwork(project: String, key: String) -> Result<tauri::ipc::Response, String> {let file = artwork_file(&project, &key)?;- std::fs::read(&file)- .map(tauri::ipc::Response::new)- .map_err(|error| format!("no cached artwork {key}: {error}"))+ tauri::async_runtime::spawn_blocking(move || {+ std::fs::read(&file).map_err(|error| format!("no cached artwork {key}: {error}"))+ })+ .await+ .map_err(|error| format!("artwork task failed: {error}"))?+ .map(tauri::ipc::Response::new)}/// Stores one artwork file in the project's cache. Best-effort: the caller/// fires and forgets, and a failed write only means regenerating next launch.#[tauri::command]-fn write_artwork(project: String, key: String, bytes: Vec<u8>) -> Result<(), String> {+async fn write_artwork(project: String, key: String, bytes: Vec<u8>) -> Result<(), String> {let file = artwork_file(&project, &key)?;- if let Some(parent) = file.parent() {- std::fs::create_dir_all(parent)- .map_err(|error| format!("could not create {}: {error}", parent.display()))?;- }- std::fs::write(&file, bytes).map_err(|error| format!("could not write {key}: {error}"))+ tauri::async_runtime::spawn_blocking(move || {+ if let Some(parent) = file.parent() {+ std::fs::create_dir_all(parent)+ .map_err(|error| format!("could not create {}: {error}", parent.display()))?;+ }+ std::fs::write(&file, bytes).map_err(|error| format!("could not write {key}: {error}"))+ })+ .await+ .map_err(|error| format!("artwork task failed: {error}"))?}/// Renders a strip of evenly spaced frames from a video as one JPEG.@@ -413,20 +432,29 @@ async fn open_project(app: tauri::AppHandle, path: String) -> Result<projects::P/// The recents list, most recent first, with vanished folders left out.#[tauri::command]-fn recent_projects(app: tauri::AppHandle) -> Result<Vec<projects::ProjectInfo>, String> {- Ok(projects::list(&config_dir(&app)?))+async fn recent_projects(app: tauri::AppHandle) -> Result<Vec<projects::ProjectInfo>, String> {+ let config = config_dir(&app)?;+ tauri::async_runtime::spawn_blocking(move || projects::list(&config))+ .await+ .map_err(|error| format!("recents task failed: {error}"))}/// Removes a project from the recents list. The folder itself is left alone.#[tauri::command]-fn forget_project(app: tauri::AppHandle, path: String) -> Result<(), String> {- projects::forget(&config_dir(&app)?, &path)+async fn forget_project(app: tauri::AppHandle, path: String) -> Result<(), String> {+ let config = config_dir(&app)?;+ tauri::async_runtime::spawn_blocking(move || projects::forget(&config, &path))+ .await+ .map_err(|error| format!("forget task failed: {error}"))?}/// The template library, for the gallery.#[tauri::command]-fn template_list(app: tauri::AppHandle) -> Result<Vec<templates::TemplateInfo>, String> {- Ok(templates::list(&config_dir(&app)?))+async fn template_list(app: tauri::AppHandle) -> Result<Vec<templates::TemplateInfo>, String> {+ let config = config_dir(&app)?;+ tauri::async_runtime::spawn_blocking(move || templates::list(&config))+ .await+ .map_err(|error| format!("template list task failed: {error}"))}/// Packs the open project into a new template bundle.@@ -469,14 +497,20 @@ async fn template_instantiate(/// Removes one template bundle for good.#[tauri::command]-fn template_delete(app: tauri::AppHandle, path: String) -> Result<(), String> {- templates::delete(&config_dir(&app)?, &path)+async fn template_delete(app: tauri::AppHandle, path: String) -> Result<(), String> {+ let config = config_dir(&app)?;+ tauri::async_runtime::spawn_blocking(move || templates::delete(&config, &path))+ .await+ .map_err(|error| format!("template delete task failed: {error}"))?}/// A template's poster, or an error the UI treats as "no art".#[tauri::command]-fn template_poster(path: String) -> Result<tauri::ipc::Response, String> {- templates::poster(&path).map(tauri::ipc::Response::new)+async fn template_poster(path: String) -> Result<tauri::ipc::Response, String> {+ tauri::async_runtime::spawn_blocking(move || templates::poster(&path))+ .await+ .map_err(|error| format!("poster task failed: {error}"))?+ .map(tauri::ipc::Response::new)}fn config_dir(app: &tauri::AppHandle) -> Result<std::path::PathBuf, String> {@@ -486,8 +520,10 @@ fn config_dir(app: &tauri::AppHandle) -> Result<std::path::PathBuf, String> {.map_err(|error| format!("could not locate the config directory: {error}"))}-/// The stop flag for the one export that can run at a time.-struct ExportState(std::sync::Arc<std::sync::atomic::AtomicBool>);+/// The slot for the one export that can run at a time - enforced, not+/// documented: a second `export_project` while one runs is refused instead of+/// racing the first for its temp files and cancel flag.+struct ExportState(std::sync::Arc<jobs::SingleFlight>);/// The reader pool behind the paused monitor's true frames. One pool for the/// app's lifetime: its whole value is what stays warm between scrubs.@@ -527,9 +563,8 @@ async fn export_project(state: tauri::State<'_, ExportState>,request: export::ExportRequest,) -> Result<String, String> {- let cancel = std::sync::Arc::clone(&state.0);- cancel.store(false, std::sync::atomic::Ordering::Relaxed);- tauri::async_runtime::spawn_blocking(move || export::run(&app, request, &cancel))+ let job = state.0.begin("export")?;+ tauri::async_runtime::spawn_blocking(move || export::run(&app, request, job.cancel_flag())).await.map_err(|error| format!("export task failed: {error}"))?}@@ -537,7 +572,7 @@ async fn export_project(/// Asks the running export to stop at the next frame. Idle is a harmless no-op.#[tauri::command]fn cancel_export(state: tauri::State<'_, ExportState>) {- state.0.store(true, std::sync::atomic::Ordering::Relaxed);+ state.0.cancel();}/// Flattens an error and its causes into one line.@@ -607,15 +642,11 @@ pub fn run() {use tauri::Manager;use_bundled_ffmpeg(app);app.manage(playback::Playback::start(app.handle().clone()));- app.manage(ExportState(std::sync::Arc::new(- std::sync::atomic::AtomicBool::new(false),- )));+ app.manage(ExportState(std::sync::Arc::new(jobs::SingleFlight::new())));app.manage(transcribe::DownloadState(std::sync::Arc::new(- std::sync::atomic::AtomicBool::new(false),- )));- app.manage(transcribe::TranscribeState(std::sync::Arc::new(- std::sync::Mutex::new(None),+ jobs::SingleFlight::new(),)));+ app.manage(transcribe::TranscribeState::new());app.manage(editor_api::EditorState(std::sync::Mutex::new(None)));app.manage(PoolState(std::sync::Arc::new(std::sync::Mutex::new(wolfcut_media::ReaderPool::with_defaults(),diff --git a/desktop/src-tauri/src/transcribe.rs b/desktop/src-tauri/src/transcribe.rsindex 70d267db..4bc9bc5d 100644--- a/desktop/src-tauri/src/transcribe.rs+++ b/desktop/src-tauri/src/transcribe.rs@@ -27,12 +27,14 @@use std::io::Read;use std::path::{Path, PathBuf};use std::process::{Child, Command, Stdio};-use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::atomic::Ordering;use std::sync::{Arc, Mutex};use serde::Serialize;use tauri::{Emitter, Manager};+use crate::jobs::SingleFlight;+/// One downloadable Whisper model. Sizes are approximate, for progress bars/// when the server declines to send a Content-Length.struct KnownModel {@@ -262,8 +264,10 @@ struct DownloadProgress {done: bool,}-/// The stop flag for the one model download that can run at a time.-pub struct DownloadState(pub Arc<AtomicBool>);+/// The slot for the one model download that can run at a time. Enforced by+/// `SingleFlight`: a second download is refused rather than sharing (and+/// resetting) the first one's cancel flag.+pub struct DownloadState(pub Arc<SingleFlight>);/// Streams one model from Hugging Face into the models folder.///@@ -276,17 +280,25 @@ pub async fn download_transcriber_model(state: tauri::State<'_, DownloadState>,id: String,) -> Result<(), String> {- let cancel = Arc::clone(&state.0);- cancel.store(false, Ordering::Relaxed);+ let job = state.0.begin("model download")?;tauri::async_runtime::spawn_blocking(move || {+ let cancel = job.cancel_flag();let destination = model_file(&app, &id)?;if destination.is_file() {return Ok(());}let estimate = known(&id).map(|model| model.approx_bytes).unwrap_or(0);- let response = ureq::get(&model_url(&id))+ // A read timeout, or a stalled connection blocks in `read` forever+ // with the cancel flag unreachable - the flag is only checked between+ // reads. Thirty seconds without a byte means the download is dead.+ let agent = ureq::AgentBuilder::new()+ .timeout_connect(std::time::Duration::from_secs(20))+ .timeout_read(std::time::Duration::from_secs(30))+ .build();+ let response = agent+ .get(&model_url(&id)).call().map_err(|error| format!("download failed: {error}"))?;let total = response@@ -345,7 +357,7 @@ pub async fn download_transcriber_model(/// Asks the running download to stop. Idle is a harmless no-op.#[tauri::command]pub fn cancel_model_download(state: tauri::State<'_, DownloadState>) {- state.0.store(true, Ordering::Relaxed);+ state.0.cancel();}/// Removes a downloaded model file.@@ -365,8 +377,24 @@ pub struct Segment {text: String,}-/// The child being run, so a cancel can kill it mid-transcription.-pub struct TranscribeState(pub Arc<Mutex<Option<Child>>>);+/// The one transcription that can run at a time: a gate that refuses a+/// second concurrent run, and the child being run so a cancel can kill it+/// mid-transcription. Without the gate, a second `transcribe_clip` used to+/// overwrite the child slot - orphaning the first child unkilled and unwaited+/// while both wait loops polled the second.+pub struct TranscribeState {+ gate: Arc<SingleFlight>,+ child: Arc<Mutex<Option<Child>>>,+}++impl TranscribeState {+ pub fn new() -> Self {+ Self {+ gate: Arc::new(SingleFlight::new()),+ child: Arc::new(Mutex::new(None)),+ }+ }+}/// Runs `command`, parking the child in `slot` so `cancel_transcribe` can/// reach it, and waits for it to finish.@@ -462,16 +490,21 @@ pub async fn transcribe_clip(state: tauri::State<'_, TranscribeState>,request: TranscribeRequest,) -> Result<Vec<Segment>, String> {- let slot = Arc::clone(&state.0);- tauri::async_runtime::spawn_blocking(move || run_transcription(&app, &slot, &request))- .await- .map_err(|error| format!("transcribe task failed: {error}"))?+ let job = state.gate.begin("transcription")?;+ let slot = Arc::clone(&state.child);+ tauri::async_runtime::spawn_blocking(move || {+ let result = run_transcription(&app, &slot, &request);+ drop(job);+ result+ })+ .await+ .map_err(|error| format!("transcribe task failed: {error}"))?}/// Kills the running transcription's child process, if any.#[tauri::command]pub fn cancel_transcribe(state: tauri::State<'_, TranscribeState>) {- let mut guard = state.0.lock().expect("transcribe slot poisoned");+ let mut guard = state.child.lock().expect("transcribe slot poisoned");if let Some(mut child) = guard.take() {let _ = child.kill();let _ = child.wait();@@ -493,7 +526,8 @@ fn run_transcription(request.model_id));}- if !(request.window > 0.0) {+ // NaN is refused along with zero and negative windows.+ if request.window.is_nan() || request.window <= 0.0 {return Err("nothing to transcribe: the clip covers no time".to_owned());}