Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop): split the Tauri app out as Cap Classic

Cursor Agente8baf75759d1
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 1b7ebd5e9..047ceef37 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -2,11 +2,9 @@
"name": "@cap/desktop",
"type": "module",
"scripts": {
- "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",
+ "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",
"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.js
index 66df72366..0abaa288c 100644
--- a/apps/desktop/scripts/prepare.js
+++ b/apps/desktop/scripts/prepare.js
@@ -3,7 +3,6 @@
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);
@@ -72,39 +71,10 @@ 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.js
index e43e2816d..b0d48edca 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.mj
import { deepMerge } from "./prepare.js";
describe("Tauri platform release configuration", () => {
- it("preserves generated Linux shared-library mappings when adding GPUI", () => {
+ it("preserves generated Linux shared-library mappings when adding sidecars", () => {
const existing = createLinuxBundleConfig(["libavcodec.so.61"]);
const merged = deepMerge(existing, {
- bundle: { externalBin: ["binaries/cap-gpui"] },
+ bundle: { externalBin: ["binaries/cap-cli"] },
});
- expect(merged.bundle.externalBin).toEqual(["binaries/cap-gpui"]);
+ expect(merged.bundle.externalBin).toEqual(["binaries/cap-cli"]);
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", "binaries/cap-gpui"],
+ externalBin: ["binaries/cap-cli"],
resources: { "ffmpeg/*.dll": "./" },
},
},
{ bundle: { windows: { wix: { version: "0.6.0" } } } },
);
- expect(merged.bundle.externalBin).toContain("binaries/cap-gpui");
+ expect(merged.bundle.externalBin).toEqual(["binaries/cap-cli"]);
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.js
index ca477fd70..c74f10c30 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", "cap-desktop"]) {
+ for (const name of ["Cap Classic", "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.nsh
new file mode 100644
index 000000000..58b8c9466
--- /dev/null
+++ b/apps/desktop/src-tauri/nsis/installer-hooks.nsh
@@ -0,0 +1,4 @@
+!macro NSIS_HOOK_PREUNINSTALL
+ StrCpy $DeleteAppDataCheckboxState 0
+ DetailPrint "Keeping recordings and settings, which Cap Classic shares with Cap."
+!macroend
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs
index 5a1c296f1..f6ea12626 100644
--- a/apps/desktop/src-tauri/src/general_settings.rs
+++ b/apps/desktop/src-tauri/src/general_settings.rs
@@ -254,9 +254,8 @@ pub struct GeneralSettingsStore {
pub camera_blur_disabled_by_crash: Option<String>,
#[serde(default)]
pub update_channel: UpdateChannel,
- /// 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`.
+ /// 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.
#[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.rs
index 3a82e010c..1c4828705 100644
--- a/apps/desktop/src-tauri/src/gpui_app.rs
+++ b/apps/desktop/src-tauri/src/gpui_app.rs
@@ -1,141 +1,31 @@
-//! Handing this app off to the experimental gpui-native app (`cap-gpui`).
+//! Cap Classic's half of switching between it and Cap.
//!
-//! 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.
+//! 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.
-use std::path::PathBuf;
+use std::path::{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 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.
+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.
fn shared_data_dir() -> PathBuf {
#[cfg(target_os = "macos")]
let base = PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| ".".into()))
@@ -156,665 +46,184 @@ fn shared_data_dir() -> PathBuf {
base
}
-fn gpui_pidfile() -> PathBuf {
- shared_data_dir().join("cap-gpui.pid")
+fn classic_pending() -> PathBuf {
+ shared_data_dir().join("cap-classic.pending")
}
-/// 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.
+/// 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.
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 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();
+/// 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");
let mut doc = match std::fs::read_to_string(&path) {
- 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;
- }
- },
+ Ok(raw) => serde_json::from_str::<serde_json::Value>(&raw)
+ .map_err(|error| format!("The shared store is unreadable: {error}"))?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => serde_json::json!({}),
- Err(error) => {
- warn!(%error, "could not read the shared store");
- return;
- }
- };
- let Some(root) = doc.as_object_mut() else {
- warn!("shared store is not a JSON object; leaving it untouched");
- return;
+ Err(error) => return Err(format!("Could not read the shared store: {error}")),
};
- root.entry("general_settings")
+ 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")
.or_insert_with(|| serde_json::json!({}))
.as_object_mut()
- .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());
+ .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())?;
let tmp = path.with_extension("tmp");
- let write = std::fs::create_dir_all(path.parent().unwrap_or(&path))
+ std::fs::create_dir_all(path.parent().unwrap_or(&path))
.and_then(|()| std::fs::write(&tmp, pretty))
- .and_then(|()| std::fs::rename(&tmp, &path));
- if let Err(error) = write {
- warn!(%error, "could not write the shared store flag");
- }
-}
-
-fn handoff_marker() -> PathBuf {
- shared_data_dir().join("cap-gpui.handoff")
-}
-
-fn update_handoff_marker() -> PathBuf {
- shared_data_dir().join("cap-gpui.update-handoff")
-}
-
-#[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)
- }
+ .and_then(|()| std::fs::rename(&tmp, &path))
+ .map_err(|error| format!("Could not write the shared store: {error}"))
}
-#[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;
+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)
}
- 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 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
- {
- return Err(std::io::Error::new(
- std::io::ErrorKind::PermissionDenied,
- "Cap GPUI instance metadata is not owner controlled",
- ));
- }
- 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",
- ));
- }
- Ok(contents)
+#[derive(Debug, PartialEq, Eq)]
+enum CapInstall {
+ #[cfg(target_os = "macos")]
+ Bundle(PathBuf),
+ Executable(PathBuf),
}
-#[cfg(target_os = "macos")]
-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);
+impl CapInstall {
+ fn path(&self) -> &Path {
+ match self {
+ #[cfg(target_os = "macos")]
+ Self::Bundle(path) => path,
+ Self::Executable(path) => path,
+ }
}
- 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(target_os = "macos")]
-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",
- )
+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"))
})
-}
-
-#[cfg(target_os = "macos")]
-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),
- }
+ .and_then(Path::parent)
+ {
+ candidates.push(parent.join(CAP_BUNDLE_NAME));
}
- 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),
- }
+ candidates.push(Path::new("/Applications").join(CAP_BUNDLE_NAME));
+ if let Some(home) = home {
+ candidates.push(home.join("Applications").join(CAP_BUNDLE_NAME));
}
+ candidates.dedup();
+ candidates
}
#[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}"))
-}
-
-#[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 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)
}
-#[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;
+#[cfg(windows)]
+fn installed_cap() -> Option<CapInstall> {
+ use winreg::{
+ RegKey,
+ enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE},
};
- 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
+ [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, _>(""))
+ .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)
}
-#[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 = "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(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())
+fn cap_install() -> Option<CapInstall> {
+ if let Some(path) = std::env::var_os("CAP_GPUI_BIN").map(PathBuf::from)
+ && path.is_file()
{
- return None;
+ return Some(CapInstall::Executable(path));
}
-
- 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);
- }
+ #[cfg(debug_assertions)]
+ if let Some(install) = development_cap() {
+ return Some(install);
}
+ installed_cap()
}
-#[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);
+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
}
+ CapInstall::Executable(executable) => std::process::Command::new(executable),
}
}
-#[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> {
+/// 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> {
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);
@@ -829,19 +238,11 @@ fn spawn_detached(path: &std::path::Path, args: &[String]) -> Result<(), String>
Err(_) => (Stdio::from(file), Stdio::null()),
},
Err(error) => {
- warn!(%error, "could not open the Cap GPUI log; discarding its output");
+ warn!(%error, "could not open the Cap launch log; discarding its output");
(Stdio::null(), Stdio::null())
}
};
-
- 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.
+ command.stdin(Stdio::null()).stdout(stdout).stderr(stderr);
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
@@ -850,8 +251,7 @@ fn spawn_detached(path: &std::path::Path, args: &[String]) -> Result<(), String>
let mut child = command
.spawn()
- .map_err(|error| format!("Failed to launch Cap GPUI: {error}"))?;
- // Reap the child when it exits so it never lingers as a zombie.
+ .map_err(|error| format!("Couldn't open Cap: {error}"))?;
std::thread::spawn(move || {
let _ = child.wait();
});
@@ -873,67 +273,32 @@ 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 Tauri's Dock presence for the GPUI handoff"),
- Err(error) => warn!(%error, "Could not retire Tauri's Dock presence for the GPUI handoff"),
+ 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"),
}
}
#[tauri::command]
#[specta::specta]
-pub async fn gpui_app_available(app: AppHandle) -> bool {
- binary_path(&app).is_some()
+pub async fn gpui_app_available() -> bool {
+ cap_install().is_some()
}
-/// 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.
+/// Close this app and open Cap. A failure has to be reported rather than
+/// swallowed: the Experimental page shows it on its overlay.
#[tauri::command]
#[specta::specta]
pub async fn switch_to_gpui_app(app: AppHandle) -> Result<(), String> {
- let path =
- binary_path(&app).ok_or_else(|| "Cap GPUI isn't included in this build".to_string())?;
+ let install =
+ cap_install().ok_or_else(|| "Cap isn't installed on this computer".to_string())?;
crate::prepare_app_exit(&app, || {
- 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);
- }
+ 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");
}
- }
- Ok(())
+ })
})?;
#[cfg(target_os = "macos")]
{
@@ -948,52 +313,38 @@ 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 GPUI handoff's Dock transition was not acknowledged before shutdown"
- );
+ warn!("The switch's Dock transition was not acknowledged before shutdown");
}
}
- Err(error) => warn!(%error, "Could not schedule the GPUI handoff's Dock transition"),
+ Err(error) => warn!(%error, "Could not schedule the switch's Dock transition"),
}
}
crate::complete_admitted_app_exit(app).await;
Ok(())
}
-/// 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;
- }
+/// 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;
}
- tokio::time::sleep(std::time::Duration::from_millis(250)).await;
}
- });
- }
- Ok(redirect)
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ }
+ });
}
fn acknowledge_classic_window(app: &AppHandle) {
@@ -1013,500 +364,54 @@ fn acknowledge_classic_window(app: &AppHandle) {
});
if ready {
match std::fs::remove_file(classic_pending()) {
- Ok(()) => info!("Acknowledged visible classic window for GPUI handoff"),
+ Ok(()) => info!("Acknowledged the switch from Cap"),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
- Err(error) => warn!(%error, "Could not acknowledge the classic app handoff"),
+ Err(error) => warn!(%error, "Could not acknowledge the switch from Cap"),
}
}
}
-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)]
- forward_deep_links_to_gpui(pid, &args);
- }
- #[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::{
- 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()
- );
- }
+ use super::CapInstall;
#[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]));
- }
+ 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);
}
#[cfg(target_os = "macos")]
#[test]
- 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 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();
+ 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");
assert_eq!(
- super::send_gpui_reopen(endpoint, expired, Duration::from_secs(2))
- .unwrap_err()
- .kind(),
- std::io::ErrorKind::TimedOut
+ command.get_args().collect::<Vec<_>>(),
+ [std::ffi::OsStr::new("-n"), bundle.as_os_str()]
);
}
#[cfg(target_os = "macos")]
#[test]
- fn macos_reopen_rejects_shared_or_linked_endpoint_and_changed_pid() {
- use std::os::unix::fs::{PermissionsExt, symlink};
+ fn cap_is_found_beside_classic_and_in_both_application_folders() {
+ use std::path::{Path, PathBuf};
- 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::read_macos_gpui_metadata(&path, true)
- .unwrap_err()
- .kind(),
- std::io::ErrorKind::PermissionDenied
+ 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"),
+ ]
);
- 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.rs
index 721e6e03c..d458255c0 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -7213,50 +7213,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: Option<PathB
specta_builder.mount_events(&app);
general_settings::init(&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(());
- }
+ gpui_app::watch_for_switches(&app);
app.manage(clean_capture::State::default());
hotkeys::init(&app);
configure_camera_blur_recovery(&app, previous_termination);
@@ -7577,9 +7534,13 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: Option<PathB
app.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, StartupOpenDestination::Desktop);
+ finish_macos_startup_opens(&app);
Ok(())
})
@@ -7963,15 +7924,6 @@ 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://"))
@@ -8055,101 +8007,48 @@ 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 {
- destination: Option<StartupOpenDestination>,
+ ready: bool,
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<StartupOpenDispatch>, String> {
+ fn request(&mut self, urls: Vec<tauri::Url>) -> Result<Option<Vec<tauri::Url>>, String> {
if self.cancelled {
return Err("Cap startup stopped before the project could be opened".into());
}
- if self.destination == Some(StartupOpenDestination::Desktop) {
- return Ok(Some(StartupOpenDispatch {
- destination: StartupOpenDestination::Desktop,
- urls,
- }));
+ if self.ready {
+ return Ok(Some(urls));
}
let mut additions = Vec::new();
for url in urls {
- if self.urls.contains(&url)
- || self.gpui_dispatched.contains(&url)
- || additions.contains(&url)
- {
+ if self.urls.contains(&url) || additions.contains(&url) {
continue;
}
- if self.urls.len() + self.gpui_dispatched.len() + additions.len() >= 64 {
+ if self.urls.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, 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
- {
+ fn finish(&mut self) -> Option<Vec<tauri::Url>> {
+ if self.cancelled || self.ready {
return None;
}
- if let Some(dispatch) = self.take_queued() {
- return Some(dispatch);
- }
- self.cancel();
- None
+ self.ready = true;
+ (!self.urls.is_empty()).then(|| std::mem::take(&mut self.urls))
}
fn cancel(&mut self) {
self.cancelled = true;
self.urls.clear();
- self.gpui_dispatched.clear();
- self.gpui_forwarding = false;
}
}
@@ -8164,7 +8063,7 @@ struct StartupOpenGuard(StartupOpenGate);
impl Drop for StartupOpenGuard {
fn drop(&mut self) {
if let Ok(mut queue) = self.0.0.lock()
- && queue.destination.is_none()
+ && !queue.ready
{
queue.cancel();
}
@@ -8181,26 +8080,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(dispatch) = dispatch {
- dispatch_macos_startup_urls(app, dispatch);
+ if let Some(urls) = dispatch {
+ dispatch_macos_startup_urls(app, urls);
}
Ok(())
}
#[cfg(target_os = "macos")]
-fn finish_macos_startup_opens(app: &AppHandle, destination: StartupOpenDestination) {
+fn finish_macos_startup_opens(app: &AppHandle) {
let Some(gate) = app.try_state::<StartupOpenGate>() else {
return;
};
let dispatch = match gate.0.lock() {
- Ok(mut queue) => queue.finish(destination),
+ Ok(mut queue) => queue.finish(),
Err(error) => {
warn!(%error, "Could not release startup project requests");
return;
}
};
- if let Some(dispatch) = dispatch {
- dispatch_macos_startup_urls(app, dispatch);
+ if let Some(urls) = dispatch {
+ dispatch_macos_startup_urls(app, urls);
}
}
@@ -8214,76 +8113,7 @@ fn cancel_macos_startup_opens(app: &AppHandle) {
}
#[cfg(target_os = "macos")]
-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;
- }
-
+fn dispatch_macos_startup_urls(app: &AppHandle, urls: Vec<tauri::Url>) {
for url in urls {
if url.scheme() == "file"
&& let Ok(path) = url.to_file_path()
@@ -8304,17 +8134,6 @@ 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
@@ -9253,7 +9072,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.destination == Some(StartupOpenDestination::Desktop)
+ !queue.cancelled && queue.ready
};
if !ready {
let path = if path.is_absolute() {
@@ -9304,7 +9123,7 @@ fn open_project_from_path(path: &Path, app: AppHandle) -> Result<(), String> {
#[cfg(test)]
mod startup_project_open_tests {
- use super::{StartupOpenDestination, StartupOpenGate, StartupOpenGuard, StartupOpenQueue};
+ use super::{StartupOpenGate, StartupOpenGuard, StartupOpenQueue};
fn project(name: &str) -> tauri::Url {
tauri::Url::parse(&format!("file:///recordings/{name}.cap")).unwrap()
@@ -9315,35 +9134,17 @@ 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());
- let dispatch = queue.finish(StartupOpenDestination::Desktop).unwrap();
- assert_eq!(dispatch.destination, StartupOpenDestination::Desktop);
- assert_eq!(dispatch.urls, urls);
+ assert_eq!(queue.finish().unwrap(), urls);
assert!(queue.urls.is_empty());
- 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")]);
+ assert!(queue.finish().is_none());
}
#[test]
fn normal_post_ready_file_opens_dispatch_immediately() {
let mut queue = StartupOpenQueue::default();
- assert!(queue.finish(StartupOpenDestination::Desktop).is_none());
+ assert!(queue.finish().is_none());
let url = project("ready");
- let dispatch = queue.request(vec![url.clone()]).unwrap().unwrap();
- assert_eq!(dispatch.destination, StartupOpenDestination::Desktop);
- assert_eq!(dispatch.urls, [url]);
+ assert_eq!(queue.request(vec![url.clone()]).unwrap().unwrap(), [url]);
}
#[test]
@@ -9362,29 +9163,23 @@ 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(StartupOpenDestination::Desktop).is_none());
- assert!(queue.finish(StartupOpenDestination::Gpui).is_none());
+ assert!(queue.finish().is_none());
}
#[test]
- 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);
- }
+ 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")]);
}
#[test]
@@ -9404,43 +9199,13 @@ mod startup_project_open_tests {
}
#[test]
- fn gpui_handoff_drains_later_batches_without_duplicate_dispatches() {
+ fn cancellation_stops_dispatch() {
let mut queue = StartupOpenQueue::default();
- 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.finish().is_none());
+ assert!(queue.request(vec![project("first")]).unwrap().is_some());
+ queue.cancel();
assert!(queue.request(vec![project("after-exit")]).is_err());
- }
-
- #[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());
- }
+ assert!(queue.urls.is_empty());
}
}
diff --git a/apps/desktop/src-tauri/src/updates.rs b/apps/desktop/src-tauri/src/updates.rs
index da4ccf8d8..5987bfb78 100644
--- a/apps/desktop/src-tauri/src/updates.rs
+++ b/apps/desktop/src-tauri/src/updates.rs
@@ -98,7 +98,9 @@ fn current_channel(app: &AppHandle) -> UpdateChannel {
.unwrap_or_default()
}
-fn updater_target() -> Result<String, String> {
+const CLASSIC_PLATFORM_SUFFIX: &str = "-classic";
+
+fn platform_target() -> Result<String, String> {
let arch = if cfg!(target_arch = "aarch64") {
"aarch64"
} else {
@@ -120,6 +122,16 @@ fn updater_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(),
@@ -421,3 +433,17 @@ 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.rs
index c7e1151e4..20dcd54f1 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, Au
let 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 GPUI; local files retained".into()),
+ Ok(_) => Err("This recording's upload is managed by Cap; 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.json
index 3297c552a..9af816915 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",
- "mainBinaryName": "Cap",
+ "productName": "Cap Classic",
+ "mainBinaryName": "Cap Classic",
"identifier": "so.cap.desktop",
"build": {
"beforeBundleCommand": "node scripts/prodBeforeBundle.js"
@@ -17,10 +17,22 @@
}
},
"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.tsx
index 2a2f89b0a..16701709a 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx
@@ -1,5 +1,7 @@
+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";
@@ -11,6 +13,7 @@ import {
import {
Section,
SectionRows,
+ SettingItem,
SettingsPageContent,
ToggleSettingItem,
} from "./Setting";
@@ -20,11 +23,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 the native Cap app.",
- "It will look almost identical. That is the point.",
+ "Switching to Cap.",
"Same Cap, rebuilt fully native for performance.",
- "Experimental. Your recordings and settings come with you.",
+ "Your recordings and settings come with you.",
];
+const CAP_DOWNLOAD_URL = "https://cap.so/download";
const SENTENCE_MS = 1300;
const COUNTDOWN_FROM = 5;
@@ -55,7 +58,7 @@ function Inner(props: {
deriveGeneralSettings(props.initialStore),
);
- const [gpuiAvailable] = createResource(() =>
+ const [capInstalled] = createResource(() =>
invoke<boolean>("gpui_app_available").catch(() => false),
);
@@ -73,39 +76,21 @@ 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 the native app.",
+ error: typeof error === "string" ? error : "Couldn't open Cap.",
}
: 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 });
@@ -183,22 +168,40 @@ function Inner(props: {
</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>
+ <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>
</SettingsPageContent>
<Show when={takeover()}>
diff --git a/apps/desktop/src/routes/(window-chrome)/update.tsx b/apps/desktop/src/routes/(window-chrome)/update.tsx
index 6b427b629..febe082eb 100644
--- a/apps/desktop/src/routes/(window-chrome)/update.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/update.tsx
@@ -10,21 +10,14 @@ import {
Switch,
} from "solid-js";
import { commands, events } from "~/utils/tauri";
-import { restartAfterUpdate, returnToGpui } from "~/utils/updater";
+import { restartAfterUpdate } 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 {
- if (simulatedUpdate) await returnToGpui();
- else await restartAfterUpdate();
+ await restartAfterUpdate();
} catch (error) {
console.error("Failed to restart after update:", error);
setUpdateError(
@@ -32,22 +25,8 @@ 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;
@@ -71,13 +50,7 @@ export default function () {
<p class="text-(--text-tertiary) text-xs">
If this issue persists, please contact support.
</p>
- <Button
- onClick={() =>
- fromGpui ? void returnSafelyToGpui() : navigate("/")
- }
- >
- {fromGpui ? "Return to Cap GPUI" : "Go Back"}
- </Button>
+ <Button onClick={() => navigate("/")}>Go Back</Button>
</div>
</Show>
<Show when={!updateError() && update.loading}>
@@ -90,11 +63,6 @@ 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>
)
}
@@ -107,57 +75,34 @@ export default function () {
const [updateStatus, setUpdateStatus] = createSignal<UpdateStatus>();
- if (simulatedUpdate) {
- let progress = 0;
+ const unlisten = events.updateDownloadProgress.listen((e) => {
+ if (updateStatus()?.type === "done") return;
setUpdateStatus({
type: "downloading",
- progress,
- contentLength: 100,
- });
- 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());
+ 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.",
- );
- });
- }
+ 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.ts
index c0eeb93b5..f878b4488 100644
--- a/apps/desktop/src/utils/general-settings.ts
+++ b/apps/desktop/src/utils/general-settings.ts
@@ -8,7 +8,6 @@ export type GeneralSettingsStore = TauriGeneralSettingsStore & {
transcriptionHints?: string[];
enableTelemetry?: boolean;
outOfProcessMuxer?: boolean;
- enableGpuiApp?: boolean;
};
export const DEFAULT_TRANSCRIPTION_HINTS = [
diff --git a/apps/desktop/src/utils/updater.test.ts b/apps/desktop/src/utils/updater.test.ts
index d3a2aa716..4be8012e0 100644
--- a/apps/desktop/src/utils/updater.test.ts
+++ b/apps/desktop/src/utils/updater.test.ts
@@ -5,7 +5,6 @@ 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),
}));
@@ -21,7 +20,6 @@ vi.mock("@tauri-apps/plugin-process", () => ({
vi.mock("~/utils/tauri", () => ({
commands: {
restartApp: mocks.restartApp,
- switchToGpuiApp: mocks.switchToGpuiApp,
updatesDownloadAndInstall: mocks.updatesDownloadAndInstall,
},
}));
@@ -32,14 +30,13 @@ 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" },
- { os: "linux", arch: "x86_64", target: "linux-x86_64-deb" },
- { os: "windows", arch: "x86", target: "windows-i686" },
+ { 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" },
])("uses the expected updater target for $os on $arch", async (platform) => {
mocks.arch.mockReturnValue(platform.arch);
mocks.osType.mockReturnValue(platform.os);
@@ -91,22 +88,4 @@ 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.ts
index 323d7b5d0..c2ae7de1b 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}`;
- if (os === "linux") return `linux-${currentArch}-deb`;
- return `${os}-${currentArch}`;
+ if (os === "macos") return `darwin-${currentArch}-classic`;
+ if (os === "linux") return `linux-${currentArch}-appimage-classic`;
+ return `${os}-${currentArch}-classic`;
}
export function getUpdaterCheckOptions(): CheckOptions {
@@ -25,7 +25,3 @@ export async function restartAfterUpdate(): Promise<void> {
await commands.updatesDownloadAndInstall();
await commands.restartApp();
}
-
-export async function returnToGpui(): Promise<void> {
- await commands.switchToGpuiApp();
-}