Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(gpui): recover interrupted recordings and guard background work
Richie McIlroya50880ff7bc1
diff --git a/apps/desktop-gpui/src/library.rs b/apps/desktop-gpui/src/library.rsindex a4eaceda7..e98b5f218 100644--- a/apps/desktop-gpui/src/library.rs+++ b/apps/desktop-gpui/src/library.rs@@ -33,6 +33,7 @@ use cap_project::{InstantRecordingMeta, RecordingMeta, RecordingMetaInner, StudioRecordingMeta,StudioRecordingStatus,};+use cap_recording::recovery::RecoveryManager;use gpui::RenderImage;use image::buffer::ConvertBuffer as _;@@ -286,6 +287,14 @@ pub struct RecordingItem {pub thumbnail: Option<PathBuf>,}+#[derive(Debug, Clone, PartialEq)]+pub struct IncompleteRecordingItem {+ pub project_path: PathBuf,+ pub pretty_name: String,+ pub segment_count: usize,+ pub estimated_duration_secs: f64,+}+impl RecordingItem {/// `hasActiveRecording` (`recordings.tsx:66-73`) minus its upload half:/// there are no uploads in this app, so `MultipartUpload` /@@ -395,6 +404,112 @@ pub fn list_recordings() -> Vec<RecordingItem> {list_recordings_in(&known_recordings_dirs())}+pub fn find_incomplete_recordings_in(+ dirs: &[PathBuf],+ active_recording: Option<&Path>,+) -> Vec<IncompleteRecordingItem> {+ list_recordings_in(dirs)+ .into_iter()+ .filter(|item| {+ item.mode == RecordingMode::Studio+ && matches!(+ item.status,+ RecordingStatus::InProgress | RecordingStatus::NeedsRemux+ )+ && active_recording != Some(item.path.as_path())+ && is_recording_after_recovery_cutoff(&item.pretty_name)+ })+ .filter_map(|item| {+ let incomplete = RecoveryManager::inspect_recording(&item.path)?;+ (!incomplete.recoverable_segments.is_empty()).then_some(IncompleteRecordingItem {+ project_path: item.path,+ pretty_name: item.pretty_name,+ segment_count: incomplete.recoverable_segments.len(),+ estimated_duration_secs: incomplete.estimated_duration.as_secs_f64(),+ })+ })+ .collect()+}++pub fn find_incomplete_recordings() -> Vec<IncompleteRecordingItem> {+ find_incomplete_recordings_in(&known_recordings_dirs(), None)+}++fn is_recording_after_recovery_cutoff(pretty_name: &str) -> bool {+ let Some(date) = pretty_name+ .strip_prefix("Cap ")+ .and_then(|name| name.split(" at ").next())+ .and_then(|value| chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d").ok())+ else {+ return false;+ };++ chrono::NaiveDate::from_ymd_opt(2025, 12, 31).is_some_and(|cutoff| date > cutoff)+}++pub fn recover_incomplete_recording(project_path: &Path) -> Result<PathBuf, String> {+ recover_incomplete_recording_in(&known_recordings_dirs(), project_path)+}++fn recover_incomplete_recording_in(+ dirs: &[PathBuf],+ project_path: &Path,+) -> Result<PathBuf, String> {+ if project_path+ .components()+ .any(|component| matches!(component, std::path::Component::ParentDir))+ || !dirs.iter().any(|dir| project_path.starts_with(dir))+ {+ return Err("Path is not inside a recordings directory".to_string());+ }++ let canonical_path = project_path+ .canonicalize()+ .map_err(|error| format!("Failed to resolve recording path: {error}"))?;+ if !dirs.iter().any(|dir| {+ dir.canonicalize()+ .is_ok_and(|canonical_dir| canonical_path.starts_with(canonical_dir))+ }) {+ return Err("Path is not inside a recordings directory".to_string());+ }++ let meta = RecordingMeta::load_for_project(&canonical_path)+ .map_err(|error| format!("Failed to load recording metadata: {error}"))?;+ let Some(studio) = meta.studio_meta() else {+ return Err("Only incomplete studio recordings can be recovered".to_string());+ };+ if !matches!(+ studio.status(),+ StudioRecordingStatus::InProgress | StudioRecordingStatus::NeedsRemux+ ) {+ return Err("Recording is not waiting for recovery".to_string());+ }++ let incomplete = RecoveryManager::inspect_recording(&canonical_path)+ .ok_or_else(|| "No recoverable segments found".to_string())?;+ let recovered = RecoveryManager::recover(&incomplete)+ .map_err(|error| format!("Failed to recover recording: {error}"))?;+ let display = match &recovered.meta {+ StudioRecordingMeta::SingleSegment { segment } => {+ segment.display.path.to_path(&recovered.project_path)+ }+ StudioRecordingMeta::MultipleSegments { inner } => inner+ .segments+ .first()+ .map(|segment| segment.display.path.to_path(&recovered.project_path))+ .ok_or_else(|| "Recovered recording has no display segments".to_string())?,+ };+ if let Err(error) = create_screenshot(+ &display,+ &bundle_thumbnail_path(&recovered.project_path),+ None,+ ) {+ tracing::warn!(path = %recovered.project_path.display(), %error, "failed to create recovered recording thumbnail");+ }++ Ok(recovered.project_path)+}+/// `delete_recording_directory` (`lib.rs:4001-4046`), guards verbatim.////// Three of them, and each one covers a hole the others leave:@@ -697,6 +812,19 @@ pub fn spawn_decode_pool<J, R>(jobs: Vec<J>,decode: impl Fn(J) -> Option<R> + Send + Sync + Clone + 'static,) -> (Vec<gpui::Task<()>>, flume::Receiver<R>)+where+ J: Send + 'static,+ R: Send + 'static,+{+ spawn_decode_pool_limited(executor, jobs, MAX_DECODE_WORKERS, decode)+}++pub fn spawn_decode_pool_limited<J, R>(+ executor: &gpui::BackgroundExecutor,+ jobs: Vec<J>,+ max_workers: usize,+ decode: impl Fn(J) -> Option<R> + Send + Sync + Clone + 'static,+) -> (Vec<gpui::Task<()>>, flume::Receiver<R>)whereJ: Send + 'static,R: Send + 'static,@@ -710,7 +838,7 @@ wherelet (result_tx, result_rx) = flume::unbounded();let workers = std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get)- .min(MAX_DECODE_WORKERS)+ .min(max_workers.max(1)).min(job_rx.len().max(1));let tasks = (0..workers).map(|_| {@@ -1367,6 +1495,181 @@ mod tests {std::fs::remove_dir_all(&root).ok();}+ fn write_incomplete_bundle(+ recordings: &Path,+ name: &str,+ pretty_name: &str,+ status: &str,+ fragments: bool,+ ) -> PathBuf {+ let bundle = write_bundle(+ recordings,+ name,+ &format!(+ r#"{{"pretty_name":"{pretty_name}","sharing":null,"segments":[],"status":{{"status":"{status}"}}}}"#+ ),+ );+ if fragments {+ let display = bundle.join("content/segments/segment-0/display");+ std::fs::create_dir_all(&display).unwrap();+ std::fs::write(display.join("init.mp4"), vec![0u8; 128]).unwrap();+ std::fs::write(display.join("segment_001.m4s"), vec![1u8; 256]).unwrap();+ std::fs::write(+ display.join("manifest.json"),+ serde_json::to_vec(&serde_json::json!({+ "version": 5,+ "type": "m4s_segments",+ "init_segment": "init.mp4",+ "segments": [{+ "path": "segment_001.m4s",+ "is_complete": true,+ "file_size": 256+ }]+ }))+ .unwrap(),+ )+ .unwrap();+ }+ bundle+ }++ #[test]+ fn recovery_scan_preserves_active_terminal_legacy_and_unrecoverable_recordings() {+ let _ = ffmpeg::init();+ let root = temp_dir("recovery-scan");+ let recordings = root.join("recordings");+ std::fs::create_dir_all(&recordings).unwrap();+ let eligible = write_incomplete_bundle(+ &recordings,+ "eligible",+ "Cap 2026-01-02 at 10.00.00",+ "InProgress",+ true,+ );+ let active = write_incomplete_bundle(+ &recordings,+ "active",+ "Cap 2026-01-03 at 10.00.00",+ "InProgress",+ true,+ );+ let remux = write_incomplete_bundle(+ &recordings,+ "remux",+ "Cap 2026-01-04 at 10.00.00",+ "NeedsRemux",+ true,+ );+ write_incomplete_bundle(+ &recordings,+ "legacy",+ "Cap 2025-12-31 at 10.00.00",+ "InProgress",+ true,+ );+ write_incomplete_bundle(+ &recordings,+ "terminal",+ "Cap 2026-01-05 at 10.00.00",+ "Complete",+ true,+ );+ let corrupt = write_incomplete_bundle(+ &recordings,+ "unrecoverable",+ "Cap 2026-01-06 at 10.00.00",+ "InProgress",+ false,+ );+ let corrupt_before = std::fs::read(corrupt.join("recording-meta.json")).unwrap();++ let found = find_incomplete_recordings_in(+ std::slice::from_ref(&recordings),+ Some(active.as_path()),+ );++ assert_eq!(found.len(), 2);+ assert!(found.iter().any(|item| item.project_path == eligible));+ assert!(found.iter().any(|item| item.project_path == remux));+ assert!(found.iter().all(|item| item.segment_count == 1));+ assert_eq!(+ std::fs::read(corrupt.join("recording-meta.json")).unwrap(),+ corrupt_before+ );+ assert!(active.exists());++ std::fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn recovery_rejects_paths_outside_the_recording_library() {+ let root = temp_dir("recovery-path");+ let recordings = root.join("recordings");+ let elsewhere = root.join("elsewhere");+ std::fs::create_dir_all(&recordings).unwrap();+ std::fs::create_dir_all(&elsewhere).unwrap();++ let result = recover_incomplete_recording_in(std::slice::from_ref(&recordings), &elsewhere);++ assert_eq!(+ result,+ Err("Path is not inside a recordings directory".to_string())+ );+ assert!(elsewhere.is_dir());++ std::fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn recovery_restores_interrupted_real_recording_when_fixture_is_provided() {+ let Ok(source) = std::env::var("CAP_GPUI_RECOVERY_FIXTURE") else {+ return;+ };+ let _ = ffmpeg::init();+ let source = PathBuf::from(source);+ let root = temp_dir("recovery-real");+ let recordings = root.join("recordings");+ let copy = recordings.join("interrupted.cap");+ std::fs::create_dir_all(©).unwrap();++ let mut pending = vec![(source, copy.clone())];+ while let Some((from, to)) = pending.pop() {+ for entry in std::fs::read_dir(from).unwrap() {+ let entry = entry.unwrap();+ let destination = to.join(entry.file_name());+ if entry.file_type().unwrap().is_dir() {+ std::fs::create_dir_all(&destination).unwrap();+ pending.push((entry.path(), destination));+ } else {+ std::fs::copy(entry.path(), destination).unwrap();+ }+ }+ }++ let dirs = std::slice::from_ref(&recordings);+ let found = find_incomplete_recordings_in(dirs, None);+ assert_eq!(found.len(), 1);+ assert_eq!(found[0].segment_count, 1);++ let recovered = recover_incomplete_recording_in(dirs, ©).unwrap();+ let meta = RecordingMeta::load_for_project(&recovered).unwrap();++ assert!(matches!(+ meta.studio_meta().unwrap().status(),+ StudioRecordingStatus::Complete+ ));+ assert!(+ recovered+ .join("content/segments/segment-0/display.mp4")+ .is_file()+ );+ assert!(recovered.join("project-config.json").is_file());+ assert!(bundle_thumbnail_path(&recovered).is_file());+ assert!(find_incomplete_recordings_in(dirs, None).is_empty());++ std::fs::remove_dir_all(root).unwrap();+ }+/// The three `delete_recording_directory` guards, one test each.#[test]fn delete_rejects_traversal_paths_outside_and_symlink_escapes() {@@ -1400,6 +1703,8 @@ mod tests {let escape = recordings.join("escape.cap");#[cfg(unix)]std::os::unix::fs::symlink(&victim, &escape).unwrap();+ #[cfg(windows)]+ std::os::windows::fs::symlink_dir(&victim, &escape).unwrap();assert_eq!(delete_recording_directory_in(&dirs, &escape),Err("Path is not inside a recordings directory".to_string()),diff --git a/apps/desktop-gpui/src/transcription.rs b/apps/desktop-gpui/src/transcription.rsindex ab4fef840..4f27fe594 100644--- a/apps/desktop-gpui/src/transcription.rs+++ b/apps/desktop-gpui/src/transcription.rs@@ -155,6 +155,16 @@ struct Hub {generation_errors: HashMap<PathBuf, String>,}+impl Hub {+ fn work_in_flight(&self) -> bool {+ self.download+ .as_ref()+ .is_some_and(|download| download.state == DownloadState::Downloading)+ || !self.generating.is_empty()+ || self.deleting.is_some()+ }+}+static HUB: LazyLock<Mutex<Hub>> = LazyLock::new(|| Mutex::new(Hub::default()));fn hub() -> std::sync::MutexGuard<'static, Hub> {@@ -188,6 +198,10 @@ pub fn download_active() -> bool {.is_some_and(|download| download.state == DownloadState::Downloading)}+pub fn work_in_flight() -> bool {+ hub().work_in_flight()+}+/// Rescan the catalogue against the disk -- `refreshDownloadedModels`/// (`CaptionsTab.tsx:481-492`), minus the async round-trips.pub fn refresh_downloaded_models() {@@ -450,6 +464,7 @@ async fn total_content_length(urls: &[&str]) -> u64 {}/// `PARAKEET_TDT_INT8_MODEL_FILES` (`captions.rs:2249-2268`).+#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]const PARAKEET_TDT_INT8_MODEL_FILES: &[(&str, &[&str])] = &[("encoder-model.int8.onnx",@@ -472,6 +487,7 @@ const PARAKEET_TDT_INT8_MODEL_FILES: &[(&str, &[&str])] = &[];/// `PARAKEET_TDT_FULL_MODEL_FILES` (`captions.rs:2270-2296`).+#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]const PARAKEET_TDT_FULL_MODEL_FILES: &[(&str, &[&str])] = &[("encoder-model.onnx",@@ -501,6 +517,7 @@ const PARAKEET_TDT_FULL_MODEL_FILES: &[(&str, &[&str])] = &[];/// `PARAKEET_MODEL_CLEANUP_FILES` (`captions.rs:2298-2306`).+#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]const PARAKEET_MODEL_CLEANUP_FILES: &[&str] = &["encoder-model.onnx","encoder-model.onnx.data",@@ -512,6 +529,7 @@ const PARAKEET_MODEL_CLEANUP_FILES: &[&str] = &[];/// `PARAKEET_KNOWN_PART_SIZES` (`captions.rs:2308-2316`).+#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]const PARAKEET_KNOWN_PART_SIZES: &[(&str, u64)] = &[("encoder-model.int8.onnx", 652_183_999),("decoder_joint-model.int8.onnx", 18_202_004),@@ -522,12 +540,14 @@ const PARAKEET_KNOWN_PART_SIZES: &[(&str, u64)] = &[("vocab.txt", 93_939),];+#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]fn parakeet_known_part_size(url: &str) -> Option<u64> {PARAKEET_KNOWN_PART_SIZES.iter().find_map(|(name, size)| url.ends_with(name).then_some(*size))}+#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]fn parakeet_model_files_for_dir(output_dir: &Path,) -> &'static [(&'static str, &'static [&'static str])] {@@ -537,6 +557,7 @@ fn parakeet_model_files_for_dir(}}+#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]fn parakeet_staging_dir(validated_dir: &Path) -> PathBuf {validated_dir.with_file_name(format!("{}.downloading",@@ -547,6 +568,7 @@ fn parakeet_staging_dir(validated_dir: &Path) -> PathBuf {))}+#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]async fn parakeet_model_file_sizes(model_files: &'static [(&'static str, &'static [&'static str])],) -> Result<Vec<(&'static str, u64)>, String> {@@ -580,6 +602,7 @@ async fn parakeet_model_file_sizes(Ok(sizes)}+#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]fn parakeet_model_files_match(dir: &Path, expected_files: &[(&str, u64)]) -> bool {expected_files.iter().all(|(filename, expected_size)| {let Ok(metadata) = std::fs::metadata(dir.join(filename)) else {@@ -589,6 +612,7 @@ fn parakeet_model_files_match(dir: &Path, expected_files: &[(&str, u64)]) -> boo})}+#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]fn finalize_parakeet_model_download(validated_dir: &Path,staging_dir: &Path,@@ -2401,6 +2425,30 @@ mod tests {assert_eq!(model_path("medium"), base.join("medium.bin"));}+ #[test]+ fn downloads_generation_and_deletion_block_application_handoffs() {+ let mut state = Hub::default();+ assert!(!state.work_in_flight());++ state.download = Some(ModelDownload {+ model: "small".to_string(),+ state: DownloadState::Downloading,+ progress: 25.0,+ message: "Downloading".to_string(),+ });+ assert!(state.work_in_flight());++ state.download.as_mut().unwrap().state = DownloadState::Completed;+ assert!(!state.work_in_flight());++ state.generating.insert(PathBuf::from("/tmp/recording.cap"));+ assert!(state.work_in_flight());+ state.generating.clear();++ state.deleting = Some("small".to_string());+ assert!(state.work_in_flight());+ }+#[test]fn source_caption_id_strips_the_edl_suffix() {assert_eq!(source_caption_id("segment-0-1"), "segment-0-1");diff --git a/crates/recording/src/recovery.rs b/crates/recording/src/recovery.rsindex b754bac01..13dfc6734 100644--- a/crates/recording/src/recovery.rs+++ b/crates/recording/src/recovery.rs@@ -1383,9 +1383,7 @@ impl RecoveryManager {None},mic: {- let mic_size = std::fs::metadata(&mic_path).map(|m| m.len()).unwrap_or(0);- const MIN_VALID_AUDIO_SIZE: u64 = 500;- if mic_path.exists() && mic_size > MIN_VALID_AUDIO_SIZE {+ if valid_recovered_audio(&mic_path) {Some(AudioMeta {path: RelativePathBuf::from(format!("{segment_base}/audio-input.ogg"@@ -1405,11 +1403,7 @@ impl RecoveryManager {}},system_audio: {- let file_size = std::fs::metadata(&system_audio_path)- .map(|m| m.len())- .unwrap_or(0);- const MIN_VALID_AUDIO_SIZE: u64 = 500;- if system_audio_path.exists() && file_size > MIN_VALID_AUDIO_SIZE {+ if valid_recovered_audio(&system_audio_path) {Some(AudioMeta {path: RelativePathBuf::from(format!("{segment_base}/system_audio.ogg"@@ -1658,6 +1652,10 @@ fn start_time_or_display_fallback(original_time.or(display_start_time)}+fn valid_recovered_audio(path: &Path) -> bool {+ path.is_file() && probe_media_valid(path)+}+fn replace_file(src: &Path, dst: &Path) -> Result<(), RecoveryError> {if dst.exists() {std::fs::remove_file(dst).map_err(RecoveryError::Io)?;@@ -1668,7 +1666,7 @@ fn replace_file(src: &Path, dst: &Path) -> Result<(), RecoveryError> {#[cfg(test)]mod tests {- use super::{replace_file, start_time_or_display_fallback};+ use super::{replace_file, start_time_or_display_fallback, valid_recovered_audio};use std::fs;use tempfile::tempdir;@@ -1687,6 +1685,40 @@ mod tests {assert!(!src.exists());}+ #[test]+ fn recovered_audio_keeps_valid_media_smaller_than_legacy_threshold() {+ let dir = tempdir().unwrap();+ let path = dir.path().join("quiet.wav");+ let samples = [0u8; 32];+ let mut bytes = Vec::new();+ bytes.extend_from_slice(b"RIFF");+ bytes.extend_from_slice(&(36 + samples.len() as u32).to_le_bytes());+ bytes.extend_from_slice(b"WAVEfmt ");+ bytes.extend_from_slice(&16u32.to_le_bytes());+ bytes.extend_from_slice(&1u16.to_le_bytes());+ bytes.extend_from_slice(&1u16.to_le_bytes());+ bytes.extend_from_slice(&8000u32.to_le_bytes());+ bytes.extend_from_slice(&16000u32.to_le_bytes());+ bytes.extend_from_slice(&2u16.to_le_bytes());+ bytes.extend_from_slice(&16u16.to_le_bytes());+ bytes.extend_from_slice(b"data");+ bytes.extend_from_slice(&(samples.len() as u32).to_le_bytes());+ bytes.extend_from_slice(&samples);+ fs::write(&path, &bytes).unwrap();++ assert!(bytes.len() < 500);+ assert!(valid_recovered_audio(&path));+ }++ #[test]+ fn recovered_audio_rejects_large_corrupt_media() {+ let dir = tempdir().unwrap();+ let path = dir.path().join("corrupt.ogg");+ fs::write(&path, [0u8; 1024]).unwrap();++ assert!(!valid_recovered_audio(&path));+ }+#[test]fn start_time_fallback_prefers_original_value() {let original = Some(0.8);