Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(gpui): harden single-instance, update, and classic-app handoffs

Richie McIlroy0fd1fb00ab29
diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs
index b4509e2bf..713f42322 100644
--- a/apps/desktop-gpui/src/main.rs
+++ b/apps/desktop-gpui/src/main.rs
@@ -10,6 +10,8 @@ mod auth;
mod camera_bench;
#[cfg(target_os = "macos")]
mod camera_blur;
+#[cfg(any(not(target_os = "macos"), test))]
+mod camera_blur_portable;
mod camera_window;
mod controls_window;
mod deeplink;
@@ -58,6 +60,7 @@ mod theme;
mod transcription;
mod tray;
mod ui;
+mod updates;
mod upload;
use gpui::{App, AppContext as _, Bounds, WindowBounds, WindowOptions, px, size};
@@ -72,6 +75,7 @@ const MAIN_WINDOW_HEIGHT: f32 = 395.;
/// material `"panel"` on both visual systems in
/// `apps/desktop/src/utils/macos-window-material.ts`, and the same 16 the
/// shell paints with (`rounded-[16px]`).
+#[cfg(target_os = "macos")]
const MAIN_WINDOW_MATERIAL_RADIUS: f64 = 16.;
fn parse_auto_record(spec: &str) -> Option<(main_window::Mode, u64)> {
@@ -253,6 +257,7 @@ fn main() {
.expect("failed to open the main window");
app_windows::init(window_handle, session, cx);
+ updates::schedule_startup_check(cx);
// The app menu (and with it ⌘W/⌘M/⌘Q) and the status-bar item. Both
// reach into the window registry, so they come after it -- and the menu
@@ -350,6 +355,7 @@ fn main() {
"main window opened"
);
view.start_enumeration(window, cx);
+ view.start_recovery_check(window, cx);
view.auto_expand(window, cx);
view.auto_open_recent(window, cx);
// The AppKit work below must not run inside this update:
@@ -366,6 +372,7 @@ fn main() {
// `applyMacOSWindowMaterial("panel")` does in the Tauri app. Nothing
// paints it; the shell paints a translucent tint *over* it, so the
// window has to be told which one landed.
+ #[cfg(target_os = "macos")]
cx.spawn(async move |cx| {
let Some(native) = native_main else {
tracing::error!("no NSWindow behind the main window; material not installed");
@@ -384,6 +391,8 @@ fn main() {
});
})
.detach();
+ #[cfg(not(target_os = "macos"))]
+ let _ = native_main;
// `CAP_GPUI_DEBUG_LIGHTS=1`: poll the main window's style mask and
// standard-button set, logging on change -- pins down *when* AppKit
diff --git a/apps/desktop-gpui/src/platform.rs b/apps/desktop-gpui/src/platform.rs
index 52c86b087..b8899ba5f 100644
--- a/apps/desktop-gpui/src/platform.rs
+++ b/apps/desktop-gpui/src/platform.rs
@@ -59,6 +59,15 @@ pub fn active_material(cx: &gpui::App) -> Option<MaterialKind> {
.and_then(|material| material.0)
}
+#[cfg(any(not(target_os = "macos"), test))]
+fn confirmation_accepted(result: rfd::MessageDialogResult, accept: &str) -> bool {
+ match result {
+ rfd::MessageDialogResult::Ok => true,
+ rfd::MessageDialogResult::Custom(label) => label == accept,
+ _ => false,
+ }
+}
+
#[derive(Debug, Clone, Copy)]
pub struct PanelBehavior {
pub level: isize,
@@ -320,7 +329,7 @@ mod mac {
c"Q@:".as_ptr(),
)
};
- if added {
+ if objc2::runtime::Bool::from_raw(added).as_bool() {
tracing::info!("installed macOS 26 occlusion shim on {name}");
}
}
@@ -368,7 +377,7 @@ mod mac {
c"{CGRect={CGPoint=dd}{CGSize=dd}}@:{CGRect={CGPoint=dd}{CGSize=dd}}@".as_ptr(),
)
};
- if added {
+ if objc2::runtime::Bool::from_raw(added).as_bool() {
tracing::info!("installed frame-constraint shim on {name}");
}
}
@@ -460,6 +469,20 @@ mod mac {
}
}
+ pub fn remove_popup_window_chrome(native: &NativeWindow) {
+ use objc2::msg_send;
+
+ const TITLED: usize = 1 << 0;
+
+ unsafe {
+ let mask: usize = msg_send![&*native.0, styleMask];
+ let borderless = mask & !TITLED;
+ if mask != borderless {
+ let _: () = msg_send![&*native.0, setStyleMask: borderless];
+ }
+ }
+ }
+
/// Dev probe (`CAP_GPUI_DEBUG_LIGHTS=1`): the window's style mask plus
/// which standard titlebar buttons AppKit has materialized. Read-only
/// `msg_send`s, safe inside a gpui update.
@@ -579,11 +602,14 @@ mod mac {
if screens.is_null() {
return true;
}
- let count: usize = msg_send![screens, count];
- for index in 0..count {
- let screen: *mut AnyObject = msg_send![screens, objectAtIndex: index];
+ let enumerator: *mut AnyObject = msg_send![screens, objectEnumerator];
+ if enumerator.is_null() {
+ return true;
+ }
+ loop {
+ let screen: *mut AnyObject = msg_send![enumerator, nextObject];
if screen.is_null() {
- continue;
+ break;
}
let bounds: NSRect = msg_send![screen, frame];
let overlap_x =
@@ -1591,6 +1617,7 @@ mod stub {
None
}
pub fn restore_borderless_style(_native: &NativeWindow) {}
+ pub fn remove_popup_window_chrome(_native: &NativeWindow) {}
pub fn place_overlay_panel(
_native: &NativeWindow,
_x: f64,
@@ -1600,9 +1627,9 @@ mod stub {
_level: isize,
) {
}
- pub fn install_occlusion_shim() {}
pub fn kick_display_link(_window: &Window) {}
- pub fn apply_panel_behavior(window: &Window, _behavior: PanelBehavior) {
+ pub fn apply_panel_behavior(window: &Window, behavior: PanelBehavior) {
+ let _ = (behavior.level, behavior.join_all_spaces, behavior.shadow);
apply_always_on_top(window);
}
@@ -1613,7 +1640,7 @@ mod stub {
use windows_sys::Win32::UI::WindowsAndMessaging::{
HWND_TOPMOST, SWP_NOMOVE, SWP_NOSIZE, SetWindowPos,
};
- if let Ok(handle) = window.window_handle()
+ if let Ok(handle) = HasWindowHandle::window_handle(window)
&& let RawWindowHandle::Win32(win) = handle.as_raw()
{
let hwnd = win.hwnd.get() as windows_sys::Win32::Foundation::HWND;
@@ -1636,7 +1663,7 @@ mod stub {
CLIENT_MESSAGE_EVENT, ClientMessageEvent, ConnectionExt, EventMask,
};
- let Ok(handle) = window.window_handle() else {
+ let Ok(handle) = HasWindowHandle::window_handle(window) else {
return;
};
let window_id = match handle.as_raw() {
@@ -1685,9 +1712,6 @@ mod stub {
}
pub fn close_native(_native: &NativeWindow) {}
- pub fn debug_window_state(_native: &NativeWindow) -> String {
- String::new()
- }
pub fn set_dock_icon(_png: &[u8]) {}
pub fn escape_hotkey_events() -> flume::Receiver<()> {
// A channel whose sender is dropped immediately: the drain task's
@@ -1724,7 +1748,7 @@ mod stub {
} else {
rfd::MessageLevel::Info
};
- rfd::MessageDialog::new()
+ let result = rfd::MessageDialog::new()
.set_title(title)
.set_description(message)
.set_buttons(rfd::MessageButtons::OkCancelCustom(
@@ -1732,8 +1756,8 @@ mod stub {
cancel.to_string(),
))
.set_level(level)
- .show()
- == rfd::MessageDialogResult::Custom(accept.to_string())
+ .show();
+ super::confirmation_accepted(result, accept)
}
pub fn alert_dialog(title: &str, message: &str) {
@@ -1809,3 +1833,36 @@ mod stub {
#[cfg(not(target_os = "macos"))]
pub use stub::*;
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn confirmation_accepts_native_ok_and_matching_custom_label_only() {
+ let accept = "Install update";
+
+ assert!(super::confirmation_accepted(
+ rfd::MessageDialogResult::Ok,
+ accept
+ ));
+ assert!(super::confirmation_accepted(
+ rfd::MessageDialogResult::Custom(accept.to_string()),
+ accept
+ ));
+ assert!(!super::confirmation_accepted(
+ rfd::MessageDialogResult::Custom("Ignore".to_string()),
+ accept
+ ));
+ assert!(!super::confirmation_accepted(
+ rfd::MessageDialogResult::Cancel,
+ accept
+ ));
+ assert!(!super::confirmation_accepted(
+ rfd::MessageDialogResult::No,
+ accept
+ ));
+ assert!(!super::confirmation_accepted(
+ rfd::MessageDialogResult::Yes,
+ accept
+ ));
+ }
+}
diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rs
index d382be345..70ff5a6e7 100644
--- a/apps/desktop-gpui/src/settings_pages.rs
+++ b/apps/desktop-gpui/src/settings_pages.rs
@@ -1967,15 +1967,22 @@ fn takeover_frame(elapsed_ms: f32) -> (usize, f32, u32) {
/// bundle and is not a dev build either.
const CLASSIC_APP_FALLBACK: &str = "/Applications/Cap.app";
+#[cfg(windows)]
+const CLASSIC_EXECUTABLE_NAME: &str = "Cap.exe";
+#[cfg(not(windows))]
+const CLASSIC_EXECUTABLE_NAME: &str = "Cap";
+
/// What "the classic app" means for this process -- decided from where its
/// binary lives, so dev sessions reopen the dev app and installed ones the
/// installed app.
#[derive(Debug, PartialEq)]
enum ClassicTarget {
/// `open` this bundle: the shipped layout is
- /// `.../Cap.app/Contents/Resources/gpui/cap-gpui`, so the nearest `.app`
+ /// `.../Cap.app/Contents/MacOS/cap-gpui`, so the nearest `.app`
/// ancestor is the classic app this binary shipped inside.
Bundle(std::path::PathBuf),
+ /// Windows and Linux install Tauri sidecars beside the main executable.
+ Executable(std::path::PathBuf),
/// A cargo-built binary (an ancestor directory literally named `target`):
/// the classic app here is the `tauri dev` harness, which cannot be
/// `open`ed -- ask the dev-session supervisor to restart it instead
@@ -1996,6 +2003,14 @@ fn classic_target_for_exe(exe: &std::path::Path) -> Option<ClassicTarget> {
{
return Some(ClassicTarget::DevSupervisor);
}
+
+ if let Some(parent) = exe.parent() {
+ let executable = parent.join(CLASSIC_EXECUTABLE_NAME);
+ if executable.is_file() && executable != exe {
+ return Some(ClassicTarget::Executable(executable));
+ }
+ }
+
let fallback = std::path::PathBuf::from(CLASSIC_APP_FALLBACK);
fallback.is_dir().then_some(ClassicTarget::Bundle(fallback))
}
@@ -2007,28 +2022,128 @@ fn classic_target() -> Option<ClassicTarget> {
.and_then(classic_target_for_exe)
}
-impl SettingsWindow {
- pub(crate) fn render_experimental(&self, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {
- let theme = self.theme;
+pub(crate) fn start_update_handoff(cx: &mut gpui::App) {
+ begin_update_handoff(cx, store::request_update_handoff);
+}
- if cfg!(target_os = "windows") {
- return vec![
- div()
- .px(px(4.))
- .text_size(px(12.))
- .line_height(px(18.))
- .text_color(theme.settings_muted())
- .child("No experimental features are currently available on this platform.")
- .into_any_element(),
- ];
+fn quit_after_flushing_editors(cx: &mut gpui::App) {
+ crate::app_windows::flush_pending_editor_saves(cx);
+ crate::menus::quit(cx);
+}
+
+#[cfg(debug_assertions)]
+pub(crate) fn simulate_update_handoff(cx: &mut gpui::App) {
+ cx.spawn(async move |cx| {
+ crate::platform::activate_app();
+ if crate::platform::confirm_dialog(
+ "Update Cap",
+ "Version 99.0.0 of Cap is available. Would you like to install it?",
+ "Update",
+ "Ignore",
+ false,
+ ) {
+ cx.update(|cx| begin_update_handoff(cx, store::request_simulated_update_handoff));
+ }
+ })
+ .detach();
+}
+
+fn begin_update_handoff(cx: &mut gpui::App, request_handoff: fn() -> std::io::Result<()>) {
+ if update_handoff_blocked(cx) {
+ return;
+ }
+
+ let Some(target) = classic_target() else {
+ cx.open_url("https://cap.so/download");
+ return;
+ };
+
+ if matches!(target, ClassicTarget::DevSupervisor) && !cfg!(debug_assertions) {
+ cx.open_url("https://cap.so/download");
+ return;
+ }
+
+ if update_handoff_blocked(cx) {
+ return;
+ }
+ crate::app_windows::flush_pending_editor_saves(cx);
+
+ if let Err(error) = request_handoff() {
+ tracing::error!("couldn't request the Tauri updater: {error}");
+ cx.open_url("https://cap.so/download");
+ return;
+ }
+
+ let started = match &target {
+ ClassicTarget::Bundle(_) | ClassicTarget::Executable(_) => launch_classic(&target),
+ ClassicTarget::DevSupervisor => {
+ store::mark_classic_pending().and_then(|()| store::request_classic_reopen())
+ }
+ };
+
+ match (started, target) {
+ (Ok(()), ClassicTarget::Bundle(_) | ClassicTarget::Executable(_)) => {
+ tracing::info!("handing off to the Tauri updater");
+ quit_after_flushing_editors(cx);
+ }
+ (Ok(()), ClassicTarget::DevSupervisor) => {
+ tracing::info!("handing off to the Tauri updater; waiting for the dev app");
+ cx.spawn(async move |cx| {
+ let started = std::time::Instant::now();
+ loop {
+ cx.background_executor()
+ .timer(Duration::from_millis(250))
+ .await;
+
+ if !store::classic_pending_path().exists() {
+ tracing::info!("the Tauri updater is ready; quitting Cap GPUI");
+ cx.update(quit_after_flushing_editors);
+ return;
+ }
+
+ if started.elapsed() > CLASSIC_WAIT_TIMEOUT {
+ store::clear_update_handoff();
+ tracing::error!("the dev app did not start for the update hand-off");
+ return;
+ }
+ }
+ })
+ .detach();
+ }
+ (Err(error), _) => {
+ store::clear_update_handoff();
+ tracing::error!("couldn't open the Tauri updater: {error}");
+ cx.open_url("https://cap.so/download");
}
+ }
+}
+
+fn update_handoff_blocked(cx: &mut gpui::App) -> bool {
+ if !crate::updates::work_in_flight(cx) {
+ return false;
+ }
+
+ tracing::info!(
+ "deferring update hand-off while recording, exporting, uploading, importing, or transcribing"
+ );
+ cx.spawn(async move |_| {
+ crate::platform::alert_dialog(
+ "Cap is busy",
+ "Finish your recording, export, upload, import, or transcription task before checking for updates.",
+ );
+ })
+ .detach();
+ true
+}
+impl SettingsWindow {
+ pub(crate) fn render_experimental(&self, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {
// No "Native camera preview" toggle here: in this app the native
// camera path is the only implementation, so the Tauri page's
// experimental switch has nothing to switch. The store key
// (`enableNativeCameraPreview`) stays readable in `store.rs` and is
// left untouched in the shared store -- the Tauri app still uses it.
- vec![
+ let sections = vec![
self.section(
"Reliability",
None,
@@ -2067,7 +2182,44 @@ impl SettingsWindow {
vec![self.rows(vec![self.native_app_row(cx)]).into_any_element()],
)
.into_any_element(),
- ]
+ ];
+
+ #[cfg(debug_assertions)]
+ let sections = {
+ let mut sections = sections;
+ sections.push(
+ self.section(
+ "Updates",
+ None,
+ None,
+ vec![
+ self.rows(vec![
+ self.setting_row(
+ "Simulate an update",
+ Some(
+ "Preview the complete update flow without downloading or \
+ installing anything.",
+ ),
+ self.button(
+ "simulate-update",
+ (ui::ButtonVariant::Dark, None),
+ "Simulate update",
+ false,
+ cx,
+ |_, _, cx| simulate_update_handoff(cx),
+ )
+ .into_any_element(),
+ ),
+ ])
+ .into_any_element(),
+ ],
+ )
+ .into_any_element(),
+ );
+ sections
+ };
+
+ sections
}
/// The mirror of the Tauri page's Native app row: it hands the session over
@@ -2205,6 +2357,10 @@ impl SettingsWindow {
}
fn start_switch_back(&mut self, cx: &mut Context<Self>) {
+ if self.switch_back_blocked(cx) {
+ return;
+ }
+
self.pages.switch_back = Some(SwitchBack::Running(std::time::Instant::now()));
// gpui only renders on invalidation, so the fades and the countdown
// need a pulse to run at all -- the `toggle_placeholders` shape.
@@ -2243,11 +2399,28 @@ impl SettingsWindow {
cx.notify();
}
+ fn switch_back_blocked(&mut self, cx: &mut Context<Self>) -> bool {
+ if !crate::updates::work_in_flight(cx) {
+ return false;
+ }
+
+ self.pages.switch_back = Some(SwitchBack::Failed(
+ "Finish your recording, export, upload, import, or transcription task before switching to the classic app."
+ .to_string(),
+ ));
+ cx.notify();
+ true
+ }
+
/// Write the flag, start the classic app, then quit -- in that order, so
/// the app that comes up already owns the session. Nothing is written when
/// there is no way to start one: the flag would strand the user in an app
/// that redirects to one that is not installed.
fn finish_switch_back(&mut self, cx: &mut Context<Self>) {
+ if self.switch_back_blocked(cx) {
+ return;
+ }
+
let Some(target) = classic_target() else {
self.pages.switch_back = Some(SwitchBack::Failed(
"Couldn't find the Cap app to switch back to.".to_string(),
@@ -2256,14 +2429,16 @@ impl SettingsWindow {
return;
};
+ if self.switch_back_blocked(cx) {
+ return;
+ }
+ crate::app_windows::flush_pending_editor_saves(cx);
+
self.settings.enable_gpui_app = false;
self.write_bool("enableGpuiApp", false, cx);
let started = match &target {
- ClassicTarget::Bundle(bundle) => std::process::Command::new("/usr/bin/open")
- .arg(bundle)
- .spawn()
- .map(drop)
+ 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())
@@ -2272,9 +2447,9 @@ impl SettingsWindow {
match (started, target) {
// An installed bundle opens in a moment; quit right away.
- (Ok(()), ClassicTarget::Bundle(_)) => {
+ (Ok(()), ClassicTarget::Bundle(_) | ClassicTarget::Executable(_)) => {
tracing::info!("handing back to the classic app");
- crate::menus::quit(cx);
+ 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
@@ -2304,7 +2479,7 @@ impl SettingsWindow {
}
if !store::classic_pending_path().exists() {
tracing::info!("classic app is up; quitting");
- cx.update(crate::menus::quit);
+ cx.update(quit_after_flushing_editors);
break;
}
if started.elapsed() > CLASSIC_WAIT_TIMEOUT {
@@ -2333,6 +2508,19 @@ impl SettingsWindow {
}
}
+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)
+ }
+ ClassicTarget::DevSupervisor => Ok(()),
+ }
+}
+
// ---------------------------------------------------------------------------
// Feedback (feedback.tsx)
// ---------------------------------------------------------------------------
@@ -5691,12 +5879,8 @@ fn action_is_dangerous(kind: ActionType) -> bool {
/// everything, with OCR only where Vision/Windows-OCR exists. `skipEditor`
/// requires no capability at all (`required_capability` returns `None`).
fn action_supported_here(action: &Action) -> bool {
- match action {
- Action::RecognizeTextToClipboard => {
- cfg!(any(target_os = "macos", target_os = "windows"))
- }
- _ => true,
- }
+ !matches!(action, Action::RecognizeTextToClipboard)
+ || cfg!(any(target_os = "macos", target_os = "windows"))
}
/// `ruleSummary`.
@@ -8455,7 +8639,7 @@ mod tests {
fn the_classic_target_matches_the_launch_context() {
assert_eq!(
classic_target_for_exe(std::path::Path::new(
- "/Applications/Cap.app/Contents/Resources/gpui/cap-gpui"
+ "/Applications/Cap.app/Contents/MacOS/cap-gpui"
)),
Some(ClassicTarget::Bundle(std::path::PathBuf::from(
"/Applications/Cap.app"
@@ -8470,7 +8654,7 @@ mod tests {
// A dev binary staged inside a bundle is still that bundle's.
assert_eq!(
classic_target_for_exe(std::path::Path::new(
- "/Users/x/Cap/target/debug/bundle/osx/Cap.app/Contents/Resources/gpui/cap-gpui"
+ "/Users/x/Cap/target/debug/bundle/osx/Cap.app/Contents/MacOS/cap-gpui"
)),
Some(ClassicTarget::Bundle(std::path::PathBuf::from(
"/Users/x/Cap/target/debug/bundle/osx/Cap.app"
diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rs
index d76018c54..5b8f47376 100644
--- a/apps/desktop-gpui/src/single_instance.rs
+++ b/apps/desktop-gpui/src/single_instance.rs
@@ -22,7 +22,21 @@
//! second instance on macOS at all -- the GURL AppleEvent goes straight to
//! the running process (`crate::platform::install_url_scheme_handler`).
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
+
+#[cfg(windows)]
+static INSTANCE_MUTEX: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
+
+#[cfg(any(windows, target_os = "macos", test))]
+const MAX_FORWARDED_DEEP_LINK_BYTES: usize = 1024 * 1024;
+
+#[cfg(any(windows, target_os = "macos", test))]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct ForwardingEndpoint {
+ pid: u32,
+ port: u16,
+ secret: u64,
+}
fn pidfile() -> PathBuf {
crate::store::app_data_dir().join("cap-gpui.pid")
@@ -30,6 +44,8 @@ fn pidfile() -> PathBuf {
pub fn acquire() {
let path = pidfile();
+ #[cfg(windows)]
+ acquire_windows_instance(&path);
#[cfg(unix)]
if let Ok(raw) = std::fs::read_to_string(&path)
&& let Ok(pid) = raw.trim().parse::<i32>()
@@ -60,6 +76,12 @@ pub fn acquire() {
if let Err(error) = std::fs::write(&path, std::process::id().to_string()) {
tracing::warn!(%error, "could not write the instance pidfile");
}
+
+ #[cfg(target_os = "macos")]
+ if let Err(error) = start_deep_link_forwarding(&path) {
+ tracing::error!(%error, "could not start Cap GPUI deep-link forwarding");
+ std::process::exit(1);
+ }
}
/// Guard against pid reuse: only ever signal a process that is actually this
@@ -73,5 +95,491 @@ fn is_cap_gpui(pid: i32) -> bool {
std::process::Command::new("ps")
.args(["-p", &pid.to_string(), "-o", "comm="])
.output()
- .is_ok_and(|output| String::from_utf8_lossy(&output.stdout).contains("cap-gpui"))
+ .is_ok_and(|output| {
+ output.status.success()
+ && is_cap_gpui_image(Path::new(String::from_utf8_lossy(&output.stdout).trim()))
+ })
+}
+
+fn is_cap_gpui_image(path: &Path) -> bool {
+ #[cfg(windows)]
+ const IMAGE_NAME: &str = "cap-gpui.exe";
+ #[cfg(not(windows))]
+ const IMAGE_NAME: &str = "cap-gpui";
+
+ path.file_name()
+ .and_then(std::ffi::OsStr::to_str)
+ .is_some_and(|name| name.eq_ignore_ascii_case(IMAGE_NAME))
+}
+
+#[cfg(windows)]
+fn acquire_windows_instance(path: &Path) {
+ use std::hash::{Hash, Hasher};
+ use windows_sys::Win32::{
+ Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GetLastError},
+ System::Threading::CreateMutexW,
+ };
+
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
+ path.hash(&mut hasher);
+ let name = format!("Local\\CapGpui-{:016x}", hasher.finish())
+ .encode_utf16()
+ .chain(std::iter::once(0))
+ .collect::<Vec<_>>();
+ let mutex = unsafe { CreateMutexW(std::ptr::null(), 0, name.as_ptr()) };
+ let last_error = unsafe { GetLastError() };
+
+ if mutex.is_null() {
+ tracing::error!(
+ error = last_error,
+ "could not acquire the Cap GPUI instance mutex"
+ );
+ std::process::exit(1);
+ }
+
+ if last_error == ERROR_ALREADY_EXISTS {
+ for _ in 0..40 {
+ if let Some(pid) = windows_instance_pid(path) {
+ tracing::info!(pid, "Cap GPUI is already running; bringing it forward");
+ forward_windows_deep_links(path, pid);
+ activate_windows_instance(pid);
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ }
+
+ let _ = unsafe { CloseHandle(mutex) };
+ std::process::exit(0);
+ }
+
+ if INSTANCE_MUTEX.set(mutex as usize).is_err() {
+ let _ = unsafe { CloseHandle(mutex) };
+ tracing::error!("the Cap GPUI instance mutex was initialized twice");
+ std::process::exit(1);
+ }
+
+ if let Err(error) = start_deep_link_forwarding(path) {
+ tracing::error!(%error, "could not start Cap GPUI deep-link forwarding");
+ std::process::exit(1);
+ }
+}
+
+#[cfg(any(windows, target_os = "macos"))]
+fn start_deep_link_forwarding(path: &Path) -> std::io::Result<()> {
+ use std::hash::BuildHasher;
+
+ let listener = std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?;
+ let endpoint = ForwardingEndpoint {
+ pid: std::process::id(),
+ port: listener.local_addr()?.port(),
+ secret: std::collections::hash_map::RandomState::new()
+ .hash_one((std::process::id(), listener.local_addr()?.port())),
+ };
+ let endpoint_path = path.with_extension("ipc");
+ let temporary_path =
+ path.with_extension(format!("ipc.{}.{:016x}.tmp", endpoint.pid, endpoint.secret));
+
+ if let Some(parent) = endpoint_path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+
+ write_forwarding_endpoint(&temporary_path, endpoint)?;
+ if let Err(error) = publish_forwarding_endpoint(&temporary_path, &endpoint_path) {
+ let _ = std::fs::remove_file(&temporary_path);
+ return Err(error);
+ }
+
+ std::thread::Builder::new()
+ .name("cap-gpui-deep-link".into())
+ .spawn(move || {
+ for connection in listener.incoming() {
+ match connection {
+ Ok(mut stream) => {
+ let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(2)));
+ match read_forwarded_deep_link(&mut stream, endpoint.secret) {
+ Ok(url) => crate::deeplink::submit_deep_link(&url),
+ Err(error) => {
+ tracing::warn!(%error, "rejected a forwarded Cap deep link");
+ }
+ }
+ }
+ Err(error) => {
+ tracing::warn!(%error, "could not accept a forwarded Cap deep link");
+ }
+ }
+ }
+ })?;
+
+ Ok(())
+}
+
+#[cfg(any(windows, target_os = "macos", test))]
+fn write_forwarding_endpoint(path: &Path, endpoint: ForwardingEndpoint) -> std::io::Result<()> {
+ use std::io::Write;
+
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+
+ let mut file = options.open(path)?;
+ write!(
+ file,
+ "{}:{}:{:016x}",
+ endpoint.pid, endpoint.port, endpoint.secret
+ )
+}
+
+#[cfg(all(unix, target_os = "macos"))]
+fn publish_forwarding_endpoint(temporary_path: &Path, endpoint_path: &Path) -> std::io::Result<()> {
+ std::fs::rename(temporary_path, endpoint_path)
+}
+
+#[cfg(windows)]
+fn publish_forwarding_endpoint(temporary_path: &Path, endpoint_path: &Path) -> std::io::Result<()> {
+ match std::fs::remove_file(endpoint_path) {
+ Ok(()) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error),
+ }
+ std::fs::rename(temporary_path, endpoint_path)
+}
+
+#[cfg(windows)]
+fn forward_windows_deep_links(path: &Path, pid: u32) {
+ use std::io::Write;
+
+ let urls = std::env::args()
+ .skip(1)
+ .filter(|argument| is_forwardable_deep_link(argument))
+ .collect::<Vec<_>>();
+ if urls.is_empty() {
+ return;
+ }
+
+ let endpoint_path = path.with_extension("ipc");
+ let endpoint = (0..40).find_map(|attempt| {
+ let endpoint = std::fs::read_to_string(&endpoint_path)
+ .ok()
+ .and_then(|contents| parse_forwarding_endpoint(&contents))
+ .filter(|endpoint| endpoint.pid == pid);
+ if endpoint.is_none() && attempt < 39 {
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ }
+ endpoint
+ });
+ let Some(endpoint) = endpoint else {
+ tracing::warn!("could not find the running Cap GPUI deep-link endpoint");
+ return;
+ };
+
+ for url in urls {
+ let result = std::net::TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, endpoint.port))
+ .and_then(|mut stream| {
+ stream.set_write_timeout(Some(std::time::Duration::from_secs(2)))?;
+ stream.write_all(&endpoint.secret.to_be_bytes())?;
+ stream.write_all(&(url.len() as u32).to_be_bytes())?;
+ stream.write_all(url.as_bytes())
+ });
+ if let Err(error) = result {
+ tracing::warn!(%error, "could not forward a Cap deep link to the running instance");
+ }
+ }
+}
+
+#[cfg(any(windows, test))]
+fn parse_forwarding_endpoint(contents: &str) -> Option<ForwardingEndpoint> {
+ let mut parts = contents.trim().split(':');
+ let pid = parts.next()?.parse().ok()?;
+ let port = parts.next()?.parse().ok()?;
+ let secret = u64::from_str_radix(parts.next()?, 16).ok()?;
+ (pid != 0 && port != 0 && parts.next().is_none()).then_some(ForwardingEndpoint {
+ pid,
+ port,
+ secret,
+ })
+}
+
+#[cfg(any(windows, target_os = "macos", test))]
+fn is_forwardable_deep_link(url: &str) -> bool {
+ !url.is_empty()
+ && url.len() <= MAX_FORWARDED_DEEP_LINK_BYTES
+ && reqwest::Url::parse(url)
+ .is_ok_and(|parsed| matches!(parsed.scheme(), "cap-desktop" | "cap"))
+}
+
+#[cfg(any(windows, target_os = "macos", test))]
+fn read_forwarded_deep_link(
+ reader: &mut impl std::io::Read,
+ expected_secret: u64,
+) -> std::io::Result<String> {
+ let mut secret = [0_u8; 8];
+ reader.read_exact(&mut secret)?;
+ if u64::from_be_bytes(secret) != expected_secret {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::PermissionDenied,
+ "incorrect forwarding secret",
+ ));
+ }
+
+ let mut size = [0_u8; 4];
+ reader.read_exact(&mut size)?;
+ let size = u32::from_be_bytes(size) as usize;
+ if size == 0 || size > MAX_FORWARDED_DEEP_LINK_BYTES {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidData,
+ "invalid forwarded deep-link size",
+ ));
+ }
+
+ let mut bytes = vec![0_u8; size];
+ reader.read_exact(&mut bytes)?;
+ let url = String::from_utf8(bytes).map_err(|error| {
+ std::io::Error::new(std::io::ErrorKind::InvalidData, error.utf8_error())
+ })?;
+ if !is_forwardable_deep_link(&url) {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidData,
+ "invalid forwarded deep-link scheme",
+ ));
+ }
+
+ Ok(url)
+}
+
+#[cfg(windows)]
+fn windows_instance_pid(path: &Path) -> Option<u32> {
+ use std::os::windows::ffi::OsStringExt;
+ use windows_sys::Win32::{
+ Foundation::CloseHandle,
+ System::Threading::{
+ OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
+ },
+ };
+
+ let pid = std::fs::read_to_string(path).ok()?.trim().parse().ok()?;
+ let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
+ if process.is_null() {
+ return None;
+ }
+
+ let mut image = [0_u16; 1024];
+ let mut len = image.len() as u32;
+ let found =
+ unsafe { QueryFullProcessImageNameW(process, 0, image.as_mut_ptr(), &mut len) } != 0;
+ let _ = unsafe { CloseHandle(process) };
+ if !found {
+ return None;
+ }
+
+ let image = PathBuf::from(std::ffi::OsString::from_wide(&image[..len as usize]));
+ is_cap_gpui_image(&image).then_some(pid)
+}
+
+#[cfg(windows)]
+fn activate_windows_instance(pid: u32) {
+ use windows_sys::Win32::{
+ Foundation::{BOOL, HWND, LPARAM, TRUE},
+ UI::WindowsAndMessaging::{
+ EnumWindows, GetWindowThreadProcessId, IsWindowVisible, SW_RESTORE,
+ SetForegroundWindow, ShowWindow,
+ },
+ };
+
+ struct Activation {
+ pid: u32,
+ visible: Option<HWND>,
+ fallback: Option<HWND>,
+ }
+
+ unsafe extern "system" fn find_window(window: HWND, data: LPARAM) -> BOOL {
+ let activation = unsafe { &mut *(data as *mut Activation) };
+ let mut owner = 0;
+ unsafe { GetWindowThreadProcessId(window, &mut owner) };
+ if owner == activation.pid {
+ if activation.fallback.is_none() {
+ activation.fallback = Some(window);
+ }
+ if activation.visible.is_none() && unsafe { IsWindowVisible(window) } != 0 {
+ activation.visible = Some(window);
+ }
+ }
+ TRUE
+ }
+
+ let mut activation = Activation {
+ pid,
+ visible: None,
+ fallback: None,
+ };
+ unsafe {
+ EnumWindows(
+ Some(find_window),
+ std::ptr::addr_of_mut!(activation) as isize,
+ );
+ }
+
+ if let Some(window) = activation.visible.or(activation.fallback) {
+ unsafe {
+ ShowWindow(window, SW_RESTORE);
+ SetForegroundWindow(window);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ ForwardingEndpoint, MAX_FORWARDED_DEEP_LINK_BYTES, is_cap_gpui_image,
+ is_forwardable_deep_link, parse_forwarding_endpoint, read_forwarded_deep_link,
+ };
+ use std::path::Path;
+
+ #[test]
+ fn gpui_process_image_must_match_exactly() {
+ #[cfg(windows)]
+ let name = "cap-gpui.exe";
+ #[cfg(not(windows))]
+ let name = "cap-gpui";
+
+ assert!(is_cap_gpui_image(Path::new(name)));
+ assert!(is_cap_gpui_image(Path::new(&name.to_ascii_uppercase())));
+ assert!(!is_cap_gpui_image(Path::new("not-cap-gpui")));
+ assert!(!is_cap_gpui_image(Path::new("cap-gpui-helper")));
+ }
+
+ #[test]
+ fn forwarding_endpoint_requires_a_live_instance_shape() {
+ assert_eq!(
+ parse_forwarding_endpoint("4321:49152:0123456789abcdef"),
+ Some(ForwardingEndpoint {
+ pid: 4321,
+ port: 49152,
+ secret: 0x0123_4567_89ab_cdef,
+ })
+ );
+ assert_eq!(parse_forwarding_endpoint("0:49152:0123"), None);
+ assert_eq!(parse_forwarding_endpoint("4321:0:0123"), None);
+ assert_eq!(parse_forwarding_endpoint("4321:49152:no-secret"), None);
+ assert_eq!(parse_forwarding_endpoint("4321:49152:0123:extra"), None);
+ }
+
+ #[test]
+ fn forwarded_deep_links_only_accept_cap_schemes() {
+ assert!(is_forwardable_deep_link("cap-desktop://auth?token=test"));
+ assert!(is_forwardable_deep_link("cap://action?value=test"));
+ assert!(!is_forwardable_deep_link("https://cap.so"));
+ assert!(!is_forwardable_deep_link("cap-desktop-evil://auth"));
+ assert!(!is_forwardable_deep_link(&format!(
+ "cap://action?value={}",
+ "x".repeat(MAX_FORWARDED_DEEP_LINK_BYTES)
+ )));
+ }
+
+ #[test]
+ fn forwarded_project_actions_use_the_existing_deep_link_protocol() {
+ let action = serde_json::json!({
+ "open_editor": {
+ "project_path": "/tmp/Recording With Spaces.cap"
+ }
+ });
+ let url = reqwest::Url::parse_with_params(
+ "cap-desktop://action",
+ &[("value", action.to_string())],
+ )
+ .unwrap();
+
+ assert!(is_forwardable_deep_link(url.as_str()));
+ let secret = 0x0123_4567_89ab_cdef_u64;
+ let mut payload = secret.to_be_bytes().to_vec();
+ payload.extend_from_slice(&(url.as_str().len() as u32).to_be_bytes());
+ payload.extend_from_slice(url.as_str().as_bytes());
+ let authenticated = read_forwarded_deep_link(&mut payload.as_slice(), secret).unwrap();
+ let authenticated = reqwest::Url::parse(&authenticated).unwrap();
+ assert!(matches!(
+ crate::deeplink::DeepLinkAction::try_from(&authenticated),
+ Ok(crate::deeplink::DeepLinkAction::OpenEditor { project_path })
+ if project_path == Path::new("/tmp/Recording With Spaces.cap")
+ ));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn forwarding_endpoint_is_private_and_never_follows_symlinks() {
+ use std::os::unix::fs::{PermissionsExt, symlink};
+
+ let root = std::env::temp_dir().join(format!(
+ "cap-gpui-forwarding-endpoint-{}",
+ std::process::id()
+ ));
+ std::fs::create_dir_all(&root).unwrap();
+ let path = root.join("endpoint.tmp");
+ let endpoint = ForwardingEndpoint {
+ pid: 4321,
+ port: 49152,
+ secret: 0x0123_4567_89ab_cdef,
+ };
+
+ super::write_forwarding_endpoint(&path, endpoint).unwrap();
+ assert_eq!(
+ std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ assert_eq!(
+ parse_forwarding_endpoint(&std::fs::read_to_string(&path).unwrap()),
+ Some(endpoint)
+ );
+ assert_eq!(
+ super::write_forwarding_endpoint(&path, endpoint)
+ .unwrap_err()
+ .kind(),
+ std::io::ErrorKind::AlreadyExists
+ );
+
+ let protected = root.join("protected");
+ std::fs::write(&protected, "unchanged").unwrap();
+ let link = root.join("endpoint-link.tmp");
+ symlink(&protected, &link).unwrap();
+ assert_eq!(
+ super::write_forwarding_endpoint(&link, endpoint)
+ .unwrap_err()
+ .kind(),
+ std::io::ErrorKind::AlreadyExists
+ );
+ assert_eq!(std::fs::read_to_string(&protected).unwrap(), "unchanged");
+
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
+ #[test]
+ fn forwarded_deep_links_require_the_owner_secret_and_bounded_payload() {
+ let secret = 0x0123_4567_89ab_cdef_u64;
+ let url = "cap-desktop://auth?token=test";
+ let mut payload = secret.to_be_bytes().to_vec();
+ payload.extend_from_slice(&(url.len() as u32).to_be_bytes());
+ payload.extend_from_slice(url.as_bytes());
+
+ assert_eq!(
+ read_forwarded_deep_link(&mut payload.as_slice(), secret).unwrap(),
+ url
+ );
+ assert_eq!(
+ read_forwarded_deep_link(&mut payload.as_slice(), secret + 1)
+ .unwrap_err()
+ .kind(),
+ std::io::ErrorKind::PermissionDenied
+ );
+
+ let mut oversized = secret.to_be_bytes().to_vec();
+ oversized.extend_from_slice(&((MAX_FORWARDED_DEEP_LINK_BYTES + 1) as u32).to_be_bytes());
+ assert_eq!(
+ read_forwarded_deep_link(&mut oversized.as_slice(), secret)
+ .unwrap_err()
+ .kind(),
+ std::io::ErrorKind::InvalidData
+ );
+ }
}
diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs
index b99f206f9..2a362c7db 100644
--- a/apps/desktop-gpui/src/store.rs
+++ b/apps/desktop-gpui/src/store.rs
@@ -14,7 +14,11 @@
//! read-modify-write on the raw JSON that touches exactly one key: see
//! [`set_store_setting`].
-use std::path::PathBuf;
+use std::{
+ io::Write,
+ path::{Path, PathBuf},
+ sync::atomic::{AtomicU64, Ordering},
+};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
@@ -154,6 +158,39 @@ pub fn app_data_dir() -> PathBuf {
}
}
+pub(crate) fn bundled_resource_dirs() -> Vec<PathBuf> {
+ let executable = std::env::current_exe().ok();
+ let override_dir = std::env::var_os("CAP_GPUI_RESOURCES_DIR").map(PathBuf::from);
+ bundled_resource_dirs_for(executable.as_deref(), override_dir.as_deref())
+}
+
+fn bundled_resource_dirs_for(
+ executable: Option<&Path>,
+ override_dir: Option<&Path>,
+) -> Vec<PathBuf> {
+ let mut directories = Vec::new();
+ if let Some(directory) = override_dir {
+ directories.push(directory.to_path_buf());
+ }
+
+ if let Some(parent) = executable.and_then(Path::parent) {
+ if parent.file_name().is_some_and(|name| name == "MacOS")
+ && let Some(contents) = parent.parent()
+ {
+ directories.push(contents.join("Resources"));
+ }
+ if parent.file_name().is_some_and(|name| name == "bin")
+ && let Some(prefix) = parent.parent()
+ {
+ directories.push(prefix.join("lib").join("cap"));
+ }
+ directories.push(parent.join("resources"));
+ directories.push(parent.to_path_buf());
+ }
+
+ directories
+}
+
/// The Tauri app's hand-off marker (`gpui_app.rs`).
///
/// It writes this file immediately before spawning this app and never deletes
@@ -177,6 +214,99 @@ pub fn clear_handoff_marker() {
}
}
+/// One-shot request for the Tauri host to own the next startup and open its
+/// updater. The GPUI preference stays enabled, so the relaunch after a signed
+/// bundle update routes back to the new GPUI binary.
+pub fn update_handoff_path() -> PathBuf {
+ app_data_dir().join("cap-gpui.update-handoff")
+}
+
+pub fn request_update_handoff() -> std::io::Result<()> {
+ write_update_handoff(&std::process::id().to_string())
+}
+
+#[cfg(debug_assertions)]
+pub fn request_simulated_update_handoff() -> std::io::Result<()> {
+ write_update_handoff(&format!("simulate:{}", std::process::id()))
+}
+
+fn write_update_handoff(contents: &str) -> std::io::Result<()> {
+ write_update_handoff_at(&update_handoff_path(), contents)
+}
+
+fn write_update_handoff_at(path: &Path, contents: &str) -> std::io::Result<()> {
+ static WRITES: std::sync::Mutex<()> = std::sync::Mutex::new(());
+ static SEQUENCE: AtomicU64 = AtomicU64::new(0);
+
+ let _guard = WRITES
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+
+ let (temporary_path, mut file) = loop {
+ let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
+ let mut temporary_path = path.as_os_str().to_os_string();
+ temporary_path.push(format!(".tmp.{}.{sequence}", std::process::id()));
+ let temporary_path = PathBuf::from(temporary_path);
+
+ match std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&temporary_path)
+ {
+ Ok(file) => break (temporary_path, file),
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
+ Err(error) => return Err(error),
+ }
+ };
+
+ let written = file.write_all(contents.as_bytes());
+ drop(file);
+ let published = written.and_then(|()| publish_update_handoff(&temporary_path, path));
+ if published.is_err() {
+ let _ = std::fs::remove_file(&temporary_path);
+ }
+ published
+}
+
+#[cfg(not(windows))]
+fn publish_update_handoff(temporary_path: &Path, path: &Path) -> std::io::Result<()> {
+ std::fs::rename(temporary_path, path)
+}
+
+#[cfg(windows)]
+fn publish_update_handoff(temporary_path: &Path, path: &Path) -> std::io::Result<()> {
+ match std::fs::rename(temporary_path, path) {
+ Ok(()) => Ok(()),
+ Err(error)
+ if matches!(
+ error.kind(),
+ std::io::ErrorKind::AlreadyExists | std::io::ErrorKind::PermissionDenied
+ ) =>
+ {
+ match std::fs::remove_file(path) {
+ Ok(()) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error),
+ }
+ std::fs::rename(temporary_path, path)
+ }
+ Err(error) => Err(error),
+ }
+}
+
+pub fn clear_update_handoff() {
+ let path = update_handoff_path();
+ match std::fs::remove_file(&path) {
+ Ok(()) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => tracing::warn!("clearing the update hand-off: {error}"),
+ }
+}
+
/// A dev-checkout switch-back has no `Cap.app` to `open`: the classic app only
/// runs inside its `tauri dev` harness, which exited with the hand-off. This
/// sentinel asks whatever supervises the dev session (`scripts/dev-desktop.mjs`
@@ -248,12 +378,24 @@ pub fn update(mutate: impl FnOnce(&mut PersistedState)) {
// The Tauri settings store
// ---------------------------------------------------------------------------
+#[cfg(test)]
+thread_local! {
+ static TEST_TAURI_STORE_PATH: std::cell::RefCell<Option<PathBuf>> = const {
+ std::cell::RefCell::new(None)
+ };
+}
+
/// The tauri-plugin-store file, shared with the shipping app.
///
/// `CAP_GPUI_TAURI_STORE` redirects it at a copy, which is how the tests --
/// and any verification run that must not touch the user's real settings --
/// work.
pub fn tauri_store_path() -> PathBuf {
+ #[cfg(test)]
+ if let Some(path) = TEST_TAURI_STORE_PATH.with(|path| path.borrow().clone()) {
+ return path;
+ }
+
match std::env::var("CAP_GPUI_TAURI_STORE") {
Ok(path) if !path.is_empty() => PathBuf::from(path),
// `Store.load("store")`: no extension, and the sibling `store.json`
@@ -1527,24 +1669,12 @@ pub fn preset_names() -> Vec<String> {
mod tests {
use super::*;
- /// `CAP_GPUI_TAURI_STORE` is process-global and `cargo test` runs these in
- /// parallel threads, so the redirect is held under a lock -- without it
- /// one test's store path is read by another's `load()`.
- static STORE_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());
-
struct TempStore {
path: PathBuf,
- /// Held for the store's lifetime so no parallel test re-points the
- /// env var mid-flight; never read, only dropped.
- _guard: std::sync::MutexGuard<'static, ()>,
}
impl TempStore {
fn new(name: &str, contents: Option<&str>) -> Self {
- let guard = STORE_ENV.lock().unwrap_or_else(|error| error.into_inner());
- // Keyed by pid too: the mutex serializes threads, but two test
- // *processes* (e.g. `cargo test` twice in parallel) sharing one
- // path race each other's writes and drops.
let path = std::env::temp_dir()
.join(format!("cap-gpui-store-test-{}-{name}", std::process::id()));
match contents {
@@ -1553,13 +1683,11 @@ mod tests {
let _ = std::fs::remove_file(&path);
}
}
- // SAFETY: the guard above is the only writer of this var, and no
- // other thread in the test binary reads the environment.
- unsafe { std::env::set_var("CAP_GPUI_TAURI_STORE", &path) };
- Self {
- path,
- _guard: guard,
- }
+ TEST_TAURI_STORE_PATH.with(|current| {
+ assert!(current.borrow().is_none());
+ *current.borrow_mut() = Some(path.clone());
+ });
+ Self { path }
}
fn read(&self) -> Value {
@@ -1570,8 +1698,37 @@ mod tests {
impl Drop for TempStore {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
- unsafe { std::env::remove_var("CAP_GPUI_TAURI_STORE") };
+ TEST_TAURI_STORE_PATH.with(|current| *current.borrow_mut() = None);
+ }
+ }
+
+ #[test]
+ fn temporary_stores_are_thread_local_without_mutating_process_environment() {
+ let original = std::env::var_os("CAP_GPUI_TAURI_STORE");
+ let barrier = std::sync::Arc::new(std::sync::Barrier::new(4));
+ let workers = (0..4)
+ .map(|index| {
+ let barrier = barrier.clone();
+ let original = original.clone();
+ std::thread::spawn(move || {
+ let store = TempStore::new(&format!("thread-local-{index}"), None);
+ assert_eq!(super::tauri_store_path(), store.path);
+ assert!(super::set_store_setting(
+ GENERAL_SETTINGS,
+ "maxFps",
+ Value::from(24 + index)
+ ));
+ barrier.wait();
+ assert_eq!(GeneralSettings::load().max_fps, 24 + index);
+ assert_eq!(std::env::var_os("CAP_GPUI_TAURI_STORE"), original);
+ })
+ })
+ .collect::<Vec<_>>();
+
+ for worker in workers {
+ worker.join().unwrap();
}
+ assert_eq!(std::env::var_os("CAP_GPUI_TAURI_STORE"), original);
}
/// The compatibility contract: writing one setting must leave every key
@@ -1786,6 +1943,98 @@ mod tests {
super::handoff_marker_path(),
super::app_data_dir().join("cap-gpui.handoff")
);
+ assert_eq!(
+ super::update_handoff_path(),
+ super::app_data_dir().join("cap-gpui.update-handoff")
+ );
+ }
+
+ #[test]
+ fn bundled_resource_paths_follow_the_installed_executable() {
+ let executable = std::path::Path::new("/Applications/Cap.app/Contents/MacOS/cap-gpui");
+ let override_dir = std::path::Path::new("/tmp/cap-resources");
+
+ assert_eq!(
+ super::bundled_resource_dirs_for(Some(executable), Some(override_dir)),
+ vec![
+ override_dir.to_path_buf(),
+ std::path::PathBuf::from("/Applications/Cap.app/Contents/Resources"),
+ std::path::PathBuf::from("/Applications/Cap.app/Contents/MacOS/resources"),
+ std::path::PathBuf::from("/Applications/Cap.app/Contents/MacOS"),
+ ]
+ );
+
+ let executable = std::path::Path::new("/opt/cap/cap-gpui");
+ assert_eq!(
+ super::bundled_resource_dirs_for(Some(executable), None),
+ vec![
+ std::path::PathBuf::from("/opt/cap/resources"),
+ std::path::PathBuf::from("/opt/cap"),
+ ]
+ );
+
+ let executable = std::path::Path::new("/usr/bin/cap-gpui");
+ assert_eq!(
+ super::bundled_resource_dirs_for(Some(executable), None),
+ vec![
+ std::path::PathBuf::from("/usr/lib/cap"),
+ std::path::PathBuf::from("/usr/bin/resources"),
+ std::path::PathBuf::from("/usr/bin"),
+ ]
+ );
+ }
+
+ #[test]
+ fn update_handoff_publication_replaces_complete_markers() {
+ let directory = std::env::temp_dir().join(format!(
+ "cap-gpui-update-handoff-replace-{}",
+ std::process::id()
+ ));
+ let marker = directory.join("cap-gpui.update-handoff");
+
+ super::write_update_handoff_at(&marker, "1234").unwrap();
+ assert_eq!(std::fs::read_to_string(&marker).unwrap(), "1234");
+
+ super::write_update_handoff_at(&marker, "simulate:5678").unwrap();
+ assert_eq!(std::fs::read_to_string(&marker).unwrap(), "simulate:5678");
+
+ let entries = std::fs::read_dir(&directory)
+ .unwrap()
+ .map(|entry| entry.unwrap().path())
+ .collect::<Vec<_>>();
+ assert_eq!(entries, vec![marker.clone()]);
+
+ std::fs::remove_file(marker).unwrap();
+ std::fs::remove_dir(directory).unwrap();
+ }
+
+ #[test]
+ fn concurrent_update_handoff_writers_publish_complete_markers() {
+ let directory = std::env::temp_dir().join(format!(
+ "cap-gpui-update-handoff-concurrent-{}",
+ std::process::id()
+ ));
+ let marker = directory.join("cap-gpui.update-handoff");
+
+ let writers = (0..8)
+ .map(|index| {
+ let marker = marker.clone();
+ std::thread::spawn(move || {
+ super::write_update_handoff_at(&marker, &(1000 + index).to_string())
+ })
+ })
+ .collect::<Vec<_>>();
+ for writer in writers {
+ writer.join().unwrap().unwrap();
+ }
+
+ let contents = std::fs::read_to_string(&marker).unwrap();
+ let pid = contents.parse::<u32>().unwrap();
+ assert!((1000..1008).contains(&pid));
+ assert_eq!(std::fs::read_dir(&directory).unwrap().count(), 1);
+
+ std::fs::remove_file(marker).unwrap();
+ std::fs::remove_dir(directory).unwrap();
}
/// `normalizeTranscriptionHints`: NULs stripped, whitespace trimmed,
@@ -1805,9 +2054,7 @@ mod tests {
}
/// An absent `transcriptionHints` key shows the four defaults
- /// (`createDefaultGeneralSettings`), an empty array shows none. Scoped
- /// blocks: each `TempStore` holds the global env lock, so the first must
- /// drop before the second is created.
+ /// (`createDefaultGeneralSettings`), an empty array shows none.
#[test]
fn transcription_hints_default_only_when_absent() {
{
diff --git a/apps/desktop-gpui/src/updates.rs b/apps/desktop-gpui/src/updates.rs
new file mode 100644
index 000000000..69af5f491
--- /dev/null
+++ b/apps/desktop-gpui/src/updates.rs
@@ -0,0 +1,516 @@
+//! Update discovery for sessions owned by GPUI.
+//!
+//! The endpoint response is advisory only. GPUI never downloads or installs
+//! it; accepting the prompt hands control to Tauri, which repeats the check
+//! and enforces the signed updater contract before changing the app bundle.
+
+use std::time::Duration;
+
+use futures_util::future::{Either, select};
+use gpui::{App, Global};
+use semver::Version;
+use serde::Deserialize;
+
+use crate::{
+ session::RecordingSession,
+ store::{GeneralSettings, UpdateChannel},
+};
+
+const UPDATE_ENDPOINT: &str =
+ "https://cdn.crabnebula.app/update/cap/cap/{target}/{current_version}";
+const STABLE_FIRST_CHECK_DELAY: Duration = Duration::from_secs(10);
+const NIGHTLY_FIRST_CHECK_DELAY: Duration = Duration::from_secs(60);
+const NIGHTLY_CHECK_INTERVAL: Duration = Duration::from_secs(2 * 60 * 60);
+const BUSY_RETRY_DELAY: Duration = Duration::from_secs(5 * 60);
+
+#[derive(Deserialize)]
+struct AvailableUpdate {
+ version: String,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct PendingUpdateRequests {
+ manual: bool,
+ channel: Option<UpdateChannel>,
+}
+
+impl PendingUpdateRequests {
+ fn request_manual(&mut self, manual_in_flight: bool) -> bool {
+ if self.manual || manual_in_flight {
+ return false;
+ }
+
+ self.manual = true;
+ true
+ }
+
+ fn request_channel(&mut self, channel: UpdateChannel) {
+ self.channel = Some(channel);
+ }
+}
+
+struct UpdateScheduler {
+ wake: flume::Sender<()>,
+ pending: PendingUpdateRequests,
+ manual_in_flight: bool,
+}
+
+impl Global for UpdateScheduler {}
+
+fn updater_target() -> String {
+ let arch = if cfg!(target_arch = "aarch64") {
+ "aarch64"
+ } else {
+ "x86_64"
+ };
+
+ if cfg!(target_os = "macos") {
+ format!("darwin-{arch}")
+ } else if cfg!(target_os = "linux") {
+ format!("linux-{arch}-deb")
+ } else {
+ format!("windows-{arch}")
+ }
+}
+
+fn endpoint(channel: UpdateChannel) -> String {
+ let url = UPDATE_ENDPOINT
+ .replace("{target}", &updater_target())
+ .replace("{current_version}", env!("CARGO_PKG_VERSION"));
+ match channel {
+ UpdateChannel::Stable => url,
+ UpdateChannel::Nightly => format!("{url}?channel=nightly"),
+ }
+}
+
+async fn remote_version(channel: UpdateChannel) -> Result<Option<Version>, String> {
+ let response = reqwest::Client::builder()
+ .timeout(Duration::from_secs(15))
+ .build()
+ .map_err(|error| error.to_string())?
+ .get(endpoint(channel))
+ .send()
+ .await
+ .map_err(|error| error.to_string())?;
+
+ if response.status() == reqwest::StatusCode::NO_CONTENT {
+ return Ok(None);
+ }
+
+ let update = response
+ .error_for_status()
+ .map_err(|error| error.to_string())?
+ .json::<AvailableUpdate>()
+ .await
+ .map_err(|error| error.to_string())?;
+ Version::parse(&update.version)
+ .map(Some)
+ .map_err(|error| error.to_string())
+}
+
+fn qualifies(
+ current: &Version,
+ remote: &Version,
+ configured_channel: UpdateChannel,
+ remote_channel: UpdateChannel,
+) -> bool {
+ remote > current
+ || (configured_channel == UpdateChannel::Stable
+ && remote_channel == UpdateChannel::Stable
+ && !current.pre.is_empty()
+ && remote.pre.is_empty()
+ && remote != current)
+}
+
+async fn available_version(channel: UpdateChannel) -> Result<Option<Version>, String> {
+ let current = Version::parse(env!("CARGO_PKG_VERSION")).map_err(|error| error.to_string())?;
+ let stable = remote_version(UpdateChannel::Stable)
+ .await
+ .map(|candidate| {
+ candidate.filter(|remote| qualifies(&current, remote, channel, UpdateChannel::Stable))
+ });
+
+ if channel == UpdateChannel::Stable {
+ return stable;
+ }
+
+ let nightly = remote_version(UpdateChannel::Nightly)
+ .await
+ .map(|candidate| {
+ candidate.filter(|remote| qualifies(&current, remote, channel, UpdateChannel::Nightly))
+ });
+
+ select_available_version(stable, nightly)
+}
+
+fn select_available_version(
+ stable: Result<Option<Version>, String>,
+ nightly: Result<Option<Version>, String>,
+) -> Result<Option<Version>, String> {
+ match (stable, nightly) {
+ (Ok(Some(stable)), Ok(Some(nightly))) => Ok(Some(stable.max(nightly))),
+ (Ok(stable), Ok(nightly)) => Ok(stable.or(nightly)),
+ (Ok(candidate), Err(error)) | (Err(error), Ok(candidate)) => {
+ tracing::warn!("update check failed for one channel: {error}");
+ Ok(candidate)
+ }
+ (Err(error), Err(_)) => Err(error),
+ }
+}
+
+pub(crate) fn work_in_flight(cx: &mut App) -> bool {
+ RecordingSession::recording_in_flight(cx)
+ || crate::app_windows::export_in_flight(cx)
+ || crate::import::imports_in_flight(cx)
+ || crate::transcription::work_in_flight()
+}
+
+pub(crate) fn check_manually(cx: &mut App) {
+ if !cx.has_global::<UpdateScheduler>() {
+ return;
+ }
+
+ let scheduler = cx.global_mut::<UpdateScheduler>();
+ if !scheduler.pending.request_manual(scheduler.manual_in_flight) {
+ return;
+ }
+
+ let _ = scheduler.wake.try_send(());
+}
+
+pub(crate) fn update_channel_changed(channel: UpdateChannel, cx: &mut App) {
+ if !cx.has_global::<UpdateScheduler>() {
+ return;
+ }
+
+ let scheduler = cx.global_mut::<UpdateScheduler>();
+ scheduler.pending.request_channel(channel);
+ let _ = scheduler.wake.try_send(());
+}
+
+fn first_check_delay(channel: UpdateChannel) -> Duration {
+ match channel {
+ UpdateChannel::Stable => STABLE_FIRST_CHECK_DELAY,
+ UpdateChannel::Nightly => NIGHTLY_FIRST_CHECK_DELAY,
+ }
+}
+
+fn next_check_delay(channel: UpdateChannel) -> Option<Duration> {
+ (channel == UpdateChannel::Nightly).then_some(NIGHTLY_CHECK_INTERVAL)
+}
+
+fn finish_manual_check(cx: &mut App, manual: bool) {
+ if manual {
+ cx.global_mut::<UpdateScheduler>().manual_in_flight = false;
+ }
+}
+
+pub(crate) fn schedule_startup_check(cx: &mut App) {
+ let (wake, requests) = flume::bounded(1);
+ cx.set_global(UpdateScheduler {
+ wake,
+ pending: PendingUpdateRequests::default(),
+ manual_in_flight: false,
+ });
+
+ cx.spawn(async move |cx| {
+ let mut channel = cx
+ .background_executor()
+ .spawn(async { GeneralSettings::load().update_channel })
+ .await;
+ let mut delay = (!cfg!(debug_assertions)).then(|| first_check_delay(channel));
+ let mut ignored_version: Option<Version> = None;
+
+ loop {
+ let signaled = match delay {
+ Some(delay) => {
+ let timer = cx.background_executor().timer(delay);
+ let request = requests.recv_async();
+ futures_util::pin_mut!(timer, request);
+ match select(timer, request).await {
+ Either::Left(_) => false,
+ Either::Right((Ok(()), _)) => true,
+ Either::Right((Err(_), _)) => return,
+ }
+ }
+ None => {
+ if requests.recv_async().await.is_err() {
+ return;
+ }
+ true
+ }
+ };
+
+ let request = cx.update(|cx| {
+ let scheduler = cx.global_mut::<UpdateScheduler>();
+ std::mem::take(&mut scheduler.pending)
+ });
+
+ if signaled && request == PendingUpdateRequests::default() {
+ continue;
+ }
+
+ if let Some(next_channel) = request.channel {
+ channel = next_channel;
+ ignored_version = None;
+ }
+
+ let manual = request.manual;
+ if cfg!(debug_assertions) && !manual {
+ delay = None;
+ continue;
+ }
+
+ if manual {
+ cx.update(|cx| cx.global_mut::<UpdateScheduler>().manual_in_flight = true);
+ }
+
+ delay = next_check_delay(channel);
+
+ if cx.update(work_in_flight) {
+ if manual {
+ crate::platform::activate_app();
+ crate::platform::alert_dialog(
+ "Cap is busy",
+ "Finish your recording, export, upload, import, or transcription task before checking for updates.",
+ );
+ cx.update(|cx| finish_manual_check(cx, true));
+ } else {
+ delay = Some(BUSY_RETRY_DELAY);
+ }
+ continue;
+ }
+
+ let result = match cx
+ .update(|cx| gpui_tokio::Tokio::spawn(cx, available_version(channel)))
+ .await
+ {
+ Ok(result) => result,
+ Err(error) => Err(error.to_string()),
+ };
+
+ let superseded = cx.update(|cx| {
+ let scheduler = cx.global_mut::<UpdateScheduler>();
+ let channel_changed = scheduler.pending.channel.is_some();
+ if channel_changed && manual {
+ scheduler.pending.manual = true;
+ scheduler.manual_in_flight = false;
+ }
+ channel_changed || (!manual && scheduler.pending.manual)
+ });
+ if superseded {
+ continue;
+ }
+
+ let version = match result {
+ Ok(Some(version)) => version,
+ Ok(None) => {
+ if manual {
+ crate::platform::activate_app();
+ crate::platform::alert_dialog(
+ "No Update Available",
+ "You're already using the latest version of Cap.",
+ );
+ cx.update(|cx| finish_manual_check(cx, true));
+ }
+ continue;
+ }
+ Err(error) => {
+ tracing::warn!("update check failed: {error}");
+ if manual {
+ crate::platform::activate_app();
+ crate::platform::alert_dialog(
+ "Update Cap",
+ &format!("Couldn't check for updates: {error}"),
+ );
+ cx.update(|cx| finish_manual_check(cx, true));
+ }
+ continue;
+ }
+ };
+
+ if !manual && ignored_version.as_ref() == Some(&version) {
+ continue;
+ }
+
+ if cx.update(work_in_flight) {
+ if manual {
+ crate::platform::activate_app();
+ crate::platform::alert_dialog(
+ "Cap is busy",
+ "Finish your recording, export, upload, import, or transcription task before checking for updates.",
+ );
+ cx.update(|cx| finish_manual_check(cx, true));
+ } else {
+ delay = Some(BUSY_RETRY_DELAY);
+ }
+ continue;
+ }
+
+ crate::platform::activate_app();
+ if crate::platform::confirm_dialog(
+ "Update Cap",
+ &format!("Version {version} of Cap is available. Would you like to install it?"),
+ "Update",
+ "Ignore",
+ false,
+ ) {
+ cx.update(|cx| {
+ finish_manual_check(cx, manual);
+ crate::settings_pages::start_update_handoff(cx);
+ });
+ } else {
+ ignored_version = Some(version);
+ cx.update(|cx| finish_manual_check(cx, manual));
+ }
+ }
+ })
+ .detach();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn version(value: &str) -> Version {
+ Version::parse(value).unwrap()
+ }
+
+ #[test]
+ fn stable_channel_accepts_newer_versions_and_explicit_prerelease_downgrades() {
+ assert!(qualifies(
+ &version("0.6.0"),
+ &version("0.6.1"),
+ UpdateChannel::Stable,
+ UpdateChannel::Stable,
+ ));
+ assert!(qualifies(
+ &version("0.6.1-nightly.4"),
+ &version("0.6.0"),
+ UpdateChannel::Stable,
+ UpdateChannel::Stable,
+ ));
+ assert!(!qualifies(
+ &version("0.6.1"),
+ &version("0.6.0"),
+ UpdateChannel::Stable,
+ UpdateChannel::Stable,
+ ));
+ }
+
+ #[test]
+ fn nightly_channel_never_uses_the_stable_downgrade_rule() {
+ assert!(!qualifies(
+ &version("0.6.1-nightly.4"),
+ &version("0.6.0"),
+ UpdateChannel::Nightly,
+ UpdateChannel::Stable,
+ ));
+ assert!(qualifies(
+ &version("0.6.1-nightly.4"),
+ &version("0.6.1-nightly.5"),
+ UpdateChannel::Nightly,
+ UpdateChannel::Nightly,
+ ));
+ }
+
+ #[test]
+ fn nightly_channel_survives_individual_endpoint_failures() {
+ assert_eq!(
+ select_available_version(Err("stable unavailable".into()), Ok(Some(version("0.6.1"))))
+ .unwrap(),
+ Some(version("0.6.1")),
+ );
+ assert_eq!(
+ select_available_version(
+ Ok(Some(version("0.6.2"))),
+ Err("nightly unavailable".into())
+ )
+ .unwrap(),
+ Some(version("0.6.2")),
+ );
+ assert_eq!(
+ select_available_version(
+ Err("stable unavailable".into()),
+ Err("nightly unavailable".into()),
+ ),
+ Err("stable unavailable".into()),
+ );
+ }
+
+ #[test]
+ fn nightly_channel_prefers_the_newest_successful_version() {
+ assert_eq!(
+ select_available_version(
+ Ok(Some(version("0.6.1"))),
+ Ok(Some(version("0.6.2-nightly.4"))),
+ )
+ .unwrap(),
+ Some(version("0.6.2-nightly.4")),
+ );
+ }
+
+ #[test]
+ fn check_cadence_preserves_each_update_channel_contract() {
+ assert_eq!(
+ first_check_delay(UpdateChannel::Stable),
+ Duration::from_secs(10)
+ );
+ assert_eq!(
+ first_check_delay(UpdateChannel::Nightly),
+ Duration::from_secs(60)
+ );
+ assert_eq!(next_check_delay(UpdateChannel::Stable), None);
+ assert_eq!(
+ next_check_delay(UpdateChannel::Nightly),
+ Some(Duration::from_secs(2 * 60 * 60))
+ );
+ }
+
+ #[test]
+ fn manual_checks_coalesce_while_pending_or_running() {
+ let mut requests = PendingUpdateRequests::default();
+
+ assert!(requests.request_manual(false));
+ assert!(!requests.request_manual(false));
+
+ requests.manual = false;
+ assert!(!requests.request_manual(true));
+ assert!(requests.request_manual(false));
+ }
+
+ #[test]
+ fn channel_changes_coalesce_without_losing_manual_checks() {
+ let mut requests = PendingUpdateRequests::default();
+
+ assert!(requests.request_manual(false));
+ requests.request_channel(UpdateChannel::Nightly);
+ requests.request_channel(UpdateChannel::Stable);
+
+ assert_eq!(
+ requests,
+ PendingUpdateRequests {
+ manual: true,
+ channel: Some(UpdateChannel::Stable),
+ }
+ );
+ }
+
+ #[test]
+ fn recording_exports_and_uploads_remain_update_blockers_until_finished() {
+ use crate::editor_export::ExportPhase;
+
+ for phase in [
+ ExportPhase::Starting,
+ ExportPhase::Rendering,
+ ExportPhase::Copying,
+ ExportPhase::Uploading,
+ ] {
+ assert!(phase.is_busy());
+ }
+
+ for phase in [ExportPhase::Idle, ExportPhase::Done, ExportPhase::Failed] {
+ assert!(!phase.is_busy());
+ }
+ }
+}