From 0e6ae12265f626d7b17af51dc751020d1fad7e71 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:12:07 -0500 Subject: [PATCH 01/13] fix(recording): stop and save a macOS recording when its capture source goes away --- 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 | 19 ++- apps/desktop-gpui/src/session.rs | 33 +++++- .../desktop-gpui/src/upload/real_app_tests.rs | 12 +- .../src/sources/screen_capture/macos.rs | 13 +++ crates/recording/src/studio_recording.rs | 109 ++++++++++++++++-- 13 files changed, 191 insertions(+), 14 deletions(-) diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index c96d36f22a2..72b447bea0b 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -1405,6 +1405,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 29f268aa5c6..0ffbf049da8 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -1407,6 +1407,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 27fbf306d17..b14bbfba8f9 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -1405,6 +1405,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 87b46c59460..bb1aa19f733 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -1405,6 +1405,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 319ed6675bb..c1972a1225e 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -1405,6 +1405,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 d007debfd05..72eb752103d 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -1405,6 +1405,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 922d4ee4a5d..9ac1126ff47 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -1405,6 +1405,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 39be8a23156..e74d19e880a 100644 --- a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs @@ -283,6 +283,11 @@ 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 928b64406e1..8761e0c125c 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 e060273d970..20caf93402e 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. @@ -504,6 +506,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, @@ -785,6 +788,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()); @@ -1090,7 +1094,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}"), @@ -1101,6 +1107,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); @@ -2177,6 +2190,14 @@ 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 { .. }) } @@ -2422,6 +2443,16 @@ mod clean_capture_tests { } } + /// 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 recording_failure_targets_only_the_current_recording() { 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 4712673fac7..41ef7e13e2b 100644 --- a/apps/desktop-gpui/src/upload/real_app_tests.rs +++ b/apps/desktop-gpui/src/upload/real_app_tests.rs @@ -818,8 +818,8 @@ async fn real_app_start_cue_waits_for_a_slow_server_video() { /// 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 +/// can never confirm cleanup. The app then stops and saves the recording in +/// both modes, well before the auto-record driver would press Stop. 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")] @@ -883,6 +883,14 @@ async fn real_app_display_sleep_ends_the_recording_with_its_media() { !log.contains("Capture cleanup is unconfirmed"), "{mode}: Stop was left waiting on a dead capture:\n{log}" ); + // The app stops the recording itself and saves it, instead of + // counting on while nothing is captured or reporting a failure. + assert!( + log.contains("capture source went away; stopping and saving the recording") + && log.contains("recording finished") + && !log.contains("recording pipeline failed"), + "{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:?}"); let project = &projects[0]; diff --git a/crates/recording/src/sources/screen_capture/macos.rs b/crates/recording/src/sources/screen_capture/macos.rs index b0f02e0fed1..a9f49bf20fd 100644 --- a/crates/recording/src/sources/screen_capture/macos.rs +++ b/crates/recording/src/sources/screen_capture/macos.rs @@ -898,6 +898,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 +1393,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 +1404,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, diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index be6d6cfc74a..8bec4a112b4 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,28 @@ 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) => { @@ -3794,7 +3809,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)), }) } @@ -4507,7 +4521,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, @@ -5593,7 +5606,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)), }; @@ -5773,6 +5785,88 @@ mod tests { } } + #[cfg(target_os = "macos")] + async fn watched_screen_pipeline() -> ( + Pipeline, + flume::Sender, + DoneFut, + 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); + ( + pipeline, + screen_tx, + completion_rx_to_done_fut(completion_rx), + 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, _temp_dir) = watched_screen_pipeline().await; + assert!(done.clone().now_or_never().is_none()); + + pipeline.screen.cancel(); + + 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, _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( @@ -5942,7 +6036,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(); @@ -6032,7 +6125,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 { @@ -6805,7 +6897,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); From 8968dad6b541c74e2773d41aa34cc61dd08876eb Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:19:00 -0500 Subject: [PATCH 02/13] style: rustfmt --- apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs | 5 ++++- apps/desktop-gpui/src/session.rs | 4 +++- crates/recording/src/studio_recording.rs | 3 +-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs index e74d19e880a..913acc67980 100644 --- a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs @@ -287,7 +287,10 @@ fn dialog_surfaces_match_the_literals_they_replaced() { 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::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/session.rs b/apps/desktop-gpui/src/session.rs index 20caf93402e..9e993dad306 100644 --- a/apps/desktop-gpui/src/session.rs +++ b/apps/desktop-gpui/src/session.rs @@ -2194,7 +2194,9 @@ fn sleep_action( /// 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 { +fn capture_ended_cleanly( + outcome: &Result, E>, +) -> bool { cfg!(target_os = "macos") && matches!(outcome, Ok(Ok(()))) } diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index 8bec4a112b4..622d74dd581 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -1845,8 +1845,7 @@ impl Pipeline { // 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) - { + 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() { From fc2cf30256e35a6f892d83ee4eec00c68604d453 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:26:02 -0500 Subject: [PATCH 03/13] test(recording): give the macOS stop-order fixture the stopping flag --- crates/recording/src/studio_recording.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index 622d74dd581..f62d3245bb3 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -5727,6 +5727,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()); From 1eb8fe365754332d9bbd67b44575a36492b25eee Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:35:22 -0500 Subject: [PATCH 04/13] test(recording): model the actor's completion sender in the macOS watcher tests --- crates/recording/src/studio_recording.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index f62d3245bb3..bafea69d8cd 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -5785,11 +5785,15 @@ 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(); @@ -5823,11 +5827,12 @@ mod tests { watcher_task: None, stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)), }; - pipeline.spawn_watcher(completion_tx); + pipeline.spawn_watcher(completion_tx.clone()); ( pipeline, screen_tx, completion_rx_to_done_fut(completion_rx), + completion_tx, temp_dir, ) } @@ -5839,10 +5844,12 @@ mod tests { #[cfg(target_os = "macos")] #[tokio::test] async fn macos_screen_capture_ending_before_stop_completes_the_recording() { - let (pipeline, _screen_tx, done, _temp_dir) = watched_screen_pipeline().await; + 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 @@ -5854,7 +5861,8 @@ mod tests { #[cfg(target_os = "macos")] #[tokio::test] async fn macos_pause_or_stop_does_not_complete_the_recording() { - let (pipeline, screen_tx, done, _temp_dir) = watched_screen_pipeline().await; + 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); From 6ac82b7f94e501c8adec7d0351f36212db1e858f Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:45:17 -0500 Subject: [PATCH 05/13] test(desktop-gpui): run the capture source test on every platform --- apps/desktop-gpui/src/session.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs index 9e993dad306..af5e0480503 100644 --- a/apps/desktop-gpui/src/session.rs +++ b/apps/desktop-gpui/src/session.rs @@ -2445,16 +2445,6 @@ mod clean_capture_tests { } } - /// 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 recording_failure_targets_only_the_current_recording() { for paused in [false, true] { @@ -2808,6 +2798,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] { From 5bd3197696e192d5be97b89f9066e38f84319119 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:47:40 -0500 Subject: [PATCH 06/13] fix(desktop-gpui): only say a lost-source recording was saved when Stop saved it --- apps/desktop-gpui/src/session.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs index af5e0480503..5d0032c6e04 100644 --- a/apps/desktop-gpui/src/session.rs +++ b/apps/desktop-gpui/src/session.rs @@ -1479,11 +1479,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()); } From 35ffc3975fb99047a10c15a41e3632063f4fcb7b Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:05:40 -0500 Subject: [PATCH 07/13] test(desktop-gpui): real-app check that closing the recorded window stops and saves --- .../desktop-gpui/src/upload/real_app_tests.rs | 124 +++++++++++++----- 1 file changed, 91 insertions(+), 33 deletions(-) diff --git a/apps/desktop-gpui/src/upload/real_app_tests.rs b/apps/desktop-gpui/src/upload/real_app_tests.rs index 41ef7e13e2b..3dd3bfd42c6 100644 --- a/apps/desktop-gpui/src/upload/real_app_tests.rs +++ b/apps/desktop-gpui/src/upload/real_app_tests.rs @@ -815,31 +815,34 @@ 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. The app then stops and saves the recording in -/// both modes, well before the auto-record driver would press Stop. 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, + 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}"); + 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, @@ -849,15 +852,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") @@ -877,22 +872,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}" ); - // The app stops the recording itself and saves it, instead of - // counting on while nothing is captured or reporting a failure. assert!( log.contains("capture source went away; stopping and saving the recording") && log.contains("recording finished") && !log.contains("recording pipeline failed"), - "{mode}: the recording was not stopped and saved when its source went away:\n{log}" + "{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 @@ -900,7 +893,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 { @@ -909,7 +902,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) ); @@ -917,6 +910,71 @@ 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 because the app that owns it quits. +#[cfg(target_os = "macos")] +#[ignore] +#[tokio::test(flavor = "multi_thread")] +async fn real_app_recorded_window_closing_ends_the_recording_with_its_media() { + let title = |mode: &str| format!("Cap capture target {mode} {}", std::process::id()); + let owners = std::sync::Mutex::new(Vec::::new()); + losing_the_capture_source_stops_and_saves( + "window-closed", + |mode| { + let title = title(mode); + let owner = Command::new("osascript") + .args([ + "-e", + &format!( + "display dialog \"{title}\" with title \"{title}\" giving up after 120" + ), + ]) + .spawn() + .unwrap(); + owners.lock().unwrap().push(owner); + std::thread::sleep(Duration::from_secs(2)); + vec![ + ("CAP_GPUI_AUTO_OVERLAY".into(), "window".into()), + ("CAP_GPUI_AUTO_WINDOW".into(), title), + ] + }, + |_| { + for mut owner in owners.lock().unwrap().drain(..) { + let _ = owner.kill(); + let _ = owner.wait(); + } + }, + ) + .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 From e33c5839e7dcfd43fbed093466e25924eaa256aa Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:12:37 +0000 Subject: [PATCH 08/13] test(desktop-gpui): record a TextEdit window and quit TextEdit in the window-close check --- .../desktop-gpui/src/upload/real_app_tests.rs | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/apps/desktop-gpui/src/upload/real_app_tests.rs b/apps/desktop-gpui/src/upload/real_app_tests.rs index 3dd3bfd42c6..90b28239efe 100644 --- a/apps/desktop-gpui/src/upload/real_app_tests.rs +++ b/apps/desktop-gpui/src/upload/real_app_tests.rs @@ -943,33 +943,31 @@ async fn real_app_display_sleep_ends_the_recording_with_its_media() { #[ignore] #[tokio::test(flavor = "multi_thread")] async fn real_app_recorded_window_closing_ends_the_recording_with_its_media() { - let title = |mode: &str| format!("Cap capture target {mode} {}", std::process::id()); - let owners = std::sync::Mutex::new(Vec::::new()); + let documents = tempfile::tempdir().unwrap(); losing_the_capture_source_stops_and_saves( "window-closed", |mode| { - let title = title(mode); - let owner = Command::new("osascript") - .args([ - "-e", - &format!( - "display dialog \"{title}\" with title \"{title}\" giving up after 120" - ), - ]) - .spawn() - .unwrap(); - owners.lock().unwrap().push(owner); - std::thread::sleep(Duration::from_secs(2)); + 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(); + assert!( + Command::new("open") + .args(["-a", "TextEdit"]) + .arg(&document) + .status() + .unwrap() + .success() + ); + std::thread::sleep(Duration::from_secs(3)); vec![ ("CAP_GPUI_AUTO_OVERLAY".into(), "window".into()), ("CAP_GPUI_AUTO_WINDOW".into(), title), ] }, |_| { - for mut owner in owners.lock().unwrap().drain(..) { - let _ = owner.kill(); - let _ = owner.wait(); - } + let _ = Command::new("osascript") + .args(["-e", "tell application \"TextEdit\" to quit saving no"]) + .status(); }, ) .await; From b3e3fbc1c059c7e1c4f16059e51c06f774204233 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:35:11 +0000 Subject: [PATCH 09/13] fix(recording): stop and save a macOS window recording when its window closes --- .../src/sources/screen_capture/macos.rs | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/crates/recording/src/sources/screen_capture/macos.rs b/crates/recording/src/sources/screen_capture/macos.rs index 6fb2f72acf8..1338c64029f 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. @@ -758,10 +766,49 @@ 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 = rebuild_params + .config + .window + .clone() + .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, @@ -1599,6 +1646,13 @@ mod tests { ); } + /// 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(); From 3e1e1f36dd62b95458def77d5c8f65e819bb1a74 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:43:28 +0000 Subject: [PATCH 10/13] test(desktop-gpui): record the closing window as a focused-window capture --- apps/desktop-gpui/src/upload/real_app_tests.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/apps/desktop-gpui/src/upload/real_app_tests.rs b/apps/desktop-gpui/src/upload/real_app_tests.rs index 90b28239efe..17404f7a2b2 100644 --- a/apps/desktop-gpui/src/upload/real_app_tests.rs +++ b/apps/desktop-gpui/src/upload/real_app_tests.rs @@ -824,12 +824,16 @@ async fn real_app_start_cue_waits_for_a_slow_server_video() { #[cfg(target_os = "macos")] 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); + for (key, value) in settings { + sandbox.set_general(key, value.clone()); + } let name = format!("{case}-{mode}"); let auto = if mode == "studio" { "studio:30" @@ -922,6 +926,7 @@ async fn real_app_display_sleep_ends_the_recording_with_its_media() { } losing_the_capture_source_stops_and_saves( "display-sleep", + &[], |_| Vec::new(), |_| { assert!( @@ -938,7 +943,9 @@ async fn real_app_display_sleep_ends_the_recording_with_its_media() { .await; } -/// The recorded window goes away because the app that owns it quits. +/// The recorded window goes away because the app that owns it quits. Only a +/// focused-window capture loses its source; a screen-region capture of a +/// window keeps recording that region of the screen. #[cfg(target_os = "macos")] #[ignore] #[tokio::test(flavor = "multi_thread")] @@ -946,6 +953,7 @@ async fn real_app_recorded_window_closing_ends_the_recording_with_its_media() { let documents = tempfile::tempdir().unwrap(); 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); From 9f5a6b76fbff5e752e0400da1c7ab6b3be525c29 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:50:14 +0000 Subject: [PATCH 11/13] test(desktop-gpui): close only the test's TextEdit document instead of quitting TextEdit --- .../desktop-gpui/src/upload/real_app_tests.rs | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/apps/desktop-gpui/src/upload/real_app_tests.rs b/apps/desktop-gpui/src/upload/real_app_tests.rs index 17404f7a2b2..46dfb6d3de5 100644 --- a/apps/desktop-gpui/src/upload/real_app_tests.rs +++ b/apps/desktop-gpui/src/upload/real_app_tests.rs @@ -943,19 +943,21 @@ async fn real_app_display_sleep_ends_the_recording_with_its_media() { .await; } -/// The recorded window goes away because the app that owns it quits. Only a -/// focused-window capture loses its source; a screen-region capture of a -/// window keeps recording that region of the screen. +/// The recorded window closes. Only a focused-window capture loses its +/// source; a screen-region capture of a window keeps recording that region of +/// the screen. Only the test's own TextEdit document is closed, so other open +/// documents and their unsaved edits are left alone. #[cfg(target_os = "macos")] #[ignore] #[tokio::test(flavor = "multi_thread")] async fn real_app_recorded_window_closing_ends_the_recording_with_its_media() { let documents = tempfile::tempdir().unwrap(); + let title = |mode: &str| format!("cap-capture-target-{mode}-{}", std::process::id()); losing_the_capture_source_stops_and_saves( "window-closed", &[("windowCaptureStyle", json!("focusedWindow"))], |mode| { - let title = format!("cap-capture-target-{mode}-{}", std::process::id()); + let title = title(mode); let document = documents.path().join(&title); std::fs::write(&document, "The window Cap records").unwrap(); assert!( @@ -972,10 +974,12 @@ async fn real_app_recorded_window_closing_ends_the_recording_with_its_media() { ("CAP_GPUI_AUTO_WINDOW".into(), title), ] }, - |_| { - let _ = Command::new("osascript") - .args(["-e", "tell application \"TextEdit\" to quit saving no"]) - .status(); + |mode| { + let script = format!( + "tell application \"TextEdit\" to close (every document whose name is \"{}\") saving no", + title(mode) + ); + let _ = Command::new("osascript").args(["-e", &script]).status(); }, ) .await; From 2a48b761023f04eb4033339c50f63d31fa17d494 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:24:32 +0000 Subject: [PATCH 12/13] test(desktop-gpui): end the test's own TextEdit instance instead of scripting a close --- .../desktop-gpui/src/upload/real_app_tests.rs | 41 +++++++++++++------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/apps/desktop-gpui/src/upload/real_app_tests.rs b/apps/desktop-gpui/src/upload/real_app_tests.rs index 46dfb6d3de5..f3767da4993 100644 --- a/apps/desktop-gpui/src/upload/real_app_tests.rs +++ b/apps/desktop-gpui/src/upload/real_app_tests.rs @@ -943,43 +943,60 @@ async fn real_app_display_sleep_ends_the_recording_with_its_media() { .await; } -/// The recorded window closes. Only a focused-window capture loses its +/// 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. Only the test's own TextEdit document is closed, so other open -/// documents and their unsaved edits are left alone. +/// 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 title = |mode: &str| format!("cap-capture-target-{mode}-{}", std::process::id()); + let opened = std::sync::Mutex::new(Vec::::new()); losing_the_capture_source_stops_and_saves( "window-closed", &[("windowCaptureStyle", json!("focusedWindow"))], |mode| { - let title = title(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(["-a", "TextEdit"]) + .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), ] }, - |mode| { - let script = format!( - "tell application \"TextEdit\" to close (every document whose name is \"{}\") saving no", - title(mode) - ); - let _ = Command::new("osascript").args(["-e", &script]).status(); + |_| { + for pid in opened.lock().unwrap().drain(..) { + let _ = Command::new("kill").arg(&pid).status(); + } }, ) .await; From 33e4fb4c5cc53a20ee528ff55e8cebe149c9c20f Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:50:03 +0000 Subject: [PATCH 13/13] fix(recording): only watch for a closed window when the stream records that window --- .../src/sources/screen_capture/macos.rs | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/crates/recording/src/sources/screen_capture/macos.rs b/crates/recording/src/sources/screen_capture/macos.rs index 1338c64029f..a5ddcce8e66 100644 --- a/crates/recording/src/sources/screen_capture/macos.rs +++ b/crates/recording/src/sources/screen_capture/macos.rs @@ -57,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, @@ -766,11 +772,9 @@ 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 = rebuild_params - .config - .window - .clone() - .map(|window| (window, tokio::time::interval(WINDOW_WATCH_INTERVAL), 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! { @@ -1646,6 +1650,18 @@ 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]