Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: preserve graceful shutdown during GPUI permission relaunch
Richie McIlroye49f06fb8682
diff --git a/apps/desktop-gpui/src/onboarding_window.rs b/apps/desktop-gpui/src/onboarding_window.rsindex fee563295..04f8a776f 100644--- a/apps/desktop-gpui/src/onboarding_window.rs+++ b/apps/desktop-gpui/src/onboarding_window.rs@@ -582,7 +582,7 @@ impl OnboardingWindow {.radius(px(8.)).icon("icons/rotate-ccw.svg").label("Relaunch Cap")- .on_click(cx.listener(|_, _, _, _| permissions::relaunch())),+ .on_click(cx.listener(|_, _, _, cx| permissions::relaunch(cx))),),),)diff --git a/apps/desktop-gpui/src/permissions.rs b/apps/desktop-gpui/src/permissions.rsindex 759f38222..d88f7d20d 100644--- a/apps/desktop-gpui/src/permissions.rs+++ b/apps/desktop-gpui/src/permissions.rs@@ -263,36 +263,68 @@ pub fn open_permission_settings(permission: OSPermission) {/// Relaunch the app -- the Tauri onboarding offers this after sending the/// user to System Settings, because a fresh screen-recording or accessibility-/// grant often only takes effect in a new process. Spawns a detached shell-/// that reopens the bundle (or the bare binary in dev) after this process has-/// had a beat to exit, then quits.-pub fn relaunch() {+/// grant often only takes effect in a new process. The replacement must wait+/// for shutdown: Tauri otherwise sees this process alive and exits without+/// starting a replacement.+pub fn relaunch(cx: &mut gpui::App) {+ static REQUESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+let Ok(exe) = std::env::current_exe() else {tracing::error!("relaunch: current_exe unavailable");return;};+ let mut command = relaunch_command(&exe, std::process::id());+ if let Err(error) = spawn_relaunch(&mut command, &REQUESTED, || crate::menus::quit(cx)) {+ tracing::error!("relaunch failed to spawn: {error}");+ }+}++fn relaunch_command(exe: &std::path::Path, pid: u32) -> std::process::Command {#[cfg(target_os = "macos")]- let command = {- let bundle = exe- .ancestors()- .find(|path| path.extension().is_some_and(|ext| ext == "app"))- .map(std::path::Path::to_path_buf);- match bundle {- Some(bundle) => format!("sleep 0.3; /usr/bin/open -n \"{}\"", bundle.display()),- None => format!("sleep 0.3; exec \"{}\"", exe.display()),- }- };+ let bundle = exe+ .ancestors()+ .find(|path| path.extension().is_some_and(|ext| ext == "app"));#[cfg(not(target_os = "macos"))]- let command = format!("sleep 0.3; exec \"{}\"", exe.display());+ let bundle: Option<&std::path::Path> = None;++ let (script, target) = match bundle {+ Some(bundle) => (+ r#"while kill -0 "$1" 2>/dev/null; do sleep 0.1; done; exec /usr/bin/open -n "$2""#,+ bundle,+ ),+ None => (+ r#"while kill -0 "$1" 2>/dev/null; do sleep 0.1; done; exec "$2""#,+ exe,+ ),+ };+ let mut command = std::process::Command::new("/bin/sh");+ command+ .args(["-c", script, "cap-relaunch"])+ .arg(pid.to_string())+ .arg(target);+ command+}- match std::process::Command::new("/bin/sh")- .arg("-c")- .arg(command)- .spawn()- {- Ok(_) => std::process::exit(0),- Err(error) => tracing::error!("relaunch failed to spawn: {error}"),+fn spawn_relaunch(+ command: &mut std::process::Command,+ requested: &std::sync::atomic::AtomicBool,+ quit: impl FnOnce(),+) -> std::io::Result<Option<std::process::Child>> {+ use std::sync::atomic::Ordering;++ if requested.swap(true, Ordering::AcqRel) {+ return Ok(None);+ }+ match command.spawn() {+ Ok(child) => {+ quit();+ Ok(Some(child))+ }+ Err(error) => {+ requested.store(false, Ordering::Release);+ Err(error)+ }}}@@ -401,6 +433,95 @@ mod macos {mod tests {use super::*;+ #[test]+ fn relaunch_requests_quit_once_after_spawn_and_allows_retry_after_failure() {+ use std::{+ cell::Cell,+ sync::atomic::{AtomicBool, Ordering},+ };++ let requested = AtomicBool::new(false);+ let quits = Cell::new(0);+ assert!(+ spawn_relaunch(&mut std::process::Command::new(""), &requested, || {+ quits.set(quits.get() + 1);+ })+ .is_err()+ );+ assert!(!requested.load(Ordering::Acquire));+ assert_eq!(quits.get(), 0);++ let mut command = std::process::Command::new(std::env::current_exe().unwrap());+ command.arg("--list").stdout(std::process::Stdio::null());+ let mut child = spawn_relaunch(&mut command, &requested, || quits.set(quits.get() + 1))+ .unwrap()+ .unwrap();+ assert!(child.wait().unwrap().success());+ assert!(+ spawn_relaunch(&mut command, &requested, || quits.set(quits.get() + 1))+ .unwrap()+ .is_none()+ );+ assert_eq!(quits.get(), 1);+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn bundled_relaunch_passes_the_bundle_as_a_literal_argument() {+ let bundle = std::path::Path::new("/Applications/Cap ' \" $ app.app");+ let command = relaunch_command(&bundle.join("Contents/MacOS/cap-gpui"), 123);+ let args = command.get_args().collect::<Vec<_>>();+ assert_eq!(command.get_program(), "/bin/sh");+ assert_eq!(args[3], "123");+ assert_eq!(args[4], bundle.as_os_str());+ assert!(+ args[1]+ .to_str()+ .unwrap()+ .ends_with(r#"exec /usr/bin/open -n "$2""#)+ );+ }++ #[cfg(unix)]+ #[test]+ fn relaunch_waits_for_the_previous_process_and_handles_literal_paths() {+ use std::os::unix::fs::PermissionsExt;++ let nonce = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let root =+ std::env::temp_dir().join(format!("cap-gpui-relaunch-{}-{nonce}", std::process::id()));+ std::fs::create_dir_all(&root).unwrap();+ let executable = root.join("replacement ' \" $ program");+ let output = root.join("relaunched");+ std::fs::write(+ &executable,+ b"#!/bin/sh\nprintf relaunched > \"$CAP_GPUI_RELAUNCH_TEST_OUTPUT\"\n",+ )+ .unwrap();+ std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o700)).unwrap();++ let mut previous = std::process::Command::new("/bin/sh")+ .args(["-c", "read -r line"])+ .stdin(std::process::Stdio::piped())+ .spawn()+ .unwrap();+ let mut replacement = relaunch_command(&executable, previous.id())+ .env("CAP_GPUI_RELAUNCH_TEST_OUTPUT", &output)+ .spawn()+ .unwrap();+ std::thread::sleep(std::time::Duration::from_millis(400));+ assert!(replacement.try_wait().unwrap().is_none());+ assert!(!output.exists());+ drop(previous.stdin.take());+ previous.wait().unwrap();+ assert!(replacement.wait().unwrap().success());+ assert_eq!(std::fs::read(&output).unwrap(), b"relaunched");+ std::fs::remove_dir_all(root).unwrap();+ }+fn raw(screen: bool,ax: bool,