From 72e07ea1890abb77acd718b106f07fbf121db1cc Mon Sep 17 00:00:00 2001 From: Tadhg Dowdall Date: Thu, 29 Oct 2026 10:34:20 +0000 Subject: [PATCH 001/720] perf(gpui): reduce PNG filter scoring work --- apps/desktop-gpui/kernels/src/png.rs | 42 ++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/apps/desktop-gpui/kernels/src/png.rs b/apps/desktop-gpui/kernels/src/png.rs index 4a0377a5853..ed7ca5ada6b 100644 --- a/apps/desktop-gpui/kernels/src/png.rs +++ b/apps/desktop-gpui/kernels/src/png.rs @@ -248,12 +248,15 @@ fn adaptive_filter( } fn sum_abs(buf: &[u8]) -> u64 { - buf.chunks(32) + // Each chunk sums to at most 256 * 128, keeping the narrow reduction exact. + buf.chunks(256) .map(|chunk| { - chunk - .iter() - .map(|&b| u64::from((b as i8).unsigned_abs())) - .sum::() + u64::from( + chunk + .iter() + .map(|&b| u16::from((b as i8).unsigned_abs())) + .sum::(), + ) }) .sum() } @@ -315,6 +318,35 @@ fn paeth(a: u8, b: u8, c: u8) -> u8 { mod tests { use super::*; + #[test] + fn signed_filter_cost_matches_wide_reference_across_chunk_boundaries() { + for len in (0..=1_025).chain([15_360, 65_537, 1_048_577]) { + for byte in [0, 127, 128, 255] { + let bytes = vec![byte; len]; + let expected = len as u64 * u64::from((byte as i8).unsigned_abs()); + assert_eq!(sum_abs(&bytes), expected, "byte {byte}, length {len}"); + } + + let mut state = 0x1234_5678_u32; + let bytes: Vec<_> = (0..len) + .map(|index| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + if len <= 1_025 { + index as u8 + } else { + state as u8 + } + }) + .collect(); + let expected = bytes.iter().fold(0u64, |sum, &byte| { + sum + u64::from((byte as i8).unsigned_abs()) + }); + assert_eq!(sum_abs(&bytes), expected, "length {len}"); + } + } + fn screen_like(width: u32, height: u32, channels: usize) -> Vec { let mut state = 0x2545_f491_u32; let mut data = Vec::with_capacity(width as usize * height as usize * channels); From 3232c742eaddf008fd8b636c01d951d751917a68 Mon Sep 17 00:00:00 2001 From: bestgopher <84328409@qq.com> Date: Tue, 27 Oct 2026 14:13:34 +0800 Subject: [PATCH 002/720] fix(desktop): avoid duplicate content type in signed uploads Use the server-provided Content-Type when present and infer a fallback only when it is absent, matching header names case-insensitively. This prevents RustFS from rejecting Instant metadata and thumbnail PUTs with InvalidRequest due to duplicate Content-Type headers. Extract request construction for regression tests covering header casing, fallback MIME types, additional headers, and Google Drive content ranges. Validation: two extracted regression tests and real RustFS uploads pass. Full desktop cargo check is blocked by the missing local zed-cap checkout. Closes CapSoftware/Cap#3462 Fixes:[CapSoftware/Cap#3462] Signed-off-by: bestgopher <84328409@qq.com> --- apps/desktop-gpui/src/upload.rs | 100 +++++++++++++++++++++++++++++--- 1 file changed, 92 insertions(+), 8 deletions(-) diff --git a/apps/desktop-gpui/src/upload.rs b/apps/desktop-gpui/src/upload.rs index ce2d1cd9f13..4910b7cfdee 100644 --- a/apps/desktop-gpui/src/upload.rs +++ b/apps/desktop-gpui/src/upload.rs @@ -2486,22 +2486,26 @@ async fn presign_put_target( .map_err(|error| AuthApiError::Other(format!("api/upload_signed/response: {error}"))) } -async fn upload_signed_bytes_inner( +fn signed_upload_request( + client: &reqwest::Client, target: SignedUploadTarget, subpath: &str, bytes: Vec, - cancel: Option<&AtomicBool>, -) -> Result<(), AuthApiError> { - static CLIENT: OnceLock = OnceLock::new(); - +) -> reqwest::RequestBuilder { let length = bytes.len() as u64; - let mut request = CLIENT - .get_or_init(upload_client) + let mut request = client .put(&target.url) .header("Content-Length", length) - .header("Content-Type", upload_content_type(subpath)) .timeout(Duration::from_secs(5 * 60)) .body(bytes); + // reqwest appends headers; duplicating the signed Content-Type makes RustFS reject the PUT. + if !target + .headers + .keys() + .any(|name| name.eq_ignore_ascii_case("content-type")) + { + request = request.header("Content-Type", upload_content_type(subpath)); + } if is_google_drive_resumable_url(&target.url) && length > 0 { request = request.header( "Content-Range", @@ -2511,6 +2515,18 @@ async fn upload_signed_bytes_inner( for (name, value) in target.headers { request = request.header(name, value); } + request +} + +async fn upload_signed_bytes_inner( + target: SignedUploadTarget, + subpath: &str, + bytes: Vec, + cancel: Option<&AtomicBool>, +) -> Result<(), AuthApiError> { + static CLIENT: OnceLock = OnceLock::new(); + + let request = signed_upload_request(CLIENT.get_or_init(upload_client), target, subpath, bytes); let response = optional_upload_step(cancel, || async { send_upload_request(request).await.map_err(|error| { if error.is_timeout() { @@ -2779,6 +2795,74 @@ mod tests { } } + #[test] + fn signed_upload_request_sends_one_content_type() { + let client = reqwest::Client::new(); + for (subpath, supplied_name, expected) in [ + ("segments/manifest.json", None, "application/json"), + ("screenshot/screen-capture.jpg", None, "image/jpeg"), + ("segments/video/segment_001.m4s", None, "video/mp4"), + ( + "segments/manifest.json", + Some("Content-Type"), + "application/json", + ), + ( + "screenshot/screen-capture.jpg", + Some("content-type"), + "image/jpeg", + ), + ( + "segments/manifest.json", + Some("cOnTeNt-TyPe"), + "application/custom+json", + ), + ] { + let mut headers = HashMap::from([("x-amz-meta-test".into(), "preserved".into())]); + if let Some(name) = supplied_name { + headers.insert(name.into(), expected.into()); + } + let request = signed_upload_request( + &client, + SignedUploadTarget { + url: "http://127.0.0.1/upload".into(), + headers, + }, + subpath, + vec![1, 2, 3], + ) + .build() + .unwrap(); + + assert_eq!(request.headers().get_all("content-type").iter().count(), 1); + assert_eq!(request.headers()["content-type"], expected); + assert_eq!(request.headers()["content-length"], "3"); + assert_eq!(request.headers()["x-amz-meta-test"], "preserved"); + assert_eq!( + request.body().unwrap().as_bytes(), + Some([1, 2, 3].as_slice()) + ); + } + } + + #[test] + fn signed_upload_request_preserves_drive_content_range() { + let request = signed_upload_request( + &reqwest::Client::new(), + SignedUploadTarget { + url: "https://www.googleapis.com/upload/drive/v3/files?upload_id=test".into(), + headers: HashMap::from([("Content-Type".into(), "image/png".into())]), + }, + "screenshot/screen-capture.png", + vec![1, 2, 3], + ) + .build() + .unwrap(); + + assert_eq!(request.headers()["content-range"], "bytes 0-2/3"); + assert_eq!(request.headers().get_all("content-type").iter().count(), 1); + } + #[tokio::test] async fn presigned_transfer_errors_never_expose_secret_urls() { let client = reqwest::Client::new(); From d59b4ab7122e9d796ca159d6c44531c06c14fb96 Mon Sep 17 00:00:00 2001 From: sheeesh3 <221579354+sheeesh3@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:25:49 +0530 Subject: [PATCH 003/720] fix(desktop-gpui): capture shortcuts no longer change the recording mode "Screenshot an area" saved Screenshot as the recording mode, so every later "Record a ..." shortcut opened its picker in Screenshot mode and took screenshots. Capture shortcuts and the tray's capture items now open the picker in their own mode for that one capture; the saved mode changes only when the user picks one. Record commands always record, in Studio when the saved mode is Screenshot. Fixes #3597 --- apps/desktop-gpui/locales/de.toml | 6 -- apps/desktop-gpui/locales/en.toml | 6 -- apps/desktop-gpui/locales/es.toml | 6 -- apps/desktop-gpui/locales/fr.toml | 6 -- apps/desktop-gpui/locales/hi.toml | 6 -- apps/desktop-gpui/locales/ja.toml | 6 -- apps/desktop-gpui/locales/zh-CN.toml | 6 -- apps/desktop-gpui/src/app_windows.rs | 30 +++++-- apps/desktop-gpui/src/hotkeys.rs | 27 ++++-- apps/desktop-gpui/src/main_window.rs | 107 +++++++++++++++++++++--- apps/desktop-gpui/src/settings_pages.rs | 27 ++---- apps/desktop-gpui/src/tray.rs | 23 ++--- 12 files changed, 153 insertions(+), 103 deletions(-) diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index 5725666b5a5..ef33fc90449 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -459,13 +459,10 @@ instant_copy_and_open = "den ausgewählten Bildschirm oder das ausgewählte Fens open_picker = "Cap zu öffnen und auszuwählen, was Sie aufnehmen möchten" pause = "die laufende Aufnahme zu pausieren oder fortzusetzen" picker_area_instant = "einen Bereich auszuwählen und ihn im Instant-Modus aufzunehmen" -picker_area_screenshot = "einen Bereich auszuwählen und ein Bildschirmfoto davon zu machen" picker_area_studio = "einen Bereich auszuwählen und ihn im Studio-Modus aufzunehmen" picker_display_instant = "einen Bildschirm zu wählen und ihn im Instant-Modus aufzunehmen" -picker_display_screenshot = "einen Bildschirm zu wählen und ein Bildschirmfoto davon zu machen" picker_display_studio = "einen Bildschirm zu wählen und ihn im Studio-Modus aufzunehmen" picker_window_instant = "ein Fenster zu wählen und es im Instant-Modus aufzunehmen" -picker_window_screenshot = "ein Fenster zu wählen und ein Bildschirmfoto davon zu machen" picker_window_studio = "ein Fenster zu wählen und es im Studio-Modus aufzunehmen" restart = "die aktuelle Aufnahme zu verwerfen und neu zu beginnen" screenshot_area_copy = "einen Bereich auszuwählen und das Bildschirmfoto in die Zwischenablage zu kopieren" @@ -492,13 +489,10 @@ instant_copy_and_open = "Ausgewählten Bildschirm oder ausgewähltes Fenster im open_picker = "Cap öffnen und auswählen, was Sie aufnehmen möchten." pause = "Die laufende Aufnahme pausieren oder fortsetzen." picker_area_instant = "Bereich auswählen und im Instant-Modus aufnehmen." -picker_area_screenshot = "Bereich auswählen und ein Bildschirmfoto davon machen." picker_area_studio = "Bereich auswählen und im Studio-Modus aufnehmen." picker_display_instant = "Bildschirm wählen und im Instant-Modus aufnehmen." -picker_display_screenshot = "Bildschirm wählen und ein Bildschirmfoto davon machen." picker_display_studio = "Bildschirm wählen und im Studio-Modus aufnehmen." picker_window_instant = "Fenster wählen und im Instant-Modus aufnehmen." -picker_window_screenshot = "Fenster wählen und ein Bildschirmfoto davon machen." picker_window_studio = "Fenster wählen und im Studio-Modus aufnehmen." restart = "Die aktuelle Aufnahme verwerfen und neu beginnen." screenshot_area_copy = "Bereich auswählen und das Bildschirmfoto in die Zwischenablage kopieren." diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index acaa9b33bdc..2fd05626831 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -461,13 +461,10 @@ instant_copy_and_open = "record your selected screen or window in Instant mode, open_picker = "open Cap so you can choose what to record" pause = "pause the current recording, or resume it" picker_area_instant = "select an area, then record it in Instant mode" -picker_area_screenshot = "select an area, then take a screenshot of it" picker_area_studio = "select an area, then record it in Studio mode" picker_display_instant = "choose a display, then record it in Instant mode" -picker_display_screenshot = "choose a display, then take a screenshot of it" picker_display_studio = "choose a display, then record it in Studio mode" picker_window_instant = "choose a window, then record it in Instant mode" -picker_window_screenshot = "choose a window, then take a screenshot of it" picker_window_studio = "choose a window, then record it in Studio mode" restart = "throw away the current take and start again" screenshot_area_copy = "select an area and copy it to your clipboard" @@ -494,13 +491,10 @@ instant_copy_and_open = "Record your selected screen or window in Instant mode, open_picker = "Open Cap so you can choose what to record." pause = "Pause the current recording, or resume it." picker_area_instant = "Select an area, then record it in Instant mode." -picker_area_screenshot = "Select an area, then take a screenshot of it." picker_area_studio = "Select an area, then record it in Studio mode." picker_display_instant = "Choose a display, then record it in Instant mode." -picker_display_screenshot = "Choose a display, then take a screenshot of it." picker_display_studio = "Choose a display, then record it in Studio mode." picker_window_instant = "Choose a window, then record it in Instant mode." -picker_window_screenshot = "Choose a window, then take a screenshot of it." picker_window_studio = "Choose a window, then record it in Studio mode." restart = "Throw away the current take and start again." screenshot_area_copy = "Select an area and copy it to your clipboard." diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index f50c16de1fd..3d84e5e335e 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -459,13 +459,10 @@ instant_copy_and_open = "grabar la pantalla o ventana seleccionada en modo Insta open_picker = "abrir Cap para elegir qué grabar" pause = "pausar la grabación actual o reanudarla" picker_area_instant = "seleccionar un área y luego grabarla en modo Instant" -picker_area_screenshot = "seleccionar un área y luego hacerle una captura de pantalla" picker_area_studio = "seleccionar un área y luego grabarla en modo Studio" picker_display_instant = "elegir una pantalla y luego grabarla en modo Instant" -picker_display_screenshot = "elegir una pantalla y luego hacerle una captura de pantalla" picker_display_studio = "elegir una pantalla y luego grabarla en modo Studio" picker_window_instant = "elegir una ventana y luego grabarla en modo Instant" -picker_window_screenshot = "elegir una ventana y luego hacerle una captura de pantalla" picker_window_studio = "elegir una ventana y luego grabarla en modo Studio" restart = "descartar la toma actual y empezar de nuevo" screenshot_area_copy = "seleccionar un área y copiar la captura al portapapeles" @@ -492,13 +489,10 @@ instant_copy_and_open = "Grabar la pantalla o ventana seleccionada en modo Insta open_picker = "Abrir Cap para elegir qué grabar." pause = "Pausar la grabación actual o reanudarla." picker_area_instant = "Seleccionar un área y luego grabarla en modo Instant." -picker_area_screenshot = "Seleccionar un área y luego hacerle una captura de pantalla." picker_area_studio = "Seleccionar un área y luego grabarla en modo Studio." picker_display_instant = "Elegir una pantalla y luego grabarla en modo Instant." -picker_display_screenshot = "Elegir una pantalla y luego hacerle una captura de pantalla." picker_display_studio = "Elegir una pantalla y luego grabarla en modo Studio." picker_window_instant = "Elegir una ventana y luego grabarla en modo Instant." -picker_window_screenshot = "Elegir una ventana y luego hacerle una captura de pantalla." picker_window_studio = "Elegir una ventana y luego grabarla en modo Studio." restart = "Descartar la toma actual y empezar de nuevo." screenshot_area_copy = "Seleccionar un área y copiar la captura al portapapeles." diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 24fa4ca3d6d..d9767d100f5 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -459,13 +459,10 @@ instant_copy_and_open = "enregistrer l'écran ou la fenêtre sélectionnés en m open_picker = "ouvrir Cap pour choisir ce que vous voulez enregistrer" pause = "mettre en pause l'enregistrement en cours, ou le reprendre" picker_area_instant = "sélectionner une zone, puis l'enregistrer en mode Instant" -picker_area_screenshot = "sélectionner une zone, puis en faire une capture d'écran" picker_area_studio = "sélectionner une zone, puis l'enregistrer en mode Studio" picker_display_instant = "choisir un écran, puis l'enregistrer en mode Instant" -picker_display_screenshot = "choisir un écran, puis en faire une capture d'écran" picker_display_studio = "choisir un écran, puis l'enregistrer en mode Studio" picker_window_instant = "choisir une fenêtre, puis l'enregistrer en mode Instant" -picker_window_screenshot = "choisir une fenêtre, puis en faire une capture d'écran" picker_window_studio = "choisir une fenêtre, puis l'enregistrer en mode Studio" restart = "abandonner la prise en cours et recommencer" screenshot_area_copy = "sélectionner une zone et copier la capture dans le presse-papiers" @@ -492,13 +489,10 @@ instant_copy_and_open = "Enregistrer l'écran ou la fenêtre sélectionnés en m open_picker = "Ouvrir Cap pour choisir ce que vous voulez enregistrer." pause = "Mettre en pause l'enregistrement en cours, ou le reprendre." picker_area_instant = "Sélectionner une zone, puis l'enregistrer en mode Instant." -picker_area_screenshot = "Sélectionner une zone, puis en faire une capture d'écran." picker_area_studio = "Sélectionner une zone, puis l'enregistrer en mode Studio." picker_display_instant = "Choisir un écran, puis l'enregistrer en mode Instant." -picker_display_screenshot = "Choisir un écran, puis en faire une capture d'écran." picker_display_studio = "Choisir un écran, puis l'enregistrer en mode Studio." picker_window_instant = "Choisir une fenêtre, puis l'enregistrer en mode Instant." -picker_window_screenshot = "Choisir une fenêtre, puis en faire une capture d'écran." picker_window_studio = "Choisir une fenêtre, puis l'enregistrer en mode Studio." restart = "Abandonner la prise en cours et recommencer." screenshot_area_copy = "Sélectionner une zone et copier la capture dans le presse-papiers." diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index af102b220d7..ae6770f3b91 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -459,13 +459,10 @@ instant_copy_and_open = "चुनी गई स्क्रीन या वि open_picker = "Cap खोलकर चुनें कि क्या रिकॉर्ड करना है" pause = "मौजूदा रिकॉर्डिंग पॉज़ करें या फिर से शुरू करें" picker_area_instant = "क्षेत्र चुनकर उसे Instant मोड में रिकॉर्ड करें" -picker_area_screenshot = "क्षेत्र चुनकर उसका स्क्रीनशॉट लें" picker_area_studio = "क्षेत्र चुनकर उसे Studio मोड में रिकॉर्ड करें" picker_display_instant = "डिस्प्ले चुनकर उसे Instant मोड में रिकॉर्ड करें" -picker_display_screenshot = "डिस्प्ले चुनकर उसका स्क्रीनशॉट लें" picker_display_studio = "डिस्प्ले चुनकर उसे Studio मोड में रिकॉर्ड करें" picker_window_instant = "विंडो चुनकर उसे Instant मोड में रिकॉर्ड करें" -picker_window_screenshot = "विंडो चुनकर उसका स्क्रीनशॉट लें" picker_window_studio = "विंडो चुनकर उसे Studio मोड में रिकॉर्ड करें" restart = "मौजूदा टेक हटाकर फिर से शुरू करें" screenshot_area_copy = "क्षेत्र चुनकर स्क्रीनशॉट को क्लिपबोर्ड पर कॉपी करें" @@ -492,13 +489,10 @@ instant_copy_and_open = "चुनी गई स्क्रीन या वि open_picker = "Cap खोलकर चुनें कि क्या रिकॉर्ड करना है।" pause = "मौजूदा रिकॉर्डिंग पॉज़ करें या फिर से शुरू करें।" picker_area_instant = "क्षेत्र चुनकर उसे Instant मोड में रिकॉर्ड करें।" -picker_area_screenshot = "क्षेत्र चुनकर उसका स्क्रीनशॉट लें।" picker_area_studio = "क्षेत्र चुनकर उसे Studio मोड में रिकॉर्ड करें।" picker_display_instant = "डिस्प्ले चुनकर उसे Instant मोड में रिकॉर्ड करें।" -picker_display_screenshot = "डिस्प्ले चुनकर उसका स्क्रीनशॉट लें।" picker_display_studio = "डिस्प्ले चुनकर उसे Studio मोड में रिकॉर्ड करें।" picker_window_instant = "विंडो चुनकर उसे Instant मोड में रिकॉर्ड करें।" -picker_window_screenshot = "विंडो चुनकर उसका स्क्रीनशॉट लें।" picker_window_studio = "विंडो चुनकर उसे Studio मोड में रिकॉर्ड करें।" restart = "मौजूदा टेक हटाकर फिर से शुरू करें।" screenshot_area_copy = "क्षेत्र चुनकर स्क्रीनशॉट को क्लिपबोर्ड पर कॉपी करें।" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 263a8534b1f..40cad636f90 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -459,13 +459,10 @@ instant_copy_and_open = "選択した画面またはウィンドウをInstantモ open_picker = "Capを開いて録画する対象を選びます" pause = "現在の録画を一時停止または再開します" picker_area_instant = "範囲を選択してInstantモードで録画します" -picker_area_screenshot = "範囲を選択してスクリーンショットを撮ります" picker_area_studio = "範囲を選択してStudioモードで録画します" picker_display_instant = "ディスプレイを選んでInstantモードで録画します" -picker_display_screenshot = "ディスプレイを選んでスクリーンショットを撮ります" picker_display_studio = "ディスプレイを選んでStudioモードで録画します" picker_window_instant = "ウィンドウを選んでInstantモードで録画します" -picker_window_screenshot = "ウィンドウを選んでスクリーンショットを撮ります" picker_window_studio = "ウィンドウを選んでStudioモードで録画します" restart = "現在のテイクを破棄してやり直します" screenshot_area_copy = "範囲を選択してクリップボードにコピーします" @@ -492,13 +489,10 @@ instant_copy_and_open = "選択した画面またはウィンドウをInstantモ open_picker = "Capを開いて録画する対象を選びます。" pause = "現在の録画を一時停止または再開します。" picker_area_instant = "範囲を選択してInstantモードで録画します。" -picker_area_screenshot = "範囲を選択してスクリーンショットを撮ります。" picker_area_studio = "範囲を選択してStudioモードで録画します。" picker_display_instant = "ディスプレイを選んでInstantモードで録画します。" -picker_display_screenshot = "ディスプレイを選んでスクリーンショットを撮ります。" picker_display_studio = "ディスプレイを選んでStudioモードで録画します。" picker_window_instant = "ウィンドウを選んでInstantモードで録画します。" -picker_window_screenshot = "ウィンドウを選んでスクリーンショットを撮ります。" picker_window_studio = "ウィンドウを選んでStudioモードで録画します。" restart = "現在のテイクを破棄してやり直します。" screenshot_area_copy = "範囲を選択してクリップボードにコピーします。" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 93ff8b6e973..1e82a727a15 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -459,13 +459,10 @@ instant_copy_and_open = "以 Instant 模式录制所选屏幕或窗口,停止 open_picker = "打开 Cap 以选择要录制的内容" pause = "暂停当前录制,或继续录制" picker_area_instant = "选择一个区域,然后以 Instant 模式录制" -picker_area_screenshot = "选择一个区域,然后截图" picker_area_studio = "选择一个区域,然后以 Studio 模式录制" picker_display_instant = "选择一个屏幕,然后以 Instant 模式录制" -picker_display_screenshot = "选择一个屏幕,然后截图" picker_display_studio = "选择一个屏幕,然后以 Studio 模式录制" picker_window_instant = "选择一个窗口,然后以 Instant 模式录制" -picker_window_screenshot = "选择一个窗口,然后截图" picker_window_studio = "选择一个窗口,然后以 Studio 模式录制" restart = "丢弃当前录制并重新开始" screenshot_area_copy = "选择一个区域并复制到剪贴板" @@ -492,13 +489,10 @@ instant_copy_and_open = "以 Instant 模式录制所选屏幕或窗口,停止 open_picker = "打开 Cap 以选择要录制的内容。" pause = "暂停当前录制,或继续录制。" picker_area_instant = "选择一个区域,然后以 Instant 模式录制。" -picker_area_screenshot = "选择一个区域,然后截图。" picker_area_studio = "选择一个区域,然后以 Studio 模式录制。" picker_display_instant = "选择一个屏幕,然后以 Instant 模式录制。" -picker_display_screenshot = "选择一个屏幕,然后截图。" picker_display_studio = "选择一个屏幕,然后以 Studio 模式录制。" picker_window_instant = "选择一个窗口,然后以 Instant 模式录制。" -picker_window_screenshot = "选择一个窗口,然后截图。" picker_window_studio = "选择一个窗口,然后以 Studio 模式录制。" restart = "丢弃当前录制并重新开始。" screenshot_area_copy = "选择一个区域并复制到剪贴板。" diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs index dde8c8d0975..586d8c651ff 100644 --- a/apps/desktop-gpui/src/app_windows.rs +++ b/apps/desktop-gpui/src/app_windows.rs @@ -6909,15 +6909,30 @@ pub fn abort_editor_recording_flow(cx: &mut App) { } } -/// The tray's Record Display / Record Window / Record Area. +/// The "Record …" shortcuts and the tray's Record Display / Record Window / +/// Record Area: the picker records, in the saved mode or Studio when that is +/// Screenshot, and the saved mode stays as it is. /// /// `crate::open_target_picker(&app, RecordingTargetMode::*)` over there, which /// sets the target mode on the main window and opens the overlays; here the -/// main window owns that state, so it is the same `arm_overlay` the tiles call. -pub fn arm_target_mode(kind: crate::main_window::TargetType, cx: &mut App) { +/// main window owns that state, so it is armed there, as its tiles arm it. +pub fn arm_record_picker(kind: TargetType, cx: &mut App) { let main = cx.global::().main; - main.update(cx, |view, _window, cx| view.arm_overlay(kind, cx)) - .ok(); + main.update(cx, |view, _window, cx| { + let mode = view.mode().for_recording(); + view.arm_overlay_for(kind, mode, cx) + }) + .ok(); +} + +/// The "Screenshot …" shortcuts and tray items that need a picker: it takes +/// a screenshot, and the saved mode stays as it is. +pub fn arm_screenshot_picker(kind: TargetType, cx: &mut App) { + let main = cx.global::().main; + main.update(cx, |view, _window, cx| { + view.arm_overlay_for(kind, Mode::Screenshot, cx) + }) + .ok(); } fn camera_window_number(cx: &mut App) -> Option { @@ -7112,6 +7127,11 @@ pub fn prepare_for_screenshot_capture(cx: &mut App) -> bool { release_camera_park(cx); keep_arranged_windows(cx); close_target_overlays(cx); + // The picker's capture is handed off, so its command's mode is spent. Not + // when the PNG lands: a picker opened while it is written keeps its own. + let main = cx.global::().main; + main.update(cx, |view, _window, cx| view.end_capture_mode(cx)) + .ok(); true } diff --git a/apps/desktop-gpui/src/hotkeys.rs b/apps/desktop-gpui/src/hotkeys.rs index 7527717ae4a..1197b62a9d3 100644 --- a/apps/desktop-gpui/src/hotkeys.rs +++ b/apps/desktop-gpui/src/hotkeys.rs @@ -1003,8 +1003,14 @@ fn dispatch(action: HotkeyAction, pressed_at: std::time::Instant, cx: &mut App) RecordingSession::global(cx).update(cx, |session, cx| session.toggle_pause(cx)); } HotkeyAction::CycleRecordingMode => { - // `Studio -> Instant -> Screenshot -> Studio` (`hotkeys.rs:262`). - let next = match Mode::from_store() { + // `Studio -> Instant -> Screenshot -> Studio` (`hotkeys.rs:262`), + // from the mode on screen: a picker a shortcut opened shows that + // shortcut's mode, not the saved one. + let main = cx.global::().main; + let current = main + .update(cx, |view, _window, cx| view.effective_mode(cx)) + .unwrap_or_else(|_| Mode::from_store()); + let next = match current { Mode::Studio => Mode::Instant, Mode::Instant => Mode::Screenshot, Mode::Screenshot => Mode::Studio, @@ -1016,12 +1022,14 @@ fn dispatch(action: HotkeyAction, pressed_at: std::time::Instant, cx: &mut App) cx.activate(true); } HotkeyAction::OpenRecordingPickerDisplay => { - app_windows::arm_target_mode(TargetType::Display, cx) + app_windows::arm_record_picker(TargetType::Display, cx) } HotkeyAction::OpenRecordingPickerWindow => { - app_windows::arm_target_mode(TargetType::Window, cx) + app_windows::arm_record_picker(TargetType::Window, cx) + } + HotkeyAction::OpenRecordingPickerArea => { + app_windows::arm_record_picker(TargetType::Area, cx) } - HotkeyAction::OpenRecordingPickerArea => app_windows::arm_target_mode(TargetType::Area, cx), HotkeyAction::ScreenshotDisplay => { let display = scap_targets::Display::get_containing_cursor() .unwrap_or_else(scap_targets::Display::primary); @@ -1042,10 +1050,11 @@ fn dispatch(action: HotkeyAction, pressed_at: std::time::Instant, cx: &mut App) } } HotkeyAction::ScreenshotArea => { - // `set_mode(Screenshot)` + the area picker (`hotkeys.rs:311-323`): - // the grab happens when the drawn area is released. - app_windows::set_recording_mode(Mode::Screenshot, cx); - app_windows::arm_target_mode(TargetType::Area, cx); + // The area picker in Screenshot mode for this capture only: the + // grab happens when the drawn area is released. The Tauri handler + // also `set_mode(Screenshot)`s (`hotkeys.rs:311-323`), which left + // every later "Record …" shortcut taking screenshots. + app_windows::arm_screenshot_picker(TargetType::Area, cx); } } } diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs index 28f6daac7bc..36473b616f6 100644 --- a/apps/desktop-gpui/src/main_window.rs +++ b/apps/desktop-gpui/src/main_window.rs @@ -107,11 +107,15 @@ pub enum Mode { Screenshot, } -fn effective_recording_mode(preferred: Mode, editor_recording: bool) -> Mode { +fn effective_recording_mode( + preferred: Mode, + capture: Option, + editor_recording: bool, +) -> Mode { if editor_recording { Mode::Studio } else { - preferred + capture.unwrap_or(preferred) } } @@ -144,6 +148,15 @@ impl Mode { .unwrap_or(Self::Instant) } + /// The mode a "Record …" shortcut or tray item records in: this one, or + /// Studio when this is Screenshot, so a Record command always records. + pub fn for_recording(self) -> Self { + match self { + Self::Screenshot => Self::Studio, + mode => mode, + } + } + pub fn icon(self) -> &'static str { match self { Self::Instant => "icons/instant.svg", @@ -943,6 +956,11 @@ struct MicrophoneWarning { pub struct MainWindow { theme: Theme, mode: Mode, + /// The mode the shortcut or tray item that opened the picker asked for, + /// in place of `mode` until that capture ends, the picker is dismissed, + /// or the user arms it or picks a mode themselves. Those commands name + /// what they capture; `mode` stays the user's own pick. + capture_mode: Option, mode_hover: ModeHoverState, mode_hover_task: Option>, mode_hover_bounds: [Rc>>>; 3], @@ -1078,6 +1096,7 @@ impl MainWindow { this.clear_mode_hover(); } if phase == Phase::Idle && previous_phase != Phase::Idle { + this.end_capture_mode(cx); this.scan_incomplete_recordings(window, cx, std::time::Duration::ZERO); if let Some(notice) = session.read(cx).storage_notice.clone() { let main = cx.global::().main; @@ -1244,6 +1263,7 @@ impl MainWindow { // window has to start where the store left it rather than at a // hardcoded Instant. mode: Mode::from_store(), + capture_mode: None, mode_hover: ModeHoverState::default(), mode_hover_task: None, mode_hover_bounds: std::array::from_fn(|_| Rc::new(Cell::new(None))), @@ -2012,11 +2032,20 @@ impl MainWindow { /// Called when the overlays are dismissed (Escape, their close button) so /// the armed tile stops looking armed. pub fn clear_target(&mut self, cx: &mut Context) { + self.end_capture_mode(cx); if self.target.take().is_some() { cx.notify(); } } + /// Back to the saved mode: the capture a shortcut or tray item opened the + /// picker for is over, or the user took the picker over. + pub fn end_capture_mode(&mut self, cx: &mut Context) { + if self.capture_mode.take().is_some() { + cx.notify(); + } + } + /// The recording mode, for whoever is showing it -- the mode select window /// seeds its cards from here, the way that route reads `rawOptions.mode`. pub fn mode(&self) -> Mode { @@ -2026,6 +2055,7 @@ impl MainWindow { pub(crate) fn effective_mode(&self, cx: &gpui::App) -> Mode { effective_recording_mode( self.mode(), + self.capture_mode, self.session.read(cx).editor_recording_target().is_some(), ) } @@ -2037,15 +2067,26 @@ impl MainWindow { pub fn set_mode(&mut self, mode: Mode, cx: &mut Context) { self.clear_mode_hover(); cx.notify(); - if self.mode == mode - || self.is_preparing_recording() + if self.is_preparing_recording() || self.session.read(cx).editor_recording_target().is_some() { return; } + // A pick ends the capture command's mode, so a picker it opened + // follows the pick even when that is already the saved mode. + let select = crate::target_overlay::TargetSelect::global(cx); + if self + .capture_mode + .take() + .is_some_and(|capture| capture != mode) + { + select.update(cx, |select, cx| select.set_recording_mode(mode, cx)); + } + if self.mode == mode { + return; + } self.mode = mode; // Open overlays label their start button with the mode. - let select = crate::target_overlay::TargetSelect::global(cx); select.update(cx, |select, cx| select.set_recording_mode(mode, cx)); tracing::info!( mode = mode.panel_title(), @@ -2292,11 +2333,25 @@ impl MainWindow { /// Arm a target mode the way clicking its tile does, picking a concrete /// window for the window variant since the harness cannot hover one. - /// - /// Also the tray's Record Display/Window/Area path: those items are - /// `crate::open_target_picker(&app, RecordingTargetMode::*)` over there, - /// which is the same "set the target mode, open the overlays" pair. pub fn arm_overlay(&mut self, kind: TargetType, cx: &mut Context) { + self.arm_overlay_in(kind, None, cx); + } + + /// [`Self::arm_overlay`] for one capture in `mode`, leaving the saved mode + /// alone: the "Record …" and "Screenshot …" shortcuts and tray items. + /// The tray's are `crate::open_target_picker(&app, RecordingTargetMode::*)` + /// over there, the same "set the target mode, open the overlays" pair. + pub fn arm_overlay_for(&mut self, kind: TargetType, mode: Mode, cx: &mut Context) { + self.arm_overlay_in(kind, Some(mode), cx); + } + + fn arm_overlay_in( + &mut self, + kind: TargetType, + capture_mode: Option, + cx: &mut Context, + ) { + self.capture_mode = capture_mode; if kind == TargetType::Window { self.selected_window = match auto_window_title() { Some(title) => self @@ -6005,6 +6060,7 @@ impl MainWindow { cx.listener(move |this, _, _window, cx| { this.selected_display = Some(chosen.clone()); this.target = Some(TargetType::Display); + this.end_capture_mode(cx); this.close_panel(cx); this.sync_overlays(cx); }), @@ -6038,6 +6094,7 @@ impl MainWindow { cx.listener(move |this, _, _window, cx| { this.selected_window = Some(chosen.clone()); this.target = Some(TargetType::Window); + this.end_capture_mode(cx); this.close_panel(cx); this.sync_overlays(cx); this.focus_selected_window(cx); @@ -6954,6 +7011,7 @@ impl MainWindow { if target == TargetType::Window { this.selected_window = None; } + this.end_capture_mode(cx); this.sync_overlays(cx); cx.notify(); })); @@ -7621,10 +7679,37 @@ mod recording_start_permit_tests { #[test] fn editor_recording_mode_does_not_change_the_normal_preference() { for preferred in [Mode::Instant, Mode::Studio, Mode::Screenshot] { - assert_eq!(effective_recording_mode(preferred, true), Mode::Studio); - assert_eq!(effective_recording_mode(preferred, false), preferred); + assert_eq!( + effective_recording_mode(preferred, None, true), + Mode::Studio + ); + assert_eq!(effective_recording_mode(preferred, None, false), preferred); + } + } + + #[test] + fn a_capture_command_mode_wins_without_changing_the_preference() { + let modes = [Mode::Instant, Mode::Studio, Mode::Screenshot]; + for preferred in modes { + for capture in modes { + assert_eq!( + effective_recording_mode(preferred, Some(capture), false), + capture + ); + assert_eq!( + effective_recording_mode(preferred, Some(capture), true), + Mode::Studio + ); + } } } + + #[test] + fn record_commands_record_whatever_the_saved_mode() { + assert_eq!(Mode::Studio.for_recording(), Mode::Studio); + assert_eq!(Mode::Instant.for_recording(), Mode::Instant); + assert_eq!(Mode::Screenshot.for_recording(), Mode::Studio); + } } #[cfg(test)] diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rs index 6dbf07e2201..74dcb511966 100644 --- a/apps/desktop-gpui/src/settings_pages.rs +++ b/apps/desktop-gpui/src/settings_pages.rs @@ -1169,8 +1169,10 @@ fn shortcut_effect( } } } + // `Mode::for_recording`: a "Record …" shortcut records in Studio when + // the saved mode is Screenshot. "openRecordingPickerArea" => match mode { - Mode::Studio => ShortcutEffect { + Mode::Studio | Mode::Screenshot => ShortcutEffect { phrase: tr::settings::shortcuts::effect::picker_area_studio, sentence: tr::settings::shortcuts::sentence::picker_area_studio, }, @@ -1178,13 +1180,9 @@ fn shortcut_effect( phrase: tr::settings::shortcuts::effect::picker_area_instant, sentence: tr::settings::shortcuts::sentence::picker_area_instant, }, - Mode::Screenshot => ShortcutEffect { - phrase: tr::settings::shortcuts::effect::picker_area_screenshot, - sentence: tr::settings::shortcuts::sentence::picker_area_screenshot, - }, }, "openRecordingPickerWindow" => match mode { - Mode::Studio => ShortcutEffect { + Mode::Studio | Mode::Screenshot => ShortcutEffect { phrase: tr::settings::shortcuts::effect::picker_window_studio, sentence: tr::settings::shortcuts::sentence::picker_window_studio, }, @@ -1192,13 +1190,9 @@ fn shortcut_effect( phrase: tr::settings::shortcuts::effect::picker_window_instant, sentence: tr::settings::shortcuts::sentence::picker_window_instant, }, - Mode::Screenshot => ShortcutEffect { - phrase: tr::settings::shortcuts::effect::picker_window_screenshot, - sentence: tr::settings::shortcuts::sentence::picker_window_screenshot, - }, }, "openRecordingPickerDisplay" => match mode { - Mode::Studio => ShortcutEffect { + Mode::Studio | Mode::Screenshot => ShortcutEffect { phrase: tr::settings::shortcuts::effect::picker_display_studio, sentence: tr::settings::shortcuts::sentence::picker_display_studio, }, @@ -1206,10 +1200,6 @@ fn shortcut_effect( phrase: tr::settings::shortcuts::effect::picker_display_instant, sentence: tr::settings::shortcuts::sentence::picker_display_instant, }, - Mode::Screenshot => ShortcutEffect { - phrase: tr::settings::shortcuts::effect::picker_display_screenshot, - sentence: tr::settings::shortcuts::sentence::picker_display_screenshot, - }, }, "openRecordingPicker" => ShortcutEffect { phrase: tr::settings::shortcuts::effect::open_picker, @@ -8301,9 +8291,10 @@ mod tests { } }; let picker = match mode { - crate::main_window::Mode::Studio => "record it in Studio mode", + crate::main_window::Mode::Studio | crate::main_window::Mode::Screenshot => { + "record it in Studio mode" + } crate::main_window::Mode::Instant => "record it in Instant mode", - crate::main_window::Mode::Screenshot => "take a screenshot of it", }; let studio_stop = match settings.post_studio_recording_behaviour { store::PostStudioBehaviour::OpenEditor => ", then open the editor when you stop", @@ -8381,7 +8372,7 @@ mod tests { } } } - assert_eq!(checked.len(), 31, "every effect message is reachable"); + assert_eq!(checked.len(), 28, "every effect message is reachable"); assert!(shortcut_effect("nope", &settings, Mode::Studio).is_none()); } diff --git a/apps/desktop-gpui/src/tray.rs b/apps/desktop-gpui/src/tray.rs index 1601cd06b21..2c134e89f46 100644 --- a/apps/desktop-gpui/src/tray.rs +++ b/apps/desktop-gpui/src/tray.rs @@ -700,20 +700,14 @@ pub fn handle_item(item: TrayItem, cx: &mut App) { // the window (and the menu bar) to come forward. cx.activate(true); } - TrayItem::RecordDisplay => record_target(TargetType::Display, cx), - TrayItem::RecordWindow => record_target(TargetType::Window, cx), - TrayItem::RecordArea => record_target(TargetType::Area, cx), + TrayItem::RecordDisplay => app_windows::arm_record_picker(TargetType::Display, cx), + TrayItem::RecordWindow => app_windows::arm_record_picker(TargetType::Window, cx), + TrayItem::RecordArea => app_windows::arm_record_picker(TargetType::Area, cx), // `TrayItem::TakeScreenshot` captures the display under the cursor, // primary as the fallback (`tray.rs:816` over there). TrayItem::TakeScreenshot | TrayItem::ScreenshotDisplay => take_display_screenshot(cx), - TrayItem::ScreenshotWindow => { - set_mode(Mode::Screenshot, cx); - app_windows::arm_target_mode(TargetType::Window, cx); - } - TrayItem::ScreenshotArea => { - set_mode(Mode::Screenshot, cx); - app_windows::arm_target_mode(TargetType::Area, cx); - } + TrayItem::ScreenshotWindow => app_windows::arm_screenshot_picker(TargetType::Window, cx), + TrayItem::ScreenshotArea => app_windows::arm_screenshot_picker(TargetType::Area, cx), // `TrayItem::ImportVideo` (`src-tauri/src/tray.rs:839-911`): one // picker over both media filters, routed by extension. TrayItem::ImportMedia => crate::import::pick_and_import_media(cx), @@ -741,13 +735,6 @@ pub fn handle_item(item: TrayItem, cx: &mut App) { } } -fn record_target(target: TargetType, cx: &mut App) { - if Mode::from_store() == Mode::Screenshot { - set_mode(Mode::Studio, cx); - } - app_windows::arm_target_mode(target, cx); -} - fn take_display_screenshot(cx: &mut App) { let display = scap_targets::Display::get_containing_cursor() .unwrap_or_else(scap_targets::Display::primary); From e7e5cde9c47325668768ae3eeca9a0560c535c4f Mon Sep 17 00:00:00 2001 From: Aditya Garud <153842990+yashranaway@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:34:09 +0000 Subject: [PATCH 004/720] fix(cli): isolate keyring operations from the async runtime --- .github/workflows/ci.yml | 3 ++ apps/cli/src/credentials.rs | 67 ++++++++++++++++++++++++++++--------- 2 files changed, 54 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 35e92d3a9c8..a11f4a47e49 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -331,6 +331,9 @@ jobs: cargo test --locked -p cap-utils -p cap-cli-install --lib cargo test --locked -p cap --bin cap record::tests cargo test --locked -p cap --bin cap recordings::tests + cargo test --locked -p cap --bin cap credentials::tests + cargo test --locked -p cap --test cli auth_status_ + cargo test --locked -p cap --test cli mcp_cancellation_stops_wait_polling cargo test --locked -p cap --bin cap automation::tests::cli_save_to_location cargo test --locked -p cap --bin cap export::tests::instant_export_preserves_a_hard_link_to_the_recording cargo test --locked -p cap --test cli recordings_list diff --git a/apps/cli/src/credentials.rs b/apps/cli/src/credentials.rs index ca3b497529e..8513e0eb2b1 100644 --- a/apps/cli/src/credentials.rs +++ b/apps/cli/src/credentials.rs @@ -206,10 +206,24 @@ fn agent_grants_path() -> Result { .ok_or_else(|| "Could not locate the user configuration directory".to_string()) } +fn with_keyring( + operation: impl FnOnce() -> keyring::Result + Send, +) -> Result { + std::thread::scope(|scope| { + std::thread::Builder::new() + .name("cap-keyring".to_string()) + .spawn_scoped(scope, operation) + .map_err(|error| error.to_string())? + .join() + .map_err(|_| "The OS credential store panicked".to_string())? + .map_err(|error| error.to_string()) + }) +} + fn load_agent_keyring() -> Result { - let entry = keyring::Entry::new(AGENT_KEYRING_SERVICE, AGENT_KEYRING_USER) - .map_err(|error| error.to_string())?; - let value = entry.get_password().map_err(|error| error.to_string())?; + let value = with_keyring(|| { + keyring::Entry::new(AGENT_KEYRING_SERVICE, AGENT_KEYRING_USER)?.get_password() + })?; serde_json::from_str(&value).map_err(|error| error.to_string()) } @@ -283,10 +297,11 @@ fn write_restricted_file(_path: &std::path::Path, _bytes: &[u8]) -> Result<(), S } fn load_agent_access_grants() -> StoredAgentAccessGrants { - let keyring = keyring::Entry::new(AGENT_KEYRING_SERVICE, AGENT_GRANTS_KEYRING_USER) - .and_then(|entry| entry.get_password()) - .ok() - .and_then(|value| serde_json::from_str(&value).ok()); + let keyring = with_keyring(|| { + keyring::Entry::new(AGENT_KEYRING_SERVICE, AGENT_GRANTS_KEYRING_USER)?.get_password() + }) + .ok() + .and_then(|value| serde_json::from_str(&value).ok()); if let Some(grants) = keyring { return grants; } @@ -333,8 +348,10 @@ pub fn store_agent_access_grant( }, ); let serialized = serde_json::to_string(&grants).map_err(|error| error.to_string())?; - let keyring_result = keyring::Entry::new(AGENT_KEYRING_SERVICE, AGENT_GRANTS_KEYRING_USER) - .and_then(|entry| entry.set_password(&serialized)); + let keyring_result = with_keyring(|| { + keyring::Entry::new(AGENT_KEYRING_SERVICE, AGENT_GRANTS_KEYRING_USER)? + .set_password(&serialized) + }); if keyring_result.is_ok() { let _ = std::fs::remove_file(agent_grants_path()?); return Ok(AgentCredentialStorage::Keyring); @@ -361,8 +378,9 @@ pub fn store_agent( ) -> Result { validate_agent_server(credential.server.clone())?; let serialized = serde_json::to_string(credential).map_err(|error| error.to_string())?; - let keyring_result = keyring::Entry::new(AGENT_KEYRING_SERVICE, AGENT_KEYRING_USER) - .and_then(|entry| entry.set_password(&serialized)); + let keyring_result = with_keyring(|| { + keyring::Entry::new(AGENT_KEYRING_SERVICE, AGENT_KEYRING_USER)?.set_password(&serialized) + }); if keyring_result.is_ok() { let _ = std::fs::remove_file(agent_credential_path()?); return Ok(AgentCredentialStorage::Keyring); @@ -419,11 +437,9 @@ pub fn resolve_agent() -> Result { } pub fn delete_agent() -> Result<(), String> { - if let Ok(entry) = keyring::Entry::new(AGENT_KEYRING_SERVICE, AGENT_KEYRING_USER) { - let _ = entry.delete_credential(); - } - if let Ok(entry) = keyring::Entry::new(AGENT_KEYRING_SERVICE, AGENT_GRANTS_KEYRING_USER) { - let _ = entry.delete_credential(); + for user in [AGENT_KEYRING_USER, AGENT_GRANTS_KEYRING_USER] { + let _ = + with_keyring(|| keyring::Entry::new(AGENT_KEYRING_SERVICE, user)?.delete_credential()); } for path in [agent_credential_path()?, agent_grants_path()?] { match std::fs::remove_file(path) { @@ -753,6 +769,25 @@ pub async fn status(format: OutputFormat) -> Result<(), String> { mod tests { use super::*; + #[tokio::test] + async fn keyring_operations_run_outside_the_async_runtime() { + assert_eq!( + with_keyring(|| { + assert!(tokio::runtime::Handle::try_current().is_err()); + Ok(42) + }), + Ok(42) + ); + } + + #[test] + fn keyring_operations_preserve_backend_errors() { + assert_eq!( + with_keyring(|| Err::<(), _>(keyring::Error::NoEntry)), + Err(keyring::Error::NoEntry.to_string()) + ); + } + #[test] fn agent_servers_require_https_except_for_loopback_development() { assert_eq!( From 5783e349ff93ea8a2f2b420dafeaee38185b40ca Mon Sep 17 00:00:00 2001 From: Paddy <89168564+patrickballard@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:29:34 +0000 Subject: [PATCH 005/720] fix(desktop-gpui): import videos whose file names are long A video import named its project folder after the source file plus the import time and never shortened it, so a file name longer than about 228 characters made a folder name over the 255 a file system allows and the import failed with "File name too long". The folder is now named through cap_utils::ensure_unique_filename, as image imports, recordings and screenshots already are, which cuts the name to fit and keeps the " (1)" suffix when the name is taken. Fixes #3931 --- apps/desktop-gpui/src/import.rs | 57 +++++++++++++++++++++++++-------- 1 file changed, 44 insertions(+), 13 deletions(-) diff --git a/apps/desktop-gpui/src/import.rs b/apps/desktop-gpui/src/import.rs index 48ac53cee7b..56126799aa2 100644 --- a/apps/desktop-gpui/src/import.rs +++ b/apps/desktop-gpui/src/import.rs @@ -91,15 +91,12 @@ fn sanitize_filename(name: &str) -> String { .collect() } -/// The `(1)`-suffix uniquing loop from `start_video_import` (`import.rs:1370-1376`). -fn unique_project_path(recordings_dir: &Path, sanitized_name: &str) -> PathBuf { - let mut project_path = recordings_dir.join(format!("{sanitized_name}.cap")); - let mut counter = 1; - while project_path.exists() { - project_path = recordings_dir.join(format!("{sanitized_name} ({counter}).cap")); - counter += 1; - } - project_path +/// The `(1)`-suffix uniquing from `start_video_import` (`import.rs:1370-1376`), +/// through the helper the image import uses so a long source name is cut to +/// fit a folder name instead of failing the import. +fn unique_project_path(recordings_dir: &Path, sanitized_name: &str) -> Result { + cap_utils::ensure_unique_filename(&format!("{sanitized_name}.cap"), recordings_dir) + .map(|name| recordings_dir.join(name)) } fn check_project_exists(project_path: &Path) -> bool { @@ -483,7 +480,20 @@ impl ProgressSink<'_> { fn run_video_import(source_path: &Path, tx: &flume::Sender) { let recordings_dir = crate::recording::recordings_dir(); let project_name = generate_project_name(source_path, "Imported Video"); - let project_path = unique_project_path(&recordings_dir, &sanitize_filename(&project_name)); + let sanitized_name = sanitize_filename(&project_name); + let project_path = match unique_project_path(&recordings_dir, &sanitized_name) { + Ok(path) => path, + Err(error) => { + ProgressSink { + tx, + kind: ImportKind::Video, + project_path: &recordings_dir.join(format!("{sanitized_name}.cap")), + pretty_name: &project_name, + } + .send(ImportStage::Failed, 0.0, &error); + return; + } + }; let sink = ProgressSink { tx, kind: ImportKind::Video, @@ -2217,20 +2227,41 @@ mod tests { fn unique_project_path_suffixes_like_the_tauri_import() { let dir = temp_dir("unique"); - let first = unique_project_path(&dir, "Video 2026-01-01 at 10.00.00"); + let first = unique_project_path(&dir, "Video 2026-01-01 at 10.00.00").unwrap(); assert!(first.ends_with("Video 2026-01-01 at 10.00.00.cap")); std::fs::create_dir_all(&first).unwrap(); - let second = unique_project_path(&dir, "Video 2026-01-01 at 10.00.00"); + let second = unique_project_path(&dir, "Video 2026-01-01 at 10.00.00").unwrap(); assert!(second.ends_with("Video 2026-01-01 at 10.00.00 (1).cap")); std::fs::create_dir_all(&second).unwrap(); - let third = unique_project_path(&dir, "Video 2026-01-01 at 10.00.00"); + let third = unique_project_path(&dir, "Video 2026-01-01 at 10.00.00").unwrap(); assert!(third.ends_with("Video 2026-01-01 at 10.00.00 (2).cap")); std::fs::remove_dir_all(&dir).ok(); } + #[test] + fn unique_project_path_fits_a_long_source_name_in_a_folder_name() { + let dir = temp_dir("long-name"); + let name = format!("{} 2026-01-01 at 10.00.00", "a".repeat(236)); + + let first = unique_project_path(&dir, &name).unwrap(); + std::fs::create_dir_all(&first).unwrap(); + let second = unique_project_path(&dir, &name).unwrap(); + std::fs::create_dir_all(&second).unwrap(); + + for path in [&first, &second] { + let folder = path.file_name().unwrap().to_str().unwrap(); + assert!(folder.len() <= 255, "{} bytes", folder.len()); + assert!(folder.starts_with("aaaa"), "{folder}"); + } + assert!(first.to_str().unwrap().ends_with(".cap")); + assert!(second.to_str().unwrap().ends_with(" (1).cap")); + + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn opus_output_rate_selection_matches_the_tauri_encoder() { let supported = [8_000, 12_000, 16_000, 24_000, 48_000]; From 63ae26b5efdeadb3bfd092db14e66f270d66d424 Mon Sep 17 00:00:00 2001 From: Akshar Patel Date: Mon, 9 Nov 2026 22:19:41 +0000 Subject: [PATCH 006/720] fix(linux): close Wayland sharing sessions after capture --- .../actions/install-desktop-deps/action.yml | 1 + .../src/sources/screen_capture/linux.rs | 60 ++- .../linux/wayland_portal_tests.rs | 385 ++++++++++++++++++ 3 files changed, 437 insertions(+), 9 deletions(-) create mode 100644 crates/recording/src/sources/screen_capture/linux/wayland_portal_tests.rs diff --git a/.github/actions/install-desktop-deps/action.yml b/.github/actions/install-desktop-deps/action.yml index 575f197509b..32da175f0cb 100644 --- a/.github/actions/install-desktop-deps/action.yml +++ b/.github/actions/install-desktop-deps/action.yml @@ -36,6 +36,7 @@ runs: libasound2-dev \ libasound2-plugins \ pulseaudio-utils \ + dbus-daemon \ libdbus-1-dev \ libudev-dev \ libx11-dev \ diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index 00eb649f7a4..3ef7a5575c1 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -44,6 +44,9 @@ mod x11_tests; #[cfg(test)] mod system_audio_channel_tests; +#[cfg(test)] +mod wayland_portal_tests; + use frame_scaler::FrameScaler; #[derive(Debug)] @@ -103,8 +106,49 @@ struct WaylandInputConfig { } struct WaylandPortalSession { - _proxy: Screencast<'static>, - _session: Session<'static, Screencast<'static>>, + session: Arc>>, + _close_on_drop: tokio::sync::oneshot::Sender<()>, +} + +impl WaylandPortalSession { + fn new(session: Session<'static, Screencast<'static>>) -> Self { + let session = Arc::new(session); + let (close_on_drop, dropped) = tokio::sync::oneshot::channel::<()>(); + let close = { + let session = session.clone(); + async move { + let _ = dropped.await; + let result = tokio::time::timeout(Duration::from_secs(3), session.close()) + .await + .context("Wayland screen capture portal session close timed out")?; + if let Err(ashpd::Error::Portal(ashpd::PortalError::ZBus( + ashpd::zbus::Error::MethodError(name, _, _), + ))) = &result + && matches!( + name.as_str(), + "org.freedesktop.DBus.Error.UnknownObject" + | "org.freedesktop.DBus.Error.UnknownMethod" + ) + { + return Ok(()); + } + result.context("close Wayland screen capture portal session") + } + }; + if let Some(scope) = crate::output_pipeline::PipelineBuildScope::current() { + scope.spawn_cleanup(close); + } else { + drop(tokio::spawn(async move { + if let Err(error) = close.await { + tracing::warn!(%error, "Could not close the Wayland screen capture portal session"); + } + })); + } + Self { + session, + _close_on_drop: close_on_drop, + } + } } pub struct VideoSource { @@ -382,6 +426,7 @@ async fn open_wayland_portal( .create_session() .await .context("create XDG Desktop Portal ScreenCast session")?; + let portal_session = WaylandPortalSession::new(session); let cursor_mode = if show_cursor { CursorMode::Embedded } else { @@ -390,7 +435,7 @@ async fn open_wayland_portal( proxy .select_sources( - &session, + &portal_session.session, cursor_mode, wayland_source_type(source), false, @@ -401,7 +446,7 @@ async fn open_wayland_portal( .context("select Wayland screen capture source")?; let response = proxy - .start(&session, None) + .start(&portal_session.session, None) .await .context("start Wayland screen capture portal request")? .response() @@ -412,17 +457,14 @@ async fn open_wayland_portal( .cloned() .ok_or_else(|| anyhow!("Wayland screen capture portal did not return a stream"))?; let fd = proxy - .open_pipe_wire_remote(&session) + .open_pipe_wire_remote(&portal_session.session) .await .context("open PipeWire remote for Wayland screen capture")?; Ok(WaylandPortalCapture { stream, fd, - portal_session: WaylandPortalSession { - _proxy: proxy, - _session: session, - }, + portal_session, }) } diff --git a/crates/recording/src/sources/screen_capture/linux/wayland_portal_tests.rs b/crates/recording/src/sources/screen_capture/linux/wayland_portal_tests.rs new file mode 100644 index 00000000000..c93e41ba0ff --- /dev/null +++ b/crates/recording/src/sources/screen_capture/linux/wayland_portal_tests.rs @@ -0,0 +1,385 @@ +use super::{LinuxCaptureSource, WaylandPortalCapture, open_wayland_portal}; +use crate::output_pipeline::PipelineBuildScope; +use ashpd::zbus::{ + self, Connection, + message::Header, + zvariant::{OwnedObjectPath, OwnedValue, Value}, +}; +use std::{ + collections::HashMap, + io::Read as _, + os::{fd::OwnedFd, unix::net::UnixStream}, + process::Command, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; + +const CHILD_CASE: &str = "CAP_TEST_PRIVATE_SCREENCAST_PORTAL"; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Behavior { + Capture, + PendingStart, + RemoteUnavailable, + CloseRejected, + MissingObject, + MissingMethod, +} + +struct PortalSession { + closes: Arc, + live: Arc, + behavior: Behavior, + closed: Arc, +} +#[zbus::interface(name = "org.freedesktop.portal.Session", crate = "ashpd::zbus")] +impl PortalSession { + fn close(&self) -> zbus::fdo::Result<()> { + self.closes.fetch_add(1, Ordering::SeqCst); + if self.behavior == Behavior::MissingObject { + return Err(zbus::fdo::Error::UnknownObject( + "fixture session already removed".into(), + )); + } + if self.behavior == Behavior::MissingMethod { + return Err(zbus::fdo::Error::UnknownMethod( + "fixture session already removed".into(), + )); + } + if self.behavior == Behavior::CloseRejected { + return Err(zbus::fdo::Error::Failed("fixture close failed".into())); + } + self.live.fetch_sub(1, Ordering::SeqCst); + self.closed.notify_one(); + Ok(()) + } + #[zbus(property)] + fn version(&self) -> u32 { + 1 + } +} +struct Portal { + closes: Arc, + live: Arc, + peers: Arc>>, + behavior: Behavior, + started: Arc, + closed: Arc, +} + +fn request_path(header: &Header<'_>, token: &str, kind: &str) -> OwnedObjectPath { + let sender = header + .sender() + .unwrap() + .as_str() + .trim_start_matches(':') + .replace('.', "_"); + format!("/org/freedesktop/portal/desktop/{kind}/{sender}/{token}") + .try_into() + .unwrap() +} +async fn respond( + connection: &Connection, + header: &Header<'_>, + token: &str, + body: HashMap<&str, Value<'_>>, +) -> zbus::fdo::Result { + let path = request_path(header, token, "request"); + connection + .emit_signal( + header.sender().map(|sender| sender.as_str()), + path.as_str(), + "org.freedesktop.portal.Request", + "Response", + &(0_u32, body), + ) + .await?; + Ok(path) +} + +#[zbus::interface(name = "org.freedesktop.portal.ScreenCast", crate = "ashpd::zbus")] +impl Portal { + async fn create_session( + &self, + options: HashMap, + #[zbus(connection)] connection: &Connection, + #[zbus(header)] header: Header<'_>, + ) -> zbus::fdo::Result { + let token = options["handle_token"].downcast_ref::<&str>().unwrap(); + let session_token = options["session_handle_token"] + .downcast_ref::<&str>() + .unwrap(); + let session_path = request_path(&header, session_token, "session"); + connection + .object_server() + .at( + session_path.clone(), + PortalSession { + closes: self.closes.clone(), + live: self.live.clone(), + behavior: self.behavior, + closed: self.closed.clone(), + }, + ) + .await?; + self.live.fetch_add(1, Ordering::SeqCst); + respond( + connection, + &header, + token, + HashMap::from([("session_handle", Value::from(session_path.as_str()))]), + ) + .await + } + async fn select_sources( + &self, + _session: OwnedObjectPath, + options: HashMap, + #[zbus(connection)] connection: &Connection, + #[zbus(header)] header: Header<'_>, + ) -> zbus::fdo::Result { + respond( + connection, + &header, + options["handle_token"].downcast_ref::<&str>().unwrap(), + HashMap::new(), + ) + .await + } + async fn start( + &self, + _session: OwnedObjectPath, + _parent: String, + options: HashMap, + #[zbus(connection)] connection: &Connection, + #[zbus(header)] header: Header<'_>, + ) -> zbus::fdo::Result { + if self.behavior == Behavior::PendingStart { + self.started.notify_one(); + self.closed.notified().await; + } + let streams = vec![( + 42_u32, + HashMap::from([ + ("size", Value::from((1920_i32, 1080_i32))), + ("position", Value::from((0_i32, 0_i32))), + ]), + )]; + respond( + connection, + &header, + options["handle_token"].downcast_ref::<&str>().unwrap(), + HashMap::from([("streams", Value::from(streams))]), + ) + .await + } + fn open_pipe_wire_remote( + &self, + _session: OwnedObjectPath, + _options: HashMap, + ) -> zbus::fdo::Result { + if self.behavior == Behavior::RemoteUnavailable { + return Err(zbus::fdo::Error::Failed( + "fixture remote unavailable".into(), + )); + } + let (fd, peer) = UnixStream::pair().unwrap(); + self.peers.lock().unwrap().push(peer); + Ok(OwnedFd::from(fd).into()) + } + #[zbus(property)] + fn version(&self) -> u32 { + 5 + } + #[zbus(property)] + fn available_source_types(&self) -> u32 { + 3 + } + #[zbus(property)] + fn available_cursor_modes(&self) -> u32 { + 3 + } +} + +async fn probe(case: &str) -> anyhow::Result<()> { + let behavior = match case { + "cancel-start" => Behavior::PendingStart, + "fd-error" => Behavior::RemoteUnavailable, + "close-error" => Behavior::CloseRejected, + "already-closed-object" => Behavior::MissingObject, + "already-closed-method" => Behavior::MissingMethod, + _ => Behavior::Capture, + }; + let closes = Arc::new(AtomicUsize::new(0)); + let live = Arc::new(AtomicUsize::new(0)); + let peers = Arc::new(Mutex::new(Vec::new())); + let started = Arc::new(tokio::sync::Notify::new()); + let closed = Arc::new(tokio::sync::Notify::new()); + let connection = zbus::connection::Builder::session()? + .name("org.freedesktop.portal.Desktop")? + .serve_at( + "/org/freedesktop/portal/desktop", + Portal { + closes: closes.clone(), + live: live.clone(), + peers: peers.clone(), + behavior, + started: started.clone(), + closed, + }, + )? + .build() + .await?; + if case == "cancel-start" { + let scope = PipelineBuildScope::new_lifetime(); + scope.run(async { + tokio::select! { + result = open_wayland_portal(&LinuxCaptureSource::Display, false) => panic!("unexpected finished start: {:?}", result.err()), + _ = started.notified() => {} + } + }).await; + scope.cancel_and_join().await.map_err(anyhow::Error::msg)?; + assert_eq!( + live.load(Ordering::SeqCst), + 0, + "cancelled startup must close its acquired session" + ); + assert_eq!(closes.load(Ordering::SeqCst), 1); + return Ok(()); + } + if case == "fd-error" { + let scope = PipelineBuildScope::new_lifetime(); + let result = scope + .run(open_wayland_portal(&LinuxCaptureSource::Display, false)) + .await; + assert!(result.is_err()); + scope.cancel_and_join().await.map_err(anyhow::Error::msg)?; + assert_eq!( + live.load(Ordering::SeqCst), + 0, + "failed startup must close its acquired session" + ); + assert_eq!(closes.load(Ordering::SeqCst), 1); + return Ok(()); + } + for _ in 1..=if case == "repeat-stop" { 2 } else { 1 } { + let parent = PipelineBuildScope::new_lifetime(); + let scope = if case == "committed-stop" { + parent.child_transaction() + } else { + parent.clone() + }; + let capture = tokio::time::timeout( + Duration::from_secs(3), + scope.run(open_wayland_portal(&LinuxCaptureSource::Display, false)), + ) + .await??; + if case == "committed-stop" { + assert!( + scope.idle_report().is_none(), + "session cleanup must be owned before commit" + ); + assert!(scope.commit()); + assert!( + parent.idle_report().is_none(), + "the lifetime parent must retain ownership after commit" + ); + } + assert_eq!(capture.stream.pipe_wire_node_id(), 42); + let WaylandPortalCapture { + stream, + fd, + portal_session, + } = capture; + drop(stream); + drop(fd); + std::thread::spawn(move || drop(portal_session)) + .join() + .unwrap(); + if behavior == Behavior::MissingObject || behavior == Behavior::MissingMethod { + live.fetch_sub(1, Ordering::SeqCst); + } + let report = parent.cancel_and_join_report().await; + let mut byte = [0_u8]; + let mut peer = peers.lock().unwrap().pop().unwrap(); + peer.set_read_timeout(Some(Duration::from_secs(1)))?; + assert_eq!( + peer.read(&mut byte)?, + 0, + "the capture PipeWire remote must have closed" + ); + if case == "close-error" { + assert!( + !report.quiescent, + "a portal close failure must not be reported as joined cleanup" + ); + assert!(report.error.is_some_and(|error| { + error.contains("close Wayland screen capture portal session") + })); + assert_eq!(live.load(Ordering::SeqCst), 1); + return Ok(()); + } + assert!(report.quiescent); + assert!(report.error.is_none()); + if behavior == Behavior::MissingObject || behavior == Behavior::MissingMethod { + assert_eq!(closes.load(Ordering::SeqCst), 1); + return Ok(()); + } + } + assert_eq!( + live.load(Ordering::SeqCst), + 0, + "dropping captures must close the portal session" + ); + assert_eq!( + closes.load(Ordering::SeqCst), + if case == "repeat-stop" { 2 } else { 1 } + ); + drop(connection); + Ok(()) +} + +#[test] +fn portal_sessions_end_with_capture() { + if let Ok(case) = std::env::var(CHILD_CASE) { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + runtime.block_on(async { + tokio::time::timeout(Duration::from_secs(8), probe(&case)) + .await + .unwrap() + .unwrap(); + }); + return; + } + let module = module_path!().split_once("::").unwrap().1; + let test = format!("{module}::portal_sessions_end_with_capture"); + for case in [ + "repeat-stop", + "committed-stop", + "cancel-start", + "fd-error", + "close-error", + "already-closed-object", + "already-closed-method", + ] { + let output = Command::new("dbus-run-session") + .arg("--") + .arg(std::env::current_exe().unwrap()) + .args(["--exact", &test, "--nocapture", "--test-threads=1"]) + .env(CHILD_CASE, case) + .output() + .expect("the Wayland portal regression requires dbus-run-session"); + assert!( + output.status.success(), + "{case}: {}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } +} From 9252f854368325953c0a8bb1974a6f4beb793076 Mon Sep 17 00:00:00 2001 From: x Date: Wed, 11 Nov 2026 14:18:45 -0500 Subject: [PATCH 007/720] feat(automation): let a host check the action before a delete --- .github/workflows/ci.yml | 1 + crates/automation/src/lib.rs | 42 +++++++++-- crates/automation/src/tests.rs | 133 ++++++++++++++++++++++++++++++++- 3 files changed, 170 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b274a54e2c2..5a8e58fab57 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -343,6 +343,7 @@ jobs: - name: Test desktop regressions run: | cargo test --locked -p cap-utils -p cap-cli-install --lib + cargo test --locked -p cap-automation cargo test --locked -p cap --bin cap record::tests cargo test --locked -p cap --bin cap recordings::tests cargo test --locked -p cap --bin cap automation::tests::cli_save_to_location diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 8189ef97f95..14aea024c45 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -271,6 +271,22 @@ pub trait AutomationHost: Send + Sync { &self, ctx: &TriggerContext, ) -> impl std::future::Future> + Send; + + /// Called before `DeleteLocalFiles` runs, once the upload checks have passed, with the action + /// that came right before it in the same rule. A host that returns an error keeps the files. + fn verify_before_delete( + &self, + _ctx: &TriggerContext, + _preceding: Option>, + ) -> impl std::future::Future> + Send { + std::future::ready(Ok(())) + } +} + +#[derive(Debug, Clone, Copy)] +pub struct PrecedingAction<'a> { + pub action: &'a Action, + pub succeeded: bool, } pub struct RunResult { @@ -343,16 +359,16 @@ pub async fn run( continue; } - let result = if matches!(action, Action::DeleteLocalFiles) - && requires_upload_verification - { - if remaining_uploads > 0 { + let result = if matches!(action, Action::DeleteLocalFiles) { + let authorized = if !requires_upload_verification { + Ok(()) + } else if remaining_uploads > 0 { Err("Upload has not finished; local recording retained".to_string()) } else if upload_failed { Err("Upload failed; local recording retained".to_string()) } else { match host.upload_is_verified(ctx).await { - Ok(true) => execute_action(host, action, ctx).await, + Ok(true) => Ok(()), Ok(false) => Err( "Upload submitted, but remote verification is unavailable; local recording retained" .to_string(), @@ -361,6 +377,22 @@ pub async fn run( "Upload verification failed; local recording retained: {error}" )), } + }; + match authorized { + Ok(()) => { + let preceding = + action_results + .last() + .map(|previous: &ActionResult| PrecedingAction { + action: &previous.action, + succeeded: previous.success, + }); + match host.verify_before_delete(ctx, preceding).await { + Ok(()) => execute_action(host, action, ctx).await, + Err(error) => Err(error), + } + } + Err(error) => Err(error), } } else { execute_action(host, action, ctx).await diff --git a/crates/automation/src/tests.rs b/crates/automation/src/tests.rs index 059564ece1d..f66f07cb94f 100644 --- a/crates/automation/src/tests.rs +++ b/crates/automation/src/tests.rs @@ -7,6 +7,9 @@ struct MockHost { actions_run: Mutex>, upload_results: Mutex>>, upload_verification: Result, + export_result: Result<(), String>, + delete_guard: Option>) -> Result<(), String>>, + preceding_seen: Mutex>>, } impl MockHost { @@ -16,6 +19,9 @@ impl MockHost { actions_run: Mutex::new(Vec::new()), upload_results: Mutex::new(VecDeque::new()), upload_verification: Ok(false), + export_result: Ok(()), + delete_guard: None, + preceding_seen: Mutex::new(Vec::new()), } } @@ -59,7 +65,7 @@ impl AutomationHost for MockHost { _dest: &ExportDestination, ) -> Result<(), String> { self.record("export"); - Ok(()) + self.export_result.clone() } async fn upload( @@ -141,6 +147,20 @@ impl AutomationHost for MockHost { self.record("delete_local_files"); Ok(()) } + + async fn verify_before_delete( + &self, + _ctx: &TriggerContext, + preceding: Option>, + ) -> Result<(), String> { + self.preceding_seen.lock().unwrap().push( + preceding.map(|preceding| (format!("{:?}", preceding.action), preceding.succeeded)), + ); + match self.delete_guard { + Some(guard) => guard(preceding), + None => Ok(()), + } + } } fn screenshot_copy_rule() -> AutomationRule { @@ -1076,3 +1096,114 @@ fn multiple_rules_same_trigger() { let matched = evaluate(&store, &Trigger::ScreenshotTaken, &TriggerContext::new()); assert_eq!(matched.len(), 2); } + +fn export_then_delete_store() -> AutomationsStore { + let mut store = AutomationsStore { + version: 1, + rules: vec![studio_export_rule()], + }; + store.rules[0].conditions.clear(); + store.rules[0].actions.push(Action::DeleteLocalFiles); + store +} + +fn require_successful_export(preceding: Option>) -> Result<(), String> { + match preceding { + Some(PrecedingAction { + action: Action::Export { .. }, + succeeded: true, + }) => Ok(()), + _ => Err("refused".to_string()), + } +} + +#[tokio::test] +async fn delete_guard_sees_the_action_right_before_it_and_its_outcome() { + for export_succeeds in [true, false] { + let mut host = MockHost::new(desktop_capabilities()); + if !export_succeeds { + host.export_result = Err("encoder failed".to_string()); + } + let result = run( + &host, + &export_then_delete_store(), + &Trigger::StudioRecordingFinished, + &TriggerContext::new(), + ) + .await; + let seen = host.preceding_seen.lock().unwrap().clone(); + assert_eq!(seen.len(), 1); + let (action, succeeded) = seen[0].clone().unwrap(); + assert!(action.starts_with("Export"), "{action}"); + assert_eq!(succeeded, export_succeeds); + assert_eq!(result[0].action_results[0].success, export_succeeds); + } +} + +#[tokio::test] +async fn delete_guard_refusal_keeps_files_and_reports_the_reason() { + let mut host = MockHost::new(desktop_capabilities()); + host.export_result = Err("encoder failed".to_string()); + host.delete_guard = Some(require_successful_export); + let result = run( + &host, + &export_then_delete_store(), + &Trigger::StudioRecordingFinished, + &TriggerContext::new(), + ) + .await; + assert_eq!(host.actions_run(), vec!["export"]); + let delete = &result[0].action_results[1]; + assert!(!delete.success); + assert_eq!(delete.error.as_deref(), Some("refused")); + + let mut host = MockHost::new(desktop_capabilities()); + host.delete_guard = Some(require_successful_export); + let mut store = export_then_delete_store(); + store.rules[0].actions.remove(0); + let result = run( + &host, + &store, + &Trigger::StudioRecordingFinished, + &TriggerContext::new(), + ) + .await; + assert!(host.actions_run().is_empty()); + assert_eq!(*host.preceding_seen.lock().unwrap(), vec![None]); + assert!(!result[0].action_results[0].success); + + let mut host = MockHost::new(desktop_capabilities()); + host.delete_guard = Some(require_successful_export); + run( + &host, + &export_then_delete_store(), + &Trigger::StudioRecordingFinished, + &TriggerContext::new(), + ) + .await; + assert_eq!(host.actions_run(), vec!["export", "delete_local_files"]); +} + +#[tokio::test] +async fn delete_guard_runs_only_after_upload_checks_pass() { + let mut host = MockHost::new(desktop_capabilities()); + host.delete_guard = Some(require_successful_export); + let store = upload_cleanup_store( + Trigger::StudioRecordingFinished, + vec![upload_action(), Action::DeleteLocalFiles], + ); + let result = run( + &host, + &store, + &Trigger::StudioRecordingFinished, + &TriggerContext::new(), + ) + .await; + assert!(host.preceding_seen.lock().unwrap().is_empty()); + assert!(!result[0].action_results[1].success); + assert!( + !host + .actions_run() + .contains(&"delete_local_files".to_string()) + ); +} From 92902059b8bcc875b1c187d28683c8ebb45e7488 Mon Sep 17 00:00:00 2001 From: x Date: Wed, 11 Nov 2026 14:18:45 -0500 Subject: [PATCH 008/720] feat(desktop-gpui): run saved automation rules --- apps/desktop-gpui/Cargo.lock | 16 + apps/desktop-gpui/Cargo.toml | 1 + apps/desktop-gpui/src/app_windows.rs | 36 +- apps/desktop-gpui/src/automation.rs | 1054 +++++++++++++++++++++ apps/desktop-gpui/src/automation/tests.rs | 646 +++++++++++++ apps/desktop-gpui/src/import.rs | 1 + apps/desktop-gpui/src/main.rs | 2 + apps/desktop-gpui/src/screenshot.rs | 14 +- apps/desktop-gpui/src/session.rs | 27 +- apps/desktop-gpui/src/store.rs | 4 + apps/desktop-gpui/src/upload/queue.rs | 12 + 11 files changed, 1801 insertions(+), 12 deletions(-) create mode 100644 apps/desktop-gpui/src/automation.rs create mode 100644 apps/desktop-gpui/src/automation/tests.rs diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock index f0376b8c303..d92ee369ed7 100644 --- a/apps/desktop-gpui/Cargo.lock +++ b/apps/desktop-gpui/Cargo.lock @@ -1397,6 +1397,21 @@ dependencies = [ "workspace-hack", ] +[[package]] +name = "cap-automation" +version = "0.1.0" +dependencies = [ + "cap-project", + "serde", + "serde_json", + "specta", + "thiserror 1.0.69", + "tokio", + "tracing", + "uuid", + "workspace-hack", +] + [[package]] name = "cap-camera" version = "0.1.0" @@ -1544,6 +1559,7 @@ dependencies = [ "block2 0.6.2", "bytes", "cap-audio", + "cap-automation", "cap-camera", "cap-camera-effects", "cap-cli-install", diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml index cfe82c3cfc3..e21e8aaeb5e 100644 --- a/apps/desktop-gpui/Cargo.toml +++ b/apps/desktop-gpui/Cargo.toml @@ -57,6 +57,7 @@ cap-enc-ffmpeg = { path = "../../crates/enc-ffmpeg" } cap-timestamp = { path = "../../crates/timestamp" } cap-utils = { path = "../../crates/utils" } cap-project = { path = "../../crates/project" } +cap-automation = { path = "../../crates/automation" } # The cursor style picker draws the same SVG assets the renderer composites. # gpui's `svg()` keeps only a glyph's alpha, so the two-tone cursor art has to # be rasterised instead: `resvg` at the pin cap-rendering already builds, into diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs index 2549b3935db..c91f2c3d027 100644 --- a/apps/desktop-gpui/src/app_windows.rs +++ b/apps/desktop-gpui/src/app_windows.rs @@ -634,10 +634,11 @@ pub fn init(main: WindowHandle, session: Entity, c if !restore_clean_capture_ui(cx) { return; } - let (finished_studio, preparing_editor, finished_instant, deleted) = + let (finished_studio, studio_behaviour, preparing_editor, finished_instant, deleted) = session.update(cx, |session, _| { ( session.finished_studio.take(), + session.studio_behaviour.take(), session.take_preparing_studio_editor(), std::mem::take(&mut session.finished_instant), std::mem::take(&mut session.deleted_recording), @@ -687,7 +688,8 @@ pub fn init(main: WindowHandle, session: Entity, c // deleted from the bar reshows it only for "Reopen recording // window", as the Tauri `delete_recording` did. let settings = crate::store::GeneralSettings::load(); - let behaviour = settings.post_studio_recording_behaviour; + let behaviour = + studio_behaviour.unwrap_or(settings.post_studio_recording_behaviour); // Linux restores the main window through the clean-capture // lease before this runs, so it keeps reshowing as before. A // main window reopened mid-recording (even if minimized since) @@ -767,8 +769,7 @@ fn open_preparing_studio_editor(session: &Entity, cx: &mut App if !pending.capture_stopped || pending.presentation != StudioEditorPresentation::Pending || !pending.finalization.is_finalizing() - || crate::store::GeneralSettings::load().post_studio_recording_behaviour - != crate::store::PostStudioBehaviour::OpenEditor + || session.read(cx).studio_behaviour != Some(crate::store::PostStudioBehaviour::OpenEditor) { return; } @@ -7489,7 +7490,7 @@ pub fn empty_overlays_for_screenshot(cx: &mut App) -> Option