Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: recover from unexpected GPUI exits throughout the session

Richie McIlroy40f194bf5d3b
diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs
index 0911ae9d5..1888df56d 100644
--- a/apps/desktop-gpui/src/main.rs
+++ b/apps/desktop-gpui/src/main.rs
@@ -179,6 +179,7 @@ fn main() {
// A relaunch means "run the code I just built": take over from any
// previous instance still alive in the tray (see `single_instance`).
single_instance::acquire();
+ store::mark_handoff_session();
platform::install_url_scheme_handler();
for argument in std::env::args().skip(1) {
@@ -260,6 +261,11 @@ fn main() {
return;
};
+ cx.on_app_quit(|_| async {
+ crate::store::clear_handoff_marker();
+ })
+ .detach();
+
app_windows::init(window_handle, session, cx);
updates::schedule_startup_check(cx);
@@ -289,18 +295,6 @@ fn main() {
}
})
.detach();
- // The other half of the Tauri app's hand-off protocol
- // (`store::handoff_marker_path`): staying up this long is what proves
- // to it that redirecting here was not a mistake.
- cx.spawn(async move |cx| {
- cx.background_executor()
- .timer(std::time::Duration::from_secs(10))
- .await;
- cx.background_executor()
- .spawn(async { crate::store::clear_handoff_marker() })
- .await;
- })
- .detach();
// `CAP_GPUI_AUTO_TRAY` / `CAP_GPUI_TRAY_DUMP`: the tray's harness path.
tray::drive_from_env(cx);
// `CAP_GPUI_AUTO_CLOSE=settings|main:<secs>`: run the ⌘W body against
diff --git a/apps/desktop-gpui/src/menus.rs b/apps/desktop-gpui/src/menus.rs
index d074e5abc..19c1678e6 100644
--- a/apps/desktop-gpui/src/menus.rs
+++ b/apps/desktop-gpui/src/menus.rs
@@ -287,10 +287,6 @@ pub fn close_window_by_handle(handle: gpui::AnyWindowHandle, cx: &mut App) {
/// quit waits for the session to come back to `Idle` (bounded, so a wedged
/// finalize cannot make the app unquittable).
pub fn quit(cx: &mut App) {
- // Reaching a deliberate quit is proof enough that this build came up, even
- // if it happens inside the marker's ten-second window.
- crate::store::clear_handoff_marker();
-
let session = RecordingSession::global(cx);
if session.read(cx).phase == Phase::Idle {
cx.quit();
diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs
index 2a362c7db..8e5543d04 100644
--- a/apps/desktop-gpui/src/store.rs
+++ b/apps/desktop-gpui/src/store.rs
@@ -193,21 +193,31 @@ fn bundled_resource_dirs_for(
/// The Tauri app's hand-off marker (`gpui_app.rs`).
///
-/// It writes this file immediately before spawning this app and never deletes
-/// it; this app deletes it once it has been alive long enough to count as
-/// healthy (`main.rs`) or on a clean quit (`menus::quit`). A marker the Tauri
-/// app still finds at startup therefore means the build it handed off to never
-/// came up, so it clears `enableGpuiApp` and takes the session back rather than
-/// bouncing the user into an app that does not start.
+/// It survives for the entire session, including recording finalization, and
+/// is removed only during clean app shutdown. A timer cannot establish health:
+/// an idle native callback can crash after any startup grace period has elapsed.
pub fn handoff_marker_path() -> PathBuf {
app_data_dir().join("cap-gpui.handoff")
}
+pub fn mark_handoff_session() {
+ if let Err(error) = mark_handoff_session_at(&handoff_marker_path()) {
+ tracing::warn!("writing the hand-off marker: {error}");
+ }
+}
+
+fn mark_handoff_session_at(path: &Path) -> std::io::Result<()> {
+ write_update_handoff_at(path, &std::process::id().to_string())
+}
+
/// Best-effort: a marker that cannot be removed only costs one fallback to the
/// Tauri app on the next launch.
pub fn clear_handoff_marker() {
- let path = handoff_marker_path();
- match std::fs::remove_file(&path) {
+ clear_handoff_marker_at(&handoff_marker_path());
+}
+
+fn clear_handoff_marker_at(path: &Path) {
+ match std::fs::remove_file(path) {
Ok(()) => tracing::info!("cleared the hand-off marker"),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => tracing::warn!("clearing the hand-off marker: {error}"),
@@ -1949,6 +1959,43 @@ mod tests {
);
}
+ #[test]
+ fn handoff_marker_survives_until_explicit_clean_shutdown() {
+ let directory =
+ std::env::temp_dir().join(format!("cap-gpui-handoff-session-{}", super::new_uuid_v4()));
+ let marker = directory.join("cap-gpui.handoff");
+
+ super::mark_handoff_session_at(&marker).unwrap();
+ assert_eq!(
+ std::fs::read_to_string(&marker).unwrap(),
+ std::process::id().to_string()
+ );
+ super::mark_handoff_session_at(&marker).unwrap();
+ assert!(marker.exists());
+
+ super::clear_handoff_marker_at(&marker);
+ assert!(!marker.exists());
+ super::clear_handoff_marker_at(&marker);
+ std::fs::remove_dir(directory).unwrap();
+ }
+
+ #[test]
+ fn handoff_marker_write_failure_leaves_existing_state_intact() {
+ let directory =
+ std::env::temp_dir().join(format!("cap-gpui-handoff-failure-{}", super::new_uuid_v4()));
+ std::fs::create_dir_all(&directory).unwrap();
+ let blocked_parent = directory.join("not-a-directory");
+ std::fs::write(&blocked_parent, "unchanged").unwrap();
+
+ assert!(super::mark_handoff_session_at(&blocked_parent.join("marker")).is_err());
+ assert_eq!(
+ std::fs::read_to_string(&blocked_parent).unwrap(),
+ "unchanged"
+ );
+ std::fs::remove_file(blocked_parent).unwrap();
+ std::fs::remove_dir(directory).unwrap();
+ }
+
#[test]
fn bundled_resource_paths_follow_the_installed_executable() {
let executable = std::path::Path::new("/Applications/Cap.app/Contents/MacOS/cap-gpui");
diff --git a/apps/desktop/src-tauri/src/gpui_app.rs b/apps/desktop/src-tauri/src/gpui_app.rs
index 43de84e91..8f6d6f1ea 100644
--- a/apps/desktop/src-tauri/src/gpui_app.rs
+++ b/apps/desktop/src-tauri/src/gpui_app.rs
@@ -17,10 +17,9 @@
//! A handoff that spawns a `cap-gpui` which then dies immediately would leave
//! the user with no app at all, and with a setting that keeps redirecting away
//! from the app that does work. So this side writes `cap-gpui.handoff` next to
-//! the shared store before spawning, and `cap-gpui` deletes it once it has been
-//! alive for ~10 seconds (`store::handoff_marker_path`, `main.rs`). A marker
-//! still present at startup therefore means the last handoff never reached a
-//! healthy instance: clear the flag, tell the user, and start normally.
+//! the shared store before spawning, and `cap-gpui` deletes it only on clean
+//! shutdown. With no live GPUI process, a surviving marker means the previous
+//! session exited unexpectedly: clear the flag, tell the user, and start normally.
use std::path::PathBuf;
@@ -775,11 +774,8 @@ fn redirect_decision(app: &AppHandle) -> bool {
return false;
}
- // A live instance is checked before the marker: within ten seconds of a
- // successful handoff the marker is still legitimately on disk, and healing
- // then would clear the flag and open this app next to a healthy native one.
- // The marker's lifecycle stays with `cap-gpui` -- if that instance dies
- // before proving itself, the marker survives it and the next launch heals.
+ // The marker exists throughout a live session. Check the process first so
+ // reopening Cap does not mistake a running native app for a crashed one.
if let Some(pid) = running_instance_pid() {
info!(pid, "Cap GPUI is already running; handing over to it");
#[cfg(any(target_os = "macos", windows))]
@@ -793,7 +789,7 @@ fn redirect_decision(app: &AppHandle) -> bool {
let marker = handoff_marker();
if marker.exists() {
- warn!("the last hand-off to Cap GPUI never reported a healthy instance; taking back over");
+ warn!("the last Cap GPUI session exited unexpectedly; taking back over");
let _ = std::fs::remove_file(&marker);
if let Err(error) = GeneralSettingsStore::update(app, |settings| {
settings.enable_gpui_app = false;
@@ -805,7 +801,7 @@ fn redirect_decision(app: &AppHandle) -> bool {
}
app.dialog()
.message(
- "The native Cap app didn't start correctly last time, so the classic app has been restored.",
+ "The native Cap app exited unexpectedly last time, so the classic app has been restored.",
)
.show(|_| {});
return false;