Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: harden classic app handoff
Richie McIlroyb4baba7755db
diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rsindex 9cb81016d..6e002f78e 100644--- a/apps/desktop-gpui/src/settings_pages.rs+++ b/apps/desktop-gpui/src/settings_pages.rs@@ -1911,9 +1911,6 @@ pub(crate) enum SwitchBack {/// The sequence, timed from its start. One clock drives the sentence, its/// fade and the countdown, so nothing can drift apart.Running(std::time::Instant),- /// Dev only: the switch is committed and the supervisor is rebuilding the- /// classic app; this app stays up until the classic one deletes the- /// pending file to say it is on screen (`store::classic_pending_path`).WaitingForClassic,/// The switch was refused; the overlay stays up with the reason and the/// toggle goes back to on, because nothing was switched.@@ -2308,11 +2305,7 @@ impl SettingsWindow {.text_size(px(14.)).text_center().text_color(gpui::hsla(0., 0., 1., 0.7))- .child(- "The dev build is compiling. This window closes by itself when \- the classic app is on screen; a cold build can take a few \- minutes.",- ),+ .child("This window will close when the classic Cap app is ready."),);}SwitchBack::Failed(error) => {@@ -2437,80 +2430,110 @@ impl SettingsWindow {return;}+ if !store::set_store_setting(GENERAL_SETTINGS, "enableGpuiApp", Value::Bool(false)) {+ self.pages.switch_back = Some(SwitchBack::Failed(+ "Couldn't save your app preference. Cap is still open.".to_string(),+ ));+ cx.notify();+ return;+ }self.settings.enable_gpui_app = false;- self.write_bool("enableGpuiApp", false, cx);-- let started = match &target {- ClassicTarget::Bundle(_) | ClassicTarget::Executable(_) => launch_classic(&target)- .map_err(|error| format!("Couldn't open the Cap app: {error}")),- ClassicTarget::DevSupervisor => store::mark_classic_pending()- .and_then(|()| store::request_classic_reopen())- .map_err(|error| format!("Couldn't request the dev app restart: {error}")),+ let dev = matches!(target, ClassicTarget::DevSupervisor);+ let timeout = if dev {+ CLASSIC_WAIT_TIMEOUT+ } else {+ Duration::from_secs(30)};+ let pending = store::mark_classic_pending();+ self.pages.switch_back = Some(SwitchBack::WaitingForClassic);+ self.pages.switch_back_ticker = None;+ cx.notify();- match (started, target) {- // An installed bundle opens in a moment; quit right away.- (Ok(()), ClassicTarget::Bundle(_) | ClassicTarget::Executable(_)) => {- tracing::info!("handing back to the classic app");- quit_after_flushing_editors(cx);- }- // The dev harness has to rebuild first, which can take minutes.- // Stay up until the classic app deletes the pending file to say- // it is on screen, so the user is never staring at no app at all.- (Ok(()), ClassicTarget::DevSupervisor) => {- tracing::info!("handing back to the classic app; waiting for the dev build");- self.pages.switch_back = Some(SwitchBack::WaitingForClassic);- self.pages.switch_back_ticker = None;- cx.notify();- // A committed handoff must finish even if its settings window closes.- cx.spawn(async move |this, cx| {- let started = std::time::Instant::now();- loop {- cx.background_executor()- .timer(Duration::from_millis(500))- .await;- if !store::classic_pending_path().exists() {- tracing::info!("classic app is up; quitting");- cx.update(quit_after_flushing_editors);- break;- }- if started.elapsed() > CLASSIC_WAIT_TIMEOUT {- this.update(cx, |this, cx| {- this.pages.switch_back = Some(SwitchBack::Failed(- "The classic app hasn't come up. Check the dev terminal for \- build errors, then toggle again."- .to_string(),- ));- cx.notify();- })- .ok();- break;- }+ // The handoff must finish even if its settings window closes.+ cx.spawn(async move |this, cx| {+ let result = cx+ .background_executor()+ .spawn(async move {+ pending?;+ match target {+ ClassicTarget::DevSupervisor => store::request_classic_reopen(),+ _ => launch_classic(&target),}})- .detach();+ .await;+ let mut failure = result.err().map(|error| format!("Couldn't open Cap: {error}"));+ let started = std::time::Instant::now();+ while failure.is_none() {+ match store::classic_pending_path().try_exists() {+ Ok(false) => {+ tracing::info!("classic app is visible; quitting GPUI");+ cx.update(quit_after_flushing_editors);+ return;+ }+ Ok(true) => {}+ Err(error) => {+ failure = Some(format!("Couldn't check whether Cap opened: {error}"));+ break;+ }+ }+ if started.elapsed() >= timeout {+ failure = Some(if dev {+ "The classic app hasn't opened. Check the dev terminal for build errors, then try again."+ .to_string()+ } else {+ "The classic app hasn't opened. Cap is still here; please try again."+ .to_string()+ });+ break;+ }+ cx.background_executor()+ .timer(Duration::from_millis(250))+ .await;}- (Err(message), _) => {- tracing::error!("{message}");- self.settings.enable_gpui_app = true;- self.write_bool("enableGpuiApp", true, cx);- self.pages.switch_back = Some(SwitchBack::Failed(message));+ let message = failure.unwrap_or_else(|| "Couldn't open Cap.".to_string());+ tracing::error!("{message}");+ store::clear_classic_pending();+ store::set_store_setting(GENERAL_SETTINGS, "enableGpuiApp", Value::Bool(true));+ this.update(cx, |this, cx| {+ this.settings = store::GeneralSettings::load();+ this.pages.switch_back = Some(SwitchBack::Failed(message));cx.notify();- }+ })+ .ok();+ })+ .detach();+ }+}++fn classic_launch_command(target: &ClassicTarget) -> Option<std::process::Command> {+ match target {+ ClassicTarget::Bundle(bundle) => {+ let mut command = std::process::Command::new("/usr/bin/open");+ // GPUI shares Cap's bundle identity, so a normal open can reactivate GPUI.+ command.arg("-n").arg(bundle);+ Some(command)}+ ClassicTarget::Executable(executable) => Some(std::process::Command::new(executable)),+ ClassicTarget::DevSupervisor => None,}}fn launch_classic(target: &ClassicTarget) -> std::io::Result<()> {- match target {- ClassicTarget::Bundle(bundle) => std::process::Command::new("/usr/bin/open")- .arg(bundle)- .spawn()- .map(drop),- ClassicTarget::Executable(executable) => {- std::process::Command::new(executable).spawn().map(drop)+ let Some(mut command) = classic_launch_command(target) else {+ return Ok(());+ };+ if matches!(target, ClassicTarget::Bundle(_)) {+ let output = command.output()?;+ if !output.status.success() {+ return Err(std::io::Error::other(format!(+ "Cap launcher failed ({}): {}",+ output.status,+ String::from_utf8_lossy(&output.stderr).trim()+ )));}- ClassicTarget::DevSupervisor => Ok(()),+ Ok(())+ } else {+ command.spawn().map(drop)}}@@ -8475,6 +8498,23 @@ mod tests {);}+ #[test]+ fn installed_handoff_launches_a_new_bundle_instance() {+ let bundle = std::path::PathBuf::from("/Applications/Cap Preview.app");+ let command = classic_launch_command(&ClassicTarget::Bundle(bundle.clone())).unwrap();+ assert_eq!(command.get_program(), "/usr/bin/open");+ assert_eq!(+ command.get_args().collect::<Vec<_>>(),+ [std::ffi::OsStr::new("-n"), bundle.as_os_str()]+ );+ assert!(classic_launch_command(&ClassicTarget::DevSupervisor).is_none());+ let executable = std::path::PathBuf::from("/opt/cap/Cap");+ let command =+ classic_launch_command(&ClassicTarget::Executable(executable.clone())).unwrap();+ assert_eq!(command.get_program(), executable.as_os_str());+ assert_eq!(command.get_args().count(), 0);+ }+/// The takeover's whole timeline, read off its one clock.#[test]fn the_takeover_counts_down_while_the_lines_fade() {diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rsindex cd12fe31c..2d78f9304 100644--- a/apps/desktop-gpui/src/store.rs+++ b/apps/desktop-gpui/src/store.rs@@ -338,13 +338,6 @@ pub fn request_classic_reopen() -> std::io::Result<()> {std::fs::write(&path, std::process::id().to_string())}-/// The dev switch-back's readiness handshake. A dev rebuild of the classic app-/// takes anywhere from seconds to many minutes, and quitting immediately-/// leaves the user with no app and no feedback for all of it. So the-/// switch-back writes this file next to the reopen sentinel and stays up-/// "waiting for the classic app"; the Tauri app deletes it when it starts and-/// decides to keep the session (`gpui_app.rs`), and only then does this app-/// quit.pub fn classic_pending_path() -> PathBuf {app_data_dir().join("cap-classic.pending")}@@ -357,6 +350,14 @@ pub fn mark_classic_pending() -> std::io::Result<()> {std::fs::write(&path, std::process::id().to_string())}+pub fn clear_classic_pending() {+ if let Err(error) = std::fs::remove_file(classic_pending_path())+ && error.kind() != std::io::ErrorKind::NotFound+ {+ tracing::warn!(%error, "couldn't clear classic handoff readiness");+ }+}+fn state_path() -> PathBuf {app_data_dir().join("gpui-state.json")}diff --git a/apps/desktop/src-tauri/src/gpui_app.rs b/apps/desktop/src-tauri/src/gpui_app.rsindex f01c87bf9..3a82e010c 100644--- a/apps/desktop/src-tauri/src/gpui_app.rs+++ b/apps/desktop/src-tauri/src/gpui_app.rs@@ -342,10 +342,6 @@ pub(crate) fn handle_update_handoff(app: &AppHandle) -> bool {true}-/// The dev switch-back's readiness handshake (`store::classic_pending_path`-/// in apps/desktop-gpui): `cap-gpui` writes this and stays on screen until the-/// classic app deletes it, so a minutes-long dev rebuild never leaves the user-/// with no app at all.fn classic_pending() -> PathBuf {shared_data_dir().join("cap-classic.pending")}@@ -975,22 +971,55 @@ pub fn redirect_at_startup_if_enabled(app: &AppHandle) -> Result<bool, String> {let update_handoff = handle_update_handoff(app);let redirect = !update_handoff && redirect_decision(app)?;if !redirect {- // Staying up IS the readiness signal the waiting `cap-gpui` needs --- // and the wait can begin while this app is ALREADY running (switching- // back with both apps up), so the signal has to keep firing, not just- // fire once at startup.let app = app.clone();tauri::async_runtime::spawn(async move {loop {- let _ = std::fs::remove_file(classic_pending());handle_update_handoff(&app);- tokio::time::sleep(std::time::Duration::from_secs(1)).await;+ if classic_pending().try_exists().unwrap_or(false) {+ let handle = app.clone();+ let (sender, receiver) = tokio::sync::oneshot::channel();+ if app+ .run_on_main_thread(move || {+ acknowledge_classic_window(&handle);+ let _ = sender.send(());+ })+ .is_ok()+ {+ let _ =+ tokio::time::timeout(std::time::Duration::from_secs(1), receiver).await;+ }+ }+ tokio::time::sleep(std::time::Duration::from_millis(250)).await;}});}Ok(redirect)}+fn acknowledge_classic_window(app: &AppHandle) {+ if crate::app_is_exiting(app) {+ return;+ }+ let ready = app+ .get_webview_window("main")+ .or_else(|| app.get_webview_window("onboarding"))+ .is_some_and(|window| {+ let frontend_ready = window.label() == "onboarding"+ || window.url().is_ok_and(|url| url.path() == "/update")+ || app+ .try_state::<crate::MainWindowReadyState>()+ .is_some_and(|state| state.is_ready());+ frontend_ready && window.is_visible().unwrap_or(false)+ });+ if ready {+ match std::fs::remove_file(classic_pending()) {+ Ok(()) => info!("Acknowledged visible classic window for GPUI handoff"),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => warn!(%error, "Could not acknowledge the classic app handoff"),+ }+ }+}+fn redirect_decision(app: &AppHandle) -> Result<bool, String> {let own = GeneralSettingsStore::get(app).ok()diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 4781ff187..8e25dc422 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -2229,7 +2229,6 @@ impl ShowCapWindow {move || {let _panel_activation_guard = panel_activation_guard;use tauri_nspanel::cocoa::appkit::NSWindowCollectionBehavior;- use tauri_nspanel::panel_delegate;use tauri_nspanel::WebviewWindowExt as NSPanelWebviewWindowExt;#[link(name = "CoreGraphics", kind = "framework")]@@ -2240,13 +2239,6 @@ impl ShowCapWindow {#[allow(non_upper_case_globals)]const kCGMaximumWindowLevelKey: i32 = 10;- let delegate = panel_delegate!(TargetSelectOverlayPanelDelegate {- window_did_become_key,- window_did_resign_key- });-- delegate.set_listener(Box::new(|_delegate_name: String| {}));-let panel = match window.to_panel() {Ok(p) => p,Err(e) => {@@ -2263,8 +2255,6 @@ impl ShowCapWindow {| NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenPrimary,);- panel.set_delegate(delegate);-#[allow(non_upper_case_globals)]const NSWindowStyleMaskNonActivatingPanel: i32 = 1 << 7;panel.set_style_mask(NSWindowStyleMaskNonActivatingPanel);@@ -2715,7 +2705,6 @@ impl ShowCapWindow {move || {let _panel_activation_guard = panel_activation_guard;use tauri_nspanel::cocoa::appkit::NSWindowCollectionBehavior;- use tauri_nspanel::panel_delegate;use crate::panel_manager::try_to_panel;#[link(name = "CoreGraphics", kind = "framework")]@@ -2726,13 +2715,6 @@ impl ShowCapWindow {#[allow(non_upper_case_globals)]const kCGMaximumWindowLevelKey: i32 = 10;- let delegate = panel_delegate!(CameraPanelDelegate {- window_did_become_key,- window_did_resign_key- });-- delegate.set_listener(Box::new(|_delegate_name: String| {}));-let panel = match try_to_panel(&window) {Ok(p) => p,Err(e) => {@@ -2748,8 +2730,6 @@ impl ShowCapWindow {| NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenPrimary,);- panel.set_delegate(delegate);-let max_level =unsafe { CGWindowLevelForKey(kCGMaximumWindowLevelKey) };panel.set_level(max_level);@@ -3219,7 +3199,6 @@ impl ShowCapWindow {return;}use tauri_nspanel::cocoa::appkit::NSWindowCollectionBehavior;- use tauri_nspanel::panel_delegate;use tauri_nspanel::WebviewWindowExt as NSPanelWebviewWindowExt;#[link(name = "CoreGraphics", kind = "framework")]@@ -3230,13 +3209,6 @@ impl ShowCapWindow {#[allow(non_upper_case_globals)]const kCGMaximumWindowLevelKey: i32 = 10;- let delegate = panel_delegate!(RecordingControlsPanelDelegate {- window_did_become_key,- window_did_resign_key- });-- delegate.set_listener(Box::new(|_delegate_name: String| {}));-let panel = match window.to_panel() {Ok(p) => p,Err(e) => {@@ -3252,8 +3224,6 @@ impl ShowCapWindow {| NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenPrimary,);- panel.set_delegate(delegate);-let max_level = unsafe { CGWindowLevelForKey(kCGMaximumWindowLevelKey) };panel.set_level(max_level);