diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index b133a1bd89..9cb5d8a72a 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -1410,6 +1410,8 @@ devices_changed_before_start = "Die ausgewählten Geräte haben sich vor Beginn shortcut_conflict = "Ctrl+Shift+F9 ist einer anderen Cap-Aktion zugewiesen. Ändern Sie dieses Kürzel vor der Aufnahme." shortcut_description = "Diese Cap-Aufnahme starten oder beenden" shortcut_hint = "Drücken Sie {shortcut} und lassen Sie los, um zu starten. Mit demselben Kürzel beenden Sie die Aufnahme. Dieses vorübergehende Kürzel ändert Ihre Einstellungen nicht." +source_lost = "Cap hat die Aufnahme beendet, weil das Aufnahmeziel nicht mehr verfügbar war, zum Beispiel weil der Bildschirm in den Ruhezustand gewechselt ist oder das Fenster geschlossen wurde. Alles bis dahin Aufgenommene wurde gespeichert." +source_lost_title = "Aufnahme beendet" tray_stop_hint = "Aktivieren Sie das Cap-Stopp-Symbol in der Taskleiste, um zu starten. Aktivieren Sie es erneut, um zu beenden. Die Aufnahme beginnt erst, wenn Sie dieses Steuerelement verwenden." window_unavailable = "Das ausgewählte Fenster ist nicht mehr verfügbar. Wählen Sie es erneut aus." diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 84a31e6c10..0455e01af7 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -1412,6 +1412,8 @@ devices_changed_before_start = "Selected devices changed before recording starte shortcut_conflict = "Ctrl+Shift+F9 is assigned to another Cap action. Change that shortcut before recording." shortcut_description = { text = "Start or stop this Cap recording", context = "Shown by the Linux desktop when it asks the user to approve a global shortcut." } shortcut_hint = { text = "Press and release {shortcut} to start. Use the same shortcut to stop. This temporary shortcut does not change your settings.", context = "{shortcut} is a key combination such as Ctrl+Shift+F9." } +source_lost = "Cap stopped recording because what it was capturing went away, for example the display went to sleep or the window closed. Everything recorded up to then was saved." +source_lost_title = "Recording stopped" tray_stop_hint = "Activate the Cap Stop tray icon to start. Activate the same icon again to stop. Recording will not start until you use that control." window_unavailable = "The selected window is no longer available. Select it again." diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index e47aaa0215..9993a6e58c 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -1410,6 +1410,8 @@ devices_changed_before_start = "Los dispositivos seleccionados cambiaron antes d shortcut_conflict = "Ctrl+Shift+F9 está asignado a otra acción de Cap. Cambia ese atajo antes de grabar." shortcut_description = "Iniciar o detener esta grabación de Cap" shortcut_hint = "Pulsa y suelta {shortcut} para empezar. Usa el mismo atajo para detener. Este atajo temporal no cambia tus ajustes." +source_lost = "Cap detuvo la grabación porque lo que estaba grabando dejó de estar disponible, por ejemplo, la pantalla entró en reposo o se cerró la ventana. Todo lo grabado hasta ese momento se guardó." +source_lost_title = "Grabación detenida" tray_stop_hint = "Activa el icono de detener de Cap en la bandeja para empezar. Vuelve a activarlo para detener. La grabación no empezará hasta que uses ese control." window_unavailable = "La ventana seleccionada ya no está disponible. Vuelve a seleccionarla." diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 130e417653..5b9a0f11da 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -1410,6 +1410,8 @@ devices_changed_before_start = "Les appareils sélectionnés ont changé avant l shortcut_conflict = "Ctrl+Shift+F9 est attribué à une autre action de Cap. Modifiez ce raccourci avant d'enregistrer." shortcut_description = "Lancer ou arrêter cet enregistrement Cap" shortcut_hint = "Appuyez sur {shortcut} puis relâchez pour démarrer. Utilisez le même raccourci pour arrêter. Ce raccourci temporaire ne modifie pas vos réglages." +source_lost = "Cap a arrêté l'enregistrement, car ce qu'il capturait n'est plus disponible, par exemple l'écran s'est mis en veille ou la fenêtre a été fermée. Tout ce qui a été enregistré jusque-là a été sauvegardé." +source_lost_title = "Enregistrement arrêté" tray_stop_hint = "Activez l'icône d'arrêt de Cap dans la zone de notification pour démarrer. Activez-la à nouveau pour arrêter. L'enregistrement ne commencera pas tant que vous n'aurez pas utilisé cette commande." window_unavailable = "La fenêtre sélectionnée n'est plus disponible. Sélectionnez-la à nouveau." diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 679436881a..1fb34db37a 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -1410,6 +1410,8 @@ devices_changed_before_start = "रिकॉर्डिंग शुरू ह shortcut_conflict = "Ctrl+Shift+F9 किसी दूसरे Cap एक्शन को दिया गया है। रिकॉर्ड करने से पहले वह शॉर्टकट बदलें।" shortcut_description = "यह Cap रिकॉर्डिंग शुरू करें या रोकें" shortcut_hint = "शुरू करने के लिए {shortcut} दबाकर छोड़ें। रोकने के लिए वही शॉर्टकट इस्तेमाल करें। यह अस्थायी शॉर्टकट आपकी सेटिंग्स नहीं बदलता।" +source_lost = "Cap ने रिकॉर्डिंग रोक दी, क्योंकि जो कैप्चर हो रहा था वह अब उपलब्ध नहीं है, जैसे डिस्प्ले स्लीप में चला गया या विंडो बंद हो गई। तब तक की पूरी रिकॉर्डिंग सेव कर ली गई है।" +source_lost_title = "रिकॉर्डिंग रुक गई" tray_stop_hint = "शुरू करने के लिए Cap Stop ट्रे आइकन सक्रिय करें। रोकने के लिए वही आइकन फिर से सक्रिय करें। जब तक आप उस कंट्रोल का इस्तेमाल नहीं करते, रिकॉर्डिंग शुरू नहीं होगी।" window_unavailable = "चुनी गई विंडो अब उपलब्ध नहीं है। इसे फिर से चुनें।" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 13b8e54ec7..ac8389feb8 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -1410,6 +1410,8 @@ devices_changed_before_start = "録画の開始前に選択したデバイスが shortcut_conflict = "Ctrl+Shift+F9はCapの別の操作に割り当てられています。録画の前にそのショートカットを変更してください。" shortcut_description = "このCap録画を開始または停止" shortcut_hint = "{shortcut}を押して離すと開始します。同じショートカットで停止できます。この一時的なショートカットは設定を変更しません。" +source_lost = "録画対象が使用できなくなったため、Capは録画を停止しました(ディスプレイのスリープ、ウィンドウを閉じた場合など)。それまでに録画した内容はすべて保存されています。" +source_lost_title = "録画を停止しました" tray_stop_hint = "Capの停止トレイアイコンをクリックすると開始します。同じアイコンをもう一度クリックすると停止します。このコントロールを使うまで録画は始まりません。" window_unavailable = "選択したウィンドウは使用できなくなりました。もう一度選択してください。" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index f71059f3cf..c1ab3aa7e4 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -1410,6 +1410,8 @@ devices_changed_before_start = "录制开始前所选设备已更改。请重新 shortcut_conflict = "Ctrl+Shift+F9 已分配给另一个 Cap 操作。请在录制前更改该快捷键。" shortcut_description = "开始或停止此 Cap 录制" shortcut_hint = "按下并松开 {shortcut} 开始录制。再次使用同一快捷键即可停止。此临时快捷键不会更改你的设置。" +source_lost = "Cap 已停止录制,因为录制的对象已不可用(例如显示器进入睡眠或窗口已关闭)。此前录制的内容已全部保存。" +source_lost_title = "录制已停止" tray_stop_hint = "点击 Cap 的“停止”托盘图标即可开始。再次点击同一图标即可停止。在你使用该控件之前,录制不会开始。" window_unavailable = "所选窗口已不可用。请重新选择。" diff --git a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs index 39be8a2315..913acc6798 100644 --- a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs @@ -283,6 +283,14 @@ fn dialog_surfaces_match_the_literals_they_replaced() { tr::dialog::file::unconfirmed(), "Cap could not confirm that the file dialog closed. Close any remaining file dialog and restart Cap before trying again.", ), + ( + tr::dialog::capture::source_lost(), + "Cap stopped recording because what it was capturing went away, for example the display went to sleep or the window closed. Everything recorded up to then was saved.", + ), + ( + tr::dialog::capture::source_lost_title(), + "Recording stopped", + ), ( tr::dialog::storage::stopped_kept(), "Recording stopped because storage is low. Your recording files were kept. Free up space, then recover the recording below.", diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs index 928b64406e..8761e0c125 100644 --- a/apps/desktop-gpui/src/main_window.rs +++ b/apps/desktop-gpui/src/main_window.rs @@ -1079,7 +1079,22 @@ impl MainWindow { } if phase == Phase::Idle && previous_phase != Phase::Idle { this.scan_incomplete_recordings(window, cx, std::time::Duration::ZERO); - if let Some(notice) = session.read(cx).storage_notice.clone() { + let notice = { + let session = session.read(cx); + session + .storage_notice + .clone() + .map(|notice| (tr::main::storage::title(), notice)) + .or_else(|| { + session.capture_source_lost.then(|| { + ( + tr::dialog::capture::source_lost_title(), + tr::dialog::capture::source_lost().into(), + ) + }) + }) + }; + if let Some((title, notice)) = notice { let main = cx.global::().main; cx.spawn(async move |_, cx| { let receiver = cx.update(|cx| { @@ -1088,7 +1103,7 @@ impl MainWindow { main.update(cx, |_, window, cx| { window.prompt( gpui::PromptLevel::Warning, - tr::main::storage::title(), + title, Some(¬ice), &[gpui::PromptButton::cancel(tr::common::ok())], cx, diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs index e90f0f0a73..3ca972d479 100644 --- a/apps/desktop-gpui/src/session.rs +++ b/apps/desktop-gpui/src/session.rs @@ -420,6 +420,8 @@ pub struct RecordingSession { pub error: Option, pub storage_warning: bool, pub storage_notice: Option, + /// The last recording stopped because what it captured went away. + pub capture_source_lost: bool, stopped_for_low_storage: bool, stopped_elapsed: Option, /// The config of the live (or last) recording, kept for restart. @@ -505,6 +507,7 @@ impl RecordingSession { error: None, storage_warning: false, storage_notice: None, + capture_source_lost: false, stopped_for_low_storage: false, stopped_elapsed: None, last_config: None, @@ -787,6 +790,7 @@ impl RecordingSession { self.error = None; self.storage_warning = false; self.storage_notice = None; + self.capture_source_lost = false; self.stopped_for_low_storage = false; self.stopped_elapsed = None; self.last_config = Some(config.clone()); @@ -1093,7 +1097,9 @@ impl RecordingSession { let generation = self.recording_generation; let task = gpui_tokio::Tokio::spawn(cx, done); self.failure_monitor = Some(cx.spawn(async move |this, cx| { - let error = match task.await { + let outcome = task.await; + let source_lost = capture_ended_cleanly(&outcome); + let error = match outcome { Ok(Ok(())) => "Recording ended unexpectedly.".to_string(), Ok(Err(error)) => error.to_string(), Err(error) => format!("Recording completion task failed: {error}"), @@ -1104,6 +1110,13 @@ impl RecordingSession { { return; } + if source_lost { + tracing::warn!("capture source went away; stopping and saving the recording"); + this.capture_source_lost = true; + this.stop(cx); + cx.notify(); + return; + } tracing::error!(%error, "recording pipeline failed"); this.pipeline_failed = true; this.error = Some(error); @@ -1489,11 +1502,13 @@ impl RecordingSession { } Ok(Err(error)) => { tracing::error!("recording failed to stop cleanly: {error:#}"); + this.capture_source_lost = false; this.storage_notice = low_storage.then(|| tr::dialog::storage::stopped_kept().into()); this.error = Some(format!("{error:#}")); } Err(join_error) => { tracing::error!("recording stop task died: {join_error}"); + this.capture_source_lost = false; this.storage_notice = low_storage.then(|| tr::dialog::storage::stopped_kept().into()); this.error = Some("Stop task failed.".into()); } @@ -2200,6 +2215,16 @@ fn sleep_action( } } +/// On macOS a pipeline only finishes cleanly before Stop when ScreenCaptureKit +/// lost what it was capturing: the display slept or went away, the window +/// closed, or sharing was stopped from the menu bar. Everything captured so far +/// is intact, so the recording is stopped and saved instead of failed. +fn capture_ended_cleanly( + outcome: &Result, E>, +) -> bool { + cfg!(target_os = "macos") && matches!(outcome, Ok(Ok(()))) +} + fn recording_failure_is_current(phase: Phase, current: u64, completed: u64) -> bool { current == completed && matches!(phase, Phase::Recording { .. }) } @@ -2798,6 +2823,16 @@ mod instant_terminal_tests { mod recording_failure_tests { use super::*; + /// A capture that lost its source ends cleanly before Stop; it is stopped + /// and saved rather than treated as a failure (#3578). + #[test] + fn a_capture_that_ends_cleanly_before_stop_is_saved_not_failed() { + let ended: Result, ()> = Ok(Ok(())); + assert_eq!(capture_ended_cleanly(&ended), cfg!(target_os = "macos")); + let task_died: Result, ()> = Err(()); + assert!(!capture_ended_cleanly(&task_died)); + } + #[test] fn only_current_recording_failure_can_request_stop() { for paused in [false, true] { diff --git a/apps/desktop-gpui/src/upload/real_app_tests.rs b/apps/desktop-gpui/src/upload/real_app_tests.rs index 51a9a3fd20..4c1fa991ff 100644 --- a/apps/desktop-gpui/src/upload/real_app_tests.rs +++ b/apps/desktop-gpui/src/upload/real_app_tests.rs @@ -826,31 +826,38 @@ async fn real_app_start_cue_waits_for_a_slow_server_video() { assert_eq!(mock.created().len(), 1); } -/// The display sleeping mid-recording makes ScreenCaptureKit report that it -/// has nothing to capture. That ends the screen track with its media on disk -/// instead of failing it and leaving Stop and Quit waiting on a capture that -/// can never confirm cleanup. Instant ends there; Studio keeps its other -/// tracks until Stop, which the auto-record driver presses at 30 s. Sleeping -/// the display disturbs whoever is at the machine, so this runs only with -/// `CAP_GPUI_REAL_APP_DISPLAY_SLEEP=1`. +/// Records in both modes, takes the capture source away with `lose`, and +/// checks that ScreenCaptureKit's "nothing to capture" ends the screen track +/// with its media on disk instead of failing it and leaving Stop and Quit +/// waiting on a capture that can never confirm cleanup. The app then stops +/// and saves the recording itself, well before the auto-record driver would +/// press Stop. #[cfg(target_os = "macos")] -#[ignore] -#[tokio::test(flavor = "multi_thread")] -async fn real_app_display_sleep_ends_the_recording_with_its_media() { - if std::env::var_os("CAP_GPUI_REAL_APP_DISPLAY_SLEEP").is_none() { - eprintln!("set CAP_GPUI_REAL_APP_DISPLAY_SLEEP=1 to sleep the display"); - return; - } +async fn losing_the_capture_source_stops_and_saves( + case: &str, + settings: &[(&str, Value)], + env: impl Fn(&str) -> Vec<(String, String)>, + lose: impl Fn(&str), +) { for mode in ["instant", "studio"] { let mock = MockCap::start(Vec::new()).await; let sandbox = Sandbox::new(&mock.url, 0); - let name = format!("display-sleep-{mode}"); + for (key, value) in settings { + sandbox.set_general(key, value.clone()); + } + let name = format!("{case}-{mode}"); let auto = if mode == "studio" { "studio:30" } else { "instant:90" }; - let app = sandbox.launch(&name, &[("CAP_GPUI_AUTO_RECORD", auto)]); + let mut vars = env(mode); + vars.push(("CAP_GPUI_AUTO_RECORD".into(), auto.into())); + let vars = vars + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())) + .collect::>(); + let app = sandbox.launch(&name, &vars); wait_for_app( &sandbox, &app, @@ -860,15 +867,7 @@ async fn real_app_display_sleep_ends_the_recording_with_its_media() { ) .await; tokio::time::sleep(Duration::from_secs(6)).await; - assert!( - Command::new("pmset") - .arg("displaysleepnow") - .status() - .unwrap() - .success() - ); - tokio::time::sleep(Duration::from_secs(8)).await; - let _ = Command::new("caffeinate").args(["-u", "-t", "2"]).status(); + lose(mode); let ended = |log: &str| { log.contains("Capture cleanup is unconfirmed") || log.contains("recording failed to stop cleanly") @@ -888,14 +887,20 @@ async fn real_app_display_sleep_ends_the_recording_with_its_media() { let log = without_ansi(&sandbox.log(&name)); assert!( log.contains("Screen capture source disappeared"), - "{mode}: the display sleep never reached the capture source:\n{log}" + "{case} {mode}: losing the source never reached the capture source:\n{log}" ); assert!( !log.contains("Capture cleanup is unconfirmed"), - "{mode}: Stop was left waiting on a dead capture:\n{log}" + "{case} {mode}: Stop was left waiting on a dead capture:\n{log}" + ); + assert!( + log.contains("capture source went away; stopping and saving the recording") + && log.contains("recording finished") + && !log.contains("recording pipeline failed"), + "{case} {mode}: the recording was not stopped and saved when its source went away:\n{log}" ); let projects = sandbox.projects(); - assert_eq!(projects.len(), 1, "{mode}: {projects:?}"); + assert_eq!(projects.len(), 1, "{case} {mode}: {projects:?}"); let project = &projects[0]; // Raw fragments alone are what the failure left behind, so only // sealed output counts: finished Instant segments, and Studio segments @@ -903,7 +908,7 @@ async fn real_app_display_sleep_ends_the_recording_with_its_media() { if mode == "instant" { assert!( finished_segments(project) > 0, - "instant: no finished display segments in {}", + "{case} instant: no finished display segments in {}", project.display() ); } else { @@ -912,7 +917,7 @@ async fn real_app_display_sleep_ends_the_recording_with_its_media() { .unwrap_or(0); assert!( saved > 0, - "studio: no saved segments in {}: {:?}", + "{case} studio: no saved segments in {}: {:?}", project.display(), meta(project) ); @@ -920,6 +925,94 @@ async fn real_app_display_sleep_ends_the_recording_with_its_media() { } } +/// The display sleeping mid-recording. Sleeping the display disturbs whoever +/// is at the machine, so this runs only with `CAP_GPUI_REAL_APP_DISPLAY_SLEEP=1`. +#[cfg(target_os = "macos")] +#[ignore] +#[tokio::test(flavor = "multi_thread")] +async fn real_app_display_sleep_ends_the_recording_with_its_media() { + if std::env::var_os("CAP_GPUI_REAL_APP_DISPLAY_SLEEP").is_none() { + eprintln!("set CAP_GPUI_REAL_APP_DISPLAY_SLEEP=1 to sleep the display"); + return; + } + losing_the_capture_source_stops_and_saves( + "display-sleep", + &[], + |_| Vec::new(), + |_| { + assert!( + Command::new("pmset") + .arg("displaysleepnow") + .status() + .unwrap() + .success() + ); + std::thread::sleep(Duration::from_secs(8)); + let _ = Command::new("caffeinate").args(["-u", "-t", "2"]).status(); + }, + ) + .await; +} + +/// The recorded window goes away. Only a focused-window capture loses its +/// source; a screen-region capture of a window keeps recording that region of +/// the screen. The document opens in a TextEdit instance of its own, and only +/// that instance is ended: scripting a close would need Automation consent, +/// which a fresh Mac asks for with a prompt nobody answers, and quitting +/// TextEdit would close every other document too. +#[cfg(target_os = "macos")] +#[ignore] +#[tokio::test(flavor = "multi_thread")] +async fn real_app_recorded_window_closing_ends_the_recording_with_its_media() { + fn text_edit_pids() -> Vec { + let out = Command::new("pgrep") + .args(["-x", "TextEdit"]) + .output() + .unwrap(); + String::from_utf8_lossy(&out.stdout) + .split_whitespace() + .map(str::to_owned) + .collect() + } + let documents = tempfile::tempdir().unwrap(); + let opened = std::sync::Mutex::new(Vec::::new()); + losing_the_capture_source_stops_and_saves( + "window-closed", + &[("windowCaptureStyle", json!("focusedWindow"))], + |mode| { + let title = format!("cap-capture-target-{mode}-{}", std::process::id()); + let document = documents.path().join(&title); + std::fs::write(&document, "The window Cap records").unwrap(); + let before = text_edit_pids(); + assert!( + Command::new("open") + .args(["-n", "-a", "TextEdit"]) + .arg(&document) + .status() + .unwrap() + .success() + ); + std::thread::sleep(Duration::from_secs(3)); + let ours: Vec = text_edit_pids() + .into_iter() + .filter(|pid| !before.contains(pid)) + .collect(); + assert_eq!(ours.len(), 1, "{mode}: no TextEdit instance of our own"); + *opened.lock().unwrap() = ours; + vec![ + ("CAP_GPUI_AUTO_OVERLAY".into(), "window".into()), + ("CAP_GPUI_AUTO_WINDOW".into(), title), + ] + }, + |_| { + for pid in opened.lock().unwrap().drain(..) { + let _ = Command::new("kill").arg(&pid).status(); + } + }, + ) + .await; +} + /// A recording whose pipeline fails mid-capture (in the field an encoder or /// capture task error; here the debug build's injected task failure) is /// stopped by the app. Every capture task has already exited, so Stop must diff --git a/crates/recording/src/sources/screen_capture/macos.rs b/crates/recording/src/sources/screen_capture/macos.rs index 5b89b22141..a5ddcce8e6 100644 --- a/crates/recording/src/sources/screen_capture/macos.rs +++ b/crates/recording/src/sources/screen_capture/macos.rs @@ -27,6 +27,14 @@ use tracing::{debug, error, info, warn}; const MAX_CAPTURE_RESTARTS: u32 = 3; const RESTART_DELAY: Duration = Duration::from_secs(2); +const WINDOW_WATCH_INTERVAL: Duration = Duration::from_secs(1); +const WINDOW_GONE_CHECKS: u32 = 2; + +/// The window server still lists a minimized, hidden or off-Space window; only +/// a closed window (or one whose app quit) disappears. +fn recorded_window_exists(window: &WindowId) -> bool { + Window::from_id_direct(window).is_some_and(|window| window.owner_name().is_some()) +} // The display filter is what hides excluded windows, so an excluded selection must stay on // the display-crop path instead of being captured on its own. @@ -49,6 +57,12 @@ fn capturable_window<'a>( Some(window_id) } +/// Only a stream with a window filter loses its source when the window closes. +/// An excluded window is recorded as a display crop, which keeps capturing. +fn window_to_watch(config: &Config, excluded_windows: &[WindowId]) -> Option { + capturable_window(config, excluded_windows, "watch").cloned() +} + fn window_content_filter( window_id: &WindowId, content: &sc::ShareableContent, @@ -758,10 +772,47 @@ impl output_pipeline::VideoSource for VideoSource { let original_capturer = capturer.clone(); ctx.tasks().spawn("screen-capture-monitor", async move { let mut restart_count = 0u32; + let mut window_watch = + window_to_watch(&rebuild_params.config, &rebuild_params.excluded_windows) + .map(|window| (window, tokio::time::interval(WINDOW_WATCH_INTERVAL), 0u32)); loop { select! { _ = monitor_cancel.cancelled() => break Ok(()), + _ = async { + match window_watch.as_mut() { + Some((_, interval, _)) => interval.tick().await, + None => std::future::pending().await, + } + } => { + let Some((window, _, missed)) = window_watch.as_mut() else { + continue; + }; + if recorded_window_exists(window) { + *missed = 0; + continue; + } + *missed += 1; + if *missed < WINDOW_GONE_CHECKS { + continue; + } + // A window filter keeps its stream running after the window closes or + // its app quits; ScreenCaptureKit just stops sending frames. The stream + // is alive, so it is stopped normally with the pipeline. + warn!( + %window, + "Screen capture source disappeared (recorded window closed); keeping what was recorded" + ); + output_pipeline::emit_health( + &health_tx, + output_pipeline::PipelineHealthEvent::CaptureTargetLost { + target: "window".to_string(), + }, + ); + stop_signal.mark_user_stopped(); + pipeline_cancel.cancel(); + break Ok(()); + } recv = error_rx.recv() => { let err = match recv { Ok(err) => err, @@ -898,6 +949,17 @@ impl output_pipeline::VideoSource for VideoSource { } } + // didStopWithError means the stream has already stopped, so Stop must + // not wait on it, or it can never confirm cleanup. + if let Ok(guard) = active_capturer.lock() { + match guard.as_ref() { + Some(c) => c.mark_stopped(), + None => original_capturer.mark_stopped(), + } + } else { + original_capturer.mark_stopped(); + } + error!(error = %err, "Screen capture stream stopped with an error"); return Err(anyhow!(format!("{err}"))); } } @@ -1382,6 +1444,7 @@ impl output_pipeline::AudioSource for SystemAudioSource { if is_system_stop_error(err.as_ref()) { system_stop_count += 1; if system_stop_count > MAX_CAPTURE_RESTARTS { + capturer_for_monitor.mark_stopped(); warn!("Screen capture audio stream stopped by the system (exhausted restarts)"); return Err(anyhow!(system_stop_message())); } @@ -1392,6 +1455,7 @@ impl output_pipeline::AudioSource for SystemAudioSource { tokio::time::sleep(RESTART_DELAY + Duration::from_secs(1)).await; continue; } + capturer_for_monitor.mark_stopped(); return Err(anyhow!("{err}")); } Err(broadcast::error::RecvError::Closed) => break, @@ -1586,6 +1650,25 @@ mod tests { ); } + #[test] + fn only_a_window_filter_is_watched_for_its_window_closing() { + let config = window_config(Some(window_id("247"))); + + assert_eq!( + window_to_watch(&config, &[window_id("12")]), + Some(window_id("247")) + ); + assert_eq!(window_to_watch(&config, &[window_id("247")]), None); + assert_eq!(window_to_watch(&window_config(None), &[]), None); + } + + /// A window filter never reports that its window closed, so the monitor + /// polls for it; an id the window server does not know counts as closed. + #[test] + fn a_window_the_window_server_does_not_list_counts_as_closed() { + assert!(!recorded_window_exists(&window_id("4294967294"))); + } + #[test] fn only_no_capture_source_counts_as_the_source_disappearing() { let sc_domain = || sc::error::domain().to_string(); diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index 23cd756a4f..54440c3e06 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -1296,7 +1296,6 @@ struct Pipeline { pub cursor: Option, pub track_failures: SharedTrackFailures, pub watcher_task: Option>, - #[cfg(any(target_os = "linux", windows))] stopping: Arc, } @@ -1621,7 +1620,6 @@ impl Pipeline { pub async fn stop(mut self) -> anyhow::Result { let stop_started = Instant::now(); let epoch = self.epoch(); - #[cfg(any(target_os = "linux", windows))] self.stopping .store(true, std::sync::atomic::Ordering::Release); #[cfg(target_os = "macos")] @@ -1838,11 +1836,27 @@ impl Pipeline { .into_iter() .flatten() .collect::>(); - #[cfg(any(target_os = "linux", windows))] let stopping = self.stopping.clone(); let track_failures = self.track_failures.clone(); self.watcher_task = Some(tokio::spawn(async move { while let Some((track, required, res)) = futures.next().await { + // ScreenCaptureKit ends the screen pipeline cleanly when its source goes away + // (display asleep or unplugged, window closed, sharing stopped). The other tracks + // are cancelled with it, so without a completion the app would keep showing a + // live recording that captures nothing. + #[cfg(target_os = "macos")] + if required && res.is_ok() && !stopping.load(std::sync::atomic::Ordering::Acquire) { + warn!(?track, "Studio screen capture ended before Stop"); + completion_tx.send_if_modified(|current| { + if current.is_none() { + *current = Some(Ok(())); + true + } else { + false + } + }); + continue; + } #[cfg(any(target_os = "linux", windows))] let res = match res { Ok(()) if !stopping.load(std::sync::atomic::Ordering::Acquire) => { @@ -3803,7 +3817,6 @@ async fn create_segment_pipeline( system_audio, track_failures: Arc::new(std::sync::Mutex::new(Vec::new())), watcher_task: None, - #[cfg(any(target_os = "linux", windows))] stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)), }) } @@ -4554,7 +4567,6 @@ mod tests { cursor: None, track_failures: Arc::new(std::sync::Mutex::new(Vec::new())), watcher_task: None, - #[cfg(windows)] stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)), }, index: 0, @@ -5640,7 +5652,6 @@ mod tests { cursor: None, track_failures: Arc::new(std::sync::Mutex::new(Vec::new())), watcher_task: None, - #[cfg(any(target_os = "linux", windows))] stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)), }; @@ -5763,6 +5774,7 @@ mod tests { cursor: None, track_failures: Arc::new(std::sync::Mutex::new(Vec::new())), watcher_task: None, + stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)), }; let stopping = tokio::spawn(pipeline.stop()); @@ -5820,6 +5832,96 @@ mod tests { } } + #[cfg(target_os = "macos")] + type CompletionSender = watch::Sender>>; + + #[cfg(target_os = "macos")] + async fn watched_screen_pipeline() -> ( + Pipeline, + flume::Sender, + DoneFut, + CompletionSender, + tempfile::TempDir, + ) { + let temp_dir = tempfile::tempdir().unwrap(); + let timestamps = Timestamps::now(); + let (screen_tx, screen_rx) = flume::bounded(4); + let screen = OutputPipeline::builder(temp_dir.path().join("display.mp4")) + .with_video::>(ChannelVideoSourceConfig::new( + test_video_info(), + screen_rx, + )) + .with_timestamps(timestamps) + .build::(()) + .await + .unwrap(); + screen_tx + .send_async(TestVideoFrame { + timestamp: Timestamp::Instant(timestamps.instant()), + }) + .await + .unwrap(); + let (completion_tx, completion_rx) = watch::channel(None); + let mut pipeline = Pipeline { + start_time: timestamps, + start_gate: None, + screen, + microphone: None, + camera: None, + system_audio: None, + cursor: None, + track_failures: Arc::new(std::sync::Mutex::new(Vec::new())), + watcher_task: None, + stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)), + }; + pipeline.spawn_watcher(completion_tx.clone()); + ( + pipeline, + screen_tx, + completion_rx_to_done_fut(completion_rx), + completion_tx, + temp_dir, + ) + } + + /// ScreenCaptureKit losing its source (display asleep or unplugged, window + /// closed) cancels the screen pipeline, which then ends without an error. + /// The recording must report that it ended, or the app keeps a live + /// recording that captures nothing (#3578). + #[cfg(target_os = "macos")] + #[tokio::test] + async fn macos_screen_capture_ending_before_stop_completes_the_recording() { + let (pipeline, screen_tx, done, _actor_completion, _temp_dir) = + watched_screen_pipeline().await; + assert!(done.clone().now_or_never().is_none()); + + pipeline.screen.cancel(); + drop(screen_tx); + + let result = tokio::time::timeout(Duration::from_secs(2), done) + .await + .expect("the recording never reported that capture ended"); + assert!(result.is_ok(), "{result:?}"); + assert!(pipeline.track_failures.lock().unwrap().is_empty()); + } + + #[cfg(target_os = "macos")] + #[tokio::test] + async fn macos_pause_or_stop_does_not_complete_the_recording() { + let (pipeline, screen_tx, done, _actor_completion, _temp_dir) = + watched_screen_pipeline().await; + let stopping = tokio::spawn(pipeline.stop()); + tokio::time::sleep(Duration::from_millis(50)).await; + drop(screen_tx); + tokio::time::timeout(Duration::from_secs(2), stopping) + .await + .unwrap() + .unwrap() + .unwrap(); + tokio::time::sleep(Duration::from_millis(100)).await; + assert!(done.now_or_never().is_none()); + } + fn test_finished_output_pipeline() -> FinishedOutputPipeline { let timestamps = Timestamps::now(); test_finished_output_pipeline_at( @@ -5989,7 +6091,6 @@ mod tests { cursor: None, track_failures: Arc::new(std::sync::Mutex::new(Vec::new())), watcher_task: None, - #[cfg(any(target_os = "linux", windows))] stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)), }; pipeline.spawn_start_time_persister(); @@ -6079,7 +6180,6 @@ mod tests { cursor: None, track_failures: Arc::new(std::sync::Mutex::new(Vec::new())), watcher_task: None, - #[cfg(any(target_os = "linux", windows))] stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)), }; let pipeline = Pipeline { @@ -6852,7 +6952,6 @@ mod tests { cursor: None, track_failures: Arc::new(std::sync::Mutex::new(Vec::new())), watcher_task: None, - #[cfg(any(target_os = "linux", windows))] stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)), }; pipeline.spawn_watcher(completion_tx);