Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
refactor: ship only the GPUI app and drop Cap Classic
Cursor Agent5b23d57743d0
diff --git a/AGENTS.md b/AGENTS.mdindex 18a3723b2..af1f3b7fe 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -50,7 +50,7 @@ Additionally, `unused_must_use = "deny"` applies to all Rust code: every `Result## Project Structure & Modules- Turborepo monorepo:- - `apps/desktop-gpui` (GPUI, ships as Cap), `apps/desktop` (Tauri v2 + SolidStart, ships separately as Cap Classic), `apps/web` (Next.js), `apps/cli` (Rust CLI).+ - `apps/desktop-gpui` (GPUI, ships as Cap), `apps/desktop` (Tauri v2 + SolidStart; last shipped in 0.6.0, kept for the dev harness), `apps/web` (Next.js), `apps/cli` (Rust CLI).- `packages/*` shared libs (e.g., `database`, `ui`, `ui-solid`, `utils`, `web-*`).- `crates/*` Rust media/recording/rendering/camera crates.- `scripts/*`, `infra/`, and `packages/local-docker/` for tooling and local services.@@ -59,7 +59,7 @@ Additionally, `unused_must_use = "deny"` applies to all Rust code: every `Result## Build, Test, Develop- Install: `bun install`; setup: `bun run env-setup` then `bun run cap-setup`.- Dev: `bun run dev` (web+desktop). Desktop only: `bun run dev:desktop`. Web only: `bun run dev:web` or `cd apps/web && bun run dev`.-- Build: `bun run build` (Turbo). Desktop release: `bun run gpui:build <target>` for Cap (GPUI) and `bun run tauri:build` for Cap Classic (Tauri).+- Build: `bun run build` (Turbo). Desktop release: `bun run gpui:build <target>` (Cap ships as the GPUI app only).- DB: `bun run db:generate` → `bun run db:push` → `bun run db:studio`.- Docker: `bun run docker:up | docker:stop | docker:clean`.- Quality: `bun run lint`, `bun run format`, `bun run typecheck`. Rust: `cargo build -p <crate>`, `cargo test -p <crate>`.diff --git a/apps/desktop-gpui/README.md b/apps/desktop-gpui/README.mdindex 7cfd99563..d2736cc2e 100644--- a/apps/desktop-gpui/README.md+++ b/apps/desktop-gpui/README.md@@ -3,9 +3,9 @@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).+This is the app that ships as **Cap**, from 0.6.1 on. The Tauri app in+`apps/desktop` last shipped in 0.6.0 and is kept only for the dev harness; see+[Shipping and updates](#shipping-and-updates).The main recording window uses a fixed 330×432 layout with device controlsand recording and screenshot browsers. The expanded view is no longer available.@@ -72,7 +72,7 @@ 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+## Shipping and updates### How Cap is packaged@@ -91,8 +91,8 @@ with what installed copies of the Tauri app already update through: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 update to 0.6.1 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 abyte-identical copy of `cap-cli`, and the self-test now runs `cap-cli`@@ -122,21 +122,14 @@ Tauri app used, and `src/installer.rs` does the rest without Tauri:Progress shows in the settings sidebar footer, and the update never installswhile 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.+### The Tauri app++Releases no longer build the Tauri app. 0.6.0 was its last version, and the+website's [all versions](https://cap.so/download/versions) page keeps it+downloadable. In a debug build started from `target/`, Settings → Experimental+still has the **Cap GPUI** switch that hands the session back to the Tauri+app running under `bun run dev:desktop`, through the dev supervisor+(`store::request_classic_reopen` and `cap-classic.pending`).## What is implementeddiff --git a/apps/desktop-gpui/src/classic.rs b/apps/desktop-gpui/src/classic.rsdeleted file mode 100644index 9aa252577..000000000--- a/apps/desktop-gpui/src/classic.rs+++ /dev/null@@ -1,268 +0,0 @@-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/installer.rs b/apps/desktop-gpui/src/installer.rsindex b5b2af5c8..8bd907c10 100644--- a/apps/desktop-gpui/src/installer.rs+++ b/apps/desktop-gpui/src/installer.rs@@ -18,40 +18,24 @@ 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",- }- }+const STAGING_SLUG: &str = "cap";- 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)),- }- }+pub(crate) fn update_platform() -> Result<String, String> {+ let arch = if cfg!(target_arch = "aarch64") {+ "aarch64"+ } else {+ "x86_64"+ };+ platform_for(arch)}#[cfg(target_os = "linux")]-fn cap_update_platform(arch: &str) -> Result<String, String> {+fn platform_for(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> {+fn platform_for(arch: &str) -> Result<String, String> {let os = if cfg!(target_os = "macos") {"darwin"} else {@@ -60,16 +44,6 @@ fn cap_update_platform(arch: &str) -> Result<String, String> {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,@@ -93,16 +67,12 @@ impl ArtifactKind {}}- 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 file_name(self) -> &'static str {+ match self {+ Self::AppArchive => "Cap.app.tar.gz",+ Self::NsisInstaller => "Cap-setup.exe",+ Self::Deb => "Cap.deb",+ Self::AppImage => "Cap.AppImage",}}@@ -171,11 +141,10 @@ fn client() -> Result<reqwest::Client, String> {}pub(crate) async fn fetch_release(- product: Product,channel: UpdateChannel,current: &Version,) -> Result<Option<Release>, String> {- let platform = product.update_platform()?;+ let platform = update_platform()?;let response = client()?.get(endpoint(&platform, channel, current)).timeout(METADATA_TIMEOUT)@@ -183,10 +152,8 @@ pub(crate) async fn fetch_release(.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),- _ => {}+ if response.status() == reqwest::StatusCode::NO_CONTENT {+ return Ok(None);}let body = response@@ -304,7 +271,6 @@ fn prune_other_versions(product_dir: &Path, keep: &Path) {}pub(crate) async fn download(- product: Product,kind: ArtifactKind,release: &Release,mut progress: impl FnMut(u64, Option<u64>) + Send,@@ -312,7 +278,6 @@ pub(crate) async fn download(download_into(&staging_root(),UPDATER_PUBLIC_KEY,- product,kind,release,&mut progress,@@ -323,16 +288,15 @@ pub(crate) async fn download(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 product_dir = root.join(STAGING_SLUG);let version_dir = product_dir.join(release.version.to_string());- let destination = version_dir.join(kind.file_name(product));+ let destination = version_dir.join(kind.file_name());if destination.is_file() && verify_file(&destination, &key, &signature).is_ok() {prune_other_versions(&product_dir, &version_dir);@@ -340,7 +304,7 @@ async fn download_into(}std::fs::create_dir_all(&version_dir).map_err(|error| error.to_string())?;- let partial = version_dir.join(format!("{}.partial", kind.file_name(product)));+ let partial = version_dir.join(format!("{}.partial", kind.file_name()));if let Err(error) = stream_to_file(&partial, &key, &signature, release, progress).await {let _ = std::fs::remove_file(&partial);return Err(error);@@ -718,20 +682,15 @@ mod tests {"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"+ endpoint("windows-x86_64", UpdateChannel::Nightly, ¤t),+ "https://cdn.crabnebula.app/update/cap/cap/windows-x86_64/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");- }+ fn update_platforms_map_to_their_artifact_kinds() {assert_eq!(- ArtifactKind::for_platform("linux-x86_64-appimage-classic"),+ ArtifactKind::for_platform("linux-x86_64-appimage"),Ok(ArtifactKind::AppImage));assert_eq!(@@ -739,7 +698,7 @@ mod tests {Ok(ArtifactKind::Deb));assert_eq!(- ArtifactKind::for_platform("darwin-aarch64-classic"),+ ArtifactKind::for_platform("darwin-aarch64"),Ok(ArtifactKind::AppArchive));assert_eq!(@@ -747,6 +706,10 @@ mod tests {Ok(ArtifactKind::NsisInstaller));assert!(ArtifactKind::for_platform("linux-x86_64-rpm").is_err());+ if !cfg!(target_os = "linux") {+ let platform = update_platform().unwrap();+ assert!(ArtifactKind::for_platform(&platform).is_ok(), "{platform}");+ }}#[test]@@ -777,7 +740,7 @@ mod tests {.build().unwrap();let root = scratch("download");- let stale = root.join("cap-classic").join("0.0.1");+ let stale = root.join("cap").join("0.0.1");std::fs::create_dir_all(&stale).unwrap();let (url, server) = serve_once(b"test");@@ -786,17 +749,13 @@ mod tests {.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!(downloaded, root.join("cap/9.9.9/Cap.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))));@@ -807,7 +766,6 @@ mod tests {.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"),@@ -848,7 +806,6 @@ mod tests {.block_on(download_into(&root,&encode(TEST_KEY),- Product::Cap,ArtifactKind::AppImage,&release(url),&mut |_, _| {},@@ -904,7 +861,7 @@ mod tests {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");+ let destination = root.join("Applications").join("Cap.AppImage");install_appimage(&source, &destination).unwrap();assert_eq!(std::fs::read(&destination).unwrap(), b"\x7fELFnew");assert_eq!(diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rsindex 4ecec3eae..57f4c0f3a 100644--- a/apps/desktop-gpui/src/main.rs+++ b/apps/desktop-gpui/src/main.rs@@ -14,7 +14,6 @@ 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;diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rsindex b8eace042..bb40305b7 100644--- a/apps/desktop-gpui/src/settings_pages.rs+++ b/apps/desktop-gpui/src/settings_pages.rs@@ -1906,7 +1906,6 @@ impl SettingsWindow {pub(crate) enum SwitchBack {Running(std::time::Instant),- Downloading(Option<f32>),WaitingForClassic,Failed(String),}@@ -1914,11 +1913,9 @@ pub(crate) enum SwitchBack {/// 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);const SWITCH_SENTENCES: &[&str] = &[- "Switching to Cap Classic.",+ "Switching back to the classic Cap app.","Your recordings and settings stay exactly where they are.",];const SWITCH_SENTENCE_MS: u64 = 2000;@@ -1949,49 +1946,25 @@ fn takeover_frame(elapsed_ms: f32) -> (usize, f32, u32) {(index, alpha, remaining)}-#[derive(Debug, PartialEq)]-enum ClassicTarget {- 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: 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)+/// Cap ships as this app alone, so the classic Tauri app only exists inside+/// the `tauri dev` harness: a debug cargo build can hand the session back to+/// it through the dev-session supervisor (`store::request_classic_reopen`),+/// and nothing else has a classic app to switch to.+fn dev_supervisor_available_for(exe: Option<&std::path::Path>, debug_build: bool) -> bool {+ debug_build+ && exe.is_some_and(|exe| {+ exe.components()+ .any(|component| component.as_os_str() == "target")+ })}-fn classic_target() -> ClassicTarget {- let exe = std::env::current_exe().ok();- classic_target_for(- exe.as_deref(),+fn dev_supervisor_available() -> bool {+ dev_supervisor_available_for(+ std::env::current_exe().ok().as_deref(),cfg!(debug_assertions),- crate::classic::installed,)}-fn switch_blocked_message() -> String {- "Finish your recording, export, upload, import, or transcription task before switching to Cap Classic."- .to_string()-}--fn classic_download_failed(error: &str) -> String {- format!("Couldn't install Cap Classic: {error}")-}-impl SettingsWindow {pub(crate) fn render_experimental(&self, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {// No "Native camera preview" toggle here: in this app the native@@ -1999,7 +1972,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.- vec![+ let mut sections = vec![self.section("Reliability",None,@@ -2031,33 +2004,39 @@ impl SettingsWindow {],).into_any_element(),- self.section(- "Cap Classic",- None,- None,- vec![self.rows(vec![self.classic_app_row(cx)]).into_any_element()],- )- .into_any_element(),- ]+ ];+ if dev_supervisor_available() {+ sections.push(+ self.section(+ "Native app",+ None,+ None,+ vec![self.rows(vec![self.native_app_row(cx)]).into_any_element()],+ )+ .into_any_element(),+ );+ }+ sections}- fn classic_app_row(&self, cx: &mut Context<Self>) -> gpui::AnyElement {- let busy = self.pages.switch_back.is_some();+ /// The dev harness's Native app row: being in this app is what the toggle+ /// means, and turning it off reopens the classic app under `tauri dev`.+ fn native_app_row(&self, cx: &mut Context<Self>) -> gpui::AnyElement {+ let checked = !matches!(self.pages.switch_back, Some(SwitchBack::Running(_)));self.setting_row(- "Switch to Cap Classic",+ "Cap GPUI",Some(- "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.",+ "You are using the native version of Cap. Turning this off closes it and reopens \+ the classic app in the dev harness. Your recordings and settings are shared.",),- self.button(- "switch-to-classic",- (ui::ButtonVariant::Dark, None),- "Switch",- busy,- cx,- |this, _, cx| this.start_switch_back(cx),- )+ 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),+ }+ }).into_any_element(),)}@@ -2080,24 +2059,6 @@ 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) =@@ -2123,62 +2084,36 @@ impl SettingsWindow {.child(SWITCH_SENTENCES[index]),);}- 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()- .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_size(px(17.))+ .font_weight(FontWeight::SEMIBOLD).text_center()- .text_color(rgb(0xf87171))- .child(SharedString::from(error.clone())),+ .text_color(white)+ .child("Opening the classic Cap app"),).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"),+ .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."),);}+ 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.@@ -2261,91 +2196,25 @@ impl SettingsWindow {return false;}- self.pages.switch_back = Some(SwitchBack::Failed(switch_blocked_message()));+ self.pages.switch_back = Some(SwitchBack::Failed(+ "Finish your recording, export, upload, import, or transcription task before switching to the classic app."+ .to_string(),+ ));cx.notify();true}+ /// Hand the session (`enableGpuiApp`) to the classic dev app, ask the dev+ /// supervisor to start it, then quit once it is visible.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),- }- }-- 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) {+ if !dev_supervisor_available() {+ self.pages.switch_back = Some(SwitchBack::Failed(+ "Couldn't find the classic Cap app to switch back to.".to_string(),+ ));+ cx.notify();return;}if let Err(error) = crate::app_windows::flush_pending_editor_saves(cx) {@@ -2361,13 +2230,6 @@ impl SettingsWindow {cx.notify();return;}- let timeout = if dev {- CLASSIC_WAIT_TIMEOUT- } else if launch.is_none() {- CLASSIC_INSTALL_WAIT_TIMEOUT- } else {- CLASSIC_LAUNCH_WAIT_TIMEOUT- };let pending = store::mark_classic_pending();self.pages.switch_back = Some(SwitchBack::WaitingForClassic);self.pages.switch_back_ticker = None;@@ -2377,46 +2239,40 @@ impl SettingsWindow {cx.spawn(async move |this, cx| {let result = cx.background_executor()- .spawn(async move {- pending?;- match (launch, dev) {- (_, true) => store::request_classic_reopen(),- (Some(path), false) => crate::classic::launch(&path),- (None, false) => Ok(()),- }- })+ .spawn(async move { pending.and_then(|()| store::request_classic_reopen()) }).await;let mut failure = result.err()- .map(|error| format!("Couldn't open Cap Classic: {error}"));+ .map(|error| format!("Couldn't open the classic Cap app: {error}"));let started = std::time::Instant::now();while failure.is_none() {match store::classic_pending_path().try_exists() {Ok(false) => {- tracing::info!("Cap Classic is visible; quitting");+ tracing::info!("classic app is visible; quitting GPUI");cx.update(crate::menus::quit);return;}Ok(true) => {}Err(error) => {- failure = Some(format!("Couldn't check whether Cap Classic opened: {error}"));+ failure = Some(format!(+ "Couldn't check whether the classic Cap app opened: {error}"+ ));break;}}- if started.elapsed() >= timeout {- failure = Some(if dev {+ if started.elapsed() >= CLASSIC_WAIT_TIMEOUT {+ failure = Some("The classic app hasn't opened. Check the dev terminal for build errors, then try again."- .to_string()- } else {- "Cap Classic hasn't opened. Cap is still here; please try again.".to_string()- });+ .to_string(),+ );break;}cx.background_executor().timer(Duration::from_millis(250)).await;}- let message = failure.unwrap_or_else(|| "Couldn't open Cap Classic.".to_string());+ let message =+ failure.unwrap_or_else(|| "Couldn't open the classic Cap app.".to_string());tracing::error!("{message}");store::clear_classic_pending();store::set_store_setting(GENERAL_SETTINGS, "enableGpuiApp", Value::Bool(true));@@ -6240,8 +6096,8 @@ impl SettingsWindow {self.section("Automations",Some(- "Rules are shared with Cap Classic and the Cap CLI. Cap saves these \- rules but does not run automations yet.",+ "Rules are shared with the Cap CLI. Cap saves these rules but does not \+ run automations yet.",),None,rule_content,@@ -6829,8 +6685,8 @@ impl SettingsWindow {.line_height(px(18.)).text_color(Hsla::from(theme.amber_11)).child(- "In Cap Classic or the Cap CLI, this automation runs commands or sends \- network requests with your permissions. Only use values you trust.",+ "In the Cap CLI, this automation runs commands or sends network \+ requests with your permissions. Only use values you trust.",),)})@@ -6843,8 +6699,7 @@ impl SettingsWindow {.text_color(Hsla::from(theme.amber_11)).child("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.",+ Saved rules remain available to the Cap CLI. No actions were run.",),)})@@ -8361,43 +8216,16 @@ mod tests {}#[test]- fn the_classic_target_matches_the_launch_context() {+ fn only_debug_cargo_builds_can_switch_back_to_the_dev_harness() {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(Some(cargo_build), true, || panic!(- "dev builds use the harness"- )),- ClassicTarget::DevSupervisor- );- assert_eq!(- classic_target_for(Some(cargo_build), false, || Some(classic.clone())),- ClassicTarget::Installed(classic.clone())- );- assert_eq!(- 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 failed_classic_installs_explain_the_cause() {- assert_eq!(- classic_download_failed("The download stopped responding"),- "Couldn't install Cap Classic: The download stopped responding"- );- assert!(switch_blocked_message().contains("Cap Classic"));+ assert!(dev_supervisor_available_for(Some(cargo_build), true));+ assert!(!dev_supervisor_available_for(Some(cargo_build), false));+ assert!(!dev_supervisor_available_for(Some(installed_app), true));+ assert!(!dev_supervisor_available_for(Some(installed_app), false));+ assert!(!dev_supervisor_available_for(None, true));}/// The takeover's whole timeline, read off its one clock.diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rsindex 681e990c2..9ac2e4f9a 100644--- a/apps/desktop-gpui/src/single_instance.rs+++ b/apps/desktop-gpui/src/single_instance.rs@@ -1267,8 +1267,8 @@ mod tests {}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")));+ assert!(!is_cap_gpui_image(Path::new("Cap Helper")));+ assert!(!is_cap_gpui_image(Path::new("cap-cli")));}#[cfg(target_os = "linux")]diff --git a/apps/desktop-gpui/src/updates.rs b/apps/desktop-gpui/src/updates.rsindex 1bd5d931f..4517fb26b 100644--- a/apps/desktop-gpui/src/updates.rs+++ b/apps/desktop-gpui/src/updates.rs@@ -5,7 +5,7 @@ use gpui::{App, Global};use semver::Version;use crate::{- installer::{self, ArtifactKind, Product, Release},+ installer::{self, ArtifactKind, Release},session::RecordingSession,store::{GeneralSettings, UpdateChannel},};@@ -90,7 +90,7 @@ fn current_version() -> Result<Version, 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)+ let stable = installer::fetch_release(UpdateChannel::Stable, ¤t).await.map(|candidate| {candidate.filter(|remote| {@@ -102,7 +102,7 @@ async fn available_release(channel: UpdateChannel) -> Result<Option<Release>, Streturn stable;}- let nightly = installer::fetch_release(Product::Cap, UpdateChannel::Nightly, ¤t)+ let nightly = installer::fetch_release(UpdateChannel::Nightly, ¤t).await.map(|candidate| {candidate.filter(|remote| {@@ -368,8 +368,7 @@ pub(crate) fn schedule_startup_check(cx: &mut App) {}fn start_download(release: Release, cx: &mut App) {- let kind = match Product::Cap- .update_platform()+ let kind = match installer::update_platform().and_then(|platform| ArtifactKind::for_platform(&platform)){Ok(kind) => kind,@@ -391,7 +390,7 @@ fn start_download(release: Release, cx: &mut App) {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| {+ installer::download(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);diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 047ceef37..1b7ebd5e9 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -2,9 +2,11 @@"name": "@cap/desktop","type": "module","scripts": {- "dev": "bun run --cwd ../.. cap-setup && bun run build:sidecar && dotenv -e ../../.env -- bun run preparescript && dotenv -e ../../.env -- node ../../scripts/dev-desktop.mjs",- "build:tauri": "bun run build:sidecar && dotenv -e ../../.env -- bun run preparescript --release && dotenv -e ../../.env -- bun run tauri build",+ "dev": "bun run --cwd ../.. cap-setup && bun run build:sidecar && bun run build:gpui:dev && dotenv -e ../../.env -- bun run preparescript && dotenv -e ../../.env -- node ../../scripts/dev-desktop.mjs",+ "build:tauri": "bun run build:sidecar && bun run build:gpui && dotenv -e ../../.env -- bun run preparescript --release && node ../../scripts/verify-gpui-release-inputs.mjs && dotenv -e ../../.env -- bun run tauri build","build:sidecar": "node ../../scripts/build-desktop-binaries.mjs",+ "build:gpui": "node ../../scripts/run-gpui-build.mjs release",+ "build:gpui:dev": "dotenv -e ../../.env -- node ../../scripts/run-gpui-build.mjs debug","preparescript": "node scripts/prepare.js","localdev": "dotenv -e ../../.env -- vinxi dev --port 3002","build": "vinxi build",diff --git a/apps/desktop/scripts/prepare.js b/apps/desktop/scripts/prepare.jsindex 0abaa288c..66df72366 100644--- a/apps/desktop/scripts/prepare.js+++ b/apps/desktop/scripts/prepare.js@@ -3,6 +3,7 @@import * as fs from "node:fs/promises";import * as path from "node:path";import { fileURLToPath } from "node:url";+import { shouldBundleGpui } from "../../../scripts/run-gpui-build.mjs";const __filename = fileURLToPath(import.meta.url);const __dirname = path.dirname(__filename);@@ -71,10 +72,39 @@ export async function createTauriPlatformConfigs(configOptions = undefined,) {const srcTauri = path.join(__dirname, "../src-tauri/");+ const profile = process.argv.includes("--release") ? "release" : "debug";+ const hostArchitecture = process.arch === "arm64" ? "aarch64" : "x86_64";+ const hostTargets = {+ darwin: `${hostArchitecture}-apple-darwin`,+ win32: `${hostArchitecture}-pc-windows-msvc`,+ linux: `${hostArchitecture}-unknown-linux-gnu`,+ };+ const target = process.env.RUST_TARGET_TRIPLE ?? hostTargets[platform];+ const extension = platform === "win32" ? ".exe" : "";+ const sidecarAvailable = target+ ? await fs+ .access(+ path.join(srcTauri, "binaries", `cap-gpui-${target}${extension}`),+ )+ .then(() => true)+ .catch(() => false)+ : false;+ const developmentWorkspaceAvailable = await fs+ .access(path.join(__dirname, "../../desktop-gpui/dev.sh"))+ .then(() => true)+ .catch(() => false);+ const includeGpui = shouldBundleGpui(+ platform,+ process.env,+ profile,+ sidecarAvailable,+ developmentWorkspaceAvailable,+ );const externalBin = ["binaries/cap-muxer","binaries/cap-exporter","binaries/cap-cli",+ ...(includeGpui ? ["binaries/cap-gpui"] : []),];let baseConfig = {};let configFileName = null;diff --git a/apps/desktop/scripts/prepare.test.js b/apps/desktop/scripts/prepare.test.jsindex b0d48edca..e43e2816d 100644--- a/apps/desktop/scripts/prepare.test.js+++ b/apps/desktop/scripts/prepare.test.js@@ -3,14 +3,14 @@ import { createLinuxBundleConfig } from "../../../scripts/linux-bundle-config.mjimport { deepMerge } from "./prepare.js";describe("Tauri platform release configuration", () => {- it("preserves generated Linux shared-library mappings when adding sidecars", () => {+ it("preserves generated Linux shared-library mappings when adding GPUI", () => {const existing = createLinuxBundleConfig(["libavcodec.so.61"]);const merged = deepMerge(existing, {- bundle: { externalBin: ["binaries/cap-cli"] },+ bundle: { externalBin: ["binaries/cap-gpui"] },});- expect(merged.bundle.externalBin).toEqual(["binaries/cap-cli"]);+ expect(merged.bundle.externalBin).toEqual(["binaries/cap-gpui"]);for (const format of ["deb", "rpm", "appimage"]) {expect(merged.bundle.linux[format]).toEqual(existing.bundle.linux[format],@@ -22,14 +22,14 @@ describe("Tauri platform release configuration", () => {const merged = deepMerge({bundle: {- externalBin: ["binaries/cap-cli"],+ externalBin: ["binaries/cap-cli", "binaries/cap-gpui"],resources: { "ffmpeg/*.dll": "./" },},},{ bundle: { windows: { wix: { version: "0.6.0" } } } },);- expect(merged.bundle.externalBin).toEqual(["binaries/cap-cli"]);+ expect(merged.bundle.externalBin).toContain("binaries/cap-gpui");expect(merged.bundle.resources).toEqual({ "ffmpeg/*.dll": "./" });expect(merged.bundle.windows.wix.version).toBe("0.6.0");});diff --git a/apps/desktop/scripts/prodBeforeBundle.js b/apps/desktop/scripts/prodBeforeBundle.jsindex c74f10c30..ca477fd70 100644--- a/apps/desktop/scripts/prodBeforeBundle.js+++ b/apps/desktop/scripts/prodBeforeBundle.js@@ -55,7 +55,7 @@ async function findReleaseBinary() {async function findReleaseFile(releaseDir) {if (!(await fileExists(releaseDir))) return null;const releaseFiles = await fs.readdir(releaseDir);- for (const name of ["Cap Classic", "cap-desktop"]) {+ for (const name of ["Cap", "cap-desktop"]) {if (releaseFiles.includes(name)) return name;}diff --git a/apps/desktop/src-tauri/nsis/installer-hooks.nsh b/apps/desktop/src-tauri/nsis/installer-hooks.nshdeleted file mode 100644index 58b8c9466..000000000--- a/apps/desktop/src-tauri/nsis/installer-hooks.nsh+++ /dev/null@@ -1,4 +0,0 @@-!macro NSIS_HOOK_PREUNINSTALL- StrCpy $DeleteAppDataCheckboxState 0- DetailPrint "Keeping recordings and settings, which Cap Classic shares with Cap."-!macroenddiff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rsindex f6ea12626..5a1c296f1 100644--- a/apps/desktop/src-tauri/src/general_settings.rs+++ b/apps/desktop/src-tauri/src/general_settings.rs@@ -254,8 +254,9 @@ pub struct GeneralSettingsStore {pub camera_blur_disabled_by_crash: Option<String>,#[serde(default)]pub update_channel: UpdateChannel,- /// Whether Cap, rather than this app, owns the session. Both apps' switch- /// flows write it and the GPUI dev loop (`apps/desktop-gpui/dev.sh`) reads it.+ /// Run the experimental gpui-native app (`cap-gpui`) *instead of* this one:+ /// while enabled, startup hands off to it and exits, and the native app's+ /// own Experimental page hands back. See `gpui_app.rs`.#[serde(default)]pub enable_gpui_app: bool,}diff --git a/apps/desktop/src-tauri/src/gpui_app.rs b/apps/desktop/src-tauri/src/gpui_app.rsindex 1c4828705..89cba6c70 100644--- a/apps/desktop/src-tauri/src/gpui_app.rs+++ b/apps/desktop/src-tauri/src/gpui_app.rs@@ -1,31 +1,141 @@-//! Cap Classic's half of switching between it and Cap.+//! Handing this app off to the experimental gpui-native app (`cap-gpui`).//!-//! Cap is installed separately and shares this app's settings store and-//! recordings library under the `so.cap.desktop` data directory. When the user-//! switches here from Cap, Cap writes `cap-classic.pending` before opening this-//! app and quits only once the marker is gone, so this side deletes it as soon-//! as one of its windows is visible. `enableGpuiApp` in the shared store-//! records which app owns the session; the GPUI dev loop reads it to decide-//! whether to launch.+//! The two apps already share one settings store and recordings library+//! (`apps/desktop-gpui/src/store.rs` reads this app's), so the `enable_gpui_app`+//! setting is not "run both": whichever app is enabled owns the session. Turning+//! it on spawns `cap-gpui` and exits this app; turning it off inside `cap-gpui`+//! reopens this one. Startup honours the same flag, so the handoff survives a+//! relaunch.+//!+//! The binary is discovered in order: `CAP_GPUI_BIN` (explicit override), the+//! installed executable directory (where Tauri bundles and signs sidecars), the+//! legacy `gpui/` resource dir, and -- in debug builds only -- the sibling+//! `apps/desktop-gpui` target dir, so the toggle works from a source checkout.+//!+//! ## The handoff marker+//!+//! A handoff that spawns a `cap-gpui` which then dies immediately would leave+//! the user with no app at all, and with a setting that keeps redirecting away+//! from the app that does work. So this side writes `cap-gpui.handoff` next to+//! the shared store before spawning, and `cap-gpui` deletes it only on clean+//! shutdown. With no live GPUI process, a surviving marker means the previous+//! session exited unexpectedly: clear the flag, tell the user, and start normally.-use std::path::{Path, PathBuf};+use std::path::PathBuf;use tauri::{AppHandle, Manager};+use tauri_plugin_dialog::DialogExt;use tracing::{info, warn};use crate::general_settings::GeneralSettingsStore;-#[cfg(target_os = "macos")]-const CAP_BUNDLE_NAME: &str = "Cap.app";#[cfg(windows)]-const CAP_EXECUTABLE_NAME: &str = "Cap.exe";-#[cfg(all(debug_assertions, windows))]-const DEV_BINARY_NAME: &str = "cap-gpui.exe";-#[cfg(all(debug_assertions, not(windows)))]-const DEV_BINARY_NAME: &str = "cap-gpui";--/// Mirror of `store::app_data_dir` in `apps/desktop-gpui`: Cap always reads-/// the production identifier's directory, even when this is a `.dev` build.+const BINARY_NAME: &str = "cap-gpui.exe";+#[cfg(not(windows))]+const BINARY_NAME: &str = "cap-gpui";++#[cfg(any(target_os = "macos", windows, test))]+const MAX_FORWARDED_DEEP_LINK_BYTES: usize = 1024 * 1024;++#[cfg(any(target_os = "macos", windows, test))]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct GpuiForwardingEndpoint {+ pid: u32,+ port: u16,+ secret: u64,+}++#[cfg(any(target_os = "macos", test))]+#[derive(Default)]+pub(crate) struct StartupRedirectState {+ phase: std::sync::atomic::AtomicU8,+ reopen_pid: Option<u32>,+}++#[cfg(any(target_os = "macos", test))]+impl StartupRedirectState {+ fn with_reopen(pid: u32) -> Self {+ Self {+ reopen_pid: Some(pid),+ ..Self::default()+ }+ }++ pub(crate) fn begin_forwarding(&self) -> bool {+ self.transition(0, 1)+ }++ pub(crate) fn exit_if_pending(&self) -> Option<Option<u32>> {+ self.transition(0, 2).then_some(self.reopen_pid)+ }++ pub(crate) fn exit_after_forwarding(&self) -> bool {+ self.transition(1, 2)+ }++ fn transition(&self, from: u8, to: u8) -> bool {+ self.phase+ .compare_exchange(+ from,+ to,+ std::sync::atomic::Ordering::AcqRel,+ std::sync::atomic::Ordering::Acquire,+ )+ .is_ok()+ }+}++fn existing_file(path: PathBuf) -> Option<PathBuf> {+ path.is_file().then_some(path)+}++fn binary_path(app: &AppHandle) -> Option<PathBuf> {+ if let Some(path) = std::env::var_os("CAP_GPUI_BIN").map(PathBuf::from)+ && path.is_file()+ {+ return Some(path);+ }++ if let Ok(executable) = std::env::current_exe()+ && let Some(parent) = executable.parent()+ && let Some(path) = existing_file(parent.join(BINARY_NAME))+ {+ return Some(path);+ }++ if let Ok(resources) = app.path().resource_dir()+ && let Some(path) = existing_file(resources.join("gpui").join(BINARY_NAME))+ {+ return Some(path);+ }++ #[cfg(debug_assertions)]+ {+ // Whichever profile was built most recently: a fixed preference here+ // hands off to a days-old binary the moment the other profile is the+ // one being actively rebuilt.+ let target =+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../desktop-gpui/target");+ let newest = ["release", "debug"]+ .into_iter()+ .filter_map(|profile| {+ let path = target.join(profile).join(BINARY_NAME);+ let modified = std::fs::metadata(&path).ok()?.modified().ok()?;+ Some((modified, path))+ })+ .max_by_key(|(modified, _)| *modified)+ .map(|(_, path)| path);+ if newest.is_some() {+ return newest;+ }+ }++ None+}++/// Mirror of `store::app_data_dir` in `apps/desktop-gpui`: the pidfile and the+/// handoff marker live under the shared production identifier+/// (`so.cap.desktop`), not this app's possibly-`.dev` one.fn shared_data_dir() -> PathBuf {#[cfg(target_os = "macos")]let base = PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| ".".into()))@@ -46,184 +156,690 @@ fn shared_data_dir() -> PathBuf {base}-fn classic_pending() -> PathBuf {- shared_data_dir().join("cap-classic.pending")+fn gpui_pidfile() -> PathBuf {+ shared_data_dir().join("cap-gpui.pid")}-/// A dev build stores under a `.dev` identifier while Cap always reads the-/// production one, so the session flag has to be written to the shared file.+/// Whether this app's own store IS the shared one. It is for the production+/// bundle (`so.cap.desktop`), but a dev build stores under a `.dev` identifier+/// while `cap-gpui` always reads and writes the shared file -- two stores that+/// silently disagree. The handoff flag therefore lives in the shared store,+/// and this app's own copy of the setting is just what its settings page+/// displays.fn own_store_is_shared(app: &AppHandle) -> bool {app.path().app_data_dir().is_ok_and(|dir| dir == shared_data_dir())}+fn shared_store_path() -> PathBuf {+ // The store plugin's file for the production identifier -- the same file+ // `store::set_store_setting` in apps/desktop-gpui operates on.+ shared_data_dir().join("store")+}++fn shared_store_flag() -> Option<bool> {+ let raw = std::fs::read_to_string(shared_store_path()).ok()?;+ let doc: serde_json::Value = serde_json::from_str(&raw).ok()?;+ doc.get("general_settings")?.get("enableGpuiApp")?.as_bool()+}+/// Single-key replace with everything else preserved, temp+rename atomic ---/// the same contract as Cap's `set_store_setting`. Only called when the-/// shared store is not this app's own, so it never races the store plugin's-/// in-memory copy.-fn write_shared_store_flag(value: bool) -> Result<(), String> {- let path = shared_data_dir().join("store");+/// the same contract as the gpui app's `set_store_setting`. A missing file is+/// created with just this key; an unparseable one is refused rather than+/// replaced. Only ever called when the shared store is NOT this app's own+/// (`own_store_is_shared` false): writing the file directly under the store+/// plugin's feet would race its in-memory copy.+fn write_shared_store_flag(value: bool) {+ let path = shared_store_path();let mut doc = match std::fs::read_to_string(&path) {- Ok(raw) => serde_json::from_str::<serde_json::Value>(&raw)- .map_err(|error| format!("The shared store is unreadable: {error}"))?,+ Ok(raw) => match serde_json::from_str::<serde_json::Value>(&raw) {+ Ok(doc) => doc,+ Err(error) => {+ warn!(%error, "shared store is unparseable; leaving it untouched");+ return;+ }+ },Err(error) if error.kind() == std::io::ErrorKind::NotFound => serde_json::json!({}),- Err(error) => return Err(format!("Could not read the shared store: {error}")),+ Err(error) => {+ warn!(%error, "could not read the shared store");+ return;+ }};- let root = doc- .as_object_mut()- .ok_or_else(|| "The shared store is not a JSON object".to_string())?;- let section = root- .entry("general_settings")+ let Some(root) = doc.as_object_mut() else {+ warn!("shared store is not a JSON object; leaving it untouched");+ return;+ };+ root.entry("general_settings").or_insert_with(|| serde_json::json!({})).as_object_mut()- .ok_or_else(|| "The shared store's general settings are not an object".to_string())?;- section.insert("enableGpuiApp".into(), serde_json::Value::Bool(value));- let pretty = serde_json::to_string_pretty(&doc).map_err(|error| error.to_string())?;+ .map(|section| section.insert("enableGpuiApp".into(), serde_json::Value::Bool(value)));+ let pretty = serde_json::to_string_pretty(&doc).unwrap_or_else(|_| doc.to_string());let tmp = path.with_extension("tmp");- std::fs::create_dir_all(path.parent().unwrap_or(&path))+ let write = std::fs::create_dir_all(path.parent().unwrap_or(&path)).and_then(|()| std::fs::write(&tmp, pretty))- .and_then(|()| std::fs::rename(&tmp, &path))- .map_err(|error| format!("Could not write the shared store: {error}"))+ .and_then(|()| std::fs::rename(&tmp, &path));+ if let Err(error) = write {+ warn!(%error, "could not write the shared store flag");+ }}-fn set_gpui_owns_session(app: &AppHandle, owns: bool) -> Result<(), String> {- if own_store_is_shared(app) {- GeneralSettingsStore::update(app, |settings| settings.enable_gpui_app = owns)- } else {- write_shared_store_flag(owns)- }+fn handoff_marker() -> PathBuf {+ shared_data_dir().join("cap-gpui.handoff")}-#[derive(Debug, PartialEq, Eq)]-enum CapInstall {- #[cfg(target_os = "macos")]- Bundle(PathBuf),- Executable(PathBuf),+fn update_handoff_marker() -> PathBuf {+ shared_data_dir().join("cap-gpui.update-handoff")}-impl CapInstall {- fn path(&self) -> &Path {- match self {- #[cfg(target_os = "macos")]- Self::Bundle(path) => path,- Self::Executable(path) => path,+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct UpdateHandoff {+ pid: u32,+ simulated: bool,+}++fn parse_update_handoff(contents: &str) -> Option<UpdateHandoff> {+ let contents = contents.trim();+ let (pid, simulated) = match contents.strip_prefix("simulate:") {+ Some(pid) if cfg!(debug_assertions) => (pid, true),+ Some(_) => return None,+ None => (contents, false),+ };+ let pid = pid.parse().ok()?;+ (pid != 0).then_some(UpdateHandoff { pid, simulated })+}++fn take_update_handoff() -> Option<bool> {+ let marker = update_handoff_marker();+ let contents = match std::fs::read_to_string(&marker) {+ Ok(contents) => contents,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return None,+ Err(error) => {+ warn!(%error, "could not read the Cap GPUI update hand-off");+ return None;}+ };++ let Some(handoff) = parse_update_handoff(&contents) else {+ warn!("discarding an invalid Cap GPUI update hand-off");+ let _ = std::fs::remove_file(&marker);+ return None;+ };++ let expected_pid = std::fs::read_to_string(gpui_pidfile())+ .ok()+ .and_then(|contents| contents.trim().parse::<u32>().ok());+ let stale = marker+ .metadata()+ .ok()+ .and_then(|metadata| metadata.modified().ok())+ .and_then(|modified| modified.elapsed().ok())+ .is_some_and(|age| age > std::time::Duration::from_secs(15 * 60));+ if expected_pid.is_some_and(|pid| pid != handoff.pid) || stale {+ warn!(+ pid = handoff.pid,+ "discarding a stale Cap GPUI update hand-off"+ );+ let _ = std::fs::remove_file(&marker);+ return None;+ }++ match std::fs::remove_file(&marker) {+ Ok(()) => {+ info!(+ pid = handoff.pid,+ "taking ownership from Cap GPUI for an update check"+ );+ Some(handoff.simulated)+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,+ Err(error) => {+ warn!(%error, "could not consume the Cap GPUI update hand-off");+ None+ }+ }+}++fn show_update_page_when_ready(app: AppHandle, simulated: bool) {+ tauri::async_runtime::spawn(async move {+ for _ in 0..300 {+ if let Some(window) = app+ .get_webview_window("main")+ .or_else(|| app.get_webview_window("onboarding"))+ {+ match window.url() {+ Ok(mut url) => {+ url.set_path("/update");+ url.set_query(Some(if simulated {+ "source=gpui&simulateUpdate=1"+ } else {+ "source=gpui"+ }));+ if let Err(error) = window.navigate(url) {+ warn!(%error, "could not open the updater after the GPUI hand-off");+ } else {+ let _ = window.show();+ let _ = window.set_focus();+ }+ }+ Err(error) => {+ warn!(%error, "could not read the window URL for the GPUI updater");+ }+ }+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ warn!("no window became ready for the GPUI update hand-off");+ });+}++pub(crate) fn handle_update_handoff(app: &AppHandle) -> bool {+ let Some(simulated) = take_update_handoff() else {+ return false;+ };+ show_update_page_when_ready(app.clone(), simulated);+ true+}++fn classic_pending() -> PathBuf {+ shared_data_dir().join("cap-classic.pending")+}++/// The pid of the live `cap-gpui` that owns the pidfile, if there is one.+fn running_instance_pid() -> Option<u32> {+ let pid = std::fs::read_to_string(gpui_pidfile())+ .ok()?+ .trim()+ .parse::<u32>()+ .ok()?;++ #[cfg(target_os = "linux")]+ {+ linux_gpui_process_is_running(pid).then_some(pid)+ }++ #[cfg(all(unix, not(target_os = "linux")))]+ {+ let alive = std::process::Command::new("ps")+ .args(["-p", &pid.to_string(), "-o", "comm="])+ .output()+ .is_ok_and(|output| {+ output.status.success()+ && is_gpui_process_image(std::path::Path::new(+ String::from_utf8_lossy(&output.stdout).trim(),+ ))+ });+ alive.then_some(pid)+ }++ #[cfg(windows)]+ {+ let process_id = sysinfo::Pid::from_u32(pid);+ let mut system = sysinfo::System::new();+ system.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[process_id]), true);+ system+ .process(process_id)+ .and_then(sysinfo::Process::exe)+ .is_some_and(is_gpui_process_image)+ .then_some(pid)+ }+}++#[cfg(target_os = "linux")]+fn linux_gpui_process_is_running(pid: u32) -> bool {+ std::fs::read_link(format!("/proc/{pid}/exe")).is_ok_and(|path| is_gpui_process_image(&path))+}++fn is_gpui_process_image(path: &std::path::Path) -> bool {+ 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(BINARY_NAME)+}++#[cfg(any(target_os = "macos", windows, test))]+fn parse_gpui_forwarding_endpoint(contents: &str) -> Option<GpuiForwardingEndpoint> {+ let mut parts = contents.trim().split(':');+ let pid = parts.next()?.parse().ok()?;+ let port = parts.next()?.parse().ok()?;+ let secret = u64::from_str_radix(parts.next()?, 16).ok()?;+ (pid != 0 && port != 0 && parts.next().is_none()).then_some(GpuiForwardingEndpoint {+ pid,+ port,+ secret,+ })+}++#[cfg(any(target_os = "macos", windows, test))]+fn is_forwardable_gpui_deep_link(url: &str) -> bool {+ !url.is_empty()+ && url.len() <= MAX_FORWARDED_DEEP_LINK_BYTES+ && reqwest::Url::parse(url)+ .is_ok_and(|parsed| matches!(parsed.scheme(), "cap-desktop" | "cap"))+}++#[cfg(any(target_os = "macos", windows, test))]+fn forwarded_gpui_argument(argument: &str) -> Option<String> {+ if is_forwardable_gpui_deep_link(argument) {+ return Some(argument.to_string());+ }++ let path = match reqwest::Url::parse(argument) {+ Ok(url) if url.scheme() == "file" => url.to_file_path().ok()?,+ _ => PathBuf::from(argument),+ };+ if !path+ .extension()+ .and_then(std::ffi::OsStr::to_str)+ .is_some_and(|extension| extension.eq_ignore_ascii_case("cap"))+ {+ return None;+ }++ let metadata = std::fs::symlink_metadata(&path).ok()?;+ if metadata.file_type().is_symlink() || !metadata.is_dir() {+ return None;}+ let path = path.canonicalize().ok()?;+ let value = serde_json::json!({ "open_editor": { "project_path": path } }).to_string();+ let mut url = reqwest::Url::parse("cap-desktop://action").ok()?;+ url.query_pairs_mut().append_pair("value", &value);+ let url = url.to_string();+ is_forwardable_gpui_deep_link(&url).then_some(url)}#[cfg(target_os = "macos")]-fn installed_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)+fn read_macos_gpui_metadata(path: &std::path::Path, private: bool) -> std::io::Result<String> {+ use nix::libc;+ use std::{+ io::Read,+ os::unix::fs::{MetadataExt, OpenOptionsExt},+ };++ let file = std::fs::OpenOptions::new()+ .read(true)+ .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)+ .open(path)?;+ let metadata = file.metadata()?;+ let forbidden_permissions = if private { 0o077 } else { 0o022 };+ if !metadata.is_file()+ || metadata.len() > 128+ || metadata.nlink() != 1+ || metadata.uid() != unsafe { libc::geteuid() }+ || metadata.mode() & forbidden_permissions != 0{- candidates.push(parent.join(CAP_BUNDLE_NAME));+ return Err(std::io::Error::new(+ std::io::ErrorKind::PermissionDenied,+ "Cap GPUI instance metadata is not owner controlled",+ ));}- candidates.push(Path::new("/Applications").join(CAP_BUNDLE_NAME));- if let Some(home) = home {- candidates.push(home.join("Applications").join(CAP_BUNDLE_NAME));+ let mut contents = String::new();+ file.take(129).read_to_string(&mut contents)?;+ if contents.len() > 128 {+ return Err(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "Cap GPUI instance metadata changed",+ ));}- candidates.dedup();- candidates+ Ok(contents)}#[cfg(target_os = "macos")]-fn installed_cap() -> Option<CapInstall> {- let executable = std::env::current_exe().ok();- let home = std::env::var_os("HOME").map(PathBuf::from);- installed_candidates(executable.as_deref(), home.as_deref())- .into_iter()- .find(|bundle| bundle.join("Contents/MacOS/Cap").is_file())- .map(CapInstall::Bundle)+fn macos_reopen_incumbent(path: &std::path::Path, pid: u32) -> std::io::Result<bool> {+ use nix::libc;+ use std::os::unix::ffi::OsStrExt;++ if pid == 0+ || pid > i32::MAX as u32+ || pid == std::process::id()+ || read_macos_gpui_metadata(path, false)?+ .trim()+ .parse::<u32>()+ .ok()+ != Some(pid)+ {+ return Ok(false);+ }+ let mut buffer = [0_u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];+ let length =+ unsafe { libc::proc_pidpath(pid as i32, buffer.as_mut_ptr().cast(), buffer.len() as u32) };+ Ok(length > 0+ && buffer.split(|byte| *byte == 0).next().is_some_and(|bytes| {+ is_gpui_process_image(std::path::Path::new(std::ffi::OsStr::from_bytes(bytes)))+ }))}-#[cfg(windows)]-fn installed_cap() -> Option<CapInstall> {- use winreg::{- RegKey,- enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE},+#[cfg(any(target_os = "macos", windows))]+fn reopen_time_remaining(+ started: std::time::Instant,+ timeout: std::time::Duration,+) -> std::io::Result<std::time::Duration> {+ timeout+ .checked_sub(started.elapsed())+ .filter(|remaining| !remaining.is_zero())+ .ok_or_else(|| {+ std::io::Error::new(+ std::io::ErrorKind::TimedOut,+ "Cap GPUI reopen request timed out",+ )+ })+}++#[cfg(any(target_os = "macos", windows))]+fn send_gpui_reopen(+ endpoint: GpuiForwardingEndpoint,+ started: std::time::Instant,+ timeout: std::time::Duration,+) -> std::io::Result<()> {+ use std::io::{Read, Write};++ let address = std::net::SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, endpoint.port));+ let mut stream =+ std::net::TcpStream::connect_timeout(&address, reopen_time_remaining(started, timeout)?)?;+ stream.set_nonblocking(true)?;+ let mut payload = [0_u8; 12];+ payload[..8].copy_from_slice(&endpoint.secret.to_be_bytes());+ let mut pending = payload.as_slice();+ while !pending.is_empty() {+ let remaining = reopen_time_remaining(started, timeout)?;+ match stream.write(pending) {+ Ok(0) => {+ return Err(std::io::Error::new(+ std::io::ErrorKind::WriteZero,+ "Cap GPUI closed its forwarding connection",+ ));+ }+ Ok(written) => pending = &pending[written..],+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {+ std::thread::sleep(remaining.min(std::time::Duration::from_millis(5)))+ }+ Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}+ Err(error) => return Err(error),+ }+ }+ let mut acknowledgment = [0_u8; 1];+ loop {+ let remaining = reopen_time_remaining(started, timeout)?;+ match stream.read(&mut acknowledgment) {+ Ok(1) if acknowledgment[0] == 1 => return Ok(()),+ Ok(_) => {+ return Err(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "Cap GPUI did not acknowledge the reopen request",+ ));+ }+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {+ std::thread::sleep(remaining.min(std::time::Duration::from_millis(5)))+ }+ Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}+ Err(error) => return Err(error),+ }+ }+}++#[cfg(target_os = "macos")]+pub(crate) fn request_gpui_reopen(pid: u32) -> Result<(), String> {+ let request = || -> std::io::Result<()> {+ let started = std::time::Instant::now();+ let timeout = std::time::Duration::from_secs(2);+ let path = gpui_pidfile();+ loop {+ reopen_time_remaining(started, timeout)?;+ if !macos_reopen_incumbent(&path, pid)? {+ return Err(std::io::Error::new(+ std::io::ErrorKind::NotConnected,+ "The Cap GPUI instance changed before reopening",+ ));+ }+ match read_macos_gpui_metadata(&path.with_extension("ipc"), true) {+ Ok(contents) => {+ if let Some(endpoint) = parse_gpui_forwarding_endpoint(&contents)+ .filter(|endpoint| endpoint.pid == pid)+ {+ return send_gpui_reopen(endpoint, started, timeout);+ }+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => return Err(error),+ }+ std::thread::sleep(+ reopen_time_remaining(started, timeout)?.min(std::time::Duration::from_millis(50)),+ );+ }};+ request().map_err(|error| format!("Could not confirm reopening the running Cap GPUI: {error}"))+}- [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE]- .into_iter()- .filter_map(|root| {- RegKey::predef(root)- .open_subkey("Software\\cap\\Cap")- .and_then(|key| key.get_value::<String, _>(""))+#[cfg(windows)]+fn request_gpui_reopen(pid: u32) -> Result<(), String> {+ use windows::Win32::UI::WindowsAndMessaging::AllowSetForegroundWindow;++ let request = || -> std::io::Result<()> {+ let started = std::time::Instant::now();+ let timeout = std::time::Duration::from_secs(2);+ let endpoint_path = gpui_pidfile().with_extension("ipc");+ loop {+ if let Some(endpoint) = std::fs::read_to_string(&endpoint_path).ok()- .map(|directory| PathBuf::from(directory.trim().trim_matches('"')))- })- .chain(- std::env::var_os("LOCALAPPDATA")- .map(PathBuf::from)- .map(|directory| directory.join("Cap")),- )- .map(|directory| directory.join(CAP_EXECUTABLE_NAME))- .find(|executable| executable.is_file())- .map(CapInstall::Executable)+ .and_then(|contents| parse_gpui_forwarding_endpoint(&contents))+ .filter(|endpoint| endpoint.pid == pid)+ {+ let _ = unsafe { AllowSetForegroundWindow(pid) };+ return send_gpui_reopen(endpoint, started, timeout);+ }+ std::thread::sleep(+ reopen_time_remaining(started, timeout)?.min(std::time::Duration::from_millis(50)),+ );+ }+ };+ request().map_err(|error| format!("Could not confirm reopening the running Cap GPUI: {error}"))}-#[cfg(target_os = "linux")]-fn installed_cap() -> Option<CapInstall> {- let executable = PathBuf::from("/usr/bin/Cap");- executable- .is_file()- .then_some(CapInstall::Executable(executable))-}--#[cfg(debug_assertions)]-fn development_cap() -> Option<CapInstall> {- let target = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../desktop-gpui/target");- ["release", "debug"]- .into_iter()- .filter_map(|profile| {- let path = target.join(profile).join(DEV_BINARY_NAME);- let modified = std::fs::metadata(&path).ok()?.modified().ok()?;- Some((modified, path))- })- .max_by_key(|(modified, _)| *modified)- .map(|(_, path)| CapInstall::Executable(path))+#[cfg(any(target_os = "macos", test))]+fn gpui_launch_needs_reopen(args: &[String]) -> bool {+ !args+ .iter()+ .any(|argument| forwarded_gpui_argument(argument).is_some())}-fn cap_install() -> Option<CapInstall> {- if let Some(path) = std::env::var_os("CAP_GPUI_BIN").map(PathBuf::from)- && path.is_file()+#[cfg(any(target_os = "macos", windows))]+fn forward_deep_links_to_gpui(pid: u32, args: &[String]) -> bool {+ use std::io::Write;++ let urls = args+ .iter()+ .filter_map(|argument| forwarded_gpui_argument(argument))+ .collect::<Vec<_>>();+ if urls.is_empty() {+ return false;+ }++ let endpoint_path = gpui_pidfile().with_extension("ipc");+ let endpoint = (0..40).find_map(|attempt| {+ let endpoint = std::fs::read_to_string(&endpoint_path)+ .ok()+ .and_then(|contents| parse_gpui_forwarding_endpoint(&contents))+ .filter(|endpoint| endpoint.pid == pid);+ if endpoint.is_none() && attempt < 39 {+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ endpoint+ });+ let Some(endpoint) = endpoint else {+ warn!(pid, "could not find the Cap GPUI deep-link endpoint");+ return false;+ };++ let mut forwarded = false;+ for url in urls {+ let result = std::net::TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, endpoint.port))+ .and_then(|mut stream| {+ stream.set_write_timeout(Some(std::time::Duration::from_secs(2)))?;+ stream.write_all(&endpoint.secret.to_be_bytes())?;+ stream.write_all(&(url.len() as u32).to_be_bytes())?;+ stream.write_all(url.as_bytes())+ });+ match result {+ Ok(()) => forwarded = true,+ Err(error) => warn!(%error, "could not forward a deep link to Cap GPUI"),+ }+ }++ forwarded+}++#[cfg(any(target_os = "macos", windows))]+pub(crate) fn forward_deep_links_to_active_gpui(app: &AppHandle, args: &[String]) -> bool {+ let own = GeneralSettingsStore::get(app)+ .ok()+ .flatten()+ .is_some_and(|settings| settings.enable_gpui_app);+ let enabled = if own_store_is_shared(app) {+ own+ } else {+ shared_store_flag().unwrap_or(false)+ };+ if !enabled {+ return false;+ }++ let Some(pid) = running_instance_pid() else {+ return false;+ };+ if !forward_deep_links_to_gpui(pid, args) {+ return false;+ }++ activate_instance(pid);+ true+}++#[cfg(target_os = "macos")]+pub(crate) fn forward_deep_links_to_gpui_when_ready(args: &[String]) -> Option<u32> {+ if !args+ .iter()+ .any(|argument| forwarded_gpui_argument(argument).is_some()){- return Some(CapInstall::Executable(path));+ return None;}- #[cfg(debug_assertions)]- if let Some(install) = development_cap() {- return Some(install);++ let pid = (0..40).find_map(|attempt| {+ let pid = running_instance_pid();+ if pid.is_none() && attempt < 39 {+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ pid+ })?;++ forward_deep_links_to_gpui(pid, args).then_some(pid)+}++#[cfg(target_os = "macos")]+pub(crate) fn activate_instance(pid: u32) {+ use objc2_app_kit::{NSApplicationActivationOptions, NSRunningApplication};++ if let Some(instance) =+ unsafe { NSRunningApplication::runningApplicationWithProcessIdentifier(pid as _) }+ {+ unsafe {+ instance.activateWithOptions(NSApplicationActivationOptions::ActivateIgnoringOtherApps);+ }}- installed_cap()}-fn launch_command(install: &CapInstall) -> std::process::Command {- match install {- #[cfg(target_os = "macos")]- CapInstall::Bundle(bundle) => {- let mut command = std::process::Command::new("/usr/bin/open");- command.arg("-n").arg(bundle);- command+#[cfg(windows)]+fn activate_instance(pid: u32) {+ use windows::{+ Win32::{+ Foundation::{HWND, LPARAM, TRUE},+ UI::WindowsAndMessaging::{+ EnumWindows, GetWindowThreadProcessId, IsWindowVisible, SW_RESTORE,+ SetForegroundWindow, ShowWindow,+ },+ },+ core::BOOL,+ };++ struct Activation {+ pid: u32,+ visible: Option<HWND>,+ fallback: Option<HWND>,+ }++ unsafe extern "system" fn find_window(window: HWND, data: LPARAM) -> BOOL {+ let activation = unsafe { &mut *(data.0 as *mut Activation) };+ let mut owner = 0;+ unsafe { GetWindowThreadProcessId(window, Some(&mut owner)) };+ if owner == activation.pid {+ if activation.fallback.is_none() {+ activation.fallback = Some(window);+ }+ if activation.visible.is_none() && unsafe { IsWindowVisible(window) }.as_bool() {+ activation.visible = Some(window);+ }+ }+ TRUE+ }++ let mut activation = Activation {+ pid,+ visible: None,+ fallback: None,+ };+ let _ = unsafe {+ EnumWindows(+ Some(find_window),+ LPARAM(std::ptr::addr_of_mut!(activation) as isize),+ )+ };++ if let Some(window) = activation.visible.or(activation.fallback) {+ unsafe {+ let _ = ShowWindow(window, SW_RESTORE);+ let _ = SetForegroundWindow(window);}- CapInstall::Executable(executable) => std::process::Command::new(executable),}}-/// A launched Cap outlives this app, so it must never inherit this process's-/// stdio: `bun run tauri dev`'s pipes close when this app exits and the next-/// log line would abort Cap. Its output goes to a file instead, because a-/// launch with no terminal is only ever diagnosable from there.-fn launch(install: &CapInstall) -> Result<(), String> {+#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]+fn activate_instance(_pid: u32) {}++#[cfg(any(target_os = "linux", test))]+fn launch_linux_activation(+ path: Option<&std::path::Path>,+ launch: impl FnOnce(&std::path::Path, &[String]) -> Result<(), String>,+) -> Result<(), String> {+ let path = path.ok_or_else(|| "Cap GPUI isn't included in this build".to_string())?;+ launch(path, &[])+}++fn write_handoff_marker() {+ let path = handoff_marker();+ if let Some(parent) = path.parent() {+ let _ = std::fs::create_dir_all(parent);+ }+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|since| since.as_secs())+ .unwrap_or_default();+ if let Err(error) = std::fs::write(&path, stamp.to_string()) {+ warn!(%error, "could not write the Cap GPUI handoff marker");+ }+}++/// The child must never inherit this process's stdio. The handoff exits this+/// app, and whatever was reading those pipes (`bun run tauri dev`'s tooling chain)+/// goes with it; `cap-gpui`'s next log line then hits EPIPE, the write panics+/// inside an ObjC run-loop callback, and the process aborts about a tenth of a+/// second after launch. Its output goes to a file instead of `/dev/null`+/// because a handoff launch has no terminal, and a startup failure there is+/// only ever diagnosable from that file.+fn spawn_detached(path: &std::path::Path, args: &[String]) -> Result<(), String> {use std::process::Stdio;- let mut command = launch_command(install);let log_path = shared_data_dir().join("cap-gpui.log");if let Some(parent) = log_path.parent() {let _ = std::fs::create_dir_all(parent);@@ -238,11 +854,19 @@ fn launch(install: &CapInstall) -> Result<(), String> {Err(_) => (Stdio::from(file), Stdio::null()),},Err(error) => {- warn!(%error, "could not open the Cap launch log; discarding its output");+ warn!(%error, "could not open the Cap GPUI log; discarding its output");(Stdio::null(), Stdio::null())}};- command.stdin(Stdio::null()).stdout(stdout).stderr(stderr);++ let mut command = std::process::Command::new(path);+ command+ .args(args)+ .stdin(Stdio::null())+ .stdout(stdout)+ .stderr(stderr);+ // Its own process group, so signals aimed at the terminal this app was+ // started from never reach the app that outlives it.#[cfg(unix)]{use std::os::unix::process::CommandExt;@@ -251,7 +875,8 @@ fn launch(install: &CapInstall) -> Result<(), String> {let mut child = command.spawn()- .map_err(|error| format!("Couldn't open Cap: {error}"))?;+ .map_err(|error| format!("Failed to launch Cap GPUI: {error}"))?;+ // Reap the child when it exits so it never lingers as a zombie.std::thread::spawn(move || {let _ = child.wait();});@@ -273,32 +898,67 @@ pub(crate) fn retire_foreground_parent_for_handoff(app: &AppHandle) {// A foreground parent exiting with a surviving child leaves a macOS background Dock tile.match app.set_activation_policy(tauri::ActivationPolicy::Accessory) {- Ok(()) => info!("Requested retirement of Cap Classic's Dock presence for the switch"),- Err(error) => warn!(%error, "Could not retire Cap Classic's Dock presence for the switch"),+ Ok(()) => info!("Requested retirement of Tauri's Dock presence for the GPUI handoff"),+ Err(error) => warn!(%error, "Could not retire Tauri's Dock presence for the GPUI handoff"),}}#[tauri::command]#[specta::specta]-pub async fn gpui_app_available() -> bool {- cap_install().is_some()+pub async fn gpui_app_available(app: AppHandle) -> bool {+ binary_path(&app).is_some()}-/// Close this app and open Cap. A failure has to be reported rather than-/// swallowed: the Experimental page shows it on its overlay.+/// Close this app and open the native one. The setting has already been written+/// by the caller, so a failure here has to be reported rather than swallowed:+/// the page reverts it.#[tauri::command]#[specta::specta]pub async fn switch_to_gpui_app(app: AppHandle) -> Result<(), String> {- let install =- cap_install().ok_or_else(|| "Cap isn't installed on this computer".to_string())?;+ let path =+ binary_path(&app).ok_or_else(|| "Cap GPUI isn't included in this build".to_string())?;crate::prepare_app_exit(&app, || {- info!(path = %install.path().display(), "switching to Cap");- set_gpui_owns_session(&app, true)?;- launch(&install).inspect_err(|_| {- if let Err(error) = set_gpui_owns_session(&app, false) {- warn!(%error, "Could not restore the session owner after a failed switch");+ let uses_shared_store = own_store_is_shared(&app);+ let previous_shared_flag = if uses_shared_store {+ None+ } else {+ let previous = shared_store_flag();+ write_shared_store_flag(true);+ previous+ };+ match running_instance_pid() {+ Some(pid) => {+ #[cfg(target_os = "linux")]+ if let Err(error) = launch_linux_activation(Some(&path), spawn_detached) {+ if !uses_shared_store {+ write_shared_store_flag(previous_shared_flag.unwrap_or(false));+ }+ return Err(error);+ }+ #[cfg(target_os = "macos")]+ if let Err(error) = request_gpui_reopen(pid) {+ if !uses_shared_store {+ write_shared_store_flag(previous_shared_flag.unwrap_or(false));+ }+ return Err(error);+ }+ #[cfg(not(target_os = "linux"))]+ activate_instance(pid);+ info!(pid, "Cap GPUI is already running; requested its controls");}- })+ None => {+ write_handoff_marker();+ info!(path = %path.display(), "handing off to Cap GPUI");+ if let Err(error) = spawn_detached(&path, &[]) {+ let _ = std::fs::remove_file(handoff_marker());+ if !uses_shared_store {+ write_shared_store_flag(previous_shared_flag.unwrap_or(false));+ }+ return Err(error);+ }+ }+ }+ Ok(())})?;#[cfg(target_os = "macos")]{@@ -313,38 +973,52 @@ pub async fn switch_to_gpui_app(app: AppHandle) -> Result<(), String> {tokio::time::timeout(std::time::Duration::from_secs(2), receiver).await,Ok(Ok(()))) {- warn!("The switch's Dock transition was not acknowledged before shutdown");+ warn!(+ "The GPUI handoff's Dock transition was not acknowledged before shutdown"+ );}}- Err(error) => warn!(%error, "Could not schedule the switch's Dock transition"),+ Err(error) => warn!(%error, "Could not schedule the GPUI handoff's Dock transition"),}}crate::complete_admitted_app_exit(app).await;Ok(())}-/// Acknowledge Cap's switch here once a window is visible, for as long as-/// this app runs: Cap may switch to an already-running Cap Classic.-pub fn watch_for_switches(app: &AppHandle) {- let app = app.clone();- tauri::async_runtime::spawn(async move {- loop {- if classic_pending().try_exists().unwrap_or(false) {- let handle = app.clone();- let (sender, receiver) = tokio::sync::oneshot::channel();- if app- .run_on_main_thread(move || {- acknowledge_classic_window(&handle);- let _ = sender.send(());- })- .is_ok()- {- let _ = tokio::time::timeout(std::time::Duration::from_secs(1), receiver).await;+/// Whether this app should hand over to `cap-gpui` instead of starting.+///+/// `true` means the caller must exit before any window is created.+pub fn redirect_at_startup_if_enabled(app: &AppHandle) -> Result<bool, String> {+ #[cfg(debug_assertions)]+ if crate::stop_editor_benchmark::enabled() {+ return Ok(false);+ }+ let update_handoff = handle_update_handoff(app);+ let redirect = !update_handoff && redirect_decision(app)?;+ if !redirect {+ let app = app.clone();+ tauri::async_runtime::spawn(async move {+ loop {+ handle_update_handoff(&app);+ if classic_pending().try_exists().unwrap_or(false) {+ let handle = app.clone();+ let (sender, receiver) = tokio::sync::oneshot::channel();+ if app+ .run_on_main_thread(move || {+ acknowledge_classic_window(&handle);+ let _ = sender.send(());+ })+ .is_ok()+ {+ let _ =+ tokio::time::timeout(std::time::Duration::from_secs(1), receiver).await;+ }}+ tokio::time::sleep(std::time::Duration::from_millis(250)).await;}- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- }- });+ });+ }+ Ok(redirect)}fn acknowledge_classic_window(app: &AppHandle) {@@ -364,54 +1038,508 @@ fn acknowledge_classic_window(app: &AppHandle) {});if ready {match std::fs::remove_file(classic_pending()) {- Ok(()) => info!("Acknowledged the switch from Cap"),+ Ok(()) => info!("Acknowledged visible classic window for GPUI handoff"),Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}- Err(error) => warn!(%error, "Could not acknowledge the switch from Cap"),+ Err(error) => warn!(%error, "Could not acknowledge the classic app handoff"),+ }+ }+}++fn redirect_decision(app: &AppHandle) -> Result<bool, String> {+ let own = GeneralSettingsStore::get(app)+ .ok()+ .flatten()+ .is_some_and(|settings| settings.enable_gpui_app);+ // In a dev build the shared store is the authority: `cap-gpui`'s+ // switch-back writes false THERE, and honouring this app's own `.dev`+ // copy instead would bounce the user straight back after every+ // switch-back (the loop this replaced).+ let enabled = if own_store_is_shared(app) {+ own+ } else {+ shared_store_flag().unwrap_or(false)+ };+ if !enabled {+ if own {+ // The stale display copy: without this the Experimental page+ // shows the toggle on while the classic app owns the session.+ if let Err(error) = GeneralSettingsStore::update(app, |settings| {+ settings.enable_gpui_app = false;+ }) {+ warn!(%error, "could not reconcile the Cap GPUI setting");+ }+ }+ return Ok(false);+ }++ // The marker exists throughout a live session. Check the process first so+ // reopening Cap does not mistake a running native app for a crashed one.+ if let Some(pid) = running_instance_pid() {+ #[cfg(any(target_os = "macos", windows))]+ {+ let args = std::env::args().skip(1).collect::<Vec<_>>();+ #[cfg(target_os = "macos")]+ if gpui_launch_needs_reopen(&args) {+ app.manage(StartupRedirectState::with_reopen(pid));+ } else {+ forward_deep_links_to_gpui(pid, &args);+ }+ #[cfg(windows)]+ if !forward_deep_links_to_gpui(pid, &args) {+ match request_gpui_reopen(pid) {+ Ok(()) => {+ info!(pid, "Cap GPUI is already running; reopened its main window");+ return Ok(true);+ }+ Err(error) => warn!(%error, "could not reopen the running Cap GPUI"),+ }+ }}+ #[cfg(target_os = "linux")]+ launch_linux_activation(binary_path(app).as_deref(), spawn_detached)?;+ #[cfg(not(target_os = "linux"))]+ activate_instance(pid);+ info!(+ pid,+ "Cap GPUI is already running; preserving the existing instance"+ );+ return Ok(true);+ }++ let marker = handoff_marker();+ if marker.exists() {+ warn!("the last Cap GPUI session exited unexpectedly; taking back over");+ let _ = std::fs::remove_file(&marker);+ if let Err(error) = GeneralSettingsStore::update(app, |settings| {+ settings.enable_gpui_app = false;+ }) {+ warn!(%error, "could not clear the Cap GPUI setting");+ }+ if !own_store_is_shared(app) {+ write_shared_store_flag(false);+ }+ app.dialog()+ .message(+ "The native Cap app exited unexpectedly last time, so the classic app has been restored.",+ )+ .show(|_| {});+ return Ok(false);+ }++ let Some(path) = binary_path(app) else {+ warn!("Cap GPUI is enabled but its binary was not found; starting this app instead");+ return Ok(false);+ };++ write_handoff_marker();+ info!(path = %path.display(), "handing off to Cap GPUI at startup");+ #[cfg(any(target_os = "macos", windows))]+ let args = std::env::args()+ .skip(1)+ .filter_map(|argument| forwarded_gpui_argument(&argument))+ .collect::<Vec<_>>();+ #[cfg(not(any(target_os = "macos", windows)))]+ let args = Vec::new();+ if let Err(error) = spawn_detached(&path, &args) {+ warn!("{error}");+ let _ = std::fs::remove_file(handoff_marker());+ return Ok(false);}+ Ok(true)}#[cfg(test)]mod tests {- use super::CapInstall;+ use super::{+ BINARY_NAME, GpuiForwardingEndpoint, MAX_FORWARDED_DEEP_LINK_BYTES, StartupRedirectState,+ UpdateHandoff, forwarded_gpui_argument, is_forwardable_gpui_deep_link,+ is_gpui_process_image, parse_gpui_forwarding_endpoint, parse_update_handoff,+ };++ #[test]+ fn linux_activation_launches_the_resolved_binary_once_without_arguments() {+ let path = std::path::Path::new("/opt/cap/cap-gpui");+ let mut launches = 0;+ super::launch_linux_activation(Some(path), |selected, args| {+ launches += 1;+ assert_eq!(selected, path);+ assert!(args.is_empty());+ Ok(())+ })+ .unwrap();+ assert_eq!(launches, 1);+ }++ #[test]+ fn linux_activation_requires_a_resolved_binary_before_launch() {+ let result = super::launch_linux_activation(None, |_, _| {+ panic!("a missing GPUI binary must not be launched")+ });+ assert_eq!(result.unwrap_err(), "Cap GPUI isn't included in this build");+ }++ #[test]+ fn linux_activation_preserves_launch_failure() {+ let path = std::path::Path::new("/opt/cap/cap-gpui");+ let result = super::launch_linux_activation(Some(path), |_, _| {+ Err("Failed to launch Cap GPUI: permission denied".into())+ });+ assert_eq!(+ result.unwrap_err(),+ "Failed to launch Cap GPUI: permission denied"+ );+ }++ #[test]+ fn startup_redirect_exits_once_when_no_open_event_arrives() {+ let state = StartupRedirectState::default();++ assert_eq!(state.exit_if_pending(), Some(None));+ assert!(state.exit_if_pending().is_none());+ assert!(!state.begin_forwarding());+ assert!(!state.exit_after_forwarding());+ }++ #[test]+ fn startup_redirect_waits_for_forwarding_before_exiting_once() {+ let state = StartupRedirectState::default();++ assert!(state.begin_forwarding());+ assert!(!state.begin_forwarding());+ assert!(state.exit_if_pending().is_none());+ assert!(state.exit_after_forwarding());+ assert!(!state.exit_after_forwarding());+ }++ #[test]+ fn startup_plain_launch_returns_its_reopen_intent_only_once() {+ let state = StartupRedirectState::with_reopen(123);++ assert_eq!(state.exit_if_pending(), Some(Some(123)));+ assert!(state.exit_if_pending().is_none());+ assert!(!state.begin_forwarding());+ assert!(!state.exit_after_forwarding());+ }++ #[test]+ fn startup_open_event_suppresses_pending_plain_reopen() {+ let state = StartupRedirectState::with_reopen(123);++ assert!(state.begin_forwarding());+ assert!(state.exit_if_pending().is_none());+ assert!(!state.begin_forwarding());+ assert!(state.exit_after_forwarding());+ assert!(state.exit_if_pending().is_none());+ assert!(!state.exit_after_forwarding());+ }++ #[test]+ fn update_handoff_requires_a_valid_process_id() {+ assert_eq!(+ parse_update_handoff("1234"),+ Some(UpdateHandoff {+ pid: 1234,+ simulated: false,+ })+ );+ assert_eq!(parse_update_handoff("0"), None);+ assert_eq!(parse_update_handoff("cap-gpui"), None);+ assert_eq!(parse_update_handoff("simulate:0"), None);+ }++ #[test]+ fn simulated_update_handoffs_are_debug_only() {+ let parsed = parse_update_handoff("simulate:4321");+ if cfg!(debug_assertions) {+ assert_eq!(+ parsed,+ Some(UpdateHandoff {+ pid: 4321,+ simulated: true,+ })+ );+ } else {+ assert_eq!(parsed, None);+ }+ }++ #[test]+ fn gpui_process_image_must_match_exactly() {+ assert!(is_gpui_process_image(std::path::Path::new(BINARY_NAME)));+ assert!(is_gpui_process_image(std::path::Path::new(+ &BINARY_NAME.to_ascii_uppercase()+ )));+ assert!(!is_gpui_process_image(std::path::Path::new("not-cap-gpui")));+ assert!(!is_gpui_process_image(std::path::Path::new(+ "cap-gpui-helper"+ )));+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn linux_process_check_distinguishes_live_unlinked_and_exited_processes() {+ let directory = tempfile::tempdir().unwrap();+ let binary = directory.path().join(BINARY_NAME);+ std::fs::copy("/bin/sleep", &binary).unwrap();+ let mut child = std::process::Command::new(&binary)+ .arg("30")+ .spawn()+ .unwrap();+ let pid = child.id();+ let started = std::time::Instant::now();+ // spawn can return before /proc stops exposing the child's pre-exec image.+ while !std::fs::read_link(format!("/proc/{pid}/exe")).is_ok_and(|path| path == binary)+ && started.elapsed() < std::time::Duration::from_secs(5)+ {+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ let live = super::linux_gpui_process_is_running(pid);+ std::fs::remove_file(&binary).unwrap();+ let unlinked = super::linux_gpui_process_is_running(pid);+ child.kill().unwrap();+ let started = std::time::Instant::now();+ let mut zombie = false;+ while started.elapsed() < std::time::Duration::from_secs(5) {+ zombie = std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| {+ stat.rsplit_once(") ")+ .is_some_and(|(_, state)| state.starts_with('Z'))+ });+ if zombie {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ let exited = super::linux_gpui_process_is_running(pid);+ child.wait().unwrap();++ assert!(live);+ assert!(unlinked);+ assert!(zombie);+ assert!(!exited);+ assert!(!super::linux_gpui_process_is_running(pid));+ assert!(!super::linux_gpui_process_is_running(std::process::id()));+ }++ #[test]+ fn gpui_forwarding_endpoint_requires_the_owner_identity() {+ assert_eq!(+ parse_gpui_forwarding_endpoint("4321:49152:0123456789abcdef"),+ Some(GpuiForwardingEndpoint {+ pid: 4321,+ port: 49152,+ secret: 0x0123_4567_89ab_cdef,+ })+ );+ assert_eq!(parse_gpui_forwarding_endpoint("0:49152:1234"), None);+ assert_eq!(parse_gpui_forwarding_endpoint("4321:0:1234"), None);+ assert_eq!(parse_gpui_forwarding_endpoint("4321:49152:xyz"), None);+ assert_eq!(+ parse_gpui_forwarding_endpoint("4321:49152:1234:extra"),+ None+ );+ }++ #[test]+ fn forwarded_gpui_deep_links_are_scheme_and_size_limited() {+ assert!(is_forwardable_gpui_deep_link(+ "cap-desktop://signin?token=test"+ ));+ assert!(is_forwardable_gpui_deep_link(+ "cap://action?value=%22stop_recording%22"+ ));+ assert!(!is_forwardable_gpui_deep_link("https://cap.so/signin"));+ assert!(!is_forwardable_gpui_deep_link("cap-desktop-other://signin"));+ assert!(!is_forwardable_gpui_deep_link(&format!(+ "cap://action?value={}",+ "x".repeat(MAX_FORWARDED_DEEP_LINK_BYTES)+ )));+ }++ #[test]+ fn project_arguments_become_encoded_open_editor_actions() {+ let directory = tempfile::tempdir().unwrap();+ let project = directory.path().join("Recording #1 & draft.cap");+ std::fs::create_dir(&project).unwrap();++ let forwarded = forwarded_gpui_argument(project.to_str().unwrap()).unwrap();+ let url = reqwest::Url::parse(&forwarded).unwrap();+ let value = url+ .query_pairs()+ .find_map(|(key, value)| (key == "value").then_some(value.into_owned()))+ .unwrap();+ let action: serde_json::Value = serde_json::from_str(&value).unwrap();++ assert_eq!(url.scheme(), "cap-desktop");+ assert_eq!(url.host_str(), Some("action"));+ assert_eq!(+ action["open_editor"]["project_path"],+ project.canonicalize().unwrap().to_string_lossy().as_ref()+ );+ }++ #[test]+ fn forwarded_project_arguments_reject_missing_and_non_project_paths() {+ let directory = tempfile::tempdir().unwrap();+ let ordinary = directory.path().join("notes.txt");+ std::fs::write(&ordinary, "notes").unwrap();++ assert!(forwarded_gpui_argument(ordinary.to_str().unwrap()).is_none());+ assert!(+ forwarded_gpui_argument(directory.path().join("missing.cap").to_str().unwrap())+ .is_none()+ );+ assert_eq!(+ forwarded_gpui_argument("cap-desktop://signin?token=secret"),+ Some("cap-desktop://signin?token=secret".to_string())+ );+ }+ #[cfg(unix)]+ #[test]+ fn forwarded_project_arguments_reject_symlinks() {+ let directory = tempfile::tempdir().unwrap();+ let project = directory.path().join("Recording.cap");+ let symlink = directory.path().join("Shortcut.cap");+ std::fs::create_dir(&project).unwrap();+ std::os::unix::fs::symlink(&project, &symlink).unwrap();++ assert!(forwarded_gpui_argument(symlink.to_str().unwrap()).is_none());+ }++ #[test]+ fn file_urls_become_open_editor_actions() {+ let directory = tempfile::tempdir().unwrap();+ let project = directory.path().join("Recording.cap");+ std::fs::create_dir(&project).unwrap();+ let file_url = reqwest::Url::from_file_path(&project).unwrap();++ assert!(forwarded_gpui_argument(file_url.as_str()).is_some());+ }++ #[test]+ fn only_launches_without_forwardable_actions_request_reopening() {+ assert!(super::gpui_launch_needs_reopen(&[]));+ let directory = tempfile::tempdir().unwrap();+ let project = directory.path().join("Recording.cap");+ std::fs::create_dir(&project).unwrap();+ for argument in [+ "cap-desktop://auth?token=fixture".to_string(),+ "cap://action?value=%22stop_recording%22".to_string(),+ project.to_str().unwrap().to_string(),+ reqwest::Url::from_file_path(&project).unwrap().to_string(),+ ] {+ assert!(!super::gpui_launch_needs_reopen(&[argument]));+ }+ }++ #[cfg(target_os = "macos")]#[test]- fn executables_launch_directly_with_no_arguments() {- let path = std::path::PathBuf::from("/opt/Cap ' \" $/Cap");- let command = super::launch_command(&CapInstall::Executable(path.clone()));- assert_eq!(command.get_program(), path.as_os_str());- assert_eq!(command.get_args().count(), 0);+ fn macos_reopen_sends_private_packet_and_requires_acknowledgment() {+ use std::{+ io::{Read, Write},+ time::{Duration, Instant},+ };++ for reply in [0_u8, 1] {+ let listener = std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).unwrap();+ listener.set_nonblocking(true).unwrap();+ let endpoint = GpuiForwardingEndpoint {+ pid: 123,+ port: listener.local_addr().unwrap().port(),+ secret: 456,+ };+ let server = std::thread::spawn(move || {+ let started = Instant::now();+ let mut stream = loop {+ match listener.accept() {+ Ok((stream, _)) => break stream,+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {+ assert!(started.elapsed() < Duration::from_secs(5));+ std::thread::sleep(Duration::from_millis(5));+ }+ Err(error) => panic!("Reopen listener failed: {error}"),+ }+ };+ stream.set_nonblocking(false).unwrap();+ stream+ .set_read_timeout(Some(Duration::from_secs(2)))+ .unwrap();+ stream+ .set_write_timeout(Some(Duration::from_secs(2)))+ .unwrap();+ let mut packet = [0_u8; 12];+ stream.read_exact(&mut packet).unwrap();+ assert_eq!(&packet[..8], &endpoint.secret.to_be_bytes());+ assert_eq!(&packet[8..], &0_u32.to_be_bytes());+ stream.write_all(&[reply]).unwrap();+ });+ let result = super::send_gpui_reopen(endpoint, Instant::now(), Duration::from_secs(2));+ server.join().unwrap();+ if reply == 1 {+ result.unwrap();+ } else {+ assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::InvalidData);+ }+ }}#[cfg(target_os = "macos")]#[test]- fn bundles_open_as_a_new_instance_with_the_path_as_a_literal_argument() {- let bundle = std::path::PathBuf::from("/Applications/Cap ' \" $.app");- let command = super::launch_command(&CapInstall::Bundle(bundle.clone()));- assert_eq!(command.get_program(), "/usr/bin/open");+ fn macos_reopen_deadline_also_bounds_missing_acknowledgment() {+ use std::time::{Duration, Instant};++ let listener = std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).unwrap();+ let endpoint = GpuiForwardingEndpoint {+ pid: 123,+ port: listener.local_addr().unwrap().port(),+ secret: 456,+ };+ assert_eq!(+ super::send_gpui_reopen(endpoint, Instant::now(), Duration::from_millis(100))+ .unwrap_err()+ .kind(),+ std::io::ErrorKind::TimedOut+ );+ let expired = Instant::now().checked_sub(Duration::from_secs(2)).unwrap();assert_eq!(- command.get_args().collect::<Vec<_>>(),- [std::ffi::OsStr::new("-n"), bundle.as_os_str()]+ super::send_gpui_reopen(endpoint, expired, Duration::from_secs(2))+ .unwrap_err()+ .kind(),+ std::io::ErrorKind::TimedOut);}#[cfg(target_os = "macos")]#[test]- fn cap_is_found_beside_classic_and_in_both_application_folders() {- use std::path::{Path, PathBuf};+ fn macos_reopen_rejects_shared_or_linked_endpoint_and_changed_pid() {+ use std::os::unix::fs::{PermissionsExt, symlink};+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("cap-gpui.ipc");+ std::fs::write(&path, "123:456:789").unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();+ assert_eq!(+ super::read_macos_gpui_metadata(&path, true).unwrap(),+ "123:456:789"+ );+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();assert_eq!(- super::installed_candidates(- Some(Path::new(- "/Volumes/Work/Apps/Cap Classic.app/Contents/MacOS/Cap Classic"- )),- Some(Path::new("/Users/x")),- ),- vec![- PathBuf::from("/Volumes/Work/Apps/Cap.app"),- PathBuf::from("/Applications/Cap.app"),- PathBuf::from("/Users/x/Applications/Cap.app"),- ]+ super::read_macos_gpui_metadata(&path, true)+ .unwrap_err()+ .kind(),+ std::io::ErrorKind::PermissionDenied);+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();+ let linked = directory.path().join("linked.ipc");+ symlink(&path, &linked).unwrap();+ assert!(super::read_macos_gpui_metadata(&linked, true).is_err());+ std::fs::remove_file(&linked).unwrap();+ std::fs::hard_link(&path, &linked).unwrap();+ assert!(super::read_macos_gpui_metadata(&path, true).is_err());+ let pidfile = directory.path().join("cap-gpui.pid");+ std::fs::write(&pidfile, "123").unwrap();+ assert!(!super::macos_reopen_incumbent(&pidfile, 456).unwrap());+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "123:456:789");+ assert_eq!(std::fs::read_to_string(&pidfile).unwrap(), "123");}}diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex d458255c0..721e6e03c 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -7213,7 +7213,50 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: Option<PathBspecta_builder.mount_events(&app);general_settings::init(&app);- gpui_app::watch_for_switches(&app);+ // Before anything shows a window or initialises further state: when+ // the native app owns the session, this one only exists to start it.+ if gpui_app::redirect_at_startup_if_enabled(&app)? {+ // Nothing is managed yet, so `ExitRequested` would otherwise+ // spawn a cleanup with no `AppExitState` to guard it. Marking+ // the exit as already begun takes the plain runtime-exit path.+ let exit_state = AppExitState::default();+ exit_state.begin();+ app.manage(exit_state);+ crash_sentinel::mark_clean_exit();++ #[cfg(target_os = "macos")]+ {+ if app.try_state::<gpui_app::StartupRedirectState>().is_none() {+ app.manage(gpui_app::StartupRedirectState::default());+ }+ finish_macos_startup_opens(&app, StartupOpenDestination::Gpui);+ gpui_app::retire_foreground_parent_for_handoff(&app);+ let app = app.clone();+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(750)).await;+ let Some(reopen_pid) = app+ .try_state::<gpui_app::StartupRedirectState>()+ .and_then(|state| state.exit_if_pending())+ else {+ return;+ };+ if let Some(pid) = reopen_pid+ {+ match tokio::task::spawn_blocking(move || gpui_app::request_gpui_reopen(pid)).await {+ Ok(Ok(())) => info!(pid, "Queued a request to reopen Cap GPUI"),+ Ok(Err(error)) => warn!(pid, %error, "Could not confirm Cap GPUI reopening; the existing instance remains unchanged"),+ Err(error) => warn!(pid, %error, "Cap GPUI reopen forwarding did not finish"),+ }+ }+ app.exit(0);+ });+ }++ #[cfg(not(target_os = "macos"))]+ app.exit(0);++ return Ok(());+ }app.manage(clean_capture::State::default());hotkeys::init(&app);configure_camera_blur_recovery(&app, previous_termination);@@ -7534,13 +7577,9 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: Option<PathBapp.deep_link().on_open_url(move |event| {deeplink_actions::handle(&app_handle, event.urls());});- #[cfg(all(not(debug_assertions), any(windows, target_os = "linux")))]- if let Err(error) = app.deep_link().register_all() {- warn!(%error, "Could not register Cap Classic's link handler");- }#[cfg(target_os = "macos")]- finish_macos_startup_opens(&app);+ finish_macos_startup_opens(&app, StartupOpenDestination::Desktop);Ok(())})@@ -7924,6 +7963,15 @@ fn handle_single_instance(app: &AppHandle, args: Vec<String>) {return;}+ if gpui_app::handle_update_handoff(app) {+ return;+ }++ #[cfg(any(target_os = "macos", windows))]+ if gpui_app::forward_deep_links_to_active_gpui(app, &args) {+ return;+ }+let action_urls = args.iter().filter(|arg| arg.starts_with("cap-desktop://"))@@ -8007,48 +8055,101 @@ where}}+#[cfg(any(target_os = "macos", test))]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum StartupOpenDestination {+ Desktop,+ Gpui,+}++#[cfg(any(target_os = "macos", test))]+struct StartupOpenDispatch {+ destination: StartupOpenDestination,+ urls: Vec<tauri::Url>,+}+#[cfg(any(target_os = "macos", test))]#[derive(Default)]struct StartupOpenQueue {- ready: bool,+ destination: Option<StartupOpenDestination>,cancelled: bool,urls: Vec<tauri::Url>,+ gpui_forwarding: bool,+ gpui_dispatched: Vec<tauri::Url>,}#[cfg(any(target_os = "macos", test))]impl StartupOpenQueue {- fn request(&mut self, urls: Vec<tauri::Url>) -> Result<Option<Vec<tauri::Url>>, String> {+ fn request(&mut self, urls: Vec<tauri::Url>) -> Result<Option<StartupOpenDispatch>, String> {if self.cancelled {return Err("Cap startup stopped before the project could be opened".into());}- if self.ready {- return Ok(Some(urls));+ if self.destination == Some(StartupOpenDestination::Desktop) {+ return Ok(Some(StartupOpenDispatch {+ destination: StartupOpenDestination::Desktop,+ urls,+ }));}let mut additions = Vec::new();for url in urls {- if self.urls.contains(&url) || additions.contains(&url) {+ if self.urls.contains(&url)+ || self.gpui_dispatched.contains(&url)+ || additions.contains(&url)+ {continue;}- if self.urls.len() + additions.len() >= 64 {+ if self.urls.len() + self.gpui_dispatched.len() + additions.len() >= 64 {return Err("Too many projects were requested while Cap was starting".into());}additions.push(url);}self.urls.extend(additions);+ if self.destination == Some(StartupOpenDestination::Gpui) && !self.gpui_forwarding {+ return Ok(self.take_queued());+ }Ok(None)}- fn finish(&mut self) -> Option<Vec<tauri::Url>> {- if self.cancelled || self.ready {+ fn finish(&mut self, destination: StartupOpenDestination) -> Option<StartupOpenDispatch> {+ if self.cancelled || self.destination.is_some() {+ return None;+ }+ self.destination = Some(destination);+ self.take_queued()+ }++ fn take_queued(&mut self) -> Option<StartupOpenDispatch> {+ let destination = self.destination?;+ if self.urls.is_empty() {+ return None;+ }+ let urls = std::mem::take(&mut self.urls);+ if destination == StartupOpenDestination::Gpui {+ self.gpui_forwarding = true;+ self.gpui_dispatched.extend(urls.iter().cloned());+ }+ Some(StartupOpenDispatch { destination, urls })+ }++ fn next_gpui_batch(&mut self) -> Option<StartupOpenDispatch> {+ if self.cancelled+ || self.destination != Some(StartupOpenDestination::Gpui)+ || !self.gpui_forwarding+ {return None;}- self.ready = true;- (!self.urls.is_empty()).then(|| std::mem::take(&mut self.urls))+ if let Some(dispatch) = self.take_queued() {+ return Some(dispatch);+ }+ self.cancel();+ None}fn cancel(&mut self) {self.cancelled = true;self.urls.clear();+ self.gpui_dispatched.clear();+ self.gpui_forwarding = false;}}@@ -8063,7 +8164,7 @@ struct StartupOpenGuard(StartupOpenGate);impl Drop for StartupOpenGuard {fn drop(&mut self) {if let Ok(mut queue) = self.0.0.lock()- && !queue.ready+ && queue.destination.is_none(){queue.cancel();}@@ -8080,26 +8181,26 @@ fn queue_macos_startup_urls(app: &AppHandle, urls: Vec<tauri::Url>) -> Result<().lock().map_err(|_| "Cap startup file-open state is unavailable".to_string())?.request(urls)?;- if let Some(urls) = dispatch {- dispatch_macos_startup_urls(app, urls);+ if let Some(dispatch) = dispatch {+ dispatch_macos_startup_urls(app, dispatch);}Ok(())}#[cfg(target_os = "macos")]-fn finish_macos_startup_opens(app: &AppHandle) {+fn finish_macos_startup_opens(app: &AppHandle, destination: StartupOpenDestination) {let Some(gate) = app.try_state::<StartupOpenGate>() else {return;};let dispatch = match gate.0.lock() {- Ok(mut queue) => queue.finish(),+ Ok(mut queue) => queue.finish(destination),Err(error) => {warn!(%error, "Could not release startup project requests");return;}};- if let Some(urls) = dispatch {- dispatch_macos_startup_urls(app, urls);+ if let Some(dispatch) = dispatch {+ dispatch_macos_startup_urls(app, dispatch);}}@@ -8113,7 +8214,76 @@ fn cancel_macos_startup_opens(app: &AppHandle) {}#[cfg(target_os = "macos")]-fn dispatch_macos_startup_urls(app: &AppHandle, urls: Vec<tauri::Url>) {+fn dispatch_macos_startup_urls(app: &AppHandle, dispatch: StartupOpenDispatch) {+ let urls = dispatch.urls;+ let arguments = urls+ .iter()+ .map(|url| url.as_str().to_string())+ .collect::<Vec<_>>();++ if dispatch.destination == StartupOpenDestination::Gpui {+ let Some(redirect) = app.try_state::<gpui_app::StartupRedirectState>() else {+ warn!("Cap GPUI startup forwarding state is unavailable");+ return;+ };+ if redirect.begin_forwarding() {+ let app = app.clone();+ tokio::spawn(async move {+ let mut arguments = arguments;+ let mut forwarded_pid = None;+ loop {+ let forwarded = tokio::task::spawn_blocking(move || {+ gpui_app::forward_deep_links_to_gpui_when_ready(&arguments)+ })+ .await+ .ok()+ .flatten();+ if let Some(pid) = forwarded {+ forwarded_pid = Some(pid);+ } else {+ warn!("Could not forward the requested project batch to Cap GPUI");+ }+ let next = app.try_state::<StartupOpenGate>().and_then(|gate| {+ gate.0+ .lock()+ .ok()+ .and_then(|mut queue| queue.next_gpui_batch())+ });+ let Some(next) = next else {+ break;+ };+ arguments = next+ .urls+ .iter()+ .map(|url| url.as_str().to_string())+ .collect();+ }++ if let Some(pid) = forwarded_pid+ && let Err(error) = app.run_on_main_thread(move || {+ gpui_app::activate_instance(pid);+ })+ {+ warn!(%error, "Could not activate Cap GPUI after forwarding a project");+ }+ if app+ .try_state::<gpui_app::StartupRedirectState>()+ .is_some_and(|state| state.exit_after_forwarding())+ {+ app.exit(0);+ }+ });+ } else {+ cancel_macos_startup_opens(app);+ warn!("Cap GPUI handoff already finished before the project could be forwarded");+ }+ return;+ }++ if gpui_app::forward_deep_links_to_active_gpui(app, &arguments) {+ return;+ }+for url in urls {if url.scheme() == "file"&& let Ok(path) = url.to_file_path()@@ -8134,6 +8304,17 @@ fn handle_run_event(_handle: &AppHandle, event: tauri::RunEvent) {}#[cfg(target_os = "macos")]tauri::RunEvent::Reopen { .. } => {+ if _handle+ .try_state::<gpui_app::StartupRedirectState>()+ .is_some()+ {+ return;+ }++ if gpui_app::handle_update_handoff(_handle) {+ return;+ }+let should_focus_onboarding = should_show_onboarding(_handle);if should_focus_onboarding@@ -9072,7 +9253,7 @@ fn open_project_from_path(path: &Path, app: AppHandle) -> Result<(), String> {.0.lock().map_err(|_| "Cap startup file-open state is unavailable".to_string())?;- !queue.cancelled && queue.ready+ !queue.cancelled && queue.destination == Some(StartupOpenDestination::Desktop)};if !ready {let path = if path.is_absolute() {@@ -9123,7 +9304,7 @@ fn open_project_from_path(path: &Path, app: AppHandle) -> Result<(), String> {#[cfg(test)]mod startup_project_open_tests {- use super::{StartupOpenGate, StartupOpenGuard, StartupOpenQueue};+ use super::{StartupOpenDestination, StartupOpenGate, StartupOpenGuard, StartupOpenQueue};fn project(name: &str) -> tauri::Url {tauri::Url::parse(&format!("file:///recordings/{name}.cap")).unwrap()@@ -9134,17 +9315,35 @@ mod startup_project_open_tests {let mut queue = StartupOpenQueue::default();let urls = vec![project("first"), project("second")];assert!(queue.request(urls.clone()).unwrap().is_none());- assert_eq!(queue.finish().unwrap(), urls);+ let dispatch = queue.finish(StartupOpenDestination::Desktop).unwrap();+ assert_eq!(dispatch.destination, StartupOpenDestination::Desktop);+ assert_eq!(dispatch.urls, urls);assert!(queue.urls.is_empty());- assert!(queue.finish().is_none());+ assert!(queue.finish(StartupOpenDestination::Desktop).is_none());+ }++ #[test]+ fn queued_files_follow_gpui_handoff_without_opening_classic_editors() {+ let mut queue = StartupOpenQueue::default();+ let url = project("handoff");+ assert!(queue.request(vec![url.clone()]).unwrap().is_none());+ let dispatch = queue.finish(StartupOpenDestination::Gpui).unwrap();+ assert_eq!(dispatch.destination, StartupOpenDestination::Gpui);+ assert_eq!(dispatch.urls, [url]);+ assert!(queue.request(vec![project("later")]).unwrap().is_none());+ let dispatch = queue.next_gpui_batch().unwrap();+ assert_eq!(dispatch.destination, StartupOpenDestination::Gpui);+ assert_eq!(dispatch.urls, [project("later")]);}#[test]fn normal_post_ready_file_opens_dispatch_immediately() {let mut queue = StartupOpenQueue::default();- assert!(queue.finish().is_none());+ assert!(queue.finish(StartupOpenDestination::Desktop).is_none());let url = project("ready");- assert_eq!(queue.request(vec![url.clone()]).unwrap().unwrap(), [url]);+ let dispatch = queue.request(vec![url.clone()]).unwrap().unwrap();+ assert_eq!(dispatch.destination, StartupOpenDestination::Desktop);+ assert_eq!(dispatch.urls, [url]);}#[test]@@ -9163,23 +9362,29 @@ mod startup_project_open_tests {let mut queue = gate.0.lock().unwrap();assert!(queue.urls.is_empty());assert!(queue.request(vec![project("later")]).is_err());- assert!(queue.finish().is_none());+ assert!(queue.finish(StartupOpenDestination::Desktop).is_none());+ assert!(queue.finish(StartupOpenDestination::Gpui).is_none());}#[test]- fn completed_setup_guard_keeps_dispatching() {- let gate = StartupOpenGate::default();- let guard = StartupOpenGuard(gate.clone());- assert!(gate.0.lock().unwrap().finish().is_none());- drop(guard);- let urls = gate- .0- .lock()- .unwrap()- .request(vec![project("ready")])- .unwrap()- .unwrap();- assert_eq!(urls, [project("ready")]);+ fn completed_setup_guard_preserves_selected_destination() {+ for destination in [+ StartupOpenDestination::Desktop,+ StartupOpenDestination::Gpui,+ ] {+ let gate = StartupOpenGate::default();+ let guard = StartupOpenGuard(gate.clone());+ assert!(gate.0.lock().unwrap().finish(destination).is_none());+ drop(guard);+ let dispatch = gate+ .0+ .lock()+ .unwrap()+ .request(vec![project("ready")])+ .unwrap()+ .unwrap();+ assert_eq!(dispatch.destination, destination);+ }}#[test]@@ -9199,13 +9404,43 @@ mod startup_project_open_tests {}#[test]- fn cancellation_stops_dispatch() {+ fn gpui_handoff_drains_later_batches_without_duplicate_dispatches() {let mut queue = StartupOpenQueue::default();- assert!(queue.finish().is_none());- assert!(queue.request(vec![project("first")]).unwrap().is_some());- queue.cancel();+ assert!(queue.finish(StartupOpenDestination::Gpui).is_none());+ let first = queue.request(vec![project("first")]).unwrap().unwrap();+ assert_eq!(first.urls, [project("first")]);+ assert!(+ queue+ .request(vec![project("first"), project("second")])+ .unwrap()+ .is_none()+ );+ assert!(queue.request(vec![project("second")]).unwrap().is_none());+ let second = queue.next_gpui_batch().unwrap();+ assert_eq!(second.urls, [project("second")]);+ assert_eq!(second.destination, StartupOpenDestination::Gpui);+ assert!(queue.request(vec![project("third")]).unwrap().is_none());+ assert_eq!(queue.next_gpui_batch().unwrap().urls, [project("third")]);+ assert!(queue.next_gpui_batch().is_none());assert!(queue.request(vec![project("after-exit")]).is_err());- assert!(queue.urls.is_empty());+ }++ #[test]+ fn cancellation_stops_desktop_dispatch_and_gpui_pending_batches() {+ for destination in [+ StartupOpenDestination::Desktop,+ StartupOpenDestination::Gpui,+ ] {+ let mut queue = StartupOpenQueue::default();+ assert!(queue.finish(destination).is_none());+ assert!(queue.request(vec![project("first")]).unwrap().is_some());+ let _ = queue.request(vec![project("pending")]).unwrap();+ queue.cancel();+ assert!(queue.request(vec![project("after-exit")]).is_err());+ assert!(queue.next_gpui_batch().is_none());+ assert!(queue.urls.is_empty());+ assert!(queue.gpui_dispatched.is_empty());+ }}}diff --git a/apps/desktop/src-tauri/src/updates.rs b/apps/desktop/src-tauri/src/updates.rsindex 5987bfb78..da4ccf8d8 100644--- a/apps/desktop/src-tauri/src/updates.rs+++ b/apps/desktop/src-tauri/src/updates.rs@@ -98,9 +98,7 @@ fn current_channel(app: &AppHandle) -> UpdateChannel {.unwrap_or_default()}-const CLASSIC_PLATFORM_SUFFIX: &str = "-classic";--fn platform_target() -> Result<String, String> {+fn updater_target() -> Result<String, String> {let arch = if cfg!(target_arch = "aarch64") {"aarch64"} else {@@ -122,16 +120,6 @@ fn platform_target() -> Result<String, String> {}}-/// Cap Classic ships beside Cap in the same release under `-classic`-/// platforms; the unsuffixed ones carry Cap itself.-fn classic_target(platform: &str) -> String {- format!("{platform}{CLASSIC_PLATFORM_SUFFIX}")-}--fn updater_target() -> Result<String, String> {- platform_target().map(|platform| classic_target(&platform))-}-fn endpoint(channel: UpdateChannel) -> Result<Url, String> {let url = match channel {UpdateChannel::Stable => UPDATE_ENDPOINT.to_string(),@@ -433,17 +421,3 @@ pub fn spawn_background_loop(app: AppHandle) {}});}--#[cfg(test)]-mod tests {- #[test]- fn classic_updates_resolve_only_to_classic_platforms() {- for (platform, expected) in [- ("darwin-aarch64", "darwin-aarch64-classic"),- ("windows-x86_64", "windows-x86_64-classic"),- ("linux-x86_64-appimage", "linux-x86_64-appimage-classic"),- ] {- assert_eq!(super::classic_target(platform), expected);- }- }-}diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 20dcd54f1..c7e1151e4 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -55,7 +55,7 @@ pub(crate) fn acquire_upload_lock(recording_dir: &Path) -> Result<UploadLock, Aulet lock = UploadLock::acquire(recording_dir).map_err(|error| error.to_string())?;match std::fs::symlink_metadata(recording_dir.join("instant-upload.json")) {Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(lock),- Ok(_) => Err("This recording's upload is managed by Cap; local files retained".into()),+ Ok(_) => Err("This recording's upload is managed by Cap GPUI; local files retained".into()),Err(error) => Err(format!("Could not verify recording upload ownership: {error}").into()),}}diff --git a/apps/desktop/src-tauri/tauri.prod.conf.json b/apps/desktop/src-tauri/tauri.prod.conf.jsonindex 9af816915..3297c552a 100644--- a/apps/desktop/src-tauri/tauri.prod.conf.json+++ b/apps/desktop/src-tauri/tauri.prod.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2",- "productName": "Cap Classic",- "mainBinaryName": "Cap Classic",+ "productName": "Cap",+ "mainBinaryName": "Cap","identifier": "so.cap.desktop","build": {"beforeBundleCommand": "node scripts/prodBeforeBundle.js"@@ -17,22 +17,10 @@}},"bundle": {- "fileAssociations": [- {- "ext": ["cap"],- "name": "Cap Classic Project",- "mimeType": "application/x-cap-project",- "role": "Editor",- "rank": "Alternate"- }- ],"macOS": {"entitlements": "Entitlements.plist"},"windows": {- "nsis": {- "installerHooks": "nsis/installer-hooks.nsh"- },"wix": {"upgradeCode": "a765d9de-0ecc-55d0-b8a0-61e9d3276664"}diff --git a/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx b/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsxindex 16701709a..2a2f89b0a 100644--- a/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx+++ b/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx@@ -1,7 +1,5 @@-import { Button } from "@cap/ui-solid";import { invoke } from "@tauri-apps/api/core";import { type } from "@tauri-apps/plugin-os";-import * as shell from "@tauri-apps/plugin-shell";import { createResource, createSignal, For, onCleanup, Show } from "solid-js";import { createStore } from "solid-js/store";@@ -13,7 +11,6 @@ import {import {Section,SectionRows,- SettingItem,SettingsPageContent,ToggleSettingItem,} from "./Setting";@@ -23,11 +20,11 @@ import {// The mirror of this sequence lives in `render_switch_overlay` in the native// app's `settings_pages.rs`.const SWITCH_SENTENCES = [- "Switching to Cap.",+ "Switching to the native Cap app.",+ "It will look almost identical. That is the point.","Same Cap, rebuilt fully native for performance.",- "Your recordings and settings come with you.",+ "Experimental. Your recordings and settings come with you.",];-const CAP_DOWNLOAD_URL = "https://cap.so/download";const SENTENCE_MS = 1300;const COUNTDOWN_FROM = 5;@@ -58,7 +55,7 @@ function Inner(props: {deriveGeneralSettings(props.initialStore),);- const [capInstalled] = createResource(() =>+ const [gpuiAvailable] = createResource(() =>invoke<boolean>("gpui_app_available").catch(() => false),);@@ -76,21 +73,39 @@ function Inner(props: {setTakeover(null);};+ // A failed takeover leaves the overlay up but puts the toggle back where+ // it was, since nothing was switched.+ const takeoverActive = () => {+ const state = takeover();+ return state !== null && state.error === null;+ };+const performSwitch = async () => {try {+ await generalSettingsStore.set({ enableGpuiApp: true });await invoke("switch_to_gpui_app");} catch (error) {+ // The setting is written first so the native app comes up already+ // owning the session; a refused handoff has to put it back.+ await generalSettingsStore+ .set({ enableGpuiApp: false })+ .catch(() => undefined);setTakeover((state) =>state? {...state,- error: typeof error === "string" ? error : "Couldn't open Cap.",+ error:+ typeof error === "string"+ ? error+ : "Couldn't open the native app.",}: state,);}};+ // The toggle is the confirmation: flipping it starts the takeover, and+ // Cancel is on screen for the whole sequence.const startTakeover = () => {clearTimers();setTakeover({ sentence: 0, remaining: COUNTDOWN_FROM, error: null });@@ -168,40 +183,22 @@ function Inner(props: {</SectionRows></Section>- <Section title="Cap">- <SectionRows>- <SettingItem- label="Switch to Cap"- description={- capInstalled()- ? "Close Cap Classic and open Cap, the fully native version. Your recordings and settings are shared, and you can come back from Cap's Experimental settings."- : "Cap, the fully native version, isn't installed on this computer yet. Download it to switch; your recordings and settings are shared."- }- >- <Show- when={capInstalled()}- fallback={- <Button- size="sm"- variant="dark"- onClick={() => void shell.open(CAP_DOWNLOAD_URL)}- >- Download- </Button>- }- >- <Button- size="sm"- variant="dark"- disabled={takeover() !== null}- onClick={startTakeover}- >- Switch- </Button>- </Show>- </SettingItem>- </SectionRows>- </Section>+ <Show when={gpuiAvailable()}>+ <Section title="Native app">+ <SectionRows>+ <ToggleSettingItem+ label="Cap GPUI"+ description="Close this app and reopen the experimental fully-native version of Cap. It is unfinished, so expect missing features. Your recordings and settings are shared, and you can switch back from its Experimental settings."+ value={!!settings.enableGpuiApp || takeoverActive()}+ onChange={(value) => {+ if (value) startTakeover();+ else if (takeover()) cancelTakeover();+ else void handleChange("enableGpuiApp", false);+ }}+ />+ </SectionRows>+ </Section>+ </Show></SettingsPageContent><Show when={takeover()}>diff --git a/apps/desktop/src/routes/(window-chrome)/update.tsx b/apps/desktop/src/routes/(window-chrome)/update.tsxindex febe082eb..6b427b629 100644--- a/apps/desktop/src/routes/(window-chrome)/update.tsx+++ b/apps/desktop/src/routes/(window-chrome)/update.tsx@@ -10,14 +10,21 @@ import {Switch,} from "solid-js";import { commands, events } from "~/utils/tauri";-import { restartAfterUpdate } from "~/utils/updater";+import { restartAfterUpdate, returnToGpui } from "~/utils/updater";export default function () {const navigate = useNavigate();const [updateError, setUpdateError] = createSignal<string | null>(null);+ const searchParams = new URLSearchParams(window.location.search);+ const fromGpui = searchParams.get("source") === "gpui";+ const simulatedUpdate =+ import.meta.env.DEV &&+ fromGpui &&+ searchParams.get("simulateUpdate") === "1";const restart = async () => {try {- await restartAfterUpdate();+ if (simulatedUpdate) await returnToGpui();+ else await restartAfterUpdate();} catch (error) {console.error("Failed to restart after update:", error);setUpdateError(@@ -25,8 +32,22 @@ export default function () {);}};+ const returnSafelyToGpui = async () => {+ try {+ await returnToGpui();+ } catch (error) {+ console.error("Failed to return to Cap GPUI:", error);+ setUpdateError(+ typeof error === "string"+ ? error+ : "Unable to return to Cap GPUI safely.",+ );+ }+ };const [update] = createResource(async () => {+ if (simulatedUpdate) return { version: "99.0.0" };+try {const update = await commands.updatesCheck();if (!update) return;@@ -50,7 +71,13 @@ export default function () {<p class="text-(--text-tertiary) text-xs">If this issue persists, please contact support.</p>- <Button onClick={() => navigate("/")}>Go Back</Button>+ <Button+ onClick={() =>+ fromGpui ? void returnSafelyToGpui() : navigate("/")+ }+ >+ {fromGpui ? "Return to Cap GPUI" : "Go Back"}+ </Button></div></Show><Show when={!updateError() && update.loading}>@@ -63,6 +90,11 @@ export default function () {!update.loading && (<div class="flex flex-col items-center gap-4"><span class="text-(--text-tertiary)">No update available</span>+ <Show when={fromGpui}>+ <Button onClick={() => void returnSafelyToGpui()}>+ Return to Cap GPUI+ </Button>+ </Show></div>)}@@ -75,34 +107,57 @@ export default function () {const [updateStatus, setUpdateStatus] = createSignal<UpdateStatus>();- const unlisten = events.updateDownloadProgress.listen((e) => {- if (updateStatus()?.type === "done") return;+ if (simulatedUpdate) {+ let progress = 0;setUpdateStatus({type: "downloading",- progress: e.payload.downloaded,- contentLength: e.payload.total ?? undefined,+ progress,+ contentLength: 100,});- });- onCleanup(() => {- unlisten.then((cleanup) => cleanup());- });-- commands- .updatesDownloadAndInstall()- .then(() => {- setUpdateStatus({ type: "done" });- getCurrentWindow().requestUserAttention(- UserAttentionType.Informational,- );- })- .catch((e) => {- console.error("Failed to download/install update:", e);- setUpdateError(- typeof e === "string"- ? e- : "Failed to download or install the update.",- );+ const interval = window.setInterval(() => {+ progress = Math.min(progress + 4, 100);+ if (progress === 100) {+ window.clearInterval(interval);+ setUpdateStatus({ type: "done" });+ return;+ }+ setUpdateStatus({+ type: "downloading",+ progress,+ contentLength: 100,+ });+ }, 120);+ onCleanup(() => window.clearInterval(interval));+ } else {+ const unlisten = events.updateDownloadProgress.listen((e) => {+ if (updateStatus()?.type === "done") return;+ setUpdateStatus({+ type: "downloading",+ progress: e.payload.downloaded,+ contentLength: e.payload.total ?? undefined,+ });});+ onCleanup(() => {+ unlisten.then((cleanup) => cleanup());+ });++ commands+ .updatesDownloadAndInstall()+ .then(() => {+ setUpdateStatus({ type: "done" });+ getCurrentWindow().requestUserAttention(+ UserAttentionType.Informational,+ );+ })+ .catch((e) => {+ console.error("Failed to download/install update:", e);+ setUpdateError(+ typeof e === "string"+ ? e+ : "Failed to download or install the update.",+ );+ });+ }return (<div>diff --git a/apps/desktop/src/utils/general-settings.ts b/apps/desktop/src/utils/general-settings.tsindex f878b4488..c0eeb93b5 100644--- a/apps/desktop/src/utils/general-settings.ts+++ b/apps/desktop/src/utils/general-settings.ts@@ -8,6 +8,7 @@ export type GeneralSettingsStore = TauriGeneralSettingsStore & {transcriptionHints?: string[];enableTelemetry?: boolean;outOfProcessMuxer?: boolean;+ enableGpuiApp?: boolean;};export const DEFAULT_TRANSCRIPTION_HINTS = [diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 79601f4b4..767b14c17 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -33,8 +33,9 @@ async gpuiAppAvailable() : Promise<boolean> {return await TAURI_INVOKE("gpui_app_available");},/**- * Close this app and open Cap. A failure has to be reported rather than- * swallowed: the Experimental page shows it on its overlay.+ * Close this app and open the native one. The setting has already been written+ * by the caller, so a failure here has to be reported rather than swallowed:+ * the page reverts it.*/async switchToGpuiApp() : Promise<null> {return await TAURI_INVOKE("switch_to_gpui_app");@@ -1103,8 +1104,9 @@ previousRecordingsPaths?: string[];*/cameraBlurDisabledByCrash?: string | null; updateChannel?: UpdateChannel;/**- * Whether Cap, rather than this app, owns the session. Both apps' switch- * flows write it and the GPUI dev loop (`apps/desktop-gpui/dev.sh`) reads it.+ * Run the experimental gpui-native app (`cap-gpui`) *instead of* this one:+ * while enabled, startup hands off to it and exits, and the native app's+ * own Experimental page hands back. See `gpui_app.rs`.*/enableGpuiApp?: boolean }export type GifExportSettings = { fps: number; resolution_base: XY<number>; quality: GifQuality | null }diff --git a/apps/desktop/src/utils/updater.test.ts b/apps/desktop/src/utils/updater.test.tsindex 4be8012e0..d3a2aa716 100644--- a/apps/desktop/src/utils/updater.test.ts+++ b/apps/desktop/src/utils/updater.test.ts@@ -5,6 +5,7 @@ const mocks = vi.hoisted(() => ({osType: vi.fn(() => "macos"),restartApp: vi.fn(async () => undefined),relaunch: vi.fn(async () => undefined),+ switchToGpuiApp: vi.fn(async () => undefined),updatesDownloadAndInstall: vi.fn(async () => undefined),}));@@ -20,6 +21,7 @@ vi.mock("@tauri-apps/plugin-process", () => ({vi.mock("~/utils/tauri", () => ({commands: {restartApp: mocks.restartApp,+ switchToGpuiApp: mocks.switchToGpuiApp,updatesDownloadAndInstall: mocks.updatesDownloadAndInstall,},}));@@ -30,13 +32,14 @@ describe("updater", () => {mocks.arch.mockReturnValue("aarch64");mocks.osType.mockReturnValue("macos");mocks.updatesDownloadAndInstall.mockResolvedValue(undefined);+ mocks.switchToGpuiApp.mockResolvedValue(undefined);mocks.restartApp.mockResolvedValue(undefined);});it.each([- { os: "macos", arch: "aarch64", target: "darwin-aarch64-classic" },- { os: "linux", arch: "x86_64", target: "linux-x86_64-appimage-classic" },- { os: "windows", arch: "x86", target: "windows-i686-classic" },+ { os: "macos", arch: "aarch64", target: "darwin-aarch64" },+ { os: "linux", arch: "x86_64", target: "linux-x86_64-deb" },+ { os: "windows", arch: "x86", target: "windows-i686" },])("uses the expected updater target for $os on $arch", async (platform) => {mocks.arch.mockReturnValue(platform.arch);mocks.osType.mockReturnValue(platform.os);@@ -88,4 +91,22 @@ describe("updater", () => {expect(mocks.updatesDownloadAndInstall).toHaveBeenCalledTimes(2);expect(mocks.relaunch).not.toHaveBeenCalled();});++ it("returns to GPUI through the guarded application handoff", async () => {+ const { returnToGpui } = await import("./updater");++ await returnToGpui();++ expect(mocks.switchToGpuiApp).toHaveBeenCalledOnce();+ expect(mocks.restartApp).not.toHaveBeenCalled();+ });++ it("does not return to GPUI while protected work is active", async () => {+ const error = new Error("Wait for your upload to finish.");+ mocks.switchToGpuiApp.mockRejectedValueOnce(error);+ const { returnToGpui } = await import("./updater");++ await expect(returnToGpui()).rejects.toBe(error);+ expect(mocks.restartApp).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/utils/updater.ts b/apps/desktop/src/utils/updater.tsindex c2ae7de1b..323d7b5d0 100644--- a/apps/desktop/src/utils/updater.ts+++ b/apps/desktop/src/utils/updater.ts@@ -12,9 +12,9 @@ function updaterTarget() {const currentArch = updaterArch();const os = ostype();- if (os === "macos") return `darwin-${currentArch}-classic`;- if (os === "linux") return `linux-${currentArch}-appimage-classic`;- return `${os}-${currentArch}-classic`;+ if (os === "macos") return `darwin-${currentArch}`;+ if (os === "linux") return `linux-${currentArch}-deb`;+ return `${os}-${currentArch}`;}export function getUpdaterCheckOptions(): CheckOptions {@@ -25,3 +25,7 @@ export async function restartAfterUpdate(): Promise<void> {await commands.updatesDownloadAndInstall();await commands.restartApp();}++export async function returnToGpui(): Promise<void> {+ await commands.switchToGpuiApp();+}