Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(desktop-gpui): ship GPUI as Cap with a native signed updater
Cursor Agent13dfd8876a14
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lockindex 635d63bb1..f4a70965f 100644--- a/apps/desktop-gpui/Cargo.lock+++ b/apps/desktop-gpui/Cargo.lock@@ -1563,6 +1563,7 @@ dependencies = ["kameo","libc","md-5",+ "minisign-verify","objc2 0.5.2","objc2-app-kit 0.2.2","objc2-foundation 0.2.2",@@ -6414,6 +6415,12 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"+[[package]]+name = "minisign-verify"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22f9645cb765ea72b8111f36c522475d2daa0d22c957a9826437e97534bc4e9e"+[[package]]name = "miniz_oxide"version = "0.8.9"diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.tomlindex de7f91841..a12310782 100644--- a/apps/desktop-gpui/Cargo.toml+++ b/apps/desktop-gpui/Cargo.toml@@ -10,6 +10,7 @@ members = ["."][package]name = "cap-desktop-gpui"version = "0.6.1"+description = "Beautiful screen recordings, owned by you."edition = "2024"license = "AGPL-3.0"publish = false@@ -22,15 +23,6 @@ path = "src/main.rs"name = "studio-finalization-benchmark"path = "../../crates/recording/examples/studio-finalization-benchmark.rs"-[package.metadata.bundle]-name = "Cap GPUI"-identifier = "so.cap.desktop.gpui"-icon = ["assets/dock-icon.png"]-category = "public.app-category.productivity"-osx_minimum_system_version = "12.3"-osx_info_plist_exts = ["resources/Info.plist"]-osx_url_schemes = ["cap-desktop"]-[dependencies]cap-audio = { path = "../../crates/audio" }# gpui — the wingleeio/zed fork Comet ships. The pinned rev carries f596cde@@ -132,6 +124,7 @@ serde = { version = "1", features = ["derive"] }sanitize-filename = "0.6.0"semver = "1"base64 = "0.22"+minisign-verify = "0.2.4"rfd = { version = "0.15", default-features = false, features = ["xdg-portal", "tokio"] }# The screenshot export compositor (`src/screenshot_export.rs`): the canvas-2d# work `renderScreenshotExportCanvas` does in the webview -- shape rasterizing,@@ -187,6 +180,7 @@ tray-icon = { version = "0.21.1", default-features = false }windows-sys = { version = "0.59", features = ["Win32_Foundation","Win32_Security",+ "Win32_System_Registry","Win32_System_SystemInformation","Win32_System_Threading","Win32_UI_Shell",@@ -275,5 +269,6 @@ opt-level = 2opt-level = 2[profile.release]+codegen-units = 1lto = "thin"strip = "symbols"diff --git a/apps/desktop-gpui/Info.plist b/apps/desktop-gpui/Info.plistnew file mode 100644index 000000000..dd740dcf9--- /dev/null+++ b/apps/desktop-gpui/Info.plist@@ -0,0 +1,33 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDocumentTypes</key>+ <array>+ <dict>+ <key>CFBundleTypeExtensions</key>+ <array>+ <string>cap</string>+ </array>+ <key>CFBundleTypeIconFile</key>+ <string>icon.icns</string>+ <key>CFBundleTypeName</key>+ <string>Cap Recording</string>+ <key>CFBundleTypeRole</key>+ <string>Editor</string>+ <key>LSHandlerRank</key>+ <string>Default</string>+ <key>LSTypeIsPackage</key>+ <true/>+ </dict>+ </array>+ <key>NSCameraUsageDescription</key>+ <string>Cap uses your camera to record you in your Caps</string>+ <key>NSMicrophoneUsageDescription</key>+ <string>Cap uses your microphone to record you in your Caps</string>+ <key>NSScreenCaptureUsageDescription</key>+ <string>Cap captures your screen as part of recording your Caps</string>+ <key>NSCameraUseContinuityCameraDeviceType</key>+ <true/>+</dict>+</plist>diff --git a/apps/desktop-gpui/README.md b/apps/desktop-gpui/README.mdindex 00cbc2a14..7cfd99563 100644--- a/apps/desktop-gpui/README.md+++ b/apps/desktop-gpui/README.md@@ -3,6 +3,10 @@Cap's desktop app, rewritten in [gpui](https://www.gpui.rs/). No Tauri, nowebview — the whole UI is drawn by gpui and every pixel is Rust.+This is the app that ships as **Cap**. The Tauri app in `apps/desktop` ships+separately as **Cap Classic**; see [Shipping, updates and Cap+Classic](#shipping-updates-and-cap-classic).+The main recording window uses a fixed 330×432 layout with device controlsand recording and screenshot browsers. The expanded view is no longer available.@@ -68,6 +72,72 @@ and CI completely untouched.gpui's dependencies need 1.89+ (`smol_str` 0.3.6, `cosmic-text` 0.19). Thenearest toolchain file wins, so the Tauri app is unaffected.+## Shipping, updates and Cap Classic++### How Cap is packaged++`tauri.conf.json` in this directory is a **packaging** config only — nothing+here links the Tauri runtime. `scripts/bundle-gpui.mjs` builds `cap-gpui`+(`scripts/build-gpui-binary.sh release <target>`), stages it as the main+binary `Cap`/`Cap.exe`, and runs `tauri bundle` against this crate+(`TAURI_APP_PATH`). Reusing the bundler keeps every artifact byte-compatible+with what installed copies of the Tauri app already update through:++- the same identity (`Cap`, `so.cap.desktop`, main binary `Cap`), so the macOS+ bundle, the NSIS uninstall key and install folder, and the `cap` deb package+ are the ones already on disk, and permissions and data carry over;+- the same updater artifacts — `Cap.app.tar.gz`, the NSIS `-setup.exe`, the+ deb and the AppImage — signed with the same updater key and published under+ the platform names (`darwin-aarch64`, `windows-x86_64`, `linux-x86_64-deb`,+ …) every existing install already polls.++The first update after the split is therefore installed by the Tauri updater+of whatever build the user has; it simply lands this app in place.++The bundle carries `cap-muxer` and `cap-cli` only: `cap-exporter` was a+byte-identical copy of `cap-cli`, and the self-test now runs `cap-cli`+directly. The NSIS install hook (`packaging/windows/installer-hooks.nsh`)+deletes the Tauri-era `cap-gpui.exe`, `cap-exporter.exe` and Rive assets an+update in place would otherwise leave behind.++### The native updater++`src/updates.rs` checks the CrabNebula endpoint on the same cadence the+Tauri app used, and `src/installer.rs` does the rest without Tauri:++1. **Download** streams the artifact to+ `<cache>/so.cap.desktop/updates/cap/<version>/` and verifies its minisign+ signature *while* it downloads (`minisign_verify::StreamVerifier`), so a+ 200 MB update never sits in memory. A verified file is reused on the next+ attempt instead of being fetched again; anything that fails verification is+ deleted.+2. **Install** checks the file's format, then: on macOS unpacks the+ `.app.tar.gz` beside the running bundle and swaps it in with two renames+ (asking for an administrator password only when the folder is not+ writable); on Windows starts the NSIS installer with `/P /R /UPDATE` and+ quits; on Linux installs the deb through `pkexec dpkg -i` or replaces the+ AppImage in place.+3. **Relaunch** waits for this process to exit and reopens the new build.++Progress shows in the settings sidebar footer, and the update never installs+while a recording, export, upload, import or transcription is running.++### Cap Classic++The Tauri app is built from the same commit and published in the same+release as **Cap Classic** (`Cap Classic.app`, `Cap Classic.exe`, and on+Linux a self-contained AppImage), under the same platform names with a+`-classic` suffix. Cap Classic's updater only ever asks for `-classic`+platforms, and this app only ever asks for unsuffixed ones, so neither can+update into the other.++Settings → Experimental → **Switch to Cap Classic** finds an installed copy+or downloads and installs the latest one (verified the same way as an+update), opens it, and quits once Cap Classic's window is visible+(`cap-classic.pending`). Both apps keep the `so.cap.desktop` identity and data+directory, so recordings, settings, sign-in and permissions are shared, and+Cap Classic's own Experimental page switches back.+## What is implementedEverything below is real, not mocked.@@ -898,9 +968,9 @@ is read off the `Report` line instead.Sidecar resolution (`resolve_selftest_binary`), in order, with`CAP_GPUI_SELFTEST_BIN` winning over all of it:-1. Next to the running executable — `cap-exporter`, `cap-exporter-<triple>`,- then `cap`. This is where the sidecar sits for an app-staged build and- where a dev `cargo build` leaves the CLI.+1. Next to the running executable — `cap-cli`, `cap-cli-<triple>`, then+ `cap`. This is where the sidecar sits in a packaged build and where a dev+ `cargo build` leaves the CLI.2. `../Resources` and `../MacOS` relative to it, the two places Tauri puts an`externalBin` inside a bundle.3. `/Applications/Cap.app/Contents/{Resources,MacOS}`. The gpui dev binary is@@ -963,7 +1033,7 @@ Settings-specific deviations:| **Settings does not park the other windows** | `ShowCapWindow::Settings::show` also calls `hide_recording_windows` and `release_camera_preview_if_idle`, and its close calls `restore_camera_window`. Neither half is reproduced — the gear hides the main window and nothing else. || **Several settings persist without a consumer** | `hideDockIcon`, `enableNotifications`, the countdown, the post-recording behaviours and the update channel write the same store keys as Tauri; the machinery that would obey them is not built yet. Theme is applied. || **No confirm on the recordings folder move** | `pickRecordingsFolder` offers to migrate existing recordings afterwards; here the path is written and nothing is moved. |-| **Version is this crate's** | The sidebar footer shows the crate version from `CARGO_PKG_VERSION` (kept in lockstep with the Tauri app, 0.6.0), not `getVersion()`; "Check for updates" is drawn in its disabled state because there is no updater. |+| **Version is this crate's** | The sidebar footer shows the crate version from `CARGO_PKG_VERSION` (kept in lockstep with the Tauri app by `scripts/sync-desktop-versions.mjs`), not `getVersion()`. "Check for updates" runs the native updater and shows its download progress in place. |## Mode selectdiff --git a/apps/desktop-gpui/build.rs b/apps/desktop-gpui/build.rsindex ab7033cbe..b4885b3e5 100644--- a/apps/desktop-gpui/build.rs+++ b/apps/desktop-gpui/build.rs@@ -18,7 +18,7 @@ fn main() {.set_icon_with_id(icon, "1").set("ProductName", "Cap").set("FileDescription", "Cap")- .set("OriginalFilename", "cap-gpui.exe")+ .set("OriginalFilename", "Cap.exe").compile().expect("failed to compile the Cap Windows icon resource");}diff --git a/apps/desktop-gpui/packaging/windows/installer-hooks.nsh b/apps/desktop-gpui/packaging/windows/installer-hooks.nshnew file mode 100644index 000000000..42749c420--- /dev/null+++ b/apps/desktop-gpui/packaging/windows/installer-hooks.nsh@@ -0,0 +1,5 @@+!macro NSIS_HOOK_POSTINSTALL+ Delete "$INSTDIR\cap-gpui.exe"+ Delete "$INSTDIR\cap-exporter.exe"+ RMDir /r "$INSTDIR\assets\rive"+!macroenddiff --git a/apps/desktop-gpui/resources/Info.plist b/apps/desktop-gpui/resources/Info.plistdeleted file mode 100644index b9ee3ed15..000000000--- a/apps/desktop-gpui/resources/Info.plist+++ /dev/null@@ -1,68 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>CFBundleDevelopmentRegion</key>- <string>en</string>- <key>CFBundleDisplayName</key>- <string>Cap GPUI</string>- <key>CFBundleDocumentTypes</key>- <array>- <dict>- <key>CFBundleTypeExtensions</key>- <array>- <string>cap</string>- </array>- <key>CFBundleTypeName</key>- <string>Cap Project</string>- <key>CFBundleTypeRole</key>- <string>Editor</string>- <key>LSHandlerRank</key>- <string>Default</string>- <key>LSTypeIsPackage</key>- <true/>- </dict>- </array>- <key>CFBundleExecutable</key>- <string>cap-gpui</string>- <key>CFBundleIconFile</key>- <string>icon.icns</string>- <key>CFBundleIdentifier</key>- <string>so.cap.desktop.gpui</string>- <key>CFBundleInfoDictionaryVersion</key>- <string>6.0</string>- <key>CFBundleName</key>- <string>Cap GPUI</string>- <key>CFBundlePackageType</key>- <string>APPL</string>- <key>CFBundleShortVersionString</key>- <string>0.1.0</string>- <key>CFBundleVersion</key>- <string>1</string>- <key>CFBundleURLTypes</key>- <array>- <dict>- <key>CFBundleURLName</key>- <string>so.cap.desktop.gpui</string>- <key>CFBundleURLSchemes</key>- <array>- <string>cap-desktop</string>- </array>- </dict>- </array>- <key>LSApplicationCategoryType</key>- <string>public.app-category.productivity</string>- <key>LSMinimumSystemVersion</key>- <string>12.3</string>- <key>NSHighResolutionCapable</key>- <true/>- <key>NSCameraUsageDescription</key>- <string>Cap uses your camera to record you in your Caps</string>- <key>NSMicrophoneUsageDescription</key>- <string>Cap uses your microphone to record you in your Caps</string>- <key>NSScreenCaptureUsageDescription</key>- <string>Cap captures your screen as part of recording your Caps</string>- <key>NSCameraUseContinuityCameraDeviceType</key>- <true/>-</dict>-</plist>diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rsindex 539e0dbff..d1622bdb4 100644--- a/apps/desktop-gpui/src/app_windows.rs+++ b/apps/desktop-gpui/src/app_windows.rs@@ -1102,6 +1102,15 @@ pub fn open_quality_settings(mode: Mode, cx: &mut App) {}}+pub(crate) fn refresh_settings(cx: &mut App) {+ if !cx.has_global::<AppWindows>() {+ return;+ }+ if let Some(handle) = cx.global::<AppWindows>().settings {+ handle.update(cx, |_, _, cx| cx.notify()).ok();+ }+}+/// Open the settings window on a page, and hide the main window.////// The header gear in `new-main/index.tsx` isdiff --git a/apps/desktop-gpui/src/classic.rs b/apps/desktop-gpui/src/classic.rsnew file mode 100644index 000000000..9aa252577--- /dev/null+++ b/apps/desktop-gpui/src/classic.rs@@ -0,0 +1,268 @@+use std::path::{Path, PathBuf};++use semver::Version;++use crate::{+ installer::{self, ArtifactKind, Product},+ store::UpdateChannel,+};++pub(crate) const DOWNLOAD_PAGE: &str = "https://cap.so/download?version=classic";++#[cfg(target_os = "macos")]+const BUNDLE_NAME: &str = "Cap Classic.app";+#[cfg(windows)]+const EXECUTABLE_NAME: &str = "Cap Classic.exe";+#[cfg(target_os = "linux")]+const APPIMAGE_NAME: &str = "Cap-Classic.AppImage";++#[cfg(target_os = "macos")]+fn candidates(executable: Option<&Path>, home: Option<&Path>) -> Vec<PathBuf> {+ let mut candidates = Vec::new();+ if let Some(parent) = executable+ .and_then(|executable| {+ executable+ .ancestors()+ .find(|path| path.extension().is_some_and(|extension| extension == "app"))+ })+ .and_then(Path::parent)+ {+ candidates.push(parent.join(BUNDLE_NAME));+ }+ candidates.push(Path::new("/Applications").join(BUNDLE_NAME));+ if let Some(home) = home {+ candidates.push(home.join("Applications").join(BUNDLE_NAME));+ }+ candidates.dedup();+ candidates+}++#[cfg(target_os = "macos")]+fn is_installed(candidate: &Path) -> bool {+ candidate.join("Contents/MacOS/Cap Classic").is_file()+}++#[cfg(target_os = "macos")]+pub(crate) fn installed() -> Option<PathBuf> {+ let executable = std::env::current_exe().ok();+ candidates(executable.as_deref(), dirs::home_dir().as_deref())+ .into_iter()+ .find(|candidate| is_installed(candidate))+}++#[cfg(windows)]+fn registry_install_dir(root: windows_sys::Win32::System::Registry::HKEY) -> Option<PathBuf> {+ use std::os::windows::ffi::OsStringExt as _;+ use windows_sys::{+ Win32::{+ Foundation::ERROR_SUCCESS,+ System::Registry::{RRF_RT_REG_SZ, RegGetValueW},+ },+ w,+ };++ let mut buffer = vec![0_u16; 1024];+ let mut size = (buffer.len() * std::mem::size_of::<u16>()) as u32;+ let status = unsafe {+ RegGetValueW(+ root,+ w!("Software\\cap\\Cap Classic"),+ std::ptr::null(),+ RRF_RT_REG_SZ,+ std::ptr::null_mut(),+ buffer.as_mut_ptr().cast(),+ &mut size,+ )+ };+ if status != ERROR_SUCCESS {+ return None;+ }+ let length = (size as usize / std::mem::size_of::<u16>()).min(buffer.len());+ let value = std::ffi::OsString::from_wide(&buffer[..length]);+ let value = value.to_string_lossy();+ let value = value.trim_end_matches('\0').trim().trim_matches('"');+ (!value.is_empty()).then(|| PathBuf::from(value))+}++#[cfg(windows)]+pub(crate) fn installed() -> Option<PathBuf> {+ use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};++ [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE]+ .into_iter()+ .filter_map(registry_install_dir)+ .chain(+ std::env::var_os("LOCALAPPDATA")+ .map(PathBuf::from)+ .map(|directory| directory.join("Cap Classic")),+ )+ .map(|directory| directory.join(EXECUTABLE_NAME))+ .find(|candidate| candidate.is_file())+}++#[cfg(target_os = "linux")]+fn install_destination() -> Option<PathBuf> {+ dirs::home_dir().map(|home| home.join("Applications").join(APPIMAGE_NAME))+}++#[cfg(target_os = "linux")]+pub(crate) fn installed() -> Option<PathBuf> {+ install_destination().filter(|candidate| candidate.is_file())+}++#[cfg(target_os = "macos")]+fn install_destination() -> Option<PathBuf> {+ let system = Path::new("/Applications");+ if writable(system) {+ return Some(system.join(BUNDLE_NAME));+ }+ dirs::home_dir().map(|home| home.join("Applications").join(BUNDLE_NAME))+}++#[cfg(target_os = "macos")]+fn writable(directory: &Path) -> bool {+ use std::os::unix::ffi::OsStrExt as _;++ let Ok(path) = std::ffi::CString::new(directory.as_os_str().as_bytes()) else {+ return false;+ };+ unsafe { libc::access(path.as_ptr(), libc::W_OK) == 0 }+}++pub(crate) async fn download_and_install(+ progress: impl FnMut(u64, Option<u64>) + Send,+) -> Result<Option<PathBuf>, String> {+ let platform = Product::Classic.update_platform()?;+ let kind = ArtifactKind::for_platform(&platform)?;+ let release = installer::fetch_release(+ Product::Classic,+ UpdateChannel::Stable,+ &Version::new(0, 0, 0),+ )+ .await?+ .ok_or_else(|| "Cap Classic isn't available to download for this computer yet.".to_string())?;+ let package = installer::download(Product::Classic, kind, &release, progress).await?;+ tokio::task::spawn_blocking(move || install(&package, kind))+ .await+ .map_err(|error| error.to_string())?+}++fn install(package: &Path, kind: ArtifactKind) -> Result<Option<PathBuf>, String> {+ installer::check_artifact_kind(package, kind)?;+ install_package(package)+}++#[cfg(target_os = "macos")]+fn install_package(package: &Path) -> Result<Option<PathBuf>, String> {+ let destination = install_destination()+ .ok_or_else(|| "Couldn't find an Applications folder to install into".to_string())?;+ installer::install_app_bundle(package, &destination)?;+ Ok(Some(destination))+}++#[cfg(windows)]+fn install_package(package: &Path) -> Result<Option<PathBuf>, String> {+ installer::launch_installer(package, &["/P", "/R"])?;+ Ok(None)+}++#[cfg(target_os = "linux")]+fn install_package(package: &Path) -> Result<Option<PathBuf>, String> {+ let destination =+ install_destination().ok_or_else(|| "Couldn't find your home folder".to_string())?;+ installer::install_appimage(package, &destination)?;+ Ok(Some(destination))+}++pub(crate) fn launch(path: &Path) -> std::io::Result<()> {+ let mut command = launch_command(path);+ #[cfg(target_os = "macos")]+ {+ let output = command.output()?;+ if output.status.success() {+ Ok(())+ } else {+ Err(std::io::Error::other(format!(+ "Cap Classic didn't open ({}): {}",+ output.status,+ String::from_utf8_lossy(&output.stderr).trim()+ )))+ }+ }+ #[cfg(not(target_os = "macos"))]+ {+ use std::process::Stdio;++ command+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt as _;+ command.process_group(0);+ }+ let mut child = command.spawn()?;+ std::thread::spawn(move || {+ let _ = child.wait();+ });+ Ok(())+ }+}++fn launch_command(path: &Path) -> std::process::Command {+ #[cfg(target_os = "macos")]+ {+ let mut command = std::process::Command::new("/usr/bin/open");+ command.arg("-n").arg(path);+ command+ }+ #[cfg(not(target_os = "macos"))]+ {+ std::process::Command::new(path)+ }+}++#[cfg(test)]+mod tests {+ #[cfg(target_os = "macos")]+ #[test]+ fn classic_is_found_beside_this_app_and_in_both_application_folders() {+ use std::path::{Path, PathBuf};++ assert_eq!(+ super::candidates(+ Some(Path::new("/Volumes/Work/Apps/Cap.app/Contents/MacOS/Cap")),+ Some(Path::new("/Users/x")),+ ),+ vec![+ PathBuf::from("/Volumes/Work/Apps/Cap Classic.app"),+ PathBuf::from("/Applications/Cap Classic.app"),+ PathBuf::from("/Users/x/Applications/Cap Classic.app"),+ ]+ );+ assert_eq!(+ super::candidates(+ Some(Path::new("/Applications/Cap.app/Contents/MacOS/Cap")),+ None+ ),+ vec![PathBuf::from("/Applications/Cap Classic.app")]+ );+ }++ #[test]+ fn launching_passes_the_install_path_as_a_literal_argument() {+ let path = std::path::Path::new("/tmp/Cap ' \" $ Classic");+ let command = super::launch_command(path);+ if cfg!(target_os = "macos") {+ assert_eq!(command.get_program(), "/usr/bin/open");+ assert_eq!(+ command.get_args().collect::<Vec<_>>(),+ [std::ffi::OsStr::new("-n"), path.as_os_str()]+ );+ } else {+ assert_eq!(command.get_program(), path.as_os_str());+ assert_eq!(command.get_args().count(), 0);+ }+ }+}diff --git a/apps/desktop-gpui/src/diagnostics.rs b/apps/desktop-gpui/src/diagnostics.rsindex 9636fdfcb..3e8eb5f77 100644--- a/apps/desktop-gpui/src/diagnostics.rs+++ b/apps/desktop-gpui/src/diagnostics.rs@@ -3,7 +3,7 @@//! Two halves, and they run very differently.//!//! The A/V sync self-test runs as a **subprocess** -- the `cap` CLI, shipped-//! inside `Cap.app` as the `cap-exporter` sidecar. It cannot run in-process:+//! inside `Cap.app` as the `cap-cli` sidecar. It cannot run in-process://! `cap selftest av-sync` builds its own winit `EventLoop` for the flashing//! test pattern and needs the process main thread, which gpui owns for the//! whole life of the app. So this module resolves the binary, drives its@@ -101,9 +101,9 @@ pub fn log_tail() -> cap_utils::log_upload::LogBundle {fn selftest_bin_name() -> &'static str {if cfg!(windows) {- "cap-exporter.exe"+ "cap-cli.exe"} else {- "cap-exporter"+ "cap-cli"}}@@ -158,10 +158,7 @@ fn selftest_binary_candidates(let mut push_dir = |dir: &Path| {candidates.push(dir.join(selftest_bin_name()));if let Some(triple) = triple {- candidates.push(dir.join(format!(- "cap-exporter-{triple}{}",- std::env::consts::EXE_SUFFIX- )));+ candidates.push(dir.join(format!("cap-cli-{triple}{}", std::env::consts::EXE_SUFFIX)));}candidates.push(dir.join(cap_bin_name()));};@@ -1088,7 +1085,7 @@ mod tests {}/// The order the run has to follow: the binary shipped next to this build,- /// then the installed app, then the dev checkout. `cap-exporter` beats a+ /// then the installed app, then the dev checkout. `cap-cli` beats a/// bare `cap` inside the same directory.#[test]fn the_sidecar_probe_walks_from_this_build_outwards() {diff --git a/apps/desktop-gpui/src/installer.rs b/apps/desktop-gpui/src/installer.rsnew file mode 100644index 000000000..b5b2af5c8--- /dev/null+++ b/apps/desktop-gpui/src/installer.rs@@ -0,0 +1,929 @@+use std::{+ io::{Read as _, Write as _},+ path::{Path, PathBuf},+ time::Duration,+};++use base64::Engine as _;+use futures_util::StreamExt as _;+use minisign_verify::{PublicKey, Signature, StreamVerifier};+use semver::Version;+use serde::Deserialize;++use crate::store::UpdateChannel;++const UPDATE_ENDPOINT: &str = "https://cdn.crabnebula.app/update/cap/cap";+const UPDATER_PUBLIC_KEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEUyOTAzOTdFNzJFQkRFOTMKUldTVDN1dHlmam1RNHFXb1VYTXlrQk1iMFFkcjN0YitqZlA5WnZNY0ZtQ1dvM1dxK211M3VIYUQK";+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);+const METADATA_TIMEOUT: Duration = Duration::from_secs(20);+const CHUNK_TIMEOUT: Duration = Duration::from_secs(60);++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum Product {+ Cap,+ Classic,+}++impl Product {+ fn slug(self) -> &'static str {+ match self {+ Self::Cap => "cap",+ Self::Classic => "cap-classic",+ }+ }++ pub(crate) fn update_platform(self) -> Result<String, String> {+ let arch = if cfg!(target_arch = "aarch64") {+ "aarch64"+ } else {+ "x86_64"+ };+ match self {+ Self::Cap => cap_update_platform(arch),+ Self::Classic => Ok(classic_update_platform(arch)),+ }+ }+}++#[cfg(target_os = "linux")]+fn cap_update_platform(arch: &str) -> Result<String, String> {+ cap_utils::linux_package::updater_target(arch)+}++#[cfg(not(target_os = "linux"))]+fn cap_update_platform(arch: &str) -> Result<String, String> {+ let os = if cfg!(target_os = "macos") {+ "darwin"+ } else {+ "windows"+ };+ Ok(format!("{os}-{arch}"))+}++fn classic_update_platform(arch: &str) -> String {+ if cfg!(target_os = "macos") {+ format!("darwin-{arch}-classic")+ } else if cfg!(target_os = "windows") {+ format!("windows-{arch}-classic")+ } else {+ format!("linux-{arch}-appimage-classic")+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum ArtifactKind {+ AppArchive,+ NsisInstaller,+ Deb,+ AppImage,+}++impl ArtifactKind {+ pub(crate) fn for_platform(platform: &str) -> Result<Self, String> {+ if platform.starts_with("darwin-") {+ Ok(Self::AppArchive)+ } else if platform.starts_with("windows-") {+ Ok(Self::NsisInstaller)+ } else if platform.starts_with("linux-") && platform.contains("-deb") {+ Ok(Self::Deb)+ } else if platform.starts_with("linux-") && platform.contains("-appimage") {+ Ok(Self::AppImage)+ } else {+ Err(format!("Unsupported update platform: {platform}"))+ }+ }++ fn file_name(self, product: Product) -> &'static str {+ match (product, self) {+ (Product::Cap, Self::AppArchive) => "Cap.app.tar.gz",+ (Product::Classic, Self::AppArchive) => "Cap Classic.app.tar.gz",+ (Product::Cap, Self::NsisInstaller) => "Cap-setup.exe",+ (Product::Classic, Self::NsisInstaller) => "Cap Classic-setup.exe",+ (Product::Cap, Self::Deb) => "Cap.deb",+ (Product::Classic, Self::Deb) => "Cap Classic.deb",+ (Product::Cap, Self::AppImage) => "Cap.AppImage",+ (Product::Classic, Self::AppImage) => "Cap-Classic.AppImage",+ }+ }++ fn matches(self, header: &[u8]) -> bool {+ match self {+ Self::AppArchive => header.starts_with(&[0x1f, 0x8b]),+ Self::NsisInstaller => header.starts_with(b"MZ"),+ Self::Deb => header.starts_with(b"!<arch>\n"),+ Self::AppImage => header.starts_with(b"\x7fELF"),+ }+ }+}++#[derive(Deserialize)]+struct RemoteRelease {+ version: String,+ url: String,+ signature: String,+ #[serde(default)]+ notes: Option<String>,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct Release {+ pub(crate) version: Version,+ pub(crate) url: String,+ pub(crate) signature: String,+ pub(crate) notes: Option<String>,+}++fn parse_release(body: &[u8]) -> Result<Release, String> {+ let remote: RemoteRelease = serde_json::from_slice(body)+ .map_err(|error| format!("Invalid update response: {error}"))?;+ let version = Version::parse(remote.version.trim().trim_start_matches('v'))+ .map_err(|error| format!("Invalid update version {:?}: {error}", remote.version))?;+ let url = reqwest::Url::parse(remote.url.trim())+ .map_err(|error| format!("Invalid update download URL: {error}"))?;+ if url.scheme() != "https" {+ return Err("Update downloads must use HTTPS".to_string());+ }+ if remote.signature.trim().is_empty() {+ return Err("The update has no signature".to_string());+ }+ Ok(Release {+ version,+ url: url.into(),+ signature: remote.signature.trim().to_string(),+ notes: remote.notes.filter(|notes| !notes.trim().is_empty()),+ })+}++fn endpoint(platform: &str, channel: UpdateChannel, current: &Version) -> String {+ let url = format!("{UPDATE_ENDPOINT}/{platform}/{current}");+ match channel {+ UpdateChannel::Stable => url,+ UpdateChannel::Nightly => format!("{url}?channel=nightly"),+ }+}++fn client() -> Result<reqwest::Client, String> {+ reqwest::Client::builder()+ .user_agent(concat!("Cap/", env!("CARGO_PKG_VERSION")))+ .connect_timeout(CONNECT_TIMEOUT)+ .build()+ .map_err(|error| error.to_string())+}++pub(crate) async fn fetch_release(+ product: Product,+ channel: UpdateChannel,+ current: &Version,+) -> Result<Option<Release>, String> {+ let platform = product.update_platform()?;+ let response = client()?+ .get(endpoint(&platform, channel, current))+ .timeout(METADATA_TIMEOUT)+ .send()+ .await+ .map_err(|error| error.to_string())?;++ match response.status() {+ reqwest::StatusCode::NO_CONTENT => return Ok(None),+ status if product == Product::Classic && status.is_client_error() => return Ok(None),+ _ => {}+ }++ let body = response+ .error_for_status()+ .map_err(|error| error.to_string())?+ .bytes()+ .await+ .map_err(|error| error.to_string())?;+ parse_release(&body).map(Some)+}++fn decode_base64_text(value: &str, what: &str) -> Result<String, String> {+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(value.trim())+ .map_err(|error| format!("Invalid {what} encoding: {error}"))?;+ String::from_utf8(bytes).map_err(|_| format!("Invalid {what} text"))+}++fn trusted_key(encoded: &str) -> Result<PublicKey, String> {+ PublicKey::decode(&decode_base64_text(encoded, "update key")?)+ .map_err(|error| format!("Invalid update key: {error}"))+}++fn decode_signature(encoded: &str) -> Result<Signature, String> {+ Signature::decode(&decode_base64_text(encoded, "update signature")?)+ .map_err(|error| format!("Invalid update signature: {error}"))+}++enum Verifier<'a> {+ Stream(StreamVerifier<'a>),+ Buffered,+}++impl<'a> Verifier<'a> {+ fn new(key: &'a PublicKey, signature: &'a Signature) -> Result<Self, String> {+ match key.verify_stream(signature) {+ Ok(verifier) => Ok(Self::Stream(verifier)),+ Err(minisign_verify::Error::UnsupportedLegacyMode) => Ok(Self::Buffered),+ Err(error) => Err(format!("The update was not signed by Cap: {error}")),+ }+ }++ fn update(&mut self, chunk: &[u8]) {+ if let Self::Stream(verifier) = self {+ verifier.update(chunk);+ }+ }++ fn finish(self, key: &PublicKey, signature: &Signature, file: &Path) -> Result<(), String> {+ let verified = match self {+ Self::Stream(mut verifier) => verifier.finalize(),+ Self::Buffered => {+ let bytes = std::fs::read(file).map_err(|error| error.to_string())?;+ key.verify(&bytes, signature, true)+ }+ };+ verified.map_err(|error| format!("The download failed signature verification: {error}"))+ }+}++fn verify_file(file: &Path, key: &PublicKey, signature: &Signature) -> Result<(), String> {+ let mut verifier = Verifier::new(key, signature)?;+ if matches!(verifier, Verifier::Stream(_)) {+ let mut reader = std::fs::File::open(file).map_err(|error| error.to_string())?;+ let mut buffer = vec![0_u8; 256 * 1024];+ loop {+ let read = reader+ .read(&mut buffer)+ .map_err(|error| error.to_string())?;+ if read == 0 {+ break;+ }+ verifier.update(&buffer[..read]);+ }+ }+ verifier.finish(key, signature, file)+}++pub(crate) fn check_artifact_kind(file: &Path, kind: ArtifactKind) -> Result<(), String> {+ let mut header = [0_u8; 8];+ let read = std::fs::File::open(file)+ .and_then(|mut reader| reader.read(&mut header))+ .map_err(|error| error.to_string())?;+ if kind.matches(&header[..read]) {+ Ok(())+ } else {+ Err("The downloaded file is not a Cap package for this platform".to_string())+ }+}++fn staging_root() -> PathBuf {+ if let Some(directory) = std::env::var_os("CAP_GPUI_UPDATE_STAGING_DIR")+ && !directory.is_empty()+ {+ return PathBuf::from(directory);+ }+ dirs::cache_dir()+ .unwrap_or_else(std::env::temp_dir)+ .join("so.cap.desktop")+ .join("updates")+}++fn prune_other_versions(product_dir: &Path, keep: &Path) {+ let Ok(entries) = std::fs::read_dir(product_dir) else {+ return;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path != keep+ && let Err(error) = std::fs::remove_dir_all(&path)+ {+ tracing::warn!(path = %path.display(), %error, "could not remove a stale update download");+ }+ }+}++pub(crate) async fn download(+ product: Product,+ kind: ArtifactKind,+ release: &Release,+ mut progress: impl FnMut(u64, Option<u64>) + Send,+) -> Result<PathBuf, String> {+ download_into(+ &staging_root(),+ UPDATER_PUBLIC_KEY,+ product,+ kind,+ release,+ &mut progress,+ )+ .await+}++async fn download_into(+ root: &Path,+ encoded_key: &str,+ product: Product,+ kind: ArtifactKind,+ release: &Release,+ progress: &mut (impl FnMut(u64, Option<u64>) + Send),+) -> Result<PathBuf, String> {+ let key = trusted_key(encoded_key)?;+ let signature = decode_signature(&release.signature)?;+ let product_dir = root.join(product.slug());+ let version_dir = product_dir.join(release.version.to_string());+ let destination = version_dir.join(kind.file_name(product));++ if destination.is_file() && verify_file(&destination, &key, &signature).is_ok() {+ prune_other_versions(&product_dir, &version_dir);+ return Ok(destination);+ }++ std::fs::create_dir_all(&version_dir).map_err(|error| error.to_string())?;+ let partial = version_dir.join(format!("{}.partial", kind.file_name(product)));+ if let Err(error) = stream_to_file(&partial, &key, &signature, release, progress).await {+ let _ = std::fs::remove_file(&partial);+ return Err(error);+ }+ std::fs::rename(&partial, &destination).map_err(|error| error.to_string())?;+ prune_other_versions(&product_dir, &version_dir);+ Ok(destination)+}++async fn stream_to_file(+ partial: &Path,+ key: &PublicKey,+ signature: &Signature,+ release: &Release,+ progress: &mut (impl FnMut(u64, Option<u64>) + Send),+) -> Result<(), String> {+ let mut verifier = Verifier::new(key, signature)?;+ let response = client()?+ .get(&release.url)+ .header(reqwest::header::ACCEPT, "application/octet-stream")+ .send()+ .await+ .map_err(|error| error.to_string())?+ .error_for_status()+ .map_err(|error| error.to_string())?;+ let total = response.content_length();+ let mut file = std::fs::File::create(partial).map_err(|error| error.to_string())?;+ let mut stream = response.bytes_stream();+ let mut downloaded = 0_u64;+ progress(0, total);++ loop {+ let next = tokio::time::timeout(CHUNK_TIMEOUT, stream.next())+ .await+ .map_err(|_| "The download stopped responding".to_string())?;+ let Some(chunk) = next else {+ break;+ };+ let chunk = chunk.map_err(|error| error.to_string())?;+ file.write_all(&chunk).map_err(|error| error.to_string())?;+ verifier.update(&chunk);+ downloaded = downloaded.saturating_add(chunk.len() as u64);+ progress(downloaded, total);+ }++ file.sync_all().map_err(|error| error.to_string())?;+ drop(file);+ if total.is_some_and(|total| total != downloaded) {+ return Err("The download ended early".to_string());+ }+ verifier.finish(key, signature, partial)+}++#[cfg(target_os = "macos")]+pub(crate) fn install_app_bundle(archive: &Path, destination: &Path) -> Result<(), String> {+ let parent = destination+ .parent()+ .ok_or_else(|| "The app has no parent folder".to_string())?;+ std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;+ let staging = match unique_directory_in(parent, ".cap-update") {+ Ok(directory) => directory,+ Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {+ unique_directory_in(&std::env::temp_dir(), "cap-update")+ .map_err(|error| error.to_string())?+ }+ Err(error) => return Err(error.to_string()),+ };++ let installed =+ extract_app_archive(archive, &staging).and_then(|app| {+ match replace_directory(&app, destination) {+ Ok(()) => Ok(()),+ Err(error)+ if matches!(+ error.kind(),+ std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::CrossesDevices+ ) =>+ {+ replace_directory_with_privileges(&app, destination)+ }+ Err(error) => Err(error.to_string()),+ }+ });+ if let Err(error) = std::fs::remove_dir_all(&staging)+ && error.kind() != std::io::ErrorKind::NotFound+ {+ tracing::warn!(%error, "could not remove the update staging folder");+ }+ installed?;++ let _ = std::process::Command::new("/usr/bin/touch")+ .arg(destination)+ .status();+ Ok(())+}++#[cfg(target_os = "macos")]+fn extract_app_archive(archive: &Path, staging: &Path) -> Result<PathBuf, String> {+ let output = std::process::Command::new("/usr/bin/tar")+ .arg("-xzf")+ .arg(archive)+ .arg("-C")+ .arg(staging)+ .output()+ .map_err(|error| format!("Could not unpack the update: {error}"))?;+ if !output.status.success() {+ return Err(format!(+ "Could not unpack the update: {}",+ String::from_utf8_lossy(&output.stderr).trim()+ ));+ }+ single_app_bundle(staging)+}++#[cfg(any(target_os = "macos", test))]+fn single_app_bundle(directory: &Path) -> Result<PathBuf, String> {+ let bundles = std::fs::read_dir(directory)+ .map_err(|error| error.to_string())?+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| {+ path.extension().is_some_and(|extension| extension == "app")+ && path.join("Contents/Info.plist").is_file()+ })+ .collect::<Vec<_>>();+ match bundles.as_slice() {+ [bundle] => Ok(bundle.clone()),+ _ => Err("The update archive does not contain exactly one app".to_string()),+ }+}++#[cfg(target_os = "macos")]+fn unique_directory_in(parent: &Path, prefix: &str) -> std::io::Result<PathBuf> {+ for attempt in 0..32_u32 {+ let candidate = parent.join(format!("{prefix}-{}-{attempt}", std::process::id()));+ match std::fs::create_dir(&candidate) {+ Ok(()) => return Ok(candidate),+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}+ Err(error) => return Err(error),+ }+ }+ Err(std::io::Error::new(+ std::io::ErrorKind::AlreadyExists,+ "no free staging folder name",+ ))+}++#[cfg(any(target_os = "macos", test))]+fn replace_directory(new: &Path, destination: &Path) -> std::io::Result<()> {+ if !destination.exists() {+ return std::fs::rename(new, destination);+ }+ let name = destination+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_default();+ let backup = destination.with_file_name(format!(".{name}.previous-{}", std::process::id()));+ if backup.exists() {+ std::fs::remove_dir_all(&backup)?;+ }+ std::fs::rename(destination, &backup)?;+ if let Err(error) = std::fs::rename(new, destination) {+ if let Err(restore) = std::fs::rename(&backup, destination) {+ tracing::error!(%restore, "could not restore the previous app after a failed update");+ }+ return Err(error);+ }+ if let Err(error) = std::fs::remove_dir_all(&backup) {+ tracing::warn!(%error, "could not remove the previous app after updating");+ }+ Ok(())+}++#[cfg(target_os = "macos")]+fn replace_directory_with_privileges(new: &Path, destination: &Path) -> Result<(), String> {+ let output = std::process::Command::new("/usr/bin/osascript")+ .args([+ "-e",+ "on run argv",+ "-e",+ "do shell script \"/bin/rm -rf \" & quoted form of (item 1 of argv) & \" && /bin/mv -f \" & quoted form of (item 2 of argv) & \" \" & quoted form of (item 1 of argv) with administrator privileges",+ "-e",+ "end run",+ ])+ .arg(destination)+ .arg(new)+ .output()+ .map_err(|error| format!("Could not ask for permission to install: {error}"))?;+ if output.status.success() {+ Ok(())+ } else {+ Err(format!(+ "Cap couldn't replace {}. {}",+ destination.display(),+ String::from_utf8_lossy(&output.stderr).trim()+ ))+ }+}++#[cfg(windows)]+pub(crate) fn launch_installer(installer: &Path, arguments: &[&str]) -> Result<(), String> {+ use std::os::windows::ffi::OsStrExt as _;+ use windows_sys::{+ Win32::UI::{Shell::ShellExecuteW, WindowsAndMessaging::SW_SHOWNORMAL},+ w,+ };++ let wide = |value: &std::ffi::OsStr| {+ value+ .encode_wide()+ .chain(std::iter::once(0))+ .collect::<Vec<u16>>()+ };+ let file = wide(installer.as_os_str());+ let parameters = wide(std::ffi::OsStr::new(&arguments.join(" ")));+ let result = unsafe {+ ShellExecuteW(+ std::ptr::null_mut(),+ w!("open"),+ file.as_ptr(),+ parameters.as_ptr(),+ std::ptr::null(),+ SW_SHOWNORMAL,+ )+ };+ if result as isize > 32 {+ Ok(())+ } else {+ Err(format!(+ "Windows could not start the installer (code {})",+ result as isize+ ))+ }+}++#[cfg(target_os = "linux")]+pub(crate) fn install_deb(package: &Path) -> Result<(), String> {+ let status = std::process::Command::new("pkexec")+ .arg("dpkg")+ .arg("-i")+ .arg(package)+ .status()+ .map_err(|error| format!("Could not ask for permission to install: {error}"))?;+ if status.success() {+ Ok(())+ } else {+ Err("The package wasn't installed. Approve the system prompt, or install it from cap.so/download.".to_string())+ }+}++#[cfg(any(target_os = "linux", all(test, unix)))]+pub(crate) fn install_appimage(image: &Path, destination: &Path) -> Result<(), String> {+ use std::os::unix::fs::PermissionsExt as _;++ let parent = destination+ .parent()+ .ok_or_else(|| "The AppImage has no parent folder".to_string())?;+ std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;+ let name = destination+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_default();+ let staged = parent.join(format!(".{name}.update-{}", std::process::id()));+ let copied = std::fs::copy(image, &staged)+ .and_then(|_| std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755)))+ .and_then(|()| std::fs::rename(&staged, destination));+ if let Err(error) = copied {+ let _ = std::fs::remove_file(&staged);+ return Err(format!(+ "Could not install {}: {error}",+ destination.display()+ ));+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use std::io::{Read as _, Write as _};++ use super::*;++ const TEST_KEY: &str = "untrusted comment: minisign public key E7620F1842B4E81F\nRWQf6LRCGA9i53mlYecO4IzT51TGPpvWucNSCh1CBM0QTaLn73Y7GFO3\n";+ const TEST_SIGNATURE: &str = "untrusted comment: signature from minisign secret key\nRUQf6LRCGA9i559r3g7V1qNyJDApGip8MfqcadIgT9CuhV3EMhHoN1mGTkUidF/z7SrlQgXdy8ofjb7bNJJylDOocrCo8KLzZwo=\ntrusted comment: timestamp:1556193335\tfile:test\ny/rUw2y8/hOUYjZU71eHp/Wo1KZ40fGy2VJEDl34XMJM+TX48Ss/17u3IvIfbVR1FkZZSNCisQbuQY+bHwhEBg==\n";++ fn encode(text: &str) -> String {+ base64::engine::general_purpose::STANDARD.encode(text)+ }++ fn scratch(name: &str) -> PathBuf {+ let directory = std::env::temp_dir().join(format!(+ "cap-gpui-installer-{name}-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ std::fs::create_dir_all(&directory).unwrap();+ directory+ }++ fn serve_once(body: &'static [u8]) -> (String, std::thread::JoinHandle<usize>) {+ let listener = std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).unwrap();+ let url = format!("http://{}/artifact", listener.local_addr().unwrap());+ let server = std::thread::spawn(move || {+ let mut served = 0;+ for stream in listener.incoming().take(1) {+ let mut stream = stream.unwrap();+ let mut request = [0_u8; 4096];+ let _ = stream.read(&mut request).unwrap();+ write!(+ stream,+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",+ body.len()+ )+ .unwrap();+ stream.write_all(body).unwrap();+ served += 1;+ }+ served+ });+ (url, server)+ }++ fn release(url: String) -> Release {+ Release {+ version: Version::new(9, 9, 9),+ url,+ signature: encode(TEST_SIGNATURE),+ notes: None,+ }+ }++ #[test]+ fn the_shipped_update_key_decodes() {+ let key = trusted_key(UPDATER_PUBLIC_KEY).unwrap();+ assert_eq!(+ key.untrusted_comment(),+ Some("untrusted comment: minisign public key: E290397E72EBDE93")+ );+ }++ #[test]+ fn release_metadata_requires_https_and_a_signature() {+ let release = parse_release(+ br#"{"version":"v0.7.0","notes":"","url":"https://cdn.crabnebula.app/asset/1","signature":"c2ln"}"#,+ )+ .unwrap();+ assert_eq!(release.version, Version::new(0, 7, 0));+ assert_eq!(release.notes, None);+ assert!(+ parse_release(+ br#"{"version":"0.7.0","url":"http://example.com/a","signature":"c2ln"}"#+ )+ .is_err()+ );+ assert!(+ parse_release(br#"{"version":"0.7.0","url":"https://example.com/a","signature":" "}"#)+ .is_err()+ );+ assert!(+ parse_release(+ br#"{"version":"seven","url":"https://example.com/a","signature":"c2ln"}"#+ )+ .is_err()+ );+ }++ #[test]+ fn endpoints_name_the_platform_version_and_channel() {+ let current = Version::parse("0.6.2-nightly.4").unwrap();+ assert_eq!(+ endpoint("darwin-aarch64", UpdateChannel::Stable, ¤t),+ "https://cdn.crabnebula.app/update/cap/cap/darwin-aarch64/0.6.2-nightly.4"+ );+ assert_eq!(+ endpoint("windows-x86_64-classic", UpdateChannel::Nightly, ¤t),+ "https://cdn.crabnebula.app/update/cap/cap/windows-x86_64-classic/0.6.2-nightly.4?channel=nightly"+ );+ }++ #[test]+ fn classic_platforms_are_suffixed_and_linux_classic_ships_as_an_appimage() {+ let platform = classic_update_platform("x86_64");+ assert!(platform.ends_with("-classic"));+ if cfg!(target_os = "linux") {+ assert_eq!(platform, "linux-x86_64-appimage-classic");+ }+ assert_eq!(+ ArtifactKind::for_platform("linux-x86_64-appimage-classic"),+ Ok(ArtifactKind::AppImage)+ );+ assert_eq!(+ ArtifactKind::for_platform("linux-x86_64-deb"),+ Ok(ArtifactKind::Deb)+ );+ assert_eq!(+ ArtifactKind::for_platform("darwin-aarch64-classic"),+ Ok(ArtifactKind::AppArchive)+ );+ assert_eq!(+ ArtifactKind::for_platform("windows-x86_64"),+ Ok(ArtifactKind::NsisInstaller)+ );+ assert!(ArtifactKind::for_platform("linux-x86_64-rpm").is_err());+ }++ #[test]+ fn signatures_verify_while_streaming_and_reject_tampering() {+ let key = trusted_key(&encode(TEST_KEY)).unwrap();+ let signature = decode_signature(&encode(TEST_SIGNATURE)).unwrap();+ let directory = scratch("verify");+ let file = directory.join("artifact");++ std::fs::write(&file, b"test").unwrap();+ verify_file(&file, &key, &signature).unwrap();++ std::fs::write(&file, b"tesT").unwrap();+ assert!(verify_file(&file, &key, &signature).is_err());++ let mut verifier = Verifier::new(&key, &signature).unwrap();+ verifier.update(b"te");+ verifier.update(b"st");+ verifier.finish(&key, &signature, &file).unwrap();+ std::fs::remove_dir_all(directory).unwrap();+ }++ #[test]+ fn downloads_are_verified_staged_and_reused() {+ let runtime = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(1)+ .enable_all()+ .build()+ .unwrap();+ let root = scratch("download");+ let stale = root.join("cap-classic").join("0.0.1");+ std::fs::create_dir_all(&stale).unwrap();++ let (url, server) = serve_once(b"test");+ let mut updates = Vec::new();+ let downloaded = runtime+ .block_on(download_into(+ &root,+ &encode(TEST_KEY),+ Product::Classic,+ ArtifactKind::AppImage,+ &release(url),+ &mut |done, total| updates.push((done, total)),+ ))+ .unwrap();+ assert_eq!(server.join().unwrap(), 1);+ assert_eq!(+ downloaded,+ root.join("cap-classic/9.9.9/Cap-Classic.AppImage")+ );+ assert_eq!(std::fs::read(&downloaded).unwrap(), b"test");+ assert_eq!(updates.first(), Some(&(0, Some(4))));+ assert_eq!(updates.last(), Some(&(4, Some(4))));+ assert!(!stale.exists());+ assert!(check_artifact_kind(&downloaded, ArtifactKind::AppImage).is_err());++ let reused = runtime+ .block_on(download_into(+ &root,+ &encode(TEST_KEY),+ Product::Classic,+ ArtifactKind::AppImage,+ &release("http://127.0.0.1:9/unreachable".to_string()),+ &mut |_, _| panic!("a verified cached download must not be fetched again"),+ ))+ .unwrap();+ assert_eq!(reused, downloaded);+ std::fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn artifact_kinds_are_recognised_by_their_headers() {+ let root = scratch("kinds");+ for (kind, header) in [+ (ArtifactKind::AppArchive, &b"\x1f\x8b\x08\x00"[..]),+ (ArtifactKind::NsisInstaller, &b"MZ\x90\x00"[..]),+ (ArtifactKind::Deb, &b"!<arch>\ndebian"[..]),+ (ArtifactKind::AppImage, &b"\x7fELF\x02\x01"[..]),+ ] {+ let file = root.join("artifact");+ std::fs::write(&file, header).unwrap();+ check_artifact_kind(&file, kind).unwrap();+ std::fs::write(&file, b"<html>").unwrap();+ assert!(check_artifact_kind(&file, kind).is_err());+ }+ std::fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn tampered_downloads_are_discarded() {+ let runtime = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(1)+ .enable_all()+ .build()+ .unwrap();+ let root = scratch("tampered");+ let (url, server) = serve_once(b"tesT");+ let error = runtime+ .block_on(download_into(+ &root,+ &encode(TEST_KEY),+ Product::Cap,+ ArtifactKind::AppImage,+ &release(url),+ &mut |_, _| {},+ ))+ .unwrap_err();+ assert_eq!(server.join().unwrap(), 1);+ assert!(error.contains("signature verification"));+ let version_dir = root.join("cap").join("9.9.9");+ assert!(!version_dir.join("Cap.AppImage").exists());+ assert!(!version_dir.join("Cap.AppImage.partial").exists());+ std::fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn app_bundles_are_swapped_atomically_with_a_single_bundle_check() {+ let root = scratch("bundle");+ let staging = root.join("staging");+ let new_app = staging.join("Cap.app");+ std::fs::create_dir_all(new_app.join("Contents")).unwrap();+ std::fs::write(new_app.join("Contents/Info.plist"), "new").unwrap();+ assert_eq!(single_app_bundle(&staging).unwrap(), new_app);++ let destination = root.join("Applications").join("Cap.app");+ std::fs::create_dir_all(destination.join("Contents")).unwrap();+ std::fs::write(destination.join("Contents/Info.plist"), "old").unwrap();+ replace_directory(&new_app, &destination).unwrap();+ assert_eq!(+ std::fs::read_to_string(destination.join("Contents/Info.plist")).unwrap(),+ "new"+ );+ assert_eq!(+ std::fs::read_dir(root.join("Applications"))+ .unwrap()+ .count(),+ 1+ );++ let other = staging.join("Other.app");+ std::fs::create_dir_all(other.join("Contents")).unwrap();+ std::fs::write(other.join("Contents/Info.plist"), "other").unwrap();+ let again = staging.join("Again.app");+ std::fs::create_dir_all(again.join("Contents")).unwrap();+ std::fs::write(again.join("Contents/Info.plist"), "again").unwrap();+ assert!(single_app_bundle(&staging).is_err());+ std::fs::remove_dir_all(root).unwrap();+ }++ #[cfg(unix)]+ #[test]+ fn appimages_are_replaced_in_place_and_made_executable() {+ use std::os::unix::fs::PermissionsExt as _;++ let root = scratch("appimage");+ let source = root.join("download.AppImage");+ std::fs::write(&source, b"\x7fELFnew").unwrap();+ let destination = root.join("Applications").join("Cap-Classic.AppImage");+ install_appimage(&source, &destination).unwrap();+ assert_eq!(std::fs::read(&destination).unwrap(), b"\x7fELFnew");+ assert_eq!(+ std::fs::metadata(&destination)+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o755+ );+ std::fs::write(&source, b"\x7fELFnewer").unwrap();+ install_appimage(&source, &destination).unwrap();+ assert_eq!(std::fs::read(&destination).unwrap(), b"\x7fELFnewer");+ assert_eq!(+ std::fs::read_dir(root.join("Applications"))+ .unwrap()+ .count(),+ 1+ );+ std::fs::remove_dir_all(root).unwrap();+ }+}diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rsindex aa22b4191..4ecec3eae 100644--- a/apps/desktop-gpui/src/main.rs+++ b/apps/desktop-gpui/src/main.rs@@ -14,6 +14,7 @@ mod camera_blur;#[cfg(any(not(target_os = "macos"), test))]mod camera_blur_portable;mod camera_window;+mod classic;mod controls_window;mod deeplink;mod dev_restore;@@ -37,6 +38,7 @@ mod editor_window;mod feeds;mod hotkeys;mod import;+mod installer;mod library;mod main_window;mod menus;@@ -249,7 +251,6 @@ fn main() {let _log_guard = init_logging();single_instance::acquire();- store::mark_handoff_session();platform::install_url_scheme_handler();for argument in std::env::args().skip(1) {@@ -367,11 +368,6 @@ fn main() {return;};- cx.on_app_quit(|_| async {- crate::store::clear_handoff_marker();- })- .detach();-app_windows::init(window_handle, session, cx);#[cfg(target_os = "macos")]match platform::install_native_quit_handler() {diff --git a/apps/desktop-gpui/src/permissions.rs b/apps/desktop-gpui/src/permissions.rsindex 462e2a987..433a505f6 100644--- a/apps/desktop-gpui/src/permissions.rs+++ b/apps/desktop-gpui/src/permissions.rs@@ -314,19 +314,26 @@ pub fn open_permission_settings(permission: OSPermission) {/// 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)) {+ if let Err(error) = relaunch_executable(&exe, cx) {tracing::error!("relaunch failed to spawn: {error}");}}+pub(crate) fn relaunch_executable(+ exe: &std::path::Path,+ cx: &mut gpui::App,+) -> std::io::Result<()> {+ static REQUESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++ let mut command = relaunch_command(exe, std::process::id());+ spawn_relaunch(&mut command, &REQUESTED, || crate::menus::quit(cx)).map(drop)+}+fn relaunch_command(exe: &std::path::Path, pid: u32) -> std::process::Command {#[cfg(target_os = "macos")]let bundle = exediff --git a/apps/desktop-gpui/src/platform/windows.rs b/apps/desktop-gpui/src/platform/windows.rsindex 9e3bed11b..207465cc8 100644--- a/apps/desktop-gpui/src/platform/windows.rs+++ b/apps/desktop-gpui/src/platform/windows.rs@@ -17,6 +17,7 @@ use super::{ForcedAppearance, MaterialKind, PanelBehavior};mod capture_exclusion;mod hidden_frame;+mod url_scheme;#[derive(Clone, Copy)]pub struct NativeWindow(isize);@@ -605,7 +606,9 @@ pub fn focus_capture_target_window(id: &scap_targets::WindowId) -> bool {}}-pub fn install_url_scheme_handler() {}+pub fn install_url_scheme_handler() {+ url_scheme::install();+}pub fn set_dock_icon(_png: &[u8]) {}diff --git a/apps/desktop-gpui/src/platform/windows/url_scheme.rs b/apps/desktop-gpui/src/platform/windows/url_scheme.rsnew file mode 100644index 000000000..869aa40ff--- /dev/null+++ b/apps/desktop-gpui/src/platform/windows/url_scheme.rs@@ -0,0 +1,126 @@+use std::path::Path;++pub(super) fn install() {+ let Ok(executable) = std::env::current_exe() else {+ return;+ };+ if !is_installed_executable(&executable) {+ return;+ }+ std::thread::Builder::new()+ .name("cap-url-scheme".into())+ .spawn(move || {+ if let Err(error) = claim_url_scheme("cap-desktop", &executable) {+ tracing::warn!(%error, "could not register the cap-desktop link handler");+ }+ })+ .ok();+}++fn is_installed_executable(executable: &Path) -> bool {+ executable+ .file_name()+ .is_some_and(|name| name.eq_ignore_ascii_case("Cap.exe"))+ && !executable+ .components()+ .any(|component| component.as_os_str() == "target")+}++fn wide_null(value: &std::ffi::OsStr) -> Vec<u16> {+ use std::os::windows::ffi::OsStrExt as _;+ value.encode_wide().chain(std::iter::once(0)).collect()+}++fn read_user_registry_string(key: &str) -> Option<String> {+ use std::os::windows::ffi::OsStringExt as _;+ use windows_sys::Win32::{+ Foundation::ERROR_SUCCESS,+ System::Registry::{HKEY_CURRENT_USER, RRF_RT_REG_SZ, RegGetValueW},+ };++ let key = wide_null(std::ffi::OsStr::new(key));+ let mut buffer = vec![0_u16; 2048];+ let mut size = (buffer.len() * std::mem::size_of::<u16>()) as u32;+ let status = unsafe {+ RegGetValueW(+ HKEY_CURRENT_USER,+ key.as_ptr(),+ std::ptr::null(),+ RRF_RT_REG_SZ,+ std::ptr::null_mut(),+ buffer.as_mut_ptr().cast(),+ &mut size,+ )+ };+ if status != ERROR_SUCCESS {+ return None;+ }+ let length = (size as usize / std::mem::size_of::<u16>()).min(buffer.len());+ let value = std::ffi::OsString::from_wide(&buffer[..length]);+ Some(value.to_string_lossy().trim_end_matches('\0').to_string())+}++fn write_user_registry_string(key: &str, name: Option<&str>, value: &str) -> Result<(), String> {+ use windows_sys::Win32::{+ Foundation::ERROR_SUCCESS,+ System::Registry::{HKEY_CURRENT_USER, REG_SZ, RegSetKeyValueW},+ };++ let key = wide_null(std::ffi::OsStr::new(key));+ let name = name.map(|name| wide_null(std::ffi::OsStr::new(name)));+ let value = wide_null(std::ffi::OsStr::new(value));+ let status = unsafe {+ RegSetKeyValueW(+ HKEY_CURRENT_USER,+ key.as_ptr(),+ name.as_ref().map_or(std::ptr::null(), |name| name.as_ptr()),+ REG_SZ,+ value.as_ptr().cast(),+ (value.len() * std::mem::size_of::<u16>()) as u32,+ )+ };+ if status == ERROR_SUCCESS {+ Ok(())+ } else {+ Err(format!("registry write failed with code {status}"))+ }+}++fn claim_url_scheme(scheme: &str, executable: &Path) -> Result<(), String> {+ let executable = executable.display().to_string();+ let class = format!("Software\\Classes\\{scheme}");+ let command_key = format!("{class}\\shell\\open\\command");+ let command = format!("\"{executable}\" \"%1\"");+ if read_user_registry_string(&command_key).as_deref() == Some(command.as_str()) {+ return Ok(());+ }+ write_user_registry_string(&class, None, "URL:so.cap.desktop protocol")?;+ write_user_registry_string(&class, Some("URL Protocol"), "")?;+ write_user_registry_string(+ &format!("{class}\\DefaultIcon"),+ None,+ &format!("\"{executable}\",0"),+ )?;+ write_user_registry_string(&command_key, None, &command)+}++#[cfg(test)]+mod tests {+ use std::path::Path;++ #[test]+ fn only_installed_builds_claim_the_link_scheme() {+ assert!(super::is_installed_executable(Path::new(+ r"C:\Users\x\AppData\Local\Cap\Cap.exe"+ )));+ assert!(!super::is_installed_executable(Path::new(+ r"C:\src\Cap\apps\desktop-gpui\target\release\Cap.exe"+ )));+ assert!(!super::is_installed_executable(Path::new(+ r"C:\Users\x\AppData\Local\Cap Classic\Cap Classic.exe"+ )));+ assert!(!super::is_installed_executable(Path::new(+ r"C:\Users\x\AppData\Local\Cap\cap-gpui.exe"+ )));+ }+}diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rsindex 6e002f78e..b8eace042 100644--- a/apps/desktop-gpui/src/settings_pages.rs+++ b/apps/desktop-gpui/src/settings_pages.rs@@ -1904,27 +1904,21 @@ impl SettingsWindow {// Experimental (experimental.tsx)// ----------------------------------------------------------------------------/// The hand-back takeover, mirroring `experimental.tsx`'s overlay: the toggle-/// is the confirmation, and the sequence is what the user reads while Cancel is-/// on screen.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),+ Downloading(Option<f32>),WaitingForClassic,- /// The switch was refused; the overlay stays up with the reason and the- /// toggle goes back to on, because nothing was switched.Failed(String),}/// A cold dev build can genuinely take this long; past it, assume the build/// failed and hand the user back their app with a pointer at the terminal.const CLASSIC_WAIT_TIMEOUT: Duration = Duration::from_secs(10 * 60);+const CLASSIC_INSTALL_WAIT_TIMEOUT: Duration = Duration::from_secs(3 * 60);+const CLASSIC_LAUNCH_WAIT_TIMEOUT: Duration = Duration::from_secs(30);-/// One line at a time, fading between them, underneath the countdown rather-/// than ahead of it: the numeral is on screen from the first frame.const SWITCH_SENTENCES: &[&str] = &[- "Switching back to the classic Cap app.",+ "Switching to Cap Classic.","Your recordings and settings stay exactly where they are.",];const SWITCH_SENTENCE_MS: u64 = 2000;@@ -1955,182 +1949,47 @@ fn takeover_frame(elapsed_ms: f32) -> (usize, f32, u32) {(index, alpha, remaining)}-/// Where the classic app lives when this build was not started from inside its-/// 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/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- /// (`store::request_classic_reopen`).+ Installed(std::path::PathBuf),+ /// A debug cargo build: the classic app here is the `tauri dev` harness,+ /// which cannot be launched directly -- ask the dev-session supervisor to+ /// restart it instead (`store::request_classic_reopen`).DevSupervisor,+ Missing,}-fn classic_target_for_exe(exe: &std::path::Path) -> Option<ClassicTarget> {- if let Some(bundle) = exe- .ancestors()- .find(|path| path.extension().is_some_and(|extension| extension == "app"))- {- return Some(ClassicTarget::Bundle(bundle.to_path_buf()));- }- if exe- .components()- .any(|component| component.as_os_str() == "target")- {- 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))-}--fn classic_target() -> Option<ClassicTarget> {- std::env::current_exe()- .ok()- .as_deref()- .and_then(classic_target_for_exe)-}--pub(crate) fn start_update_handoff(cx: &mut gpui::App) {- begin_update_handoff(cx, store::request_update_handoff);+fn classic_target_for(+ exe: Option<&std::path::Path>,+ debug_build: bool,+ installed: impl FnOnce() -> Option<std::path::PathBuf>,+) -> ClassicTarget {+ let cargo_build = exe.is_some_and(|exe| {+ exe.components()+ .any(|component| component.as_os_str() == "target")+ });+ if debug_build && cargo_build {+ return ClassicTarget::DevSupervisor;+ }+ installed().map_or(ClassicTarget::Missing, ClassicTarget::Installed)}-fn quit_after_flushing_editors(cx: &mut gpui::App) {- crate::menus::quit(cx);+fn classic_target() -> ClassicTarget {+ let exe = std::env::current_exe().ok();+ classic_target_for(+ exe.as_deref(),+ cfg!(debug_assertions),+ crate::classic::installed,+ )}-#[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;- }- if let Err(error) = crate::app_windows::flush_pending_editor_saves(cx) {- cx.spawn(async move |_| {- crate::platform::alert_dialog("Cap is still open", &error);- })- .detach();- return;- }-- 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 switch_blocked_message() -> String {+ "Finish your recording, export, upload, import, or transcription task before switching to Cap Classic."+ .to_string()}-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+fn classic_download_failed(error: &str) -> String {+ format!("Couldn't install Cap Classic: {error}")}impl SettingsWindow {@@ -2140,7 +1999,7 @@ impl SettingsWindow {// 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.- let sections = vec![+ vec![self.section("Reliability",None,@@ -2173,74 +2032,32 @@ impl SettingsWindow {).into_any_element(),self.section(- "Native app",+ "Cap Classic",None,None,- vec![self.rows(vec![self.native_app_row(cx)]).into_any_element()],+ vec![self.rows(vec![self.classic_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- /// to this app, this one hands it back.- fn native_app_row(&self, cx: &mut Context<Self>) -> gpui::AnyElement {- // Being in this app is what the toggle means, so it reads on even when- // the stored flag does not -- a `cargo run` or `dev.sh` launch never- // went through the hand-off. The flag only routes the Tauri app's- // startup.- let checked = !matches!(self.pages.switch_back, Some(SwitchBack::Running(_)));+ fn classic_app_row(&self, cx: &mut Context<Self>) -> gpui::AnyElement {+ let busy = self.pages.switch_back.is_some();self.setting_row(- "Cap GPUI",+ "Switch to Cap Classic",Some(- "You are using the native version of Cap. Turning this off closes it and reopens \- the classic app. Your recordings and settings are shared.",+ "Prefer the original Cap app? Cap Classic is a separate download that Cap installs \+ for you the first time. Your recordings and settings are shared, and you can \+ switch back from Cap Classic's settings at any time.",),- self.toggle("enable-gpui-app", checked, cx, |this, cx| {- match this.pages.switch_back {- Some(SwitchBack::Running(_)) => this.cancel_switch_back(cx),- // Committed: the classic app is already being brought up.- Some(SwitchBack::WaitingForClassic) => {}- _ => this.start_switch_back(cx),- }- })+ self.button(+ "switch-to-classic",+ (ui::ButtonVariant::Dark, None),+ "Switch",+ busy,+ cx,+ |this, _, cx| this.start_switch_back(cx),+ ).into_any_element(),)}@@ -2263,6 +2080,24 @@ impl SettingsWindow {.gap(px(28.)).bg(gpui::hsla(0., 0., 0., 0.92));+ let heading = |text: SharedString| {+ div()+ .max_w(px(380.))+ .text_size(px(17.))+ .font_weight(FontWeight::SEMIBOLD)+ .text_center()+ .text_color(white)+ .child(text)+ };+ let detail = |text: SharedString| {+ div()+ .max_w(px(380.))+ .text_size(px(14.))+ .text_center()+ .text_color(gpui::hsla(0., 0., 1., 0.7))+ .child(text)+ };+match switch {SwitchBack::Running(started) => {let (index, alpha, remaining) =@@ -2288,36 +2123,62 @@ impl SettingsWindow {.child(SWITCH_SENTENCES[index]),);}- SwitchBack::WaitingForClassic => {+ SwitchBack::Downloading(fraction) => {+ let label = match fraction {+ Some(fraction) => format!(+ "Downloading Cap Classic… {}%",+ (fraction * 100.).round() as u32+ ),+ None => "Downloading Cap Classic…".to_string(),+ };column = column+ .child(heading(label.into())).child(div()- .max_w(px(380.))- .text_size(px(17.))- .font_weight(FontWeight::SEMIBOLD)- .text_center()- .text_color(white)- .child("Opening the classic Cap app"),+ .w(px(280.))+ .h(px(6.))+ .rounded(px(3.))+ .bg(gpui::hsla(0., 0., 1., 0.15))+ .child(+ div()+ .h_full()+ .rounded(px(3.))+ .bg(white)+ .w(px(280. * fraction.unwrap_or(0.).clamp(0., 1.))),+ ),)+ .child(detail(+ "Cap Classic is verified before it's installed.".into(),+ ));+ }+ SwitchBack::WaitingForClassic => {+ column = column+ .child(heading("Opening Cap Classic".into()))+ .child(detail(+ "This window will close when Cap Classic is ready.".into(),+ ));+ }+ SwitchBack::Failed(error) => {+ column = column.child(div().max_w(px(380.)).text_size(px(14.)).text_center()- .text_color(gpui::hsla(0., 0., 1., 0.7))- .child("This window will close when the classic Cap app is ready."),+ .text_color(rgb(0xf87171))+ .child(SharedString::from(error.clone())),+ )+ .child(+ div()+ .id("switch-back-download-page")+ .text_size(px(13.))+ .text_color(white)+ .cursor_pointer()+ .hover(|style| style.text_color(gpui::hsla(0., 0., 1., 0.7)))+ .on_click(|_, _, cx| cx.open_url(crate::classic::DOWNLOAD_PAGE))+ .child("Download Cap Classic from cap.so"),);}- SwitchBack::Failed(error) => {- column = column.child(- div()- .max_w(px(380.))- .text_size(px(14.))- .text_center()- .text_color(rgb(0xf87171))- .child(SharedString::from(error.clone())),- );- }}// Committed states have nothing to cancel.@@ -2342,7 +2203,11 @@ impl SettingsWindow {.cursor_pointer().hover(|style| style.bg(gpui::hsla(0., 0., 1., 0.12))).on_click(cx.listener(|this, _, _window, cx| this.cancel_switch_back(cx)))- .child("Cancel"),+ .child(if matches!(switch, SwitchBack::Failed(_)) {+ "Close"+ } else {+ "Cancel"+ }),).into_any_element(),)@@ -2396,31 +2261,90 @@ impl SettingsWindow {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(),- ));+ self.pages.switch_back = Some(SwitchBack::Failed(switch_blocked_message()));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;}+ match classic_target() {+ ClassicTarget::Missing => self.install_classic(cx),+ ClassicTarget::Installed(path) => self.hand_off_to_classic(Some(path), false, cx),+ ClassicTarget::DevSupervisor => self.hand_off_to_classic(None, true, cx),+ }+ }- 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(),- ));- cx.notify();- return;- };+ fn install_classic(&mut self, cx: &mut Context<Self>) {+ self.pages.switch_back = Some(SwitchBack::Downloading(None));+ cx.notify();++ let (progress_sender, progress) = flume::bounded::<Option<f32>>(1);+ let download = gpui_tokio::Tokio::spawn(cx, async move {+ let mut reported = None::<u16>;+ crate::classic::download_and_install(move |done, total| {+ let fraction = total+ .filter(|total| *total > 0)+ .map(|total| (done as f64 / total as f64).clamp(0., 1.) as f32);+ let step = fraction.map(|fraction| (fraction * 100.) as u16);+ if step != reported {+ reported = step;+ let _ = progress_sender.try_send(fraction);+ }+ })+ .await+ });+ self.pages.switch_back_ticker = Some(cx.spawn(async move |this, cx| {+ let progress_view = this.clone();+ let progress_updates = cx.spawn(async move |cx| {+ while let Ok(fraction) = progress.recv_async().await {+ let updated = progress_view.update(cx, |this, cx| {+ if matches!(this.pages.switch_back, Some(SwitchBack::Downloading(_))) {+ this.pages.switch_back = Some(SwitchBack::Downloading(fraction));+ cx.notify();+ }+ });+ if updated.is_err() {+ return;+ }+ }+ });+ let result = match download.await {+ Ok(result) => result,+ Err(error) => Err(error.to_string()),+ };+ drop(progress_updates);+ this.update(cx, |this, cx| {+ if !matches!(this.pages.switch_back, Some(SwitchBack::Downloading(_))) {+ return;+ }+ match result {+ Ok(Some(path)) => this.hand_off_to_classic(Some(path), false, cx),+ Ok(None) => this.hand_off_to_classic(None, false, cx),+ Err(error) => {+ tracing::error!("installing Cap Classic failed: {error}");+ this.pages.switch_back =+ Some(SwitchBack::Failed(classic_download_failed(&error)));+ cx.notify();+ }+ }+ })+ .ok();+ }));+ }++ /// Hand the session (`enableGpuiApp`) to Cap Classic, start it, then quit+ /// once it is visible. `launch` is `None` when something else opens it:+ /// the dev supervisor, or the Windows installer that just ran.+ fn hand_off_to_classic(+ &mut self,+ launch: Option<std::path::PathBuf>,+ dev: bool,+ cx: &mut Context<Self>,+ ) {if self.switch_back_blocked(cx) {return;}@@ -2437,12 +2361,12 @@ impl SettingsWindow {cx.notify();return;}- self.settings.enable_gpui_app = false;- let dev = matches!(target, ClassicTarget::DevSupervisor);let timeout = if dev {CLASSIC_WAIT_TIMEOUT+ } else if launch.is_none() {+ CLASSIC_INSTALL_WAIT_TIMEOUT} else {- Duration::from_secs(30)+ CLASSIC_LAUNCH_WAIT_TIMEOUT};let pending = store::mark_classic_pending();self.pages.switch_back = Some(SwitchBack::WaitingForClassic);@@ -2455,24 +2379,27 @@ impl SettingsWindow {.background_executor().spawn(async move {pending?;- match target {- ClassicTarget::DevSupervisor => store::request_classic_reopen(),- _ => launch_classic(&target),+ match (launch, dev) {+ (_, true) => store::request_classic_reopen(),+ (Some(path), false) => crate::classic::launch(&path),+ (None, false) => Ok(()),}}).await;- let mut failure = result.err().map(|error| format!("Couldn't open Cap: {error}"));+ let mut failure = result+ .err()+ .map(|error| format!("Couldn't open Cap Classic: {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);+ tracing::info!("Cap Classic is visible; quitting");+ cx.update(crate::menus::quit);return;}Ok(true) => {}Err(error) => {- failure = Some(format!("Couldn't check whether Cap opened: {error}"));+ failure = Some(format!("Couldn't check whether Cap Classic opened: {error}"));break;}}@@ -2481,8 +2408,7 @@ impl SettingsWindow {"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()+ "Cap Classic hasn't opened. Cap is still here; please try again.".to_string()});break;}@@ -2490,12 +2416,11 @@ impl SettingsWindow {.timer(Duration::from_millis(250)).await;}- let message = failure.unwrap_or_else(|| "Couldn't open Cap.".to_string());+ let message = failure.unwrap_or_else(|| "Couldn't open Cap Classic.".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();})@@ -2505,38 +2430,6 @@ impl SettingsWindow {}}-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<()> {- 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()- )));- }- Ok(())- } else {- command.spawn().map(drop)- }-}-// ---------------------------------------------------------------------------// Feedback (feedback.tsx)// ---------------------------------------------------------------------------@@ -6347,8 +6240,8 @@ impl SettingsWindow {self.section("Automations",Some(- "Rules are shared with classic Cap and the Cap CLI. Experimental GPUI \- saves these rules but does not run automations.",+ "Rules are shared with Cap Classic and the Cap CLI. Cap saves these \+ rules but does not run automations yet.",),None,rule_content,@@ -6936,7 +6829,7 @@ impl SettingsWindow {.line_height(px(18.)).text_color(Hsla::from(theme.amber_11)).child(- "In classic Cap or the Cap CLI, this automation runs commands or sends \+ "In Cap Classic or the Cap CLI, this automation runs commands or sends \network requests with your permissions. Only use values you trust.",),)@@ -6949,8 +6842,8 @@ impl SettingsWindow {.line_height(px(18.)).text_color(Hsla::from(theme.amber_11)).child(- "Compatibility checked: this automation cannot run in Experimental \- GPUI. Saved rules remain available to classic Cap and the Cap CLI. \+ "Compatibility checked: this automation doesn't run in Cap yet. \+ Saved rules remain available to Cap Classic and the Cap CLI. \No actions were run.",),)@@ -8467,52 +8360,44 @@ mod tests {);}- /// The switch-back target matches how this binary was started: the `.app`- /// it is staged inside beats everything, a cargo `target/` path means the- /// dev harness (never the installed app), and only a bare binary from- /// neither falls through to `/Applications`.#[test]fn the_classic_target_matches_the_launch_context() {+ let cargo_build =+ std::path::Path::new("/Users/x/Cap/apps/desktop-gpui/target/debug/cap-gpui");+ let installed_app = std::path::Path::new("/Applications/Cap.app/Contents/MacOS/Cap");+ let classic = std::path::PathBuf::from("/Applications/Cap Classic.app");+assert_eq!(- classic_target_for_exe(std::path::Path::new(- "/Applications/Cap.app/Contents/MacOS/cap-gpui"+ classic_target_for(Some(cargo_build), true, || panic!(+ "dev builds use the harness")),- Some(ClassicTarget::Bundle(std::path::PathBuf::from(- "/Applications/Cap.app"- )))+ ClassicTarget::DevSupervisor);assert_eq!(- classic_target_for_exe(std::path::Path::new(- "/Users/x/Cap/apps/desktop-gpui/target/debug/cap-gpui"- )),- Some(ClassicTarget::DevSupervisor)+ classic_target_for(Some(cargo_build), false, || Some(classic.clone())),+ ClassicTarget::Installed(classic.clone()));- // 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/MacOS/cap-gpui"- )),- Some(ClassicTarget::Bundle(std::path::PathBuf::from(- "/Users/x/Cap/target/debug/bundle/osx/Cap.app"- )))+ classic_target_for(Some(installed_app), true, || Some(classic.clone())),+ ClassicTarget::Installed(classic)+ );+ assert_eq!(+ classic_target_for(Some(installed_app), false, || None),+ ClassicTarget::Missing+ );+ assert_eq!(+ classic_target_for(None, true, || None),+ ClassicTarget::Missing);}#[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");+ fn failed_classic_installs_explain_the_cause() {assert_eq!(- command.get_args().collect::<Vec<_>>(),- [std::ffi::OsStr::new("-n"), bundle.as_os_str()]+ classic_download_failed("The download stopped responding"),+ "Couldn't install Cap Classic: The download stopped responding");- 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);+ assert!(switch_blocked_message().contains("Cap Classic"));}/// The takeover's whole timeline, read off its one clock.diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rsindex 6772d3a8a..13163e958 100644--- a/apps/desktop-gpui/src/settings_window.rs+++ b/apps/desktop-gpui/src/settings_window.rs@@ -1805,6 +1805,28 @@ impl SettingsWindow {fn render_account(&self, cx: &mut Context<Self>) -> impl IntoElement {let theme = self.theme;+ let (update_label, update_ready) = match crate::updates::status(cx) {+ crate::updates::UpdateStatus::Idle => ("Check for updates".to_string(), false),+ crate::updates::UpdateStatus::Downloading {+ version,+ fraction: Some(fraction),+ } => (+ format!(+ "Downloading v{version}… {}%",+ (fraction * 100.).round() as u32+ ),+ false,+ ),+ crate::updates::UpdateStatus::Downloading { version, .. } => {+ (format!("Downloading v{version}…"), false)+ }+ crate::updates::UpdateStatus::Ready { version } => {+ (format!("Restart to update to v{version}"), true)+ }+ crate::updates::UpdateStatus::Installing { version } => {+ (format!("Installing v{version}…"), false)+ }+ };let update_links = div().flex()@@ -1820,10 +1842,7 @@ impl SettingsWindow {.px(px(4.)).py(px(2.)).rounded(px(4.))- .child(format!(- "v{} (Experimental GPUI)",- env!("CARGO_PKG_VERSION")- )),+ .child(format!("v{}", env!("CARGO_PKG_VERSION"))),).child(div()@@ -1836,11 +1855,18 @@ impl SettingsWindow {div().id("settings-check-updates").cursor_pointer()+ .when(update_ready, |link| {+ link.text_color(rgb(Theme::SETTINGS_ACCENT))+ }).hover(|style| style.text_color(theme.settings_text()))- .on_click(cx.listener(|_, _, _, cx| {- crate::updates::check_manually(cx);+ .on_click(cx.listener(move |_, _, _, cx| {+ if update_ready {+ crate::updates::install_and_relaunch(cx);+ } else {+ crate::updates::check_manually(cx);+ }}))- .child("Check for updates"),+ .child(update_label),);div()diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rsindex d8e990b57..2de9af071 100644--- a/apps/desktop-gpui/src/single_instance.rs+++ b/apps/desktop-gpui/src/single_instance.rs@@ -123,16 +123,18 @@ fn is_cap_gpui(pid: i32) -> bool {fn is_cap_gpui_image(path: &Path) -> bool {#[cfg(windows)]- const IMAGE_NAME: &str = "cap-gpui.exe";+ const IMAGE_NAMES: [&str; 2] = ["Cap.exe", "cap-gpui.exe"];#[cfg(not(windows))]- const IMAGE_NAME: &str = "cap-gpui";+ const IMAGE_NAMES: [&str; 2] = ["Cap", "cap-gpui"];let Some(name) = path.file_name().and_then(std::ffi::OsStr::to_str) else {return false;};#[cfg(target_os = "linux")]let name = name.strip_suffix(" (deleted)").unwrap_or(name);- name.eq_ignore_ascii_case(IMAGE_NAME)+ IMAGE_NAMES+ .iter()+ .any(|image| name.eq_ignore_ascii_case(image))}#[cfg(target_os = "macos")]@@ -1209,14 +1211,18 @@ mod tests {#[test]fn gpui_process_image_must_match_exactly() {#[cfg(windows)]- let name = "cap-gpui.exe";+ let names = ["cap-gpui.exe", "Cap.exe"];#[cfg(not(windows))]- let name = "cap-gpui";+ let names = ["cap-gpui", "Cap"];- assert!(is_cap_gpui_image(Path::new(name)));- assert!(is_cap_gpui_image(Path::new(&name.to_ascii_uppercase())));+ for name in names {+ 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")));+ assert!(!is_cap_gpui_image(Path::new("Cap Classic")));+ assert!(!is_cap_gpui_image(Path::new("Cap Classic.exe")));}#[cfg(target_os = "linux")]diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rsindex 2d78f9304..ed5a328a9 100644--- a/apps/desktop-gpui/src/store.rs+++ b/apps/desktop-gpui/src/store.rs@@ -14,11 +14,7 @@//! read-modify-write on the raw JSON that touches exactly one key: see//! [`set_store_setting`].-use std::{- io::Write,- path::{Path, PathBuf},- sync::atomic::{AtomicU64, Ordering},-};+use std::path::{Path, PathBuf};use serde::{Deserialize, Serialize};use serde_json::{Map, Value};@@ -194,132 +190,6 @@ fn bundled_resource_dirs_for(directories}-/// The Tauri app's hand-off marker (`gpui_app.rs`).-///-/// 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() {- 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}"),- }-}--/// 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`@@ -932,10 +802,6 @@ pub struct GeneralSettings {/// `!!settings.outOfProcessMuxer` in experimental.tsx).pub enable_native_camera_preview: bool,pub out_of_process_muxer: bool,- /// Whether this app, rather than the Tauri one, owns the session. Reads- /// true for anyone who arrived here through the Tauri app's hand-off; the- /// Experimental page's Native app row turns it back off.- pub enable_gpui_app: bool,/// Not part of `general_settings` at all: the mic-confirmation toggle/// lives in the store's own `recording_start_safety` section/// (`RECORDING_START_SAFETY_DEFAULTS`), and the page renders it in the@@ -1267,7 +1133,6 @@ impl GeneralSettings {editor_preview_quality: enum_at(general, "editorPreviewQuality"),enable_native_camera_preview: bool_at(general, "enableNativeCameraPreview", false),out_of_process_muxer: bool_at(general, "outOfProcessMuxer", false),- enable_gpui_app: bool_at(general, "enableGpuiApp", false),confirm_without_microphone: bool_at(safety,"confirmBeforeRecordingWithoutMicrophone",@@ -2353,73 +2218,6 @@ mod tests {assert!(!GeneralSettings::load().enable_telemetry);}- /// The Tauri app hands off by setting `enableGpuiApp`, so this app has to- /// read the same key -- and default it off, since the vast majority of- /// stores predate it.- #[test]- fn the_hand_off_flag_reads_from_general_settings() {- let _store = TempStore::new("gpui-flag", None);- assert!(!GeneralSettings::load().enable_gpui_app);-- assert!(super::set_store_setting(- GENERAL_SETTINGS,- "enableGpuiApp",- Value::Bool(true)- ));- assert!(GeneralSettings::load().enable_gpui_app);- }-- /// Both apps have to name the same file, and it has to sit next to the- /// store rather than in a per-app dir.- #[test]- fn the_hand_off_marker_sits_beside_the_store() {- assert_eq!(- 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 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");@@ -2455,59 +2253,6 @@ mod tests {);}- #[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,/// empties and duplicates dropped, first occurrence wins.#[test]diff --git a/apps/desktop-gpui/src/updates.rs b/apps/desktop-gpui/src/updates.rsindex d0a5434ce..1bd5d931f 100644--- a/apps/desktop-gpui/src/updates.rs+++ b/apps/desktop-gpui/src/updates.rs@@ -1,31 +1,36 @@-//! 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 std::{path::PathBuf, time::Duration};use futures_util::future::{Either, select};use gpui::{App, Global};use semver::Version;-use serde::Deserialize;use crate::{+ installer::{self, ArtifactKind, Product, Release},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,+const BUSY_MESSAGE: &str =+ "Finish your recording, export, upload, import, or transcription task before updating Cap.";++#[derive(Clone, Debug, Default, PartialEq)]+pub(crate) enum UpdateStatus {+ #[default]+ Idle,+ Downloading {+ version: Version,+ fraction: Option<f32>,+ },+ Ready {+ version: Version,+ },+ Installing {+ version: Version,+ },}#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]@@ -49,71 +54,22 @@ impl PendingUpdateRequests {}}+struct StagedUpdate {+ kind: ArtifactKind,+ package: PathBuf,+}+struct UpdateScheduler {wake: flume::Sender<()>,pending: PendingUpdateRequests,manual_in_flight: bool,+ status: UpdateStatus,+ staged: Option<StagedUpdate>,+ download: Option<gpui::Task<()>>,}impl Global for UpdateScheduler {}-fn updater_target() -> Result<String, String> {- let arch = if cfg!(target_arch = "aarch64") {- "aarch64"- } else {- "x86_64"- };-- #[cfg(target_os = "linux")]- {- cap_utils::linux_package::updater_target(arch)- }- #[cfg(not(target_os = "linux"))]- {- let platform = if cfg!(target_os = "macos") {- "darwin"- } else {- "windows"- };- Ok(format!("{platform}-{arch}"))- }-}--fn endpoint(channel: UpdateChannel) -> Result<String, String> {- let url = UPDATE_ENDPOINT- .replace("{target}", &updater_target()?)- .replace("{current_version}", env!("CARGO_PKG_VERSION"));- Ok(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,@@ -128,33 +84,45 @@ fn qualifies(&& 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)+fn current_version() -> Result<Version, String> {+ Version::parse(env!("CARGO_PKG_VERSION")).map_err(|error| error.to_string())+}++async fn available_release(channel: UpdateChannel) -> Result<Option<Release>, String> {+ let current = current_version()?;+ let stable = installer::fetch_release(Product::Cap, UpdateChannel::Stable, ¤t).await.map(|candidate| {- candidate.filter(|remote| qualifies(¤t, remote, channel, UpdateChannel::Stable))+ candidate.filter(|remote| {+ qualifies(¤t, &remote.version, channel, UpdateChannel::Stable)+ })});if channel == UpdateChannel::Stable {return stable;}- let nightly = remote_version(UpdateChannel::Nightly)+ let nightly = installer::fetch_release(Product::Cap, UpdateChannel::Nightly, ¤t).await.map(|candidate| {- candidate.filter(|remote| qualifies(¤t, remote, channel, UpdateChannel::Nightly))+ candidate.filter(|remote| {+ qualifies(¤t, &remote.version, channel, UpdateChannel::Nightly)+ })});- select_available_version(stable, nightly)+ select_available_release(stable, nightly)}-fn select_available_version(- stable: Result<Option<Version>, String>,- nightly: Result<Option<Version>, String>,-) -> Result<Option<Version>, String> {+fn select_available_release(+ stable: Result<Option<Release>, String>,+ nightly: Result<Option<Release>, String>,+) -> Result<Option<Release>, String> {match (stable, nightly) {- (Ok(Some(stable)), Ok(Some(nightly))) => Ok(Some(stable.max(nightly))),+ (Ok(Some(stable)), Ok(Some(nightly))) => Ok(Some(if nightly.version > stable.version {+ nightly+ } else {+ stable+ })),(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}");@@ -171,11 +139,47 @@ pub(crate) fn work_in_flight(cx: &mut App) -> bool {|| crate::transcription::work_in_flight()}+pub(crate) fn status(cx: &App) -> UpdateStatus {+ if cx.has_global::<UpdateScheduler>() {+ cx.global::<UpdateScheduler>().status.clone()+ } else {+ UpdateStatus::Idle+ }+}++fn set_status(status: UpdateStatus, cx: &mut App) {+ let scheduler = cx.global_mut::<UpdateScheduler>();+ if scheduler.status == status {+ return;+ }+ scheduler.status = status;+ crate::app_windows::refresh_settings(cx);+}+pub(crate) fn check_manually(cx: &mut App) {if !cx.has_global::<UpdateScheduler>() {return;}+ match status(cx) {+ UpdateStatus::Ready { .. } => {+ prompt_restart(cx);+ return;+ }+ UpdateStatus::Downloading { version, .. } | UpdateStatus::Installing { version } => {+ cx.spawn(async move |_| {+ crate::platform::activate_app();+ crate::platform::alert_dialog(+ "Update Cap",+ &format!("Cap is already getting version {version} ready."),+ );+ })+ .detach();+ return;+ }+ UpdateStatus::Idle => {}+ }+let scheduler = cx.global_mut::<UpdateScheduler>();if !scheduler.pending.request_manual(scheduler.manual_in_flight) {return;@@ -211,12 +215,23 @@ fn finish_manual_check(cx: &mut App, manual: bool) {}}+fn busy_alert(cx: &mut App) {+ cx.spawn(async move |_| {+ crate::platform::activate_app();+ crate::platform::alert_dialog("Cap is busy", BUSY_MESSAGE);+ })+ .detach();+}+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,+ status: UpdateStatus::Idle,+ staged: None,+ download: None,});cx.spawn(async move |cx| {@@ -273,22 +288,13 @@ pub(crate) fn schedule_startup_check(cx: &mut App) {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);- }+ if cx.update(|cx| status(cx) != UpdateStatus::Idle) {+ cx.update(|cx| finish_manual_check(cx, manual));continue;}let result = match cx- .update(|cx| gpui_tokio::Tokio::spawn(cx, available_version(channel)))+ .update(|cx| gpui_tokio::Tokio::spawn(cx, available_release(channel))).await{Ok(result) => result,@@ -308,8 +314,8 @@ pub(crate) fn schedule_startup_check(cx: &mut App) {continue;}- let version = match result {- Ok(Some(version)) => version,+ let release = match result {+ Ok(Some(release)) => release,Ok(None) => {if manual {crate::platform::activate_app();@@ -335,45 +341,268 @@ pub(crate) fn schedule_startup_check(cx: &mut App) {}};- 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);- }+ if !manual && ignored_version.as_ref() == Some(&release.version) {continue;}crate::platform::activate_app();- if crate::platform::confirm_dialog(+ let accepted = crate::platform::confirm_dialog("Update Cap",- &format!("Version {version} of Cap is available. Would you like to install it?"),- "Update",- "Ignore",+ &format!(+ "Version {} of Cap is available. Cap will download it in the background and let you know when it's ready to install.",+ release.version+ ),+ "Download",+ "Not Now",false,- ) {+ );+ cx.update(|cx| finish_manual_check(cx, manual));+ if accepted {+ cx.update(|cx| start_download(release, cx));+ } else {+ ignored_version = Some(release.version);+ }+ }+ })+ .detach();+}++fn start_download(release: Release, cx: &mut App) {+ let kind = match Product::Cap+ .update_platform()+ .and_then(|platform| ArtifactKind::for_platform(&platform))+ {+ Ok(kind) => kind,+ Err(error) => {+ update_failed(&error, cx);+ return;+ }+ };++ let version = release.version.clone();+ set_status(+ UpdateStatus::Downloading {+ version: version.clone(),+ fraction: None,+ },+ cx,+ );++ let (progress_sender, progress) = flume::bounded::<Option<f32>>(1);+ let download = gpui_tokio::Tokio::spawn(cx, async move {+ let mut reported = None::<u16>;+ installer::download(Product::Cap, kind, &release, move |done, total| {+ let fraction = total+ .filter(|total| *total > 0)+ .map(|total| (done as f64 / total as f64).clamp(0., 1.) as f32);+ let step = fraction.map(|fraction| (fraction * 100.) as u16);+ if step != reported {+ reported = step;+ let _ = progress_sender.try_send(fraction);+ }+ })+ .await+ });++ let task = cx.spawn(async move |cx| {+ let progress_version = version.clone();+ let progress_updates = cx.spawn(async move |cx| {+ while let Ok(fraction) = progress.recv_async().await {cx.update(|cx| {- finish_manual_check(cx, manual);- crate::settings_pages::start_update_handoff(cx);+ set_status(+ UpdateStatus::Downloading {+ version: progress_version.clone(),+ fraction,+ },+ cx,+ )});- } else {- ignored_version = Some(version);- cx.update(|cx| finish_manual_check(cx, manual));}+ });++ let result = match download.await {+ Ok(result) => result,+ Err(error) => Err(error.to_string()),+ };+ drop(progress_updates);++ cx.update(|cx| {+ cx.global_mut::<UpdateScheduler>().download = None;+ match result {+ Ok(package) => {+ tracing::info!(%version, path = %package.display(), "update downloaded and verified");+ cx.global_mut::<UpdateScheduler>().staged =+ Some(StagedUpdate { kind, package });+ set_status(UpdateStatus::Ready { version }, cx);+ prompt_restart(cx);+ }+ Err(error) => {+ tracing::warn!(%version, "update download failed: {error}");+ update_failed(&format!("Couldn't download version {version}: {error}"), cx);+ }+ }+ });+ });+ cx.global_mut::<UpdateScheduler>().download = Some(task);+}++fn update_failed(message: &str, cx: &mut App) {+ set_status(UpdateStatus::Idle, cx);+ let message =+ format!("{message}\n\nYou can always download the latest version from cap.so/download.");+ cx.spawn(async move |_| {+ crate::platform::activate_app();+ crate::platform::alert_dialog("Update Cap", &message);+ })+ .detach();+}++fn prompt_restart(cx: &mut App) {+ let UpdateStatus::Ready { version } = status(cx) else {+ return;+ };+ if work_in_flight(cx) {+ tracing::info!(%version, "update ready; waiting for in-flight work before prompting");+ cx.spawn(async move |cx| {+ cx.background_executor().timer(BUSY_RETRY_DELAY).await;+ cx.update(prompt_restart);+ })+ .detach();+ return;+ }++ cx.spawn(async move |cx| {+ crate::platform::activate_app();+ if crate::platform::confirm_dialog(+ "Update Cap",+ &format!("Cap {version} is ready. Restart Cap to finish updating."),+ "Restart Now",+ "Later",+ false,+ ) {+ cx.update(install_and_relaunch);}}).detach();}+pub(crate) fn install_and_relaunch(cx: &mut App) {+ if !cx.has_global::<UpdateScheduler>() {+ return;+ }+ let UpdateStatus::Ready { version } = status(cx) else {+ return;+ };+ if work_in_flight(cx) {+ busy_alert(cx);+ return;+ }+ if let Err(error) = crate::app_windows::flush_pending_editor_saves(cx) {+ cx.spawn(async move |_| {+ crate::platform::alert_dialog("Cap is still open", &error);+ })+ .detach();+ return;+ }+ let Some((package, kind)) = cx+ .global::<UpdateScheduler>()+ .staged+ .as_ref()+ .map(|staged| (staged.package.clone(), staged.kind))+ else {+ return;+ };++ set_status(+ UpdateStatus::Installing {+ version: version.clone(),+ },+ cx,+ );+ cx.spawn(async move |cx| {+ let applied = cx+ .background_executor()+ .spawn(async move { apply(&package, kind) })+ .await;+ cx.update(|cx| match applied {+ Ok(Some(executable)) => {+ tracing::info!(%version, "update installed; relaunching");+ if let Err(error) = crate::permissions::relaunch_executable(&executable, cx) {+ tracing::error!(%error, "could not relaunch after updating");+ crate::menus::quit(cx);+ }+ }+ Ok(None) => {+ tracing::info!(%version, "update installer started; quitting");+ crate::menus::quit(cx);+ }+ Err(error) => {+ tracing::error!(%version, "update install failed: {error}");+ cx.global_mut::<UpdateScheduler>().staged = None;+ update_failed(&format!("Couldn't install version {version}: {error}"), cx);+ }+ });+ })+ .detach();+}++fn apply(package: &std::path::Path, kind: ArtifactKind) -> Result<Option<PathBuf>, String> {+ installer::check_artifact_kind(package, kind)?;+ apply_package(package, kind)+}++#[cfg(target_os = "macos")]+fn apply_package(+ package: &std::path::Path,+ _kind: ArtifactKind,+) -> Result<Option<PathBuf>, String> {+ let executable = std::env::current_exe().map_err(|error| error.to_string())?;+ let bundle = executable+ .ancestors()+ .find(|path| path.extension().is_some_and(|extension| extension == "app"))+ .ok_or_else(|| "This copy of Cap isn't running from an app bundle".to_string())?;+ installer::install_app_bundle(package, bundle)?;+ Ok(Some(executable))+}++#[cfg(windows)]+fn apply_package(+ package: &std::path::Path,+ _kind: ArtifactKind,+) -> Result<Option<PathBuf>, String> {+ installer::launch_installer(package, &["/P", "/R", "/UPDATE"])?;+ Ok(None)+}++#[cfg(target_os = "linux")]+fn apply_package(package: &std::path::Path, kind: ArtifactKind) -> Result<Option<PathBuf>, String> {+ match kind {+ ArtifactKind::Deb => {+ let executable = std::env::current_exe().map_err(|error| error.to_string())?;+ let executable = without_deleted_suffix(&executable);+ installer::install_deb(package)?;+ Ok(Some(executable))+ }+ ArtifactKind::AppImage => {+ let image = std::env::var_os("APPIMAGE")+ .map(PathBuf::from)+ .filter(|path| path.is_absolute())+ .ok_or_else(|| "This copy of Cap isn't running from an AppImage".to_string())?;+ installer::install_appimage(package, &image)?;+ Ok(Some(image))+ }+ ArtifactKind::AppArchive | ArtifactKind::NsisInstaller => {+ Err("This package can't be installed on Linux".to_string())+ }+ }+}++#[cfg(any(target_os = "linux", test))]+fn without_deleted_suffix(executable: &std::path::Path) -> PathBuf {+ let path = executable.to_string_lossy();+ PathBuf::from(path.strip_suffix(" (deleted)").unwrap_or(&path))+}+#[cfg(test)]mod tests {use super::*;@@ -382,6 +611,15 @@ mod tests {Version::parse(value).unwrap()}+ fn release(value: &str) -> Release {+ Release {+ version: version(value),+ url: format!("https://cdn.crabnebula.app/asset/{value}"),+ signature: "c2ln".to_string(),+ notes: None,+ }+ }+#[test]fn stable_channel_accepts_newer_versions_and_explicit_prerelease_downgrades() {assert!(qualifies(@@ -423,20 +661,20 @@ mod tests {#[test]fn nightly_channel_survives_individual_endpoint_failures() {assert_eq!(- select_available_version(Err("stable unavailable".into()), Ok(Some(version("0.6.1"))))+ select_available_release(Err("stable unavailable".into()), Ok(Some(release("0.6.1")))).unwrap(),- Some(version("0.6.1")),+ Some(release("0.6.1")),);assert_eq!(- select_available_version(- Ok(Some(version("0.6.2"))),+ select_available_release(+ Ok(Some(release("0.6.2"))),Err("nightly unavailable".into())).unwrap(),- Some(version("0.6.2")),+ Some(release("0.6.2")),);assert_eq!(- select_available_version(+ select_available_release(Err("stable unavailable".into()),Err("nightly unavailable".into()),),@@ -447,12 +685,20 @@ mod tests {#[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"))),+ select_available_release(+ Ok(Some(release("0.6.1"))),+ Ok(Some(release("0.6.2-nightly.4"))),).unwrap(),- Some(version("0.6.2-nightly.4")),+ Some(release("0.6.2-nightly.4")),+ );+ assert_eq!(+ select_available_release(+ Ok(Some(release("0.6.3"))),+ Ok(Some(release("0.6.3-nightly.9"))),+ )+ .unwrap(),+ Some(release("0.6.3")),);}@@ -519,4 +765,16 @@ mod tests {assert!(!phase.is_busy());}}++ #[test]+ fn deb_relaunch_targets_the_installed_path_even_after_replacement() {+ assert_eq!(+ without_deleted_suffix(std::path::Path::new("/usr/bin/Cap (deleted)")),+ PathBuf::from("/usr/bin/Cap")+ );+ assert_eq!(+ without_deleted_suffix(std::path::Path::new("/usr/bin/Cap")),+ PathBuf::from("/usr/bin/Cap")+ );+ }}diff --git a/apps/desktop-gpui/tauri.conf.json b/apps/desktop-gpui/tauri.conf.jsonnew file mode 100644index 000000000..bd7d7b2ea--- /dev/null+++ b/apps/desktop-gpui/tauri.conf.json@@ -0,0 +1,100 @@+{+ "$schema": "https://schema.tauri.app/config/2",+ "productName": "Cap",+ "mainBinaryName": "Cap",+ "identifier": "so.cap.desktop",+ "plugins": {+ "updater": {+ "endpoints": [+ "https://cdn.crabnebula.app/update/cap/cap/{{target}}/{{current_version}}"+ ],+ "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEUyOTAzOTdFNzJFQkRFOTMKUldTVDN1dHlmam1RNHFXb1VYTXlrQk1iMFFkcjN0YitqZlA5WnZNY0ZtQ1dvM1dxK211M3VIYUQK"+ },+ "deep-link": {+ "desktop": {+ "schemes": ["cap-desktop"]+ }+ }+ },+ "bundle": {+ "active": true,+ "createUpdaterArtifacts": true,+ "targets": "all",+ "category": "Video",+ "longDescription": "Cap is the open source alternative to Loom. Lightweight, powerful, and cross-platform. Record and share in seconds.",+ "externalBin": [+ "../desktop/src-tauri/binaries/cap-muxer",+ "../desktop/src-tauri/binaries/cap-cli"+ ],+ "icon": [+ "../desktop/src-tauri/icons/32x32.png",+ "../desktop/src-tauri/icons/128x128.png",+ "../desktop/src-tauri/icons/[email protected]",+ "../desktop/src-tauri/icons/macos/icon.icns",+ "../desktop/src-tauri/icons/icon.ico"+ ],+ "resources": {+ "../desktop/src-tauri/assets/backgrounds/macOS/*": "assets/backgrounds/macOS/",+ "../desktop/src-tauri/assets/backgrounds/blue/*": "assets/backgrounds/blue/",+ "../desktop/src-tauri/assets/backgrounds/cities/*": "assets/backgrounds/cities/",+ "../desktop/src-tauri/assets/backgrounds/dark/*": "assets/backgrounds/dark/",+ "../desktop/src-tauri/assets/backgrounds/orange/*": "assets/backgrounds/orange/",+ "../desktop/src-tauri/assets/backgrounds/purple/*": "assets/backgrounds/purple/",+ "../desktop/src/assets/music/*.mp3": "assets/music/"+ },+ "fileAssociations": [+ {+ "ext": ["cap"],+ "name": "Cap Project",+ "mimeType": "application/x-cap-project",+ "role": "Editor"+ }+ ],+ "macOS": {+ "minimumSystemVersion": "12.3",+ "entitlements": "../desktop/src-tauri/Entitlements.plist",+ "frameworks": ["../../target/native-deps/Spacedrive.framework"],+ "dmg": {+ "background": "../desktop/src-tauri/assets/dmg-background.png",+ "appPosition": {+ "x": 180,+ "y": 140+ },+ "applicationFolderPosition": {+ "x": 480,+ "y": 140+ }+ }+ },+ "windows": {+ "nsis": {+ "headerImage": "../desktop/src-tauri/assets/nsis-header.bmp",+ "sidebarImage": "../desktop/src-tauri/assets/nsis-sidebar.bmp",+ "installerIcon": "../desktop/src-tauri/icons/icon.ico",+ "installerHooks": "packaging/windows/installer-hooks.nsh"+ },+ "webviewInstallMode": {+ "type": "skip"+ }+ },+ "linux": {+ "deb": {+ "depends": [+ "libva2",+ "libva-drm2",+ "pulseaudio-utils",+ "libpipewire-0.3-0",+ "libasound2t64 | libasound2",+ "libxkbcommon0",+ "libxkbcommon-x11-0",+ "libx11-6",+ "libssl3t64 | libssl3",+ "libwayland-client0",+ "libwayland-egl1",+ "libegl1",+ "libvulkan1"+ ]+ }+ }+ }+}