From 73252b5a7123699ceab4a7128365bf9345c21f84 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:35:43 +0000 Subject: [PATCH 01/19] feat(recording): report what a stopping Windows Studio recording is doing --- .../workflows/windows-recording-encoder.yml | 2 + crates/recording/src/lib.rs | 2 + .../src/output_pipeline/win_fragmented_m4s.rs | 42 +- crates/recording/src/stop_progress.rs | 576 ++++++++++++++++++ 4 files changed, 613 insertions(+), 9 deletions(-) create mode 100644 crates/recording/src/stop_progress.rs diff --git a/.github/workflows/windows-recording-encoder.yml b/.github/workflows/windows-recording-encoder.yml index 3a0f2b26fc8..689091f0496 100644 --- a/.github/workflows/windows-recording-encoder.yml +++ b/.github/workflows/windows-recording-encoder.yml @@ -15,6 +15,7 @@ on: - "crates/recording/src/output_pipeline/win_fragmented_m4s.rs" - "crates/recording/src/output_pipeline/core.rs" - "crates/recording/src/studio_recording.rs" + - "crates/recording/src/stop_progress.rs" - "crates/recording/src/recovery.rs" - "Cargo.lock" - ".github/workflows/windows-recording-encoder.yml" @@ -28,6 +29,7 @@ on: - "crates/recording/src/output_pipeline/win_fragmented_m4s.rs" - "crates/recording/src/output_pipeline/core.rs" - "crates/recording/src/studio_recording.rs" + - "crates/recording/src/stop_progress.rs" - "crates/recording/src/recovery.rs" - "Cargo.lock" - ".github/workflows/windows-recording-encoder.yml" diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rs index 56ab1cfdb1a..fd3d3821f82 100644 --- a/crates/recording/src/lib.rs +++ b/crates/recording/src/lib.rs @@ -16,6 +16,8 @@ pub mod recovery; mod resolution_limits; pub mod screenshot; pub mod sources; +#[cfg(windows)] +mod stop_progress; pub mod studio_recording; pub mod sync_calibration; pub mod track_heal; diff --git a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs index 808733afb54..3a4c8edd939 100644 --- a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs +++ b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs @@ -9,6 +9,7 @@ use crate::{ AudioFrame, AudioMuxer, Muxer, SharedPauseState, TaskPool, VideoMuxer, output_pipeline::{NativeCameraFrame, camera_frame_to_ffmpeg}, screen_capture, + stop_progress::StopProgress, }; use anyhow::{Context, anyhow}; use cap_enc_ffmpeg::h264::{H264EncoderBuilder, H264Preset}; @@ -150,19 +151,34 @@ const ENCODER_FINISH_LIMIT: Duration = Duration::from_secs(5); /// waits for the encoder thread however long it takes, so a slow encoder is /// finalized instead of abandoned while still writing. #[derive(Clone, Debug, Default)] -pub struct EncoderFinishWait(Arc); +pub struct EncoderFinishWait { + without_limit: Arc, + progress: StopProgress, +} impl EncoderFinishWait { pub fn wait_without_limit(&self) { - self.0.store(true, Ordering::Release); + self.without_limit.store(true, Ordering::Release); + } + + /// What the encoders of this recording report while they stop. + pub(crate) fn progress(&self) -> &StopProgress { + &self.progress } fn limit(wait: Option<&Self>) -> Duration { match wait { - Some(wait) if wait.0.load(Ordering::Acquire) => Duration::MAX, + Some(wait) if wait.without_limit.load(Ordering::Acquire) => Duration::MAX, _ => ENCODER_FINISH_LIMIT, } } + + fn watch_packets(wait: Option<&Self>, encoder: &SegmentedVideoEncoder) { + if let Some(wait) = wait { + wait.progress + .watch_packets(encoder.packets_written_counter()); + } + } } fn finish_encoder_thread( @@ -280,8 +296,10 @@ fn finish_segmented_encoder_impl( thread_label: &str, finish_label: &str, health_tx: &SharedHealthSender, - limit: Duration, + wait: Option<&EncoderFinishWait>, ) -> anyhow::Result<()> { + let limit = EncoderFinishWait::limit(wait); + let progress = wait.map(EncoderFinishWait::progress); state.close_channel(thread_label); let thread_result = state @@ -295,9 +313,14 @@ fn finish_segmented_encoder_impl( BlockingThreadFinish::TimedOut(error) => return Err(error), }; + let storage_stage = progress.map(|progress| { + progress.step(); + progress.storage_stage(thread_label) + }); let finalize_error = state .finish_encoder(timestamp, finish_label, health_tx, limit) .err(); + drop(storage_stage); match (thread_error, finalize_error) { (None, None) => Ok(()), @@ -439,7 +462,7 @@ impl Muxer for WindowsFragmentedM4SMuxer { "Windows M4S encoder", "Failed to finish segmented encoder", &self.health_tx, - EncoderFinishWait::limit(self.finish_wait.as_ref()), + self.finish_wait.as_ref(), ) { return Ok(Err(error)); @@ -491,6 +514,7 @@ impl WindowsFragmentedM4SMuxer { if let Some(tx) = self.segment_tx.take() { encoder.set_segment_callback(tx); } + EncoderFinishWait::watch_packets(self.finish_wait.as_ref(), &encoder); let encoder = Arc::new(Mutex::new(encoder)); let encoder_clone = encoder.clone(); @@ -879,7 +903,7 @@ impl Muxer for WindowsFragmentedM4SCameraMuxer { "Windows M4S camera encoder", "Failed to finish camera segmented encoder", &self.health_tx, - EncoderFinishWait::limit(self.finish_wait.as_ref()), + self.finish_wait.as_ref(), ) { return Ok(Err(error)); @@ -970,6 +994,7 @@ impl WindowsFragmentedM4SCameraMuxer { { warn!(%error, "Camera segment bookkeeping thread unavailable, keeping it on the encoder thread"); } + EncoderFinishWait::watch_packets(self.finish_wait.as_ref(), &encoder); let encoder = Arc::new(Mutex::new(encoder)); let encoder_clone = encoder.clone(); @@ -1286,8 +1311,7 @@ mod tests { fn late_stop_still_ends_promptly_when_the_encoder_thread_died() { let wait = EncoderFinishWait::default(); wait.wait_without_limit(); - let limit = EncoderFinishWait::limit(Some(&wait)); - assert_eq!(limit, Duration::MAX); + assert_eq!(EncoderFinishWait::limit(Some(&wait)), Duration::MAX); let failed = std::thread::spawn(|| Err(anyhow::anyhow!("encoder failed"))); let panicked = std::thread::spawn(|| -> anyhow::Result<()> { panic!("encoder panicked") }); for (thread, expected) in [(failed, "encoder failed"), (panicked, "panicked")] { @@ -1298,7 +1322,7 @@ mod tests { "test encoder", "Failed to finish test encoder", &SharedHealthSender::new(), - limit, + Some(&wait), ) .expect_err("an encoder thread that died must fail the finish"); assert!(started.elapsed() < Duration::from_secs(2)); diff --git a/crates/recording/src/stop_progress.rs b/crates/recording/src/stop_progress.rs new file mode 100644 index 00000000000..05820b7a903 --- /dev/null +++ b/crates/recording/src/stop_progress.rs @@ -0,0 +1,576 @@ +//! Tells a late Studio stop that is slow from one that is stuck. +//! +//! A stop whose tracks are still finishing at the stop limit is waited for. +//! That wait is only worth its time while the tracks are getting somewhere, +//! so the stop path reports what it does here and the waiter gives up once +//! nothing has moved for a while. + +use std::{ + path::{Path, PathBuf}, + sync::{ + Arc, Mutex, PoisonError, + atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, + }, + time::{Duration, Instant, SystemTime}, +}; + +const SAMPLE_INTERVAL: Duration = Duration::from_secs(1); +const UNCHANGED_SAMPLES_FOR_A_STALL: u32 = 2; +/// In a folder with more files than this, only the newest are read one by +/// one: older segments are closed, and their listed size is final. +const FILES_READ_PER_FOLDER: usize = 16; + +/// What the tracks of one recording have done on their way to a stop. +#[derive(Clone, Debug, Default)] +pub(crate) struct StopProgress(Arc); + +#[derive(Debug, Default)] +struct Inner { + steps: AtomicU64, + storage_stages: AtomicU32, + packets: Mutex>>, + storage_held: Mutex>, + tracks_finished: AtomicBool, +} + +/// Held while a track's finish writes out what its encoder still holds and +/// then waits on storage (trailer, segment bookkeeping, fsync, manifest). A +/// file held open by a scan moves nothing in that time, on disk or in the +/// process, so the track counts as alive for as long as one of these exists. +pub(crate) struct StorageStage { + progress: StopProgress, + label: String, + started: Instant, +} + +impl Drop for StorageStage { + fn drop(&mut self) { + self.progress + .0 + .storage_held + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push((std::mem::take(&mut self.label), self.started.elapsed())); + self.progress + .0 + .storage_stages + .fetch_sub(1, Ordering::AcqRel); + self.progress.step(); + } +} + +impl StopProgress { + /// Counts every packet `written` gains as progress. + pub(crate) fn watch_packets(&self, written: Arc) { + self.0 + .packets + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(written); + } + + pub(crate) fn step(&self) { + self.0.steps.fetch_add(1, Ordering::AcqRel); + } + + pub(crate) fn storage_stage(&self, label: &str) -> StorageStage { + self.0.storage_stages.fetch_add(1, Ordering::AcqRel); + StorageStage { + progress: self.clone(), + label: label.to_string(), + started: Instant::now(), + } + } + + pub(crate) fn tracks_finished(&self) { + self.0.tracks_finished.store(true, Ordering::Release); + } + + fn are_tracks_finished(&self) -> bool { + self.0.tracks_finished.load(Ordering::Acquire) + } + + fn sample(&self) -> InProcess { + InProcess { + packets: self + .0 + .packets + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .map(|written| written.load(Ordering::Relaxed)) + .sum(), + steps: self.0.steps.load(Ordering::Acquire), + in_storage_stage: self.0.storage_stages.load(Ordering::Acquire) > 0, + } + } + + fn storage_held(&self) -> Vec<(String, Duration)> { + self.0 + .storage_held + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } + + /// Resolves once the tracks have shown no progress for `window`. Stays + /// pending for good once they finish, and when it cannot watch. + pub(crate) async fn stalled(&self, recording_dir: PathBuf, window: Duration) { + let (stalled_tx, stalled_rx) = tokio::sync::oneshot::channel(); + let progress = self.clone(); + let watcher = std::thread::Builder::new() + .name("studio-stop-progress".to_string()) + .spawn(move || watch(&progress, &recording_dir, window, stalled_tx)); + if let Err(error) = watcher { + tracing::warn!(%error, "Could not watch the progress of a late Studio stop"); + } else if stalled_rx.await.is_ok() { + return; + } + std::future::pending::<()>().await; + } +} + +/// Samples until the tracks stall or finish, or until nobody waits for the +/// answer. Runs on its own thread: reading the folder can block behind the +/// same file scans that hold the tracks up. +fn watch( + progress: &StopProgress, + recording_dir: &Path, + window: Duration, + stalled_tx: tokio::sync::oneshot::Sender<()>, +) { + let mut detector = StallDetector::new(window, Instant::now()); + let outcome = loop { + if progress.are_tracks_finished() { + break "finished"; + } + if stalled_tx.is_closed() { + break "abandoned"; + } + let folder = FolderSample::read(recording_dir); + if detector.observe(Instant::now(), progress.sample(), folder) { + break "stalled"; + } + std::thread::sleep(SAMPLE_INTERVAL); + }; + let quiet = detector.finish(Instant::now()); + tracing::info!( + path = %recording_dir.display(), + outcome, + samples = quiet.samples, + folder_unknown = quiet.folder_unknown, + longest_quiet_ms = quiet.overall.as_millis() as u64, + longest_quiet_outside_storage_stages_ms = quiet.outside_storage_stages.as_millis() as u64, + longest_quiet_packets_ms = quiet.packets.as_millis() as u64, + longest_quiet_steps_ms = quiet.steps.as_millis() as u64, + longest_quiet_folder_ms = quiet.folder.as_millis() as u64, + storage_stages = ?progress.storage_held(), + "Late Studio stop progress" + ); + if outcome == "stalled" { + let _ = stalled_tx.send(()); + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct InProcess { + packets: u64, + steps: u64, + in_storage_stage: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct FolderSample { + files: u64, + bytes: u64, + newest_modified: Option, +} + +impl FolderSample { + /// `None` when the folder could not be read: its state is unknown, which + /// is not the same as unchanged. + fn read(dir: &Path) -> Option { + let mut sample = Self { + files: 0, + bytes: 0, + newest_modified: None, + }; + sample.add_folder(dir).ok()?; + Some(sample) + } + + fn add_folder(&mut self, dir: &Path) -> std::io::Result<()> { + let mut files = Vec::new(); + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let listed = entry.metadata()?; + if listed.is_dir() { + self.add_folder(&entry.path())?; + } else { + files.push((entry.path(), listed)); + } + } + // A listing reports the size a file had when it was last closed, so a + // file still being written is read on its own. Only the newest files + // of a folder can still be open. + files.sort_by_key(|(_, listed)| std::cmp::Reverse(listed.created().ok())); + for (index, (path, listed)) in files.into_iter().enumerate() { + let metadata = if index < FILES_READ_PER_FOLDER { + match std::fs::metadata(&path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, + Err(error) => return Err(error), + } + } else { + listed + }; + self.files += 1; + self.bytes += metadata.len(); + self.newest_modified = self.newest_modified.max(metadata.modified().ok()); + } + Ok(()) + } +} + +/// The longest stretches without progress one watch saw, by source. +#[derive(Clone, Copy, Debug, Default)] +struct QuietGaps { + samples: u32, + folder_unknown: u32, + overall: Duration, + outside_storage_stages: Duration, + packets: Duration, + steps: Duration, + folder: Duration, +} + +struct Quiet { + since: Instant, + longest: Duration, +} + +impl Quiet { + fn new(at: Instant) -> Self { + Self { + since: at, + longest: Duration::ZERO, + } + } + + fn close(&mut self, at: Instant) { + self.longest = self.longest.max(at.saturating_duration_since(self.since)); + } + + fn moved(&mut self, at: Instant) { + self.close(at); + self.since = at; + } +} + +/// Decides a stall from samples. A stall takes a full window in which every +/// source was sampled and none moved, confirmed by at least +/// [`UNCHANGED_SAMPLES_FOR_A_STALL`] samples in a row equal to the one before +/// them. A sample that could not read the folder confirms nothing. +struct StallDetector { + window: Duration, + last: Option<(InProcess, FolderSample)>, + unchanged: u32, + overall: Quiet, + outside_storage_stages: Quiet, + packets: Quiet, + steps: Quiet, + folder: Quiet, + samples: u32, + folder_unknown: u32, + last_in_process: InProcess, +} + +impl StallDetector { + fn new(window: Duration, at: Instant) -> Self { + Self { + window, + last: None, + unchanged: 0, + overall: Quiet::new(at), + outside_storage_stages: Quiet::new(at), + packets: Quiet::new(at), + steps: Quiet::new(at), + folder: Quiet::new(at), + samples: 0, + folder_unknown: 0, + last_in_process: InProcess::default(), + } + } + + fn observe( + &mut self, + at: Instant, + in_process: InProcess, + folder: Option, + ) -> bool { + self.samples += 1; + let first = self.samples == 1; + let packets_moved = !first && in_process.packets != self.last_in_process.packets; + let steps_moved = !first && in_process.steps != self.last_in_process.steps; + self.last_in_process = in_process; + if packets_moved { + self.packets.moved(at); + } + if steps_moved { + self.steps.moved(at); + } + let folder_moved = match (folder, &self.last) { + (Some(folder), Some((_, last))) => folder != *last, + _ => false, + }; + if folder_moved { + self.folder.moved(at); + } + if packets_moved || steps_moved || folder_moved { + self.outside_storage_stages.moved(at); + } + if packets_moved || steps_moved || folder_moved || in_process.in_storage_stage { + self.overall.moved(at); + self.unchanged = 0; + } + + let Some(folder) = folder else { + self.folder_unknown += 1; + return false; + }; + let unchanged = self.last.replace((in_process, folder)) == Some((in_process, folder)) + && !in_process.in_storage_stage; + if !unchanged { + self.unchanged = 0; + return false; + } + self.unchanged += 1; + self.unchanged >= UNCHANGED_SAMPLES_FOR_A_STALL + && at.saturating_duration_since(self.overall.since) >= self.window + } + + fn finish(mut self, at: Instant) -> QuietGaps { + for quiet in [ + &mut self.overall, + &mut self.outside_storage_stages, + &mut self.packets, + &mut self.steps, + &mut self.folder, + ] { + quiet.close(at); + } + QuietGaps { + samples: self.samples, + folder_unknown: self.folder_unknown, + overall: self.overall.longest, + outside_storage_stages: self.outside_storage_stages.longest, + packets: self.packets.longest, + steps: self.steps.longest, + folder: self.folder.longest, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const WINDOW: Duration = Duration::from_secs(10); + + fn folder(bytes: u64) -> Option { + Some(FolderSample { + files: 3, + bytes, + newest_modified: None, + }) + } + + fn in_process(packets: u64, steps: u64) -> InProcess { + InProcess { + packets, + steps, + in_storage_stage: false, + } + } + + fn seconds(start: Instant, seconds: u64) -> Instant { + start + Duration::from_secs(seconds) + } + + #[test] + fn late_stop_stalls_after_a_window_in_which_nothing_moved() { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + for second in 0..10 { + assert!( + !detector.observe(seconds(start, second), in_process(7, 1), folder(100)), + "stalled after {second} s" + ); + } + assert!(detector.observe(seconds(start, 10), in_process(7, 1), folder(100))); + } + + #[test] + fn late_stop_stays_alive_while_any_one_source_moves() { + type Step = fn(u64) -> (InProcess, Option); + let sources: [Step; 4] = [ + |second| (in_process(second, 0), folder(100)), + |second| (in_process(0, second / 5), folder(100)), + |second| (in_process(0, 0), folder(100 + second / 8)), + |_| { + ( + InProcess { + in_storage_stage: true, + ..in_process(0, 0) + }, + folder(100), + ) + }, + ]; + for source in sources { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + for second in 0..600 { + let (in_process, folder) = source(second); + assert!(!detector.observe(seconds(start, second), in_process, folder)); + } + } + } + + #[test] + fn late_stop_is_not_stalled_by_one_late_sample() { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + assert!(!detector.observe(start, in_process(7, 1), folder(100))); + assert!(!detector.observe(seconds(start, 45), in_process(7, 1), folder(100))); + assert!(detector.observe(seconds(start, 46), in_process(7, 1), folder(100))); + } + + #[test] + fn late_stop_is_not_stalled_while_the_folder_cannot_be_read() { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + assert!(!detector.observe(start, in_process(7, 1), folder(100))); + for second in 1..300 { + assert!(!detector.observe(seconds(start, second), in_process(7, 1), None)); + } + assert!(!detector.observe(seconds(start, 300), in_process(7, 1), folder(100))); + assert!(detector.observe(seconds(start, 301), in_process(7, 1), folder(100))); + assert_eq!(detector.finish(seconds(start, 301)).folder_unknown, 299); + } + + #[test] + fn late_stop_counts_what_changed_while_the_folder_could_not_be_read() { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + assert!(!detector.observe(start, in_process(7, 1), folder(100))); + for second in 1..30 { + assert!(!detector.observe(seconds(start, second), in_process(7, 1), None)); + } + assert!(!detector.observe(seconds(start, 30), in_process(7, 1), folder(101))); + assert!(!detector.observe(seconds(start, 31), in_process(7, 1), folder(101))); + for second in 32..40 { + assert!(!detector.observe(seconds(start, second), in_process(7, 1), folder(101))); + } + assert!(detector.observe(seconds(start, 40), in_process(7, 1), folder(101))); + } + + #[test] + fn late_stop_restarts_its_window_when_a_storage_stage_ends() { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + let held = InProcess { + in_storage_stage: true, + ..in_process(7, 1) + }; + for second in 0..100 { + assert!(!detector.observe(seconds(start, second), held, folder(100))); + } + for second in 100..109 { + assert!(!detector.observe(seconds(start, second), in_process(7, 2), folder(100))); + } + assert!(detector.observe(seconds(start, 110), in_process(7, 2), folder(100))); + let quiet = detector.finish(seconds(start, 110)); + assert_eq!(quiet.overall, Duration::from_secs(10)); + assert_eq!(quiet.outside_storage_stages, Duration::from_secs(100)); + } + + #[test] + fn late_stop_storage_stage_counts_until_it_is_dropped() { + let progress = StopProgress::default(); + let written = Arc::new(AtomicU64::new(4)); + progress.watch_packets(written.clone()); + assert_eq!(progress.sample(), in_process(4, 0)); + let stage = progress.storage_stage("test"); + written.fetch_add(2, Ordering::Relaxed); + assert_eq!( + progress.sample(), + InProcess { + in_storage_stage: true, + ..in_process(6, 0) + } + ); + drop(stage); + assert_eq!(progress.sample(), in_process(6, 1)); + assert_eq!(progress.storage_held().len(), 1); + } + + #[test] + fn late_stop_folder_sample_sees_bytes_written_to_an_open_file() { + use std::io::Write as _; + + let temp = tempfile::tempdir().unwrap(); + let nested = temp.path().join("content/segments/segment-0/display"); + std::fs::create_dir_all(&nested).unwrap(); + std::fs::write(nested.join("init.mp4"), [0u8; 10]).unwrap(); + let mut open = std::fs::File::create(nested.join("segment_000.m4s")).unwrap(); + let before = FolderSample::read(temp.path()).unwrap(); + assert_eq!((before.files, before.bytes), (2, 10)); + + open.write_all(&[0u8; 4096]).unwrap(); + open.flush().unwrap(); + let after = FolderSample::read(temp.path()).unwrap(); + assert_eq!((after.files, after.bytes), (2, 4106)); + assert_ne!(before, after); + + assert!(FolderSample::read(&temp.path().join("missing")).is_none()); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn late_stop_watch_reports_a_stall_and_ends_when_the_tracks_finish() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("display.mp4"), [0u8; 10]).unwrap(); + + let stuck = StopProgress::default(); + tokio::time::timeout( + Duration::from_secs(30), + stuck.stalled(temp.path().to_path_buf(), Duration::from_secs(2)), + ) + .await + .expect("a track that never moves must be reported as stalled"); + + let finishing = StopProgress::default(); + let written = Arc::new(AtomicU64::new(0)); + finishing.watch_packets(written.clone()); + let feeder = std::thread::spawn({ + let finishing = finishing.clone(); + move || { + for _ in 0..12 { + std::thread::sleep(Duration::from_millis(250)); + written.fetch_add(1, Ordering::Relaxed); + } + finishing.tracks_finished(); + } + }); + assert!( + tokio::time::timeout( + Duration::from_secs(6), + finishing.stalled(temp.path().to_path_buf(), Duration::from_secs(2)), + ) + .await + .is_err(), + "a track that keeps writing and then finishes must never be reported as stalled" + ); + feeder.join().unwrap(); + } +} From 84ff9946ef593209f6e0710b90d87297a48ac0e1 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:35:43 +0000 Subject: [PATCH 02/19] feat(recording): tell a stalled late Studio stop from a slow one --- crates/recording/src/studio_recording.rs | 196 +++++++++++++++++++++-- 1 file changed, 186 insertions(+), 10 deletions(-) diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index 25ddfb86777..431b59ff65c 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -397,6 +397,7 @@ struct LateStopInner { late: watch::Sender, finishing: std::sync::Mutex>, inputs: std::sync::Mutex>, + progress: std::sync::OnceLock, } /// The microphone and camera a stopping recording still holds. A stop that @@ -415,6 +416,7 @@ impl Default for LateStopInner { late: watch::channel(false).0, finishing: std::sync::Mutex::new(None), inputs: std::sync::Mutex::new(None), + progress: std::sync::OnceLock::new(), } } } @@ -467,7 +469,18 @@ impl LateStop { .take() } + /// Follows `progress`, which the recording's encoders report to, unless + /// this stop already follows one. + fn follow(&self, progress: &crate::stop_progress::StopProgress) { + let _ = self.0.progress.set(progress.clone()); + } + + fn progress(&self) -> &crate::stop_progress::StopProgress { + self.0.progress.get_or_init(Default::default) + } + fn release(&self) { + self.progress().tracks_finished(); drop(self.take_inputs()); let finished = self .0 @@ -489,6 +502,13 @@ impl LateStop { } } +/// How long the tracks of a late stop may show no progress before waiting +/// for them is given up. A track that is only slow keeps writing packets, +/// growing its files or working through its storage stages; one that moves +/// nothing for this long is not expected to finish. +#[cfg(windows)] +pub const STUDIO_FINISH_STALL: Duration = Duration::from_secs(20); + /// Completes a stop that returned while its tracks were still finishing. #[cfg(windows)] #[derive(Clone)] @@ -521,6 +541,23 @@ impl StudioFinishing { }); studio_stop_outcome(report) } + + /// Resolves once the tracks still finishing have shown no progress for + /// [`STUDIO_FINISH_STALL`]: nothing written by their encoders, no stage + /// of their stop completed and nothing changed in the recording folder. + /// Stays pending for good once the tracks have finished, so it never + /// cuts short the saving that follows them. + pub async fn stalled(&self) { + self.stalled_for(STUDIO_FINISH_STALL).await; + } + + async fn stalled_for(&self, window: Duration) { + self.terminal + .late_stop + .progress() + .stalled(self.recording_dir.clone(), window) + .await; + } } #[cfg(any(target_os = "macos", windows))] @@ -541,6 +578,17 @@ fn studio_stop_outcome(report: WindowsStudioStopReport) -> StudioStopOutcome { } } +#[cfg(windows)] +async fn stop_track_or_late( + track: OutputPipeline, + late: impl FnOnce(), + progress: &crate::stop_progress::StopProgress, +) -> anyhow::Result { + let stopped = track.stop_with_outcome_or_late(late).await; + progress.step(); + stopped +} + #[derive(Clone)] pub struct ActorHandle { #[cfg(target_os = "linux")] @@ -872,10 +920,9 @@ impl Actor { #[cfg(windows)] let late_stop = (!discard).then(|| { - self.segment_factory - .encoder_preferences - .finish_wait() - .wait_without_limit(); + let finish_wait = self.segment_factory.encoder_preferences.finish_wait(); + finish_wait.wait_without_limit(); + self.late_stop.follow(finish_wait.progress()); self.late_stop.clone() }); match self @@ -2073,18 +2120,20 @@ impl Pipeline { ), Some((late_stop, recording_dir)) => { let late = || late_stop.mark(recording_dir); + let progress = late_stop.progress(); + let stop = |track: OutputPipeline| stop_track_or_late(track, late, progress); let (screen, microphone, camera, system_audio) = (self.screen, self.microphone, self.camera, self.system_audio); let stops = async { futures::join!( - screen.stop_with_outcome_or_late(late), - OptionFuture::from(microphone.map(|s| s.stop_with_outcome_or_late(late))), - OptionFuture::from(camera.map(|s| s.stop_with_outcome_or_late(late))), - OptionFuture::from(system_audio.map(|s| s.stop_with_outcome_or_late(late))) + stop(screen), + OptionFuture::from(microphone.map(stop)), + OptionFuture::from(camera.map(stop)), + OptionFuture::from(system_audio.map(stop)) ) }; let mut stops = std::pin::pin!(stops); - tokio::select! { + let stopped = tokio::select! { biased; stopped = &mut stops => stopped, () = late_stop.wait() => { @@ -2093,7 +2142,9 @@ impl Pipeline { } stops.await } - } + }; + progress.tracks_finished(); + stopped } }; @@ -5646,6 +5697,131 @@ mod tests { assert!(!crate::recovery::finishing::contains(path)); } + /// A track that never moves is reported as stalled, and giving up on it + /// changes nothing: the project is as a stop still waiting leaves it, and + /// is saved normally if the track does finish. + #[cfg(windows)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn late_stop_reports_a_stall_when_its_tracks_show_no_progress() { + let temp = tempfile::tempdir().unwrap(); + let project = temp.path().join("recording.cap"); + let path = project.as_path(); + let (handle, release, _screen_tx, _sent) = studio_with_slow_screen_finish(path).await; + + let outcome = tokio::time::timeout(Duration::from_secs(30), handle.stop_with_outcome()) + .await + .expect("Stop must return at its limit while a track is still finishing"); + let finishing = outcome.finishing.clone().unwrap(); + let waiting = Instant::now(); + tokio::time::timeout( + Duration::from_secs(20), + finishing.stalled_for(Duration::from_secs(3)), + ) + .await + .expect("a track that shows no progress must be reported as stalled"); + assert!(waiting.elapsed() >= Duration::from_secs(3)); + + assert!(matches!( + studio_status(path), + StudioRecordingStatus::InProgress + )); + assert!(crate::recovery::finishing::contains(path)); + assert!(crate::recovery::RecoveryManager::find_incomplete(temp.path()).is_empty()); + + release.send(()).unwrap(); + let finished = finishing.wait().await; + assert!(matches!( + finished.result.unwrap().meta.status(), + StudioRecordingStatus::Complete + )); + assert!(!crate::recovery::finishing::contains(path)); + } + + /// A slow track is waited for as long as it reports progress, whichever + /// way it reports it, and nothing stalls once the tracks have finished and + /// the recording is being saved. + #[cfg(windows)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn late_stop_is_not_stalled_while_its_tracks_report_progress() { + let temp = tempfile::tempdir().unwrap(); + let project = temp.path().join("recording.cap"); + let path = project.as_path(); + let (handle, release, _screen_tx, _sent) = studio_with_slow_screen_finish(path).await; + + let outcome = tokio::time::timeout(Duration::from_secs(30), handle.stop_with_outcome()) + .await + .expect("Stop must return at its limit while a track is still finishing"); + let finishing = outcome.finishing.clone().unwrap(); + let progress = handle.terminal.late_stop.progress().clone(); + let window = Duration::from_secs(2); + let not_stalled = |what: &'static str| { + let finishing = finishing.clone(); + async move { + assert!( + tokio::time::timeout(Duration::from_secs(6), finishing.stalled_for(window)) + .await + .is_err(), + "{what} must keep the stop alive" + ); + } + }; + let feed = |feed: Box| { + let (stop, stopped) = std::sync::mpsc::channel::<()>(); + let feeder = std::thread::spawn(move || { + loop { + feed(); + if stopped.recv_timeout(Duration::from_millis(250)) + != Err(std::sync::mpsc::RecvTimeoutError::Timeout) + { + break; + } + } + }); + (stop, feeder) + }; + + let written = Arc::new(std::sync::atomic::AtomicU64::new(0)); + progress.watch_packets(written.clone()); + let (stop, feeder) = feed(Box::new(move || { + written.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + })); + not_stalled("an encoder writing packets").await; + drop(stop); + feeder.join().unwrap(); + + let steps = progress.clone(); + let (stop, feeder) = feed(Box::new(move || steps.step())); + not_stalled("a stop working through its stages").await; + drop(stop); + feeder.join().unwrap(); + + let media = path.join("content/display.mp4"); + let (stop, feeder) = feed(Box::new(move || { + use std::io::Write as _; + let mut file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&media) + .unwrap(); + file.write_all(&[0u8; 512]).unwrap(); + })); + not_stalled("a file that keeps growing").await; + drop(stop); + feeder.join().unwrap(); + + let stage = progress.storage_stage("test"); + not_stalled("a finish waiting on storage").await; + drop(stage); + + tokio::time::timeout(Duration::from_secs(20), finishing.stalled_for(window)) + .await + .expect("the stop must stall once nothing reports progress any more"); + + release.send(()).unwrap(); + finishing.wait().await.result.unwrap(); + not_stalled("a stop whose tracks have finished").await; + } + /// The user asks to stop, but the Stop reaches the recording long after /// (its runtime was busy): what the screen captured in between is not /// saved, and the stop still goes late and finishes normally. From 29e6c9d8a9ce0a1ad9a3fad13c2b163e8e2e3bb1 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:35:43 +0000 Subject: [PATCH 03/19] fix(cli): stop waiting for a late Studio stop that shows no progress --- apps/cli/src/record.rs | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/apps/cli/src/record.rs b/apps/cli/src/record.rs index 4fbcdc54d14..ad18b8f030d 100644 --- a/apps/cli/src/record.rs +++ b/apps/cli/src/record.rs @@ -962,7 +962,8 @@ impl ActorHandle { } /// How long `cap record` waits for Studio tracks still finishing after the -/// stop limit before it exits and leaves the recording to recovery. +/// stop limit before it exits and leaves the recording to recovery. It stops +/// waiting sooner once the tracks show no progress. #[cfg(windows)] const STUDIO_FINISH_WAIT: Duration = Duration::from_secs(120); @@ -979,27 +980,38 @@ async fn wait_for_studio_finish( "Recording is still finishing; waiting up to {}s for it to save: {path}", STUDIO_FINISH_WAIT.as_secs() ); - match tokio::time::timeout(STUDIO_FINISH_WAIT, finishing.wait()).await { - Ok(outcome) => { + let waiting = std::time::Instant::now(); + let finished = tokio::select! { + biased; + finished = tokio::time::timeout(STUDIO_FINISH_WAIT, finishing.wait()) => finished.ok(), + () = finishing.stalled() => None, + }; + match finished { + Some(outcome) => { if outcome.result.is_ok() { eprintln!("Recording finished saving: {path}"); } outcome } - Err(_) => { + None => { STUDIO_STILL_FINISHING.store(true, std::sync::atomic::Ordering::SeqCst); studio_recording::StudioStopOutcome { capture_stopped: false, - result: Err(format!( - "Recording is still finishing after {}s. Nothing was discarded; it will be recovered when it is next exported (cap export \"{path}\") or opened in Cap", - STUDIO_FINISH_WAIT.as_secs() - )), + result: Err(still_finishing_message(waiting.elapsed(), &path)), finishing: None, } } } } +#[cfg(windows)] +fn still_finishing_message(waited: Duration, path: &str) -> String { + format!( + "Recording is still finishing after {}s. Nothing was discarded; it will be recovered when it is next exported (cap export \"{path}\") or opened in Cap", + waited.as_secs() + ) +} + /// Ends the process after `report` once `cap record` has given up waiting /// for Studio tracks still finishing. A writer still blocked in the OS keeps /// both the runtime and the normal process exit waiting on it, so the process From e2d1f7e7ef5a31680dac46d29cabe661fb88e8d0 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:35:43 +0000 Subject: [PATCH 04/19] fix(desktop): hand the app back when a late Studio stop shows no progress --- apps/desktop-gpui/src/recording.rs | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rs index 192390cc425..ff4b1f9bba7 100644 --- a/apps/desktop-gpui/src/recording.rs +++ b/apps/desktop-gpui/src/recording.rs @@ -650,7 +650,8 @@ where /// How long Stop stays in its stopping state once a Studio stop went past the /// stop limit, for the tracks to finish and the recording to be finalized. /// Late finishes measured 12 to 47 s past the limit; after this the app is -/// handed back and the recording keeps saving. +/// handed back and the recording keeps saving. The app is handed back sooner +/// once the tracks show no progress. #[cfg(windows)] const STUDIO_FINISH_WAIT: std::time::Duration = std::time::Duration::from_secs(60); @@ -676,10 +677,12 @@ async fn wait_for_studio_finish( let Some(finishing) = outcome.finishing.clone() else { return Ok(outcome); }; - match tokio::time::timeout(STUDIO_FINISH_WAIT, finishing.wait()).await { - Ok(outcome) => Ok(outcome), - Err(_) => Err(finishing), - } + let finished = tokio::select! { + biased; + finished = tokio::time::timeout(STUDIO_FINISH_WAIT, finishing.wait()) => finished.ok(), + () = finishing.stalled() => None, + }; + finished.ok_or(finishing) } /// Keeps waiting for a failed Studio stop the app stopped waiting for and @@ -718,6 +721,7 @@ async fn finish_late_studio_stop( in_progress: Arc, ) -> (bool, anyhow::Result) { let path = finishing.project_path().to_path_buf(); + let tracks = finishing.clone(); let mut save = tokio::spawn(async move { let _in_progress = in_progress; finish_after_capture_stop( @@ -732,8 +736,13 @@ async fn finish_late_studio_stop( ) .await }); - match tokio::time::timeout(STUDIO_FINISH_WAIT, &mut save).await { - Ok(joined) => joined.unwrap_or_else(|error| { + let saved = tokio::select! { + biased; + saved = tokio::time::timeout(STUDIO_FINISH_WAIT, &mut save) => saved.ok(), + () = tracks.stalled() => None, + }; + match saved { + Some(joined) => joined.unwrap_or_else(|error| { ( true, Err(anyhow!( @@ -741,7 +750,7 @@ async fn finish_late_studio_stop( )), ) }), - Err(_) => { + None => { tracing::warn!(path = %path.display(), "Studio recording is still saving; finishing it in the background"); drop(tokio::spawn(async move { match save.await { From f29a1b6eddbb4e64cd13666f6a30c3ea02a87704 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:49:13 +0000 Subject: [PATCH 05/19] feat(desktop): say when a late Studio save stopped making progress --- apps/desktop-gpui/locales/de.toml | 2 ++ apps/desktop-gpui/locales/en.toml | 2 ++ apps/desktop-gpui/locales/es.toml | 2 ++ apps/desktop-gpui/locales/fr.toml | 2 ++ apps/desktop-gpui/locales/hi.toml | 2 ++ apps/desktop-gpui/locales/ja.toml | 2 ++ apps/desktop-gpui/locales/zh-CN.toml | 2 ++ .../src/i18n/dialogs_surface_tests.rs | 5 ++++ apps/desktop-gpui/src/main_window.rs | 18 ++++++++---- apps/desktop-gpui/src/recording.rs | 28 +++++++++++++++---- apps/desktop-gpui/src/session.rs | 22 +++++++++++++++ 11 files changed, 76 insertions(+), 11 deletions(-) diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index c7fb57662f5..7130b6f75e5 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -1578,6 +1578,8 @@ title = "Aufnahmemodus wählen" [dialog.saving] in_background = "Ihre Aufnahme wird noch gespeichert und erscheint in Ihrer Bibliothek, sobald sie fertig ist. Sie können jetzt eine neue Aufnahme starten." +stalled = "Beim Speichern Ihrer Aufnahme ging es nicht mehr voran. Es wurde nichts gelöscht, und Cap bietet beim nächsten Start an, sie wiederherzustellen. Sie können jetzt eine neue Aufnahme starten." +stalled_title = "Noch nicht gespeichert" title = "Wird noch gespeichert" [dialog.storage] diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index a259d731926..8708948c68f 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -1580,6 +1580,8 @@ title = "Choose Recording Mode" [dialog.saving] in_background = "Your recording is still saving and will appear in your library when it is done. You can start a new recording now." +stalled = "Your recording stopped making progress while it was saving. Nothing was deleted, and Cap will offer to recover it the next time it starts. You can start a new recording now." +stalled_title = "Not saved yet" title = "Still saving" [dialog.storage] diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index dbd580d5c7f..8396acbcca5 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -1578,6 +1578,8 @@ title = "Elegir modo de grabación" [dialog.saving] in_background = "Tu grabación todavía se está guardando y aparecerá en tu biblioteca cuando termine. Ya puedes iniciar una nueva grabación." +stalled = "Tu grabación dejó de avanzar mientras se guardaba. No se ha borrado nada, y Cap te ofrecerá recuperarla la próxima vez que se inicie. Ya puedes iniciar una nueva grabación." +stalled_title = "Aún no se ha guardado" title = "Todavía se está guardando" [dialog.storage] diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index b71e0f82c8d..9398163f08a 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -1578,6 +1578,8 @@ title = "Choisir le mode d'enregistrement" [dialog.saving] in_background = "Votre enregistrement est encore en cours de sauvegarde et apparaîtra dans votre bibliothèque une fois terminé. Vous pouvez lancer un nouvel enregistrement dès maintenant." +stalled = "La sauvegarde de votre enregistrement a cessé de progresser. Rien n'a été supprimé, et Cap vous proposera de le récupérer à son prochain démarrage. Vous pouvez lancer un nouvel enregistrement dès maintenant." +stalled_title = "Pas encore sauvegardé" title = "Sauvegarde en cours" [dialog.storage] diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index c6562cae7a1..7dd022960ba 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -1578,6 +1578,8 @@ title = "रिकॉर्डिंग मोड चुनें" [dialog.saving] in_background = "आपकी रिकॉर्डिंग अभी सहेजी जा रही है और पूरी होने पर आपकी लाइब्रेरी में दिखेगी। आप अभी नई रिकॉर्डिंग शुरू कर सकते हैं।" +stalled = "सहेजते समय आपकी रिकॉर्डिंग का आगे बढ़ना रुक गया। कुछ भी हटाया नहीं गया है, और Cap अगली बार शुरू होने पर इसे रिकवर करने का विकल्प देगा। आप अभी नई रिकॉर्डिंग शुरू कर सकते हैं।" +stalled_title = "अभी तक सहेजा नहीं गया" title = "अभी सहेजा जा रहा है" [dialog.storage] diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index dbaf6c62104..f679a2526b9 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -1578,6 +1578,8 @@ title = "録画モードを選択" [dialog.saving] in_background = "録画はまだ保存中です。完了するとライブラリに表示されます。新しい録画をすぐに開始できます。" +stalled = "録画の保存が途中で進まなくなりました。削除されたものはありません。次回 Cap を起動したときに復元できます。新しい録画をすぐに開始できます。" +stalled_title = "まだ保存されていません" title = "保存中です" [dialog.storage] diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 2389e04f45c..5e0a980a72c 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -1578,6 +1578,8 @@ title = "选择录制模式" [dialog.saving] in_background = "你的录制仍在保存,完成后会显示在你的资料库中。你现在可以开始新的录制。" +stalled = "你的录制在保存时停止了进展。没有删除任何内容,下次启动 Cap 时会提示你恢复它。你现在可以开始新的录制。" +stalled_title = "尚未保存" title = "仍在保存" [dialog.storage] diff --git a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs index a5ec2a7cc33..78fdd08f07b 100644 --- a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs @@ -301,6 +301,11 @@ fn dialog_surfaces_match_the_literals_they_replaced() { tr::dialog::saving::in_background(), "Your recording is still saving and will appear in your library when it is done. You can start a new recording now.", ), + ( + tr::dialog::saving::stalled(), + "Your recording stopped making progress while it was saving. Nothing was deleted, and Cap will offer to recover it the next time it starts. You can start a new recording now.", + ), + (tr::dialog::saving::stalled_title(), "Not saved yet"), (tr::dialog::saving::title(), "Still saving"), ( tr::dialog::storage::stopped_kept(), diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs index 17899ebba5d..b12c334c13f 100644 --- a/apps/desktop-gpui/src/main_window.rs +++ b/apps/desktop-gpui/src/main_window.rs @@ -1242,6 +1242,17 @@ impl MainWindow { debug_assert!(!still_saving); #[cfg(windows)] if still_saving { + let (title, message) = if session.read(cx).recording_save_stalled { + ( + tr::dialog::saving::stalled_title(), + tr::dialog::saving::stalled(), + ) + } else { + ( + tr::dialog::saving::title(), + tr::dialog::saving::in_background(), + ) + }; // Shown in the window: a native dialog can stall the // window while the earlier recording is still being written. let main = cx.global::().main; @@ -1250,12 +1261,7 @@ impl MainWindow { app_windows::show_main_window(cx); cx.activate(true); main.update(cx, |_, window, cx| { - crate::editor_modal::informational_alert( - &tr::dialog::saving::title(), - &tr::dialog::saving::in_background(), - window, - cx, - ) + crate::editor_modal::informational_alert(title, message, window, cx) }) }); if let Ok(response) = response { diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rs index ff4b1f9bba7..725fe386f42 100644 --- a/apps/desktop-gpui/src/recording.rs +++ b/apps/desktop-gpui/src/recording.rs @@ -670,6 +670,22 @@ impl std::fmt::Display for StudioStillSaving { #[cfg(windows)] impl std::error::Error for StudioStillSaving {} +/// Stop handed the app back because the recording stopped making progress +/// while saving, so it is not expected to finish. +#[cfg(windows)] +#[derive(Debug)] +pub(crate) struct StudioSaveStalled; + +#[cfg(windows)] +impl std::fmt::Display for StudioSaveStalled { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("The recording stopped making progress while saving") + } +} + +#[cfg(windows)] +impl std::error::Error for StudioSaveStalled {} + #[cfg(windows)] async fn wait_for_studio_finish( outcome: studio_recording::StudioStopOutcome, @@ -738,11 +754,13 @@ async fn finish_late_studio_stop( }); let saved = tokio::select! { biased; - saved = tokio::time::timeout(STUDIO_FINISH_WAIT, &mut save) => saved.ok(), - () = tracks.stalled() => None, + saved = tokio::time::timeout(STUDIO_FINISH_WAIT, &mut save) => { + saved.map_err(|_| anyhow::Error::new(StudioStillSaving)) + } + () = tracks.stalled() => Err(anyhow::Error::new(StudioSaveStalled)), }; match saved { - Some(joined) => joined.unwrap_or_else(|error| { + Ok(joined) => joined.unwrap_or_else(|error| { ( true, Err(anyhow!( @@ -750,7 +768,7 @@ async fn finish_late_studio_stop( )), ) }), - None => { + Err(handed_back) => { tracing::warn!(path = %path.display(), "Studio recording is still saving; finishing it in the background"); drop(tokio::spawn(async move { match save.await { @@ -767,7 +785,7 @@ async fn finish_late_studio_stop( } refresh_library_after_background_save().await; })); - (true, Err(anyhow::Error::new(StudioStillSaving))) + (true, Err(handed_back)) } } } diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs index be81a420350..9500c89383e 100644 --- a/apps/desktop-gpui/src/session.rs +++ b/apps/desktop-gpui/src/session.rs @@ -440,6 +440,10 @@ pub struct RecordingSession { pub capture_source_lost: bool, /// Stop handed the app back while the last recording was still saving. pub recording_still_saving: bool, + /// That recording stopped making progress, so it is not expected to + /// finish saving in this session. + #[cfg(windows)] + pub recording_save_stalled: bool, stopped_for_low_storage: bool, stopped_elapsed: Option, /// The config of the live (or last) recording, kept for restart. @@ -534,6 +538,8 @@ impl RecordingSession { storage_notice: None, capture_source_lost: false, recording_still_saving: false, + #[cfg(windows)] + recording_save_stalled: false, stopped_for_low_storage: false, stopped_elapsed: None, last_config: None, @@ -845,6 +851,10 @@ impl RecordingSession { self.storage_notice = None; self.capture_source_lost = false; self.recording_still_saving = false; + #[cfg(windows)] + { + self.recording_save_stalled = false; + } self.stopped_for_low_storage = false; self.stopped_elapsed = None; self.last_config = Some(config.clone()); @@ -1715,6 +1725,18 @@ impl RecordingSession { tracing::warn!("Studio recording is still saving; the app is free for a new recording"); this.capture_source_lost = false; this.recording_still_saving = true; + this.recording_save_stalled = false; + } + #[cfg(windows)] + Ok(Err(error)) + if error + .chain() + .any(|cause| cause.is::()) => + { + tracing::warn!("Studio recording stopped making progress while saving; the app is free for a new recording"); + this.capture_source_lost = false; + this.recording_still_saving = true; + this.recording_save_stalled = true; } Ok(Err(error)) => { tracing::error!("recording failed to stop cleanly: {error:#}"); From 4368573803dfd6c4dcee28c04843024996bc4451 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:55:07 +0000 Subject: [PATCH 06/19] feat(recording): count a Windows Studio audio muxer's finish as a storage stage --- crates/recording/src/stop_progress.rs | 68 ++++++++++++++++++++++++ crates/recording/src/studio_recording.rs | 44 ++++++++++++--- 2 files changed, 104 insertions(+), 8 deletions(-) diff --git a/crates/recording/src/stop_progress.rs b/crates/recording/src/stop_progress.rs index 05820b7a903..f6b49391dcb 100644 --- a/crates/recording/src/stop_progress.rs +++ b/crates/recording/src/stop_progress.rs @@ -5,6 +5,8 @@ //! so the stop path reports what it does here and the waiter gives up once //! nothing has moved for a while. +use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, output_pipeline::HealthSender}; +use cap_media_info::{AudioInfo, VideoInfo}; use std::{ path::{Path, PathBuf}, sync::{ @@ -130,6 +132,72 @@ impl StopProgress { } } +/// Reports the finish of the muxer it wraps as a storage stage. The audio +/// muxers write on the thread that finishes them, so their finish is the one +/// part of an audio track's stop that has no limit of its own. +pub(crate) struct StopReportingMuxer { + inner: M, + progress: StopProgress, + label: String, +} + +impl Muxer for StopReportingMuxer +where + M::Config: Send, +{ + type Config = (M::Config, StopProgress); + + async fn setup( + (config, progress): Self::Config, + output_path: PathBuf, + video_config: Option, + audio_config: Option, + pause_flag: Arc, + tasks: &mut TaskPool, + ) -> anyhow::Result { + let label = output_path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + let inner = M::setup( + config, + output_path, + video_config, + audio_config, + pause_flag, + tasks, + ) + .await?; + Ok(Self { + inner, + progress, + label, + }) + } + + fn stop(&mut self) { + self.inner.stop(); + } + + fn finish(&mut self, timestamp: Duration) -> anyhow::Result> { + let _storage_stage = self.progress.storage_stage(&self.label); + self.inner.finish(timestamp) + } + + fn set_health_sender(&mut self, tx: HealthSender) { + self.inner.set_health_sender(tx); + } +} + +impl AudioMuxer for StopReportingMuxer +where + M::Config: Send, +{ + fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> { + self.inner.send_audio_frame(frame, timestamp) + } +} + /// Samples until the tracks stall or finish, or until nobody waits for the /// answer. Runs on its own thread: reading the folder can block behind the /// same file scans that hold the tracks up. diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index 431b59ff65c..1b5136fea5a 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -578,6 +578,26 @@ fn studio_stop_outcome(report: WindowsStudioStopReport) -> StudioStopOutcome { } } +/// The muxer of a fragmented Studio audio track. On Windows its finish is +/// reported to the recording's stop progress. +#[cfg(windows)] +type StudioAudioMuxer = crate::stop_progress::StopReportingMuxer; +#[cfg(not(windows))] +type StudioAudioMuxer = M; + +#[cfg(windows)] +fn studio_audio_muxer_config( + config: C, + encoder_preferences: &crate::capture_pipeline::EncoderPreferences, +) -> (C, crate::stop_progress::StopProgress) { + (config, encoder_preferences.finish_wait().progress().clone()) +} + +#[cfg(not(windows))] +fn studio_audio_muxer_config(config: C) -> C { + config +} + #[cfg(windows)] async fn stop_track_or_late( track: OutputPipeline, @@ -4426,10 +4446,14 @@ async fn create_segment_pipeline( .with_audio_source::(mic_feed) .with_timestamps(start_time) .with_start_gate(start_gate.clone()) - .build::(FragmentedAudioMuxerConfig { - shared_pause_state: shared_pause_state.clone(), - write_behind: cfg!(target_os = "macos"), - }) + .build::>(studio_audio_muxer_config( + FragmentedAudioMuxerConfig { + shared_pause_state: shared_pause_state.clone(), + write_behind: cfg!(target_os = "macos"), + }, + #[cfg(windows)] + &encoder_preferences, + )) .instrument(error_span!("mic-out")) .await } else { @@ -4461,10 +4485,14 @@ async fn create_segment_pipeline( .with_timestamps(start_time) .with_start_gate(start_gate.clone()) .with_audio_anchor(AudioAnchor::PipelineEpoch) - .build::(FragmentedAudioMuxerConfig { - shared_pause_state: shared_pause_state.clone(), - write_behind: cfg!(target_os = "macos"), - }) + .build::>(studio_audio_muxer_config( + FragmentedAudioMuxerConfig { + shared_pause_state: shared_pause_state.clone(), + write_behind: cfg!(target_os = "macos"), + }, + #[cfg(windows)] + &encoder_preferences, + )) .instrument(error_span!("system-audio-out")) .await } else { From ea33083f82355d7c336a7f93cd882dece003af32 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:22:57 +0000 Subject: [PATCH 07/19] fix(cli): drop a comment that restates the stall check --- apps/cli/src/record.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/apps/cli/src/record.rs b/apps/cli/src/record.rs index ad18b8f030d..ea137616589 100644 --- a/apps/cli/src/record.rs +++ b/apps/cli/src/record.rs @@ -962,8 +962,7 @@ impl ActorHandle { } /// How long `cap record` waits for Studio tracks still finishing after the -/// stop limit before it exits and leaves the recording to recovery. It stops -/// waiting sooner once the tracks show no progress. +/// stop limit before it exits and leaves the recording to recovery. #[cfg(windows)] const STUDIO_FINISH_WAIT: Duration = Duration::from_secs(120); From 612693777f6583fb3215730f0952420c272048ca Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:22:57 +0000 Subject: [PATCH 08/19] fix(desktop): drop a comment that restates the stall check --- apps/desktop-gpui/src/recording.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rs index 725fe386f42..89daa7d2ccc 100644 --- a/apps/desktop-gpui/src/recording.rs +++ b/apps/desktop-gpui/src/recording.rs @@ -650,8 +650,7 @@ where /// How long Stop stays in its stopping state once a Studio stop went past the /// stop limit, for the tracks to finish and the recording to be finalized. /// Late finishes measured 12 to 47 s past the limit; after this the app is -/// handed back and the recording keeps saving. The app is handed back sooner -/// once the tracks show no progress. +/// handed back and the recording keeps saving. #[cfg(windows)] const STUDIO_FINISH_WAIT: std::time::Duration = std::time::Duration::from_secs(60); From 0cec5f60543da339dbc8cecee2283e13b6e1826a Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:35:39 +0000 Subject: [PATCH 09/19] feat(recording): log when a late Studio stop is given up for showing no progress --- crates/recording/src/stop_progress.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/recording/src/stop_progress.rs b/crates/recording/src/stop_progress.rs index f6b49391dcb..2c897d68c78 100644 --- a/crates/recording/src/stop_progress.rs +++ b/crates/recording/src/stop_progress.rs @@ -236,6 +236,11 @@ fn watch( "Late Studio stop progress" ); if outcome == "stalled" { + tracing::warn!( + path = %recording_dir.display(), + window_ms = window.as_millis() as u64, + "Studio tracks showed no progress; no longer waiting for them" + ); let _ = stalled_tx.send(()); } } From 8f73c95f234ed2867cde7e97ae455f87bf6ad1fb Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:39:04 +0000 Subject: [PATCH 10/19] feat(recording): count audio muxed after a Studio stop began as progress --- crates/recording/src/stop_progress.rs | 106 ++++++++++++++++++++++- crates/recording/src/studio_recording.rs | 1 + 2 files changed, 103 insertions(+), 4 deletions(-) diff --git a/crates/recording/src/stop_progress.rs b/crates/recording/src/stop_progress.rs index 2c897d68c78..d2f171059c1 100644 --- a/crates/recording/src/stop_progress.rs +++ b/crates/recording/src/stop_progress.rs @@ -33,6 +33,7 @@ struct Inner { packets: Mutex>>, storage_held: Mutex>, tracks_finished: AtomicBool, + stop_began: AtomicBool, } /// Held while a track's finish writes out what its encoder still holds and @@ -84,6 +85,11 @@ impl StopProgress { } } + /// From here on, an audio frame a track still muxes counts as progress. + pub(crate) fn stop_began(&self) { + self.0.stop_began.store(true, Ordering::Release); + } + pub(crate) fn tracks_finished(&self) { self.0.tracks_finished.store(true, Ordering::Release); } @@ -132,9 +138,11 @@ impl StopProgress { } } -/// Reports the finish of the muxer it wraps as a storage stage. The audio -/// muxers write on the thread that finishes them, so their finish is the one -/// part of an audio track's stop that has no limit of its own. +/// Reports the finish of the muxer it wraps as a storage stage, and the audio +/// frames it muxes once the stop has begun as steps. The audio muxers write +/// on the thread that finishes them, so their finish has no limit of its own, +/// and what a track still drains after the stop reaches the folder only once +/// per fragment. pub(crate) struct StopReportingMuxer { inner: M, progress: StopProgress, @@ -194,7 +202,11 @@ where M::Config: Send, { fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> { - self.inner.send_audio_frame(frame, timestamp) + let sent = self.inner.send_audio_frame(frame, timestamp); + if self.progress.0.stop_began.load(Ordering::Relaxed) { + self.progress.step(); + } + sent } } @@ -609,6 +621,92 @@ mod tests { assert!(FolderSample::read(&temp.path().join("missing")).is_none()); } + #[derive(Default)] + struct Calls { + stops: AtomicU32, + finishes: AtomicU32, + health_senders: AtomicU32, + audio_frames: AtomicU32, + } + + struct CountingMuxer(Arc); + + impl Muxer for CountingMuxer { + type Config = Arc; + + async fn setup( + calls: Self::Config, + _: PathBuf, + _: Option, + _: Option, + _: Arc, + _: &mut TaskPool, + ) -> anyhow::Result { + Ok(Self(calls)) + } + + fn stop(&mut self) { + self.0.stops.fetch_add(1, Ordering::Relaxed); + } + + fn finish(&mut self, _: Duration) -> anyhow::Result> { + self.0.finishes.fetch_add(1, Ordering::Relaxed); + Ok(Ok(())) + } + + fn set_health_sender(&mut self, _: HealthSender) { + self.0.health_senders.fetch_add(1, Ordering::Relaxed); + } + } + + impl AudioMuxer for CountingMuxer { + fn send_audio_frame(&mut self, _: AudioFrame, _: Duration) -> anyhow::Result<()> { + self.0.audio_frames.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + } + + #[tokio::test] + async fn late_stop_reporting_muxer_forwards_every_call_and_steps_only_once_the_stop_began() { + let calls = Arc::new(Calls::default()); + let progress = StopProgress::default(); + let mut muxer = StopReportingMuxer::::setup( + (calls.clone(), progress.clone()), + PathBuf::from("content/segments/segment-0/audio-input.m4a"), + None, + None, + Arc::new(AtomicBool::new(false)), + &mut TaskPool::default(), + ) + .await + .unwrap(); + let frame = || { + AudioFrame::new( + ffmpeg::frame::Audio::empty(), + cap_timestamp::Timestamp::Instant(Instant::now()), + ) + }; + + muxer.set_health_sender(tokio::sync::mpsc::channel(1).0); + muxer.send_audio_frame(frame(), Duration::ZERO).unwrap(); + muxer.send_audio_frame(frame(), Duration::ZERO).unwrap(); + assert_eq!(progress.sample(), in_process(0, 0)); + + progress.stop_began(); + muxer.send_audio_frame(frame(), Duration::ZERO).unwrap(); + assert_eq!(progress.sample(), in_process(0, 1)); + + muxer.stop(); + muxer.finish(Duration::ZERO).unwrap().unwrap(); + assert_eq!(progress.sample(), in_process(0, 2)); + assert_eq!(progress.storage_held()[0].0, "audio-input.m4a"); + + assert_eq!(calls.stops.load(Ordering::Relaxed), 1); + assert_eq!(calls.finishes.load(Ordering::Relaxed), 1); + assert_eq!(calls.health_senders.load(Ordering::Relaxed), 1); + assert_eq!(calls.audio_frames.load(Ordering::Relaxed), 3); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn late_stop_watch_reports_a_stall_and_ends_when_the_tracks_finish() { let temp = tempfile::tempdir().unwrap(); diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index 1b5136fea5a..f01d7b15c8b 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -473,6 +473,7 @@ impl LateStop { /// this stop already follows one. fn follow(&self, progress: &crate::stop_progress::StopProgress) { let _ = self.0.progress.set(progress.clone()); + self.progress().stop_began(); } fn progress(&self) -> &crate::stop_progress::StopProgress { From 0c5b92843018de4c0934b6e37aad6f44dc466e2f Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:44:33 +0000 Subject: [PATCH 11/19] feat(enc-ffmpeg): mark a segment write that has not returned on Windows --- crates/enc-ffmpeg/src/mux/mod.rs | 2 + crates/enc-ffmpeg/src/mux/segmented_stream.rs | 70 +++++++++++++++++++ crates/enc-ffmpeg/src/mux/write_behind.rs | 37 ++++++++++ 3 files changed, 109 insertions(+) diff --git a/crates/enc-ffmpeg/src/mux/mod.rs b/crates/enc-ffmpeg/src/mux/mod.rs index 70acda46660..cf910afa69f 100644 --- a/crates/enc-ffmpeg/src/mux/mod.rs +++ b/crates/enc-ffmpeg/src/mux/mod.rs @@ -12,4 +12,6 @@ pub mod segmented_audio; pub mod segmented_stream; pub(crate) mod write_behind; +#[cfg(windows)] +pub use write_behind::StorageCall; pub use write_behind::StorageStalled; diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rs index 9505fbc794e..d81398425ee 100644 --- a/crates/enc-ffmpeg/src/mux/segmented_stream.rs +++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs @@ -228,6 +228,8 @@ struct SegmentMux { bookkeeping: Bookkeeping, initial_manifest_pending: bool, encoder_tail_lost: bool, + #[cfg(windows)] + storage_call: Option, } struct SegmentLedger { @@ -259,7 +261,27 @@ impl MuxTarget for SegmentMux { if scan { self.frames_since_segment_scan = 0; } + // Bookkeeping left on this thread reads the segments back, which is + // a storage call like the write itself. + #[cfg(windows)] + let storage_call = self + .storage_call + .as_ref() + .filter(|_| matches!(self.bookkeeping, Bookkeeping::Inline(_))); + #[cfg(windows)] + if let Some(call) = storage_call { + call.set(true); + } self.bookkeeping.packet_written(scan); + #[cfg(windows)] + if let Some(call) = storage_call { + call.set(false); + } + } + + #[cfg(windows)] + fn storage_call(&self) -> Option<&super::write_behind::StorageCall> { + self.storage_call.as_ref() } } @@ -770,6 +792,8 @@ impl SegmentedVideoEncoder { }), initial_manifest_pending: true, encoder_tail_lost: false, + #[cfg(windows)] + storage_call: None, }; let mut instance = Self { @@ -838,6 +862,17 @@ impl SegmentedVideoEncoder { .with_target(|mux| mux.bookkeeping.move_to_background()) } + /// Hands out a marker that is raised while a write to the segment files + /// has not returned, so whoever waits on this encoder can tell slow + /// storage from an encoder that is stuck. + #[cfg(windows)] + pub fn watch_storage_calls(&mut self) -> super::write_behind::StorageCall { + let call = super::write_behind::StorageCall::default(); + self.mux + .with_target(|mux| mux.storage_call = Some(call.clone())); + call + } + /// Whether frames should be queued as CVPixelBuffers via /// [`Self::queue_hw_pixel_buffer`] instead of software frames. #[cfg(target_os = "macos")] @@ -2111,6 +2146,41 @@ mod tests { (names, mpd, manifest) } + #[cfg(windows)] + #[test] + fn storage_call_marker_is_lowered_once_every_write_returned() { + ffmpeg::init().unwrap(); + let temp = tempfile::tempdir().unwrap(); + for offloaded in [false, true] { + let base_path = temp.path().join(format!("offloaded-{offloaded}")); + let mut encoder = SegmentedVideoEncoder::init_libx264( + base_path, + test_video_info(), + SegmentedVideoEncoderConfig::default(), + ) + .unwrap(); + if offloaded { + encoder.offload_segment_bookkeeping().unwrap(); + } + let call = encoder.watch_storage_calls(); + assert!(!call.in_progress()); + for i in 0..120u64 { + encoder + .queue_frame( + create_test_frame(320, 240), + Duration::from_micros(i * 33_333), + ) + .unwrap(); + assert!(!call.in_progress()); + } + assert!(encoder.packets_written() > 0); + encoder + .finish_with_timestamp(Duration::from_secs(4)) + .unwrap(); + assert!(!call.in_progress()); + } + } + #[test] fn write_behind_counts_the_packets_the_writer_put_in_the_file() { ffmpeg::init().unwrap(); diff --git a/crates/enc-ffmpeg/src/mux/write_behind.rs b/crates/enc-ffmpeg/src/mux/write_behind.rs index 139e62cddf8..1d219ed23a0 100644 --- a/crates/enc-ffmpeg/src/mux/write_behind.rs +++ b/crates/enc-ffmpeg/src/mux/write_behind.rs @@ -78,6 +78,31 @@ pub(crate) trait MuxTarget: Send + 'static { fn writer_started(&mut self) {} fn packet_written(&mut self) {} + + /// The marker to raise around this target's writes, when someone waits + /// on its writer. + #[cfg(windows)] + fn storage_call(&self) -> Option<&StorageCall> { + None + } +} + +/// Raised while a write to an output has not returned. A writer blocked on +/// slow storage and one stuck anywhere else both stop producing packets; +/// this tells whoever waits on the writer which of the two it is. +#[cfg(windows)] +#[derive(Clone, Debug, Default)] +pub struct StorageCall(Arc); + +#[cfg(windows)] +impl StorageCall { + pub fn in_progress(&self) -> bool { + self.0.load(Ordering::Relaxed) + } + + pub fn set(&self, in_progress: bool) { + self.0.store(in_progress, Ordering::Relaxed); + } } /// The writer thread did not finish the output in time and may still write @@ -237,7 +262,19 @@ impl PacketSink for MuxSink { fn write_packet(&mut self, packet: Packet) -> Result<(), ffmpeg::Error> { match self { + #[cfg(not(windows))] Self::Direct(target) => packet.write_interleaved(target.output_mut()), + #[cfg(windows)] + Self::Direct(target) => { + if let Some(call) = target.storage_call() { + call.set(true); + } + let written = packet.write_interleaved(target.output_mut()); + if let Some(call) = target.storage_call() { + call.set(false); + } + written + } Self::Behind(writer) => writer.write_packet(packet), Self::Detached => unreachable!("mux sink detached"), } From 04c8cb0665b065be14859cc621138c71559f2462 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:44:33 +0000 Subject: [PATCH 12/19] feat(recording): count a segment write in flight as progress of a late Studio stop --- .../src/output_pipeline/win_fragmented_m4s.rs | 8 +- crates/recording/src/stop_progress.rs | 73 ++++++++++++++++++- 2 files changed, 75 insertions(+), 6 deletions(-) diff --git a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs index 3a4c8edd939..3d84de3afa8 100644 --- a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs +++ b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs @@ -173,10 +173,12 @@ impl EncoderFinishWait { } } - fn watch_packets(wait: Option<&Self>, encoder: &SegmentedVideoEncoder) { + fn watch(wait: Option<&Self>, encoder: &mut SegmentedVideoEncoder) { if let Some(wait) = wait { wait.progress .watch_packets(encoder.packets_written_counter()); + wait.progress + .watch_storage_calls(encoder.watch_storage_calls()); } } } @@ -514,7 +516,7 @@ impl WindowsFragmentedM4SMuxer { if let Some(tx) = self.segment_tx.take() { encoder.set_segment_callback(tx); } - EncoderFinishWait::watch_packets(self.finish_wait.as_ref(), &encoder); + EncoderFinishWait::watch(self.finish_wait.as_ref(), &mut encoder); let encoder = Arc::new(Mutex::new(encoder)); let encoder_clone = encoder.clone(); @@ -994,7 +996,7 @@ impl WindowsFragmentedM4SCameraMuxer { { warn!(%error, "Camera segment bookkeeping thread unavailable, keeping it on the encoder thread"); } - EncoderFinishWait::watch_packets(self.finish_wait.as_ref(), &encoder); + EncoderFinishWait::watch(self.finish_wait.as_ref(), &mut encoder); let encoder = Arc::new(Mutex::new(encoder)); let encoder_clone = encoder.clone(); diff --git a/crates/recording/src/stop_progress.rs b/crates/recording/src/stop_progress.rs index d2f171059c1..c3c3ec1e4fc 100644 --- a/crates/recording/src/stop_progress.rs +++ b/crates/recording/src/stop_progress.rs @@ -6,6 +6,7 @@ //! nothing has moved for a while. use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, output_pipeline::HealthSender}; +use cap_enc_ffmpeg::StorageCall; use cap_media_info::{AudioInfo, VideoInfo}; use std::{ path::{Path, PathBuf}, @@ -31,6 +32,7 @@ struct Inner { steps: AtomicU64, storage_stages: AtomicU32, packets: Mutex>>, + storage_calls: Mutex>, storage_held: Mutex>, tracks_finished: AtomicBool, stop_began: AtomicBool, @@ -72,6 +74,16 @@ impl StopProgress { .push(written); } + /// Counts a write `call` reports as not returned yet as progress: the + /// encoder making it is waiting on storage, not stuck. + pub(crate) fn watch_storage_calls(&self, call: StorageCall) { + self.0 + .storage_calls + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(call); + } + pub(crate) fn step(&self) { self.0.steps.fetch_add(1, Ordering::AcqRel); } @@ -110,6 +122,13 @@ impl StopProgress { .sum(), steps: self.0.steps.load(Ordering::Acquire), in_storage_stage: self.0.storage_stages.load(Ordering::Acquire) > 0, + in_storage_call: self + .0 + .storage_calls + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .any(StorageCall::in_progress), } } @@ -239,6 +258,7 @@ fn watch( outcome, samples = quiet.samples, folder_unknown = quiet.folder_unknown, + storage_call_samples = quiet.storage_call_samples, longest_quiet_ms = quiet.overall.as_millis() as u64, longest_quiet_outside_storage_stages_ms = quiet.outside_storage_stages.as_millis() as u64, longest_quiet_packets_ms = quiet.packets.as_millis() as u64, @@ -262,6 +282,13 @@ struct InProcess { packets: u64, steps: u64, in_storage_stage: bool, + in_storage_call: bool, +} + +impl InProcess { + fn waits_on_storage(&self) -> bool { + self.in_storage_stage || self.in_storage_call + } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -322,6 +349,7 @@ impl FolderSample { struct QuietGaps { samples: u32, folder_unknown: u32, + storage_call_samples: u32, overall: Duration, outside_storage_stages: Duration, packets: Duration, @@ -367,6 +395,7 @@ struct StallDetector { folder: Quiet, samples: u32, folder_unknown: u32, + storage_call_samples: u32, last_in_process: InProcess, } @@ -383,6 +412,7 @@ impl StallDetector { folder: Quiet::new(at), samples: 0, folder_unknown: 0, + storage_call_samples: 0, last_in_process: InProcess::default(), } } @@ -414,7 +444,10 @@ impl StallDetector { if packets_moved || steps_moved || folder_moved { self.outside_storage_stages.moved(at); } - if packets_moved || steps_moved || folder_moved || in_process.in_storage_stage { + if in_process.in_storage_call { + self.storage_call_samples += 1; + } + if packets_moved || steps_moved || folder_moved || in_process.waits_on_storage() { self.overall.moved(at); self.unchanged = 0; } @@ -424,7 +457,7 @@ impl StallDetector { return false; }; let unchanged = self.last.replace((in_process, folder)) == Some((in_process, folder)) - && !in_process.in_storage_stage; + && !in_process.waits_on_storage(); if !unchanged { self.unchanged = 0; return false; @@ -447,6 +480,7 @@ impl StallDetector { QuietGaps { samples: self.samples, folder_unknown: self.folder_unknown, + storage_call_samples: self.storage_call_samples, overall: self.overall.longest, outside_storage_stages: self.outside_storage_stages.longest, packets: self.packets.longest, @@ -475,6 +509,7 @@ mod tests { packets, steps, in_storage_stage: false, + in_storage_call: false, } } @@ -498,7 +533,7 @@ mod tests { #[test] fn late_stop_stays_alive_while_any_one_source_moves() { type Step = fn(u64) -> (InProcess, Option); - let sources: [Step; 4] = [ + let sources: [Step; 5] = [ |second| (in_process(second, 0), folder(100)), |second| (in_process(0, second / 5), folder(100)), |second| (in_process(0, 0), folder(100 + second / 8)), @@ -511,6 +546,15 @@ mod tests { folder(100), ) }, + |_| { + ( + InProcess { + in_storage_call: true, + ..in_process(0, 0) + }, + folder(100), + ) + }, ]; for source in sources { let start = Instant::now(); @@ -600,6 +644,29 @@ mod tests { assert_eq!(progress.storage_held().len(), 1); } + #[test] + fn late_stop_write_that_has_not_returned_counts_until_it_returns() { + let progress = StopProgress::default(); + let call = StorageCall::default(); + progress.watch_storage_calls(call.clone()); + assert!(!progress.sample().waits_on_storage()); + + call.set(true); + assert!(progress.sample().in_storage_call); + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + for second in 0..60 { + assert!(!detector.observe(seconds(start, second), progress.sample(), folder(100))); + } + + call.set(false); + for second in 60..69 { + assert!(!detector.observe(seconds(start, second), progress.sample(), folder(100))); + } + assert!(detector.observe(seconds(start, 69), progress.sample(), folder(100))); + assert_eq!(detector.finish(seconds(start, 69)).storage_call_samples, 60); + } + #[test] fn late_stop_folder_sample_sees_bytes_written_to_an_open_file() { use std::io::Write as _; From 598ffde7155cdb049b278c895f2b4d97e20f9391 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:35:40 +0000 Subject: [PATCH 13/19] fix(recording): give a late Studio stop five seconds without progress --- crates/recording/src/studio_recording.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index f01d7b15c8b..68e89fe8f01 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -508,7 +508,7 @@ impl LateStop { /// growing its files or working through its storage stages; one that moves /// nothing for this long is not expected to finish. #[cfg(windows)] -pub const STUDIO_FINISH_STALL: Duration = Duration::from_secs(20); +pub const STUDIO_FINISH_STALL: Duration = Duration::from_secs(5); /// Completes a stop that returned while its tracks were still finishing. #[cfg(windows)] From 1d423631cb5e80f29605e4574c916d9898ebb1c2 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:01:46 +0000 Subject: [PATCH 14/19] fix(recording): count an audio write that has not returned as waiting on storage --- crates/recording/src/stop_progress.rs | 37 ++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/crates/recording/src/stop_progress.rs b/crates/recording/src/stop_progress.rs index c3c3ec1e4fc..5d85b610d60 100644 --- a/crates/recording/src/stop_progress.rs +++ b/crates/recording/src/stop_progress.rs @@ -157,14 +157,16 @@ impl StopProgress { } } -/// Reports the finish of the muxer it wraps as a storage stage, and the audio -/// frames it muxes once the stop has begun as steps. The audio muxers write -/// on the thread that finishes them, so their finish has no limit of its own, -/// and what a track still drains after the stop reaches the folder only once -/// per fragment. +/// Reports the finish of the muxer it wraps as a storage stage, a frame it +/// is still writing as a write in flight, and the frames it muxes once the +/// stop has begun as steps. The audio muxers write on the thread that calls +/// them, so a write or a finish held by storage has no limit of its own, and +/// what a track still drains after the stop reaches the folder only once per +/// fragment. pub(crate) struct StopReportingMuxer { inner: M, progress: StopProgress, + write: StorageCall, label: String, } @@ -195,9 +197,12 @@ where tasks, ) .await?; + let write = StorageCall::default(); + progress.watch_storage_calls(write.clone()); Ok(Self { inner, progress, + write, label, }) } @@ -221,7 +226,9 @@ where M::Config: Send, { fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> { + self.write.set(true); let sent = self.inner.send_audio_frame(frame, timestamp); + self.write.set(false); if self.progress.0.stop_began.load(Ordering::Relaxed) { self.progress.step(); } @@ -694,6 +701,8 @@ mod tests { finishes: AtomicU32, health_senders: AtomicU32, audio_frames: AtomicU32, + frames_seen_as_a_write_in_flight: AtomicU32, + progress: StopProgress, } struct CountingMuxer(Arc); @@ -729,14 +738,22 @@ mod tests { impl AudioMuxer for CountingMuxer { fn send_audio_frame(&mut self, _: AudioFrame, _: Duration) -> anyhow::Result<()> { self.0.audio_frames.fetch_add(1, Ordering::Relaxed); + if self.0.progress.sample().in_storage_call { + self.0 + .frames_seen_as_a_write_in_flight + .fetch_add(1, Ordering::Relaxed); + } Ok(()) } } #[tokio::test] async fn late_stop_reporting_muxer_forwards_every_call_and_steps_only_once_the_stop_began() { - let calls = Arc::new(Calls::default()); let progress = StopProgress::default(); + let calls = Arc::new(Calls { + progress: progress.clone(), + ..Default::default() + }); let mut muxer = StopReportingMuxer::::setup( (calls.clone(), progress.clone()), PathBuf::from("content/segments/segment-0/audio-input.m4a"), @@ -772,6 +789,14 @@ mod tests { assert_eq!(calls.finishes.load(Ordering::Relaxed), 1); assert_eq!(calls.health_senders.load(Ordering::Relaxed), 1); assert_eq!(calls.audio_frames.load(Ordering::Relaxed), 3); + assert_eq!( + calls + .frames_seen_as_a_write_in_flight + .load(Ordering::Relaxed), + 3, + "a frame being written counts as a write in flight, before and after the stop began" + ); + assert!(!progress.sample().in_storage_call); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] From eff66f865a74617cf00b9ad999de43f6814a1eab Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:06:33 +0000 Subject: [PATCH 15/19] feat(recording): count a disk space query that has not returned as waiting on storage --- crates/recording/src/output_pipeline/core.rs | 22 +++++++++++++++- .../src/output_pipeline/win_fragmented_m4s.rs | 25 ++++++++++++------- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs index cacf985a640..0391b7ae089 100644 --- a/crates/recording/src/output_pipeline/core.rs +++ b/crates/recording/src/output_pipeline/core.rs @@ -566,6 +566,8 @@ pub struct DiskSpaceMonitor { last_poll: Option, last_status: cap_utils::disk_space::DiskSpaceStatus, stopped: bool, + #[cfg(windows)] + query: Option, } impl DiskSpaceMonitor { @@ -574,9 +576,18 @@ impl DiskSpaceMonitor { last_poll: None, last_status: cap_utils::disk_space::DiskSpaceStatus::Ok, stopped: false, + #[cfg(windows)] + query: None, } } + /// Raises `call` while a free-space query has not returned: a volume slow + /// to answer holds the thread that polls as a slow write would. + #[cfg(windows)] + pub fn report_query_to(&mut self, call: cap_enc_ffmpeg::StorageCall) { + self.query = Some(call); + } + pub fn is_stopped(&self) -> bool { self.stopped } @@ -594,7 +605,16 @@ impl DiskSpaceMonitor { } self.last_poll = Some(now); - let bytes = match cap_utils::disk_space::free_bytes_for_path(path) { + #[cfg(windows)] + if let Some(query) = &self.query { + query.set(true); + } + let bytes = cap_utils::disk_space::free_bytes_for_path(path); + #[cfg(windows)] + if let Some(query) = &self.query { + query.set(false); + } + let bytes = match bytes { Ok(bytes) => bytes, Err(err) => { trace!(error = %err, path = %path.display(), "DiskSpaceMonitor: free_bytes_for_path failed"); diff --git a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs index 3d84de3afa8..50d42dacb2d 100644 --- a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs +++ b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs @@ -12,6 +12,7 @@ use crate::{ stop_progress::StopProgress, }; use anyhow::{Context, anyhow}; +use cap_enc_ffmpeg::StorageCall; use cap_enc_ffmpeg::h264::{H264EncoderBuilder, H264Preset}; use cap_enc_ffmpeg::segmented_stream::{ DiskSpaceCallback, QueueFrameError, SegmentedVideoEncoder, SegmentedVideoEncoderConfig, @@ -173,13 +174,13 @@ impl EncoderFinishWait { } } - fn watch(wait: Option<&Self>, encoder: &mut SegmentedVideoEncoder) { - if let Some(wait) = wait { - wait.progress - .watch_packets(encoder.packets_written_counter()); - wait.progress - .watch_storage_calls(encoder.watch_storage_calls()); - } + fn watch(wait: Option<&Self>, encoder: &mut SegmentedVideoEncoder) -> Option { + let wait = wait?; + wait.progress + .watch_packets(encoder.packets_written_counter()); + let storage_call = encoder.watch_storage_calls(); + wait.progress.watch_storage_calls(storage_call.clone()); + Some(storage_call) } } @@ -516,7 +517,7 @@ impl WindowsFragmentedM4SMuxer { if let Some(tx) = self.segment_tx.take() { encoder.set_segment_callback(tx); } - EncoderFinishWait::watch(self.finish_wait.as_ref(), &mut encoder); + let storage_call = EncoderFinishWait::watch(self.finish_wait.as_ref(), &mut encoder); let encoder = Arc::new(Mutex::new(encoder)); let encoder_clone = encoder.clone(); @@ -543,6 +544,9 @@ impl WindowsFragmentedM4SMuxer { let mut total_frames = 0u64; let mut duplicated_frames = 0u64; let mut disk_monitor = DiskSpaceMonitor::new(); + if let Some(storage_call) = storage_call { + disk_monitor.report_query_to(storage_call); + } let mut disk_exhausted = false; const SLOW_THRESHOLD_MS: u128 = 5; let encode_failures = Cell::new(0u64); @@ -996,7 +1000,7 @@ impl WindowsFragmentedM4SCameraMuxer { { warn!(%error, "Camera segment bookkeeping thread unavailable, keeping it on the encoder thread"); } - EncoderFinishWait::watch(self.finish_wait.as_ref(), &mut encoder); + let storage_call = EncoderFinishWait::watch(self.finish_wait.as_ref(), &mut encoder); let encoder = Arc::new(Mutex::new(encoder)); let encoder_clone = encoder.clone(); @@ -1025,6 +1029,9 @@ impl WindowsFragmentedM4SCameraMuxer { let mut total_frames = 0u64; let mut duplicated_frames = 0u64; let mut disk_monitor = DiskSpaceMonitor::new(); + if let Some(storage_call) = storage_call { + disk_monitor.report_query_to(storage_call); + } let mut disk_exhausted = false; let mut mjpeg_decoder = MjpegDecoder::default(); const SLOW_THRESHOLD_MS: u128 = 5; From 1bee9032505e2ec4e0aca6a50ff9aa09d67de14f Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:06:33 +0000 Subject: [PATCH 16/19] fix(recording): never judge a late stop whose muxers report no progress source --- crates/recording/src/stop_progress.rs | 36 +++++++++++++++++++++++- crates/recording/src/studio_recording.rs | 14 +++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/crates/recording/src/stop_progress.rs b/crates/recording/src/stop_progress.rs index 5d85b610d60..53e2bf8919e 100644 --- a/crates/recording/src/stop_progress.rs +++ b/crates/recording/src/stop_progress.rs @@ -140,9 +140,31 @@ impl StopProgress { .clone() } + /// Whether any muxer of the recording reports here. One whose muxers do + /// not (a recording that is not written as segments) cannot show that it + /// is waiting on storage, so it is never judged. + fn has_sources(&self) -> bool { + !self + .0 + .packets + .lock() + .unwrap_or_else(PoisonError::into_inner) + .is_empty() + || !self + .0 + .storage_calls + .lock() + .unwrap_or_else(PoisonError::into_inner) + .is_empty() + } + /// Resolves once the tracks have shown no progress for `window`. Stays - /// pending for good once they finish, and when it cannot watch. + /// pending for good once they finish, when no muxer reports here, and + /// when it cannot watch. pub(crate) async fn stalled(&self, recording_dir: PathBuf, window: Duration) { + if !self.has_sources() { + return std::future::pending::<()>().await; + } let (stalled_tx, stalled_rx) = tokio::sync::oneshot::channel(); let progress = self.clone(); let watcher = std::thread::Builder::new() @@ -804,7 +826,19 @@ mod tests { let temp = tempfile::tempdir().unwrap(); std::fs::write(temp.path().join("display.mp4"), [0u8; 10]).unwrap(); + let unwatched = StopProgress::default(); + assert!( + tokio::time::timeout( + Duration::from_secs(5), + unwatched.stalled(temp.path().to_path_buf(), Duration::from_secs(2)), + ) + .await + .is_err(), + "a recording whose muxers report nothing must never be reported as stalled" + ); + let stuck = StopProgress::default(); + stuck.watch_packets(Arc::new(AtomicU64::new(0))); tokio::time::timeout( Duration::from_secs(30), stuck.stalled(temp.path().to_path_buf(), Duration::from_secs(2)), diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index 68e89fe8f01..a317d00a185 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -5741,6 +5741,20 @@ mod tests { .await .expect("Stop must return at its limit while a track is still finishing"); let finishing = outcome.finishing.clone().unwrap(); + assert!( + tokio::time::timeout( + Duration::from_secs(6), + finishing.stalled_for(Duration::from_secs(2)), + ) + .await + .is_err(), + "a recording whose muxers report nothing must never be reported as stalled" + ); + handle + .terminal + .late_stop + .progress() + .watch_packets(Arc::new(std::sync::atomic::AtomicU64::new(0))); let waiting = Instant::now(); tokio::time::timeout( Duration::from_secs(20), From 8f1b630268448ae731c3936a60c9b3b6ae8e0c52 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:06:33 +0000 Subject: [PATCH 17/19] fix(desktop): keep the stalled save notice true when the save still completes --- apps/desktop-gpui/locales/de.toml | 2 +- apps/desktop-gpui/locales/en.toml | 2 +- apps/desktop-gpui/locales/es.toml | 2 +- apps/desktop-gpui/locales/fr.toml | 2 +- apps/desktop-gpui/locales/hi.toml | 2 +- apps/desktop-gpui/locales/ja.toml | 2 +- apps/desktop-gpui/locales/zh-CN.toml | 2 +- apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index 7130b6f75e5..ee2fce95b5a 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -1578,7 +1578,7 @@ title = "Aufnahmemodus wählen" [dialog.saving] in_background = "Ihre Aufnahme wird noch gespeichert und erscheint in Ihrer Bibliothek, sobald sie fertig ist. Sie können jetzt eine neue Aufnahme starten." -stalled = "Beim Speichern Ihrer Aufnahme ging es nicht mehr voran. Es wurde nichts gelöscht, und Cap bietet beim nächsten Start an, sie wiederherzustellen. Sie können jetzt eine neue Aufnahme starten." +stalled = "Beim Speichern Ihrer Aufnahme ging es nicht mehr voran. Es wurde nichts gelöscht. Falls sie nicht in Ihrer Bibliothek erscheint, bietet Cap beim nächsten Start an, sie wiederherzustellen. Sie können jetzt eine neue Aufnahme starten." stalled_title = "Noch nicht gespeichert" title = "Wird noch gespeichert" diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 8708948c68f..4f6e67e595b 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -1580,7 +1580,7 @@ title = "Choose Recording Mode" [dialog.saving] in_background = "Your recording is still saving and will appear in your library when it is done. You can start a new recording now." -stalled = "Your recording stopped making progress while it was saving. Nothing was deleted, and Cap will offer to recover it the next time it starts. You can start a new recording now." +stalled = "Your recording stopped making progress while it was saving. Nothing was deleted. If it does not appear in your library, Cap will offer to recover it the next time it starts. You can start a new recording now." stalled_title = "Not saved yet" title = "Still saving" diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index 8396acbcca5..b85095afd27 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -1578,7 +1578,7 @@ title = "Elegir modo de grabación" [dialog.saving] in_background = "Tu grabación todavía se está guardando y aparecerá en tu biblioteca cuando termine. Ya puedes iniciar una nueva grabación." -stalled = "Tu grabación dejó de avanzar mientras se guardaba. No se ha borrado nada, y Cap te ofrecerá recuperarla la próxima vez que se inicie. Ya puedes iniciar una nueva grabación." +stalled = "Tu grabación dejó de avanzar mientras se guardaba. No se ha borrado nada. Si no aparece en tu biblioteca, Cap te ofrecerá recuperarla la próxima vez que se inicie. Ya puedes iniciar una nueva grabación." stalled_title = "Aún no se ha guardado" title = "Todavía se está guardando" diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 9398163f08a..a3d1e145120 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -1578,7 +1578,7 @@ title = "Choisir le mode d'enregistrement" [dialog.saving] in_background = "Votre enregistrement est encore en cours de sauvegarde et apparaîtra dans votre bibliothèque une fois terminé. Vous pouvez lancer un nouvel enregistrement dès maintenant." -stalled = "La sauvegarde de votre enregistrement a cessé de progresser. Rien n'a été supprimé, et Cap vous proposera de le récupérer à son prochain démarrage. Vous pouvez lancer un nouvel enregistrement dès maintenant." +stalled = "La sauvegarde de votre enregistrement a cessé de progresser. Rien n'a été supprimé. S'il n'apparaît pas dans votre bibliothèque, Cap vous proposera de le récupérer à son prochain démarrage. Vous pouvez lancer un nouvel enregistrement dès maintenant." stalled_title = "Pas encore sauvegardé" title = "Sauvegarde en cours" diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 7dd022960ba..fdfa4928841 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -1578,7 +1578,7 @@ title = "रिकॉर्डिंग मोड चुनें" [dialog.saving] in_background = "आपकी रिकॉर्डिंग अभी सहेजी जा रही है और पूरी होने पर आपकी लाइब्रेरी में दिखेगी। आप अभी नई रिकॉर्डिंग शुरू कर सकते हैं।" -stalled = "सहेजते समय आपकी रिकॉर्डिंग का आगे बढ़ना रुक गया। कुछ भी हटाया नहीं गया है, और Cap अगली बार शुरू होने पर इसे रिकवर करने का विकल्प देगा। आप अभी नई रिकॉर्डिंग शुरू कर सकते हैं।" +stalled = "सहेजते समय आपकी रिकॉर्डिंग का आगे बढ़ना रुक गया। कुछ भी हटाया नहीं गया है। अगर यह आपकी लाइब्रेरी में नहीं दिखती, तो Cap अगली बार शुरू होने पर इसे रिकवर करने का विकल्प देगा। आप अभी नई रिकॉर्डिंग शुरू कर सकते हैं।" stalled_title = "अभी तक सहेजा नहीं गया" title = "अभी सहेजा जा रहा है" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index f679a2526b9..098b9d54eb1 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -1578,7 +1578,7 @@ title = "録画モードを選択" [dialog.saving] in_background = "録画はまだ保存中です。完了するとライブラリに表示されます。新しい録画をすぐに開始できます。" -stalled = "録画の保存が途中で進まなくなりました。削除されたものはありません。次回 Cap を起動したときに復元できます。新しい録画をすぐに開始できます。" +stalled = "録画の保存が途中で進まなくなりました。削除されたものはありません。ライブラリに表示されない場合は、次回 Cap を起動したときに復元できます。新しい録画をすぐに開始できます。" stalled_title = "まだ保存されていません" title = "保存中です" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 5e0a980a72c..9bd11904815 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -1578,7 +1578,7 @@ title = "选择录制模式" [dialog.saving] in_background = "你的录制仍在保存,完成后会显示在你的资料库中。你现在可以开始新的录制。" -stalled = "你的录制在保存时停止了进展。没有删除任何内容,下次启动 Cap 时会提示你恢复它。你现在可以开始新的录制。" +stalled = "你的录制在保存时停止了进展。没有删除任何内容。如果它没有出现在你的资料库中,下次启动 Cap 时会提示你恢复它。你现在可以开始新的录制。" stalled_title = "尚未保存" title = "仍在保存" diff --git a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs index 78fdd08f07b..d3eb2ddd747 100644 --- a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs @@ -303,7 +303,7 @@ fn dialog_surfaces_match_the_literals_they_replaced() { ), ( tr::dialog::saving::stalled(), - "Your recording stopped making progress while it was saving. Nothing was deleted, and Cap will offer to recover it the next time it starts. You can start a new recording now.", + "Your recording stopped making progress while it was saving. Nothing was deleted. If it does not appear in your library, Cap will offer to recover it the next time it starts. You can start a new recording now.", ), (tr::dialog::saving::stalled_title(), "Not saved yet"), (tr::dialog::saving::title(), "Still saving"), From 6c264168c4513472a4ab754ce2442bcdd3d3c9a4 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:33:10 +0000 Subject: [PATCH 18/19] ci: fall back to the Azure Ubuntu mirror in the Linux desktop harness --- .../workflows/linux-desktop-reliability.yml | 11 +++++++ .../appimage-pipewire/run.sh | 18 ++++++++--- scripts/linux-desktop-harness/apt-install.sh | 31 +++++++++++++++++++ .../linux-desktop-harness/gnome.Dockerfile | 29 +++++++---------- scripts/linux-desktop-harness/run-desktop.sh | 25 ++++++--------- 5 files changed, 75 insertions(+), 39 deletions(-) create mode 100755 scripts/linux-desktop-harness/apt-install.sh diff --git a/.github/workflows/linux-desktop-reliability.yml b/.github/workflows/linux-desktop-reliability.yml index c3691806c37..26f8c2dd4e3 100644 --- a/.github/workflows/linux-desktop-reliability.yml +++ b/.github/workflows/linux-desktop-reliability.yml @@ -632,6 +632,17 @@ jobs: curl --fail --location --retry 3 -o "$RUNNER_TEMP/Cap.AppImage" "$CAP_APPIMAGE_URL" echo "$CAP_APPIMAGE_SHA256 $RUNNER_TEMP/Cap.AppImage" | sha256sum --check + - name: apt-install.sh falls back when the Ubuntu archive is unreachable + run: | + log="$RUNNER_TEMP/apt-install-self-test.log" + status=0 + docker run --rm --add-host archive.ubuntu.com:127.0.0.1 --add-host security.ubuntu.com:127.0.0.1 \ + -v "$PWD/scripts/linux-desktop-harness/apt-install.sh":/apt-install.sh:ro ubuntu:24.04 \ + sh -c 'sh /apt-install.sh -qq hello >/dev/null && hello' 2>"$log" || status=$? + cat "$log" + [ "$status" = 0 ] + grep -q "falling back to http://azure.archive.ubuntu.com/ubuntu" "$log" + - name: Connect a capture stream in NixOS appimage-run timeout-minutes: 30 env: diff --git a/scripts/linux-desktop-harness/appimage-pipewire/run.sh b/scripts/linux-desktop-harness/appimage-pipewire/run.sh index 023b79cb598..c46a59d1f46 100755 --- a/scripts/linux-desktop-harness/appimage-pipewire/run.sh +++ b/scripts/linux-desktop-harness/appimage-pipewire/run.sh @@ -20,8 +20,9 @@ chmod -R a+rX squashfs-root # Built like Cap: a host-ABI binary (Ubuntu's toolchain) that finds the # bundled FFmpeg through RUNPATH $ORIGIN/../lib. -docker run --rm -v "$here":/src:ro -v "$work":/work -w /work ubuntu:24.04 bash -euc ' - apt-get update -qq >/dev/null && apt-get install -y -qq gcc pkg-config libpipewire-0.3-dev >/dev/null +apt_install=(-v "$here/../apt-install.sh":/apt-install.sh:ro) +docker run --rm "${apt_install[@]}" -v "$here":/src:ro -v "$work":/work -w /work ubuntu:24.04 bash -euc ' + sh /apt-install.sh -qq gcc pkg-config libpipewire-0.3-dev >/dev/null gcc -o probe /src/probe.c $(pkg-config --cflags --libs libpipewire-0.3) \ -L squashfs-root/usr/lib -l:libavutil.so.59 -Wl,--allow-shlib-undefined -Wl,-rpath,"\$ORIGIN/../lib" chmod 755 probe' @@ -36,7 +37,14 @@ FINALIZE="$repo/scripts/finalize-linux-appimage.mjs" APPDIR_FIXED="$work/fixed" node --input-type=module -e ' const { isolateBundledLibva, directAppRunWrapper, fallbackLibvaDirectory } = await import(process.env.FINALIZE); const { writeFile } = await import("node:fs/promises"); - const replacement = await fallbackLibvaDirectory(process.env.LIBVA_WORK); + const mirrored = (url) => url.replace("http://archive.ubuntu.com/", "http://azure.archive.ubuntu.com/"); + const download = async (url) => { + const response = await fetch(url, { signal: AbortSignal.timeout(30000) }).catch((error) => error); + if (response.ok) return response; + console.error("apt-install: " + url + " failed (" + (response.status ?? response.cause?.code ?? response.name) + "), falling back to " + mirrored(url)); + return fetch(mirrored(url)); + }; + const replacement = await fallbackLibvaDirectory(process.env.LIBVA_WORK, { download }); const moved = await isolateBundledLibva(process.env.APPDIR_FIXED, { replacement }); await writeFile(process.env.APPDIR_FIXED + "/AppRun", directAppRunWrapper, { mode: 0o755 }); console.log("moved " + moved.join(" ") + "; fallback from " + replacement); @@ -49,8 +57,8 @@ chmod -R a+rX "$work" # packed the way the original was. offset=$(./Cap.AppImage --appimage-offset) head -c "$offset" Cap.AppImage >runtime -docker run --rm -v "$work":/work -w /work ubuntu:24.04 bash -euc ' - apt-get update -qq >/dev/null && apt-get install -y -qq squashfs-tools >/dev/null +docker run --rm "${apt_install[@]}" -v "$work":/work -w /work ubuntu:24.04 bash -euc ' + sh /apt-install.sh -qq squashfs-tools >/dev/null for layout in shipped fixed; do mksquashfs "$layout" "$layout.squashfs" -root-owned -noappend -comp zstd -quiet >/dev/null cat runtime "$layout.squashfs" >"$layout.AppImage" diff --git a/scripts/linux-desktop-harness/apt-install.sh b/scripts/linux-desktop-harness/apt-install.sh new file mode 100755 index 00000000000..a57907b8b71 --- /dev/null +++ b/scripts/linux-desktop-harness/apt-install.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# apt-get install inside an Ubuntu container: from the image's own sources +# first, and from the Azure mirror (which also carries the -security pocket) +# when archive.ubuntu.com or security.ubuntu.com does not answer. +# Usage: apt-install.sh [--no-update] +set -u +mirror=http://azure.archive.ubuntu.com/ubuntu +update=yes +if [ "${1:-}" = --no-update ]; then + update=no + shift +fi + +fetch() { + opts=$1 + shift + if [ "$update" = yes ]; then + # shellcheck disable=SC2086 + apt-get $opts --error-on=any update || return + fi + # shellcheck disable=SC2086 + apt-get $opts install -y "$@" +} + +fetch "-o Acquire::Retries=1 -o Acquire::http::Timeout=10" "$@" && exit 0 +echo "apt-install: the Ubuntu archive failed, falling back to $mirror" | tee -a /var/log/apt-install.log >&2 +for list in /etc/apt/sources.list /etc/apt/sources.list.d/ubuntu.sources; do + [ -f "$list" ] && sed -i -E "s#https?://(archive|security)\.ubuntu\.com/ubuntu#$mirror#g" "$list" +done +update=yes +fetch "-o Acquire::Retries=4" "$@" diff --git a/scripts/linux-desktop-harness/gnome.Dockerfile b/scripts/linux-desktop-harness/gnome.Dockerfile index 138308103e0..89221a52a6c 100644 --- a/scripts/linux-desktop-harness/gnome.Dockerfile +++ b/scripts/linux-desktop-harness/gnome.Dockerfile @@ -5,24 +5,17 @@ # where the portal reads a host app's id from. FROM ubuntu:26.04 ENV DEBIAN_FRONTEND=noninteractive -# Ubuntu's mirrors answer 502 for minutes at a time: apt retries each file, -# and a failed install is tried again from another mirror. -RUN for mirror in "" http://azure.archive.ubuntu.com/ubuntu; do \ - if [ -n "$mirror" ]; then \ - sed -i "s#http://archive.ubuntu.com/ubuntu#$mirror#g" /etc/apt/sources.list.d/ubuntu.sources || continue; \ - fi; \ - apt-get -o Acquire::Retries=4 update \ - && apt-get -o Acquire::Retries=4 install -y --no-install-recommends \ - systemd systemd-sysv dbus dbus-user-session libpam-systemd \ - gnome-shell mutter xdg-desktop-portal xdg-desktop-portal-gnome \ - ubuntu-session yaru-theme-gnome-shell yaru-theme-icon yaru-theme-gtk \ - gnome-shell-extension-ubuntu-dock gnome-settings-daemon \ - gnome-shell-extension-appindicator pipewire wireplumber pipewire-pulse \ - mesa-vulkan-drivers libgl1-mesa-dri libegl-mesa0 python3 python3-gi gir1.2-glib-2.0 \ - at-spi2-core gir1.2-atspi-2.0 gnome-backgrounds \ - procps psmisc ca-certificates xdg-utils \ - && apt-get clean && exit 0; \ - done; exit 1 +COPY apt-install.sh /usr/local/bin/apt-install.sh +RUN sh /usr/local/bin/apt-install.sh --no-install-recommends \ + systemd systemd-sysv dbus dbus-user-session libpam-systemd \ + gnome-shell mutter xdg-desktop-portal xdg-desktop-portal-gnome \ + ubuntu-session yaru-theme-gnome-shell yaru-theme-icon yaru-theme-gtk \ + gnome-shell-extension-ubuntu-dock gnome-settings-daemon \ + gnome-shell-extension-appindicator pipewire wireplumber pipewire-pulse \ + mesa-vulkan-drivers libgl1-mesa-dri libegl-mesa0 python3 python3-gi gir1.2-glib-2.0 \ + at-spi2-core gir1.2-atspi-2.0 gnome-backgrounds \ + procps psmisc ca-certificates xdg-utils \ + && apt-get clean RUN useradd -m -u 1001 tester \ && mkdir -p /var/lib/systemd/linger && touch /var/lib/systemd/linger/tester \ && systemctl mask systemd-binfmt.service proc-sys-fs-binfmt_misc.automount \ diff --git a/scripts/linux-desktop-harness/run-desktop.sh b/scripts/linux-desktop-harness/run-desktop.sh index b8c67927554..e41bd00cad3 100644 --- a/scripts/linux-desktop-harness/run-desktop.sh +++ b/scripts/linux-desktop-harness/run-desktop.sh @@ -53,6 +53,7 @@ docker run -d --name "$name" --privileged --cgroupns=host "${docker_extra[@]}" \ -v "$package":/pkgs/"$(basename "$package")":ro -v "$here":/harness:ro -v "$out":/out \ "${cache_mounts[@]}" "${dev_mounts[@]}" "$image" >/dev/null trap 'docker rm -f "$name" >/dev/null 2>&1' EXIT +docker exec "$name" cat /var/log/apt-install.log 2>/dev/null || true for _ in $(seq 60); do state=$(docker exec "$name" systemctl is-system-running 2>/dev/null || true) [[ $state == running || $state == degraded ]] && break @@ -62,27 +63,19 @@ done # test user the access a seat grants it on a real machine. docker exec "$name" sh -c 'chmod 666 /dev/dri/* 2>/dev/null || true' envs=(-e HARNESS_OUT=/out -e DESKTOP="$desktop" "${extra_env[@]}") -# Ubuntu's mirrors answer 502 for minutes at a time: apt retries each file, -# a failed install is tried again, and then again from another mirror. +# Ubuntu's mirrors answer 502 for minutes at a time: apt-install.sh falls back +# to another mirror, and a failed install is tried again. install_deb() { - local deb mirror attempt + local deb attempt deb=/pkgs/$(basename "$package") : >"$out/install.log" # The image's apt deletes packages once installed; keep them in the cache. docker exec "$name" rm -f /etc/apt/apt.conf.d/docker-clean - for mirror in "" http://azure.archive.ubuntu.com/ubuntu; do - if [[ -n $mirror ]]; then - echo "switching to $mirror" >>"$out/install.log" - docker exec "$name" sed -i "s#http://archive.ubuntu.com/ubuntu#$mirror#g" \ - /etc/apt/sources.list.d/ubuntu.sources >>"$out/install.log" 2>&1 || continue - docker exec "$name" apt-get update -qq >>"$out/install.log" 2>&1 || continue - fi - for attempt in 1 2; do - docker exec "$name" apt-get install -y -qq -o Acquire::Retries=4 "$deb" \ - >>"$out/install.log" 2>&1 && return 0 - echo "install attempt $attempt failed" >>"$out/install.log" - sleep $((attempt * 15)) - done + for attempt in 1 2; do + docker exec "$name" sh /harness/apt-install.sh --no-update -qq "$deb" \ + >>"$out/install.log" 2>&1 && return 0 + echo "install attempt $attempt failed" >>"$out/install.log" + sleep $((attempt * 15)) done return 100 } From c06f2a6c85076ed1ab2bbd8b9d85d37274237f4b Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:50:09 +0000 Subject: [PATCH 19/19] ci: retry the libva body read from the Azure mirror too --- .../linux-desktop-harness/appimage-pipewire/run.sh | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/scripts/linux-desktop-harness/appimage-pipewire/run.sh b/scripts/linux-desktop-harness/appimage-pipewire/run.sh index c46a59d1f46..1161cf48e22 100755 --- a/scripts/linux-desktop-harness/appimage-pipewire/run.sh +++ b/scripts/linux-desktop-harness/appimage-pipewire/run.sh @@ -39,10 +39,14 @@ FINALIZE="$repo/scripts/finalize-linux-appimage.mjs" APPDIR_FIXED="$work/fixed" const { writeFile } = await import("node:fs/promises"); const mirrored = (url) => url.replace("http://archive.ubuntu.com/", "http://azure.archive.ubuntu.com/"); const download = async (url) => { - const response = await fetch(url, { signal: AbortSignal.timeout(30000) }).catch((error) => error); - if (response.ok) return response; - console.error("apt-install: " + url + " failed (" + (response.status ?? response.cause?.code ?? response.name) + "), falling back to " + mirrored(url)); - return fetch(mirrored(url)); + try { + const response = await fetch(url, { signal: AbortSignal.timeout(30000) }); + if (!response.ok) throw new Error("HTTP " + response.status); + return new Response(await response.arrayBuffer()); + } catch (error) { + console.error("apt-install: " + url + " failed (" + (error.cause?.code ?? error.message) + "), falling back to " + mirrored(url)); + return fetch(mirrored(url)); + } }; const replacement = await fallbackLibvaDirectory(process.env.LIBVA_WORK, { download }); const moved = await isolateBundledLibva(process.env.APPDIR_FIXED, { replacement });