Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add export session guard & binary resolution fixes

Richie McIlroya693e17f0445
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index 82914df8b..f73cfb018 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -60,7 +60,6 @@ async fn run_protected_export(
}
}
-const EXPORTER_ENV_BIN_PATH: &str = "CAP_EXPORTER_BIN";
const EXPORTER_STDERR_TAIL_LIMIT: usize = 80;
const EXPORT_PROGRESS_FORWARD_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);
static ACTIVE_EXPORT_SESSIONS: AtomicUsize = AtomicUsize::new(0);
@@ -173,6 +172,18 @@ pub fn export_session_active() -> bool {
ACTIVE_EXPORT_SESSIONS.load(Ordering::Acquire) > 0
}
+#[tauri::command]
+#[specta::specta]
+pub fn begin_export_session() {
+ retain_export_session();
+}
+
+#[tauri::command]
+#[specta::specta]
+pub fn end_export_session() {
+ release_export_session();
+}
+
struct ExportSessionGuard;
impl ExportSessionGuard {
@@ -382,27 +393,12 @@ async fn collect_exporter_stderr_tail(stderr: tokio::process::ChildStderr) -> Ve
}
fn resolve_exporter_binary() -> Result<PathBuf, String> {
- if let Ok(override_path) = std::env::var(EXPORTER_ENV_BIN_PATH) {
- let path = PathBuf::from(override_path);
- if path.exists() {
- return Ok(path);
- }
- return Err(format!(
- "{EXPORTER_ENV_BIN_PATH} points to missing path: {}",
- path.display()
- ));
- }
-
let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
if let Some(dir) = exe.parent() {
- let candidate = dir.join(exporter_bin_name());
- if candidate.exists() {
- return Ok(candidate);
- }
-
- let candidate = dir.join("..").join("MacOS").join(exporter_bin_name());
- if candidate.exists() {
- return Ok(candidate);
+ for candidate in adjacent_exporter_binary_candidates(dir) {
+ if candidate.exists() {
+ return Ok(candidate);
+ }
}
}
@@ -417,7 +413,7 @@ fn resolve_exporter_binary() -> Result<PathBuf, String> {
}
Err(format!(
- "Export worker binary not found; set {EXPORTER_ENV_BIN_PATH} or place {} next to the app executable",
+ "Export worker binary not found; place {} next to the app executable or build the Tauri sidecar bundle",
exporter_bin_name()
))
}
@@ -432,7 +428,7 @@ fn exporter_binary_candidates(root: &Path) -> Vec<PathBuf> {
];
if let Some(target_triple) = current_target_triple() {
- candidates.extend([
+ candidates.push(
root.join("apps")
.join("desktop")
.join("src-tauri")
@@ -441,21 +437,33 @@ fn exporter_binary_candidates(root: &Path) -> Vec<PathBuf> {
"cap-exporter-{target_triple}{}",
std::env::consts::EXE_SUFFIX
)),
- root.join("target")
- .join(target_triple)
- .join("release")
- .join(cli_bin_name()),
- root.join("target")
- .join(target_triple)
- .join("debug")
- .join(cli_bin_name()),
- ]);
+ );
+ }
+
+ candidates
+}
+
+fn adjacent_exporter_binary_candidates(dir: &Path) -> Vec<PathBuf> {
+ let mut candidates = Vec::new();
+
+ candidates.push(dir.join(exporter_bin_name()));
+
+ if let Some(target_triple) = current_target_triple() {
+ candidates.push(dir.join(format!(
+ "cap-exporter-{target_triple}{}",
+ std::env::consts::EXE_SUFFIX
+ )));
}
- candidates.extend([
- root.join("target").join("release").join(cli_bin_name()),
- root.join("target").join("debug").join(cli_bin_name()),
- ]);
+ for subdir in ["../MacOS", "../Resources"] {
+ candidates.push(dir.join(subdir).join(exporter_bin_name()));
+ if let Some(target_triple) = current_target_triple() {
+ candidates.push(dir.join(subdir).join(format!(
+ "cap-exporter-{target_triple}{}",
+ std::env::consts::EXE_SUFFIX
+ )));
+ }
+ }
candidates
}
@@ -473,6 +481,10 @@ fn current_target_triple() -> Option<&'static str> {
target_env = "msvc"
)) {
Some("aarch64-pc-windows-msvc")
+ } else if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
+ Some("aarch64-apple-darwin")
+ } else if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
+ Some("x86_64-apple-darwin")
} else {
None
}
@@ -486,10 +498,6 @@ fn exporter_bin_name() -> &'static str {
}
}
-fn cli_bin_name() -> &'static str {
- if cfg!(windows) { "cap.exe" } else { "cap" }
-}
-
struct ExportActiveGuard<'a>(&'a AtomicBool);
impl Drop for ExportActiveGuard<'_> {
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 61410a4c2..67d4b3489 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -3922,6 +3922,8 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
fake_window::remove_fake_window,
focus_captures_panel,
get_current_recording,
+ export::begin_export_session,
+ export::end_export_session,
export::export_video,
export::get_export_estimates,
export::generate_export_preview,
@@ -4895,6 +4897,8 @@ fn handle_run_event(_handle: &AppHandle, event: tauri::RunEvent) {
}
}
tauri::RunEvent::ExitRequested { code, api, .. } => {
+ info!(?code, "App exit requested");
+
if _handle
.try_state::<AppExitState>()
.is_some_and(|state| state.is_exiting())
diff --git a/apps/desktop/src/routes/editor/ExportPage.tsx b/apps/desktop/src/routes/editor/ExportPage.tsx
index 8c20a5f57..d9a3bfe05 100644
--- a/apps/desktop/src/routes/editor/ExportPage.tsx
+++ b/apps/desktop/src/routes/editor/ExportPage.tsx
@@ -28,7 +28,7 @@ import CaptionControlsWindows11 from "~/components/titlebar/controls/CaptionCont
import { authStore } from "~/store";
import { trackEvent } from "~/utils/analytics";
import { createSignInMutation } from "~/utils/auth";
-import { createExportTask } from "~/utils/export";
+import { beginExportSessionGuard, createExportTask } from "~/utils/export";
import { createSelectedOrganization } from "~/utils/organization-branding";
import {
commands,
@@ -534,18 +534,23 @@ export function ExportPage() {
mutationFn: async () => {
setIsCancelled(false);
if (exportState.type !== "idle") return;
- setExportState(reconcile({ action: "copy", type: "starting" }));
+ const releaseExportSession = await beginExportSessionGuard();
+ try {
+ setExportState(reconcile({ action: "copy", type: "starting" }));
- const outputPath = await exportWithSettings((progress) => {
- if (isCancelled()) throw new SilentError("Cancelled");
- setExportState({ type: "rendering", progress });
- });
+ const outputPath = await exportWithSettings((progress) => {
+ if (isCancelled()) throw new SilentError("Cancelled");
+ setExportState({ type: "rendering", progress });
+ });
- if (isCancelled()) throw new SilentError("Cancelled");
+ if (isCancelled()) throw new SilentError("Cancelled");
- setExportState({ type: "copying" });
+ setExportState({ type: "copying" });
- await commands.copyVideoToClipboard(outputPath);
+ await commands.copyVideoToClipboard(outputPath);
+ } finally {
+ await releaseExportSession();
+ }
},
onError: (error) => {
if (isCancelled() || isCancellationError(error)) {
@@ -567,43 +572,47 @@ export function ExportPage() {
mutationFn: async () => {
setIsCancelled(false);
if (exportState.type !== "idle") return;
+ const releaseExportSession = await beginExportSessionGuard();
+ try {
+ const extension = exportFileExtension();
+ const savePath = await saveDialog({
+ filters: [
+ {
+ name: `${extension.toUpperCase()} filter`,
+ extensions: [extension],
+ },
+ ],
+ defaultPath: `~/Desktop/${meta().prettyName}.${extension}`,
+ });
+ if (!savePath) {
+ throw new SilentError("Save dialog cancelled");
+ }
- const extension = exportFileExtension();
- const savePath = await saveDialog({
- filters: [
- {
- name: `${extension.toUpperCase()} filter`,
- extensions: [extension],
- },
- ],
- defaultPath: `~/Desktop/${meta().prettyName}.${extension}`,
- });
- if (!savePath) {
- throw new SilentError("Save dialog cancelled");
- }
+ setExportState(reconcile({ action: "save", type: "starting" }));
- setExportState(reconcile({ action: "save", type: "starting" }));
+ setOutputPath(savePath);
- setOutputPath(savePath);
+ trackEvent("export_started", {
+ resolution: settings.resolution,
+ fps: settings.fps,
+ path: savePath,
+ });
- trackEvent("export_started", {
- resolution: settings.resolution,
- fps: settings.fps,
- path: savePath,
- });
+ const videoPath = await exportWithSettings((progress) => {
+ if (isCancelled()) throw new SilentError("Cancelled");
+ setExportState({ type: "rendering", progress });
+ });
- const videoPath = await exportWithSettings((progress) => {
if (isCancelled()) throw new SilentError("Cancelled");
- setExportState({ type: "rendering", progress });
- });
-
- if (isCancelled()) throw new SilentError("Cancelled");
- setExportState({ type: "copying" });
+ setExportState({ type: "copying" });
- await commands.copyFileToPath(videoPath, savePath);
+ await commands.copyFileToPath(videoPath, savePath);
- setExportState({ type: "done" });
+ setExportState({ type: "done" });
+ } finally {
+ await releaseExportSession();
+ }
},
onError: (error) => {
if (isCancelled() || isCancellationError(error)) {
@@ -626,73 +635,78 @@ export function ExportPage() {
mutationFn: async () => {
setIsCancelled(false);
if (exportState.type !== "idle") return;
- setExportState(reconcile({ action: "upload", type: "starting" }));
-
- const existingAuth = await authStore.get();
- if (!existingAuth) createSignInMutation();
- trackEvent("create_shareable_link_clicked", {
- resolution: settings.resolution,
- fps: settings.fps,
- has_existing_auth: !!existingAuth,
- });
-
- const metadata = await commands.getVideoMetadata(projectPath);
- const plan = await commands.checkUpgradedAndUpdate();
- const canShare = {
- allowed: plan || metadata.duration < 300,
- reason: !plan && metadata.duration >= 300 ? "upgrade_required" : null,
- };
-
- if (!canShare.allowed) {
- if (canShare.reason === "upgrade_required") {
- await commands.showWindow("Upgrade");
- await new Promise((resolve) => setTimeout(resolve, 1000));
- throw new SilentError();
+ const releaseExportSession = await beginExportSessionGuard();
+ try {
+ setExportState(reconcile({ action: "upload", type: "starting" }));
+
+ const existingAuth = await authStore.get();
+ if (!existingAuth) createSignInMutation();
+ trackEvent("create_shareable_link_clicked", {
+ resolution: settings.resolution,
+ fps: settings.fps,
+ has_existing_auth: !!existingAuth,
+ });
+
+ const metadata = await commands.getVideoMetadata(projectPath);
+ const plan = await commands.checkUpgradedAndUpdate();
+ const canShare = {
+ allowed: plan || metadata.duration < 300,
+ reason: !plan && metadata.duration >= 300 ? "upgrade_required" : null,
+ };
+
+ if (!canShare.allowed) {
+ if (canShare.reason === "upgrade_required") {
+ await commands.showWindow("Upgrade");
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ throw new SilentError();
+ }
}
- }
-
- const uploadChannel = new Channel<UploadProgress>((progress) => {
- console.log("Upload progress:", progress);
- setExportState(
- produce((state) => {
- if (state.type !== "uploading") return;
-
- state.progress = Math.round(progress.progress * 100);
- }),
- );
- });
-
- await exportWithSettings((progress) => {
- if (isCancelled()) throw new SilentError("Cancelled");
- setExportState({ type: "rendering", progress });
- });
- if (isCancelled()) throw new SilentError("Cancelled");
+ const uploadChannel = new Channel<UploadProgress>((progress) => {
+ console.log("Upload progress:", progress);
+ setExportState(
+ produce((state) => {
+ if (state.type !== "uploading") return;
- setExportState({ type: "uploading", progress: 0 });
+ state.progress = Math.round(progress.progress * 100);
+ }),
+ );
+ });
- console.log({ organizationId: settings.organizationId });
+ await exportWithSettings((progress) => {
+ if (isCancelled()) throw new SilentError("Cancelled");
+ setExportState({ type: "rendering", progress });
+ });
- const result = meta().sharing
- ? await commands.uploadExportedVideo(
- projectPath,
- "Reupload",
- uploadChannel,
- settings.organizationId ?? null,
- )
- : await commands.uploadExportedVideo(
- projectPath,
- { Initial: { pre_created_video: null } },
- uploadChannel,
- settings.organizationId ?? null,
- );
+ if (isCancelled()) throw new SilentError("Cancelled");
- if (result === "NotAuthenticated")
- throw new Error("You need to sign in to share recordings");
- else if (result === "PlanCheckFailed")
- throw new Error("Failed to verify your subscription status");
- else if (result === "UpgradeRequired")
- throw new Error("This feature requires an upgraded plan");
+ setExportState({ type: "uploading", progress: 0 });
+
+ console.log({ organizationId: settings.organizationId });
+
+ const result = meta().sharing
+ ? await commands.uploadExportedVideo(
+ projectPath,
+ "Reupload",
+ uploadChannel,
+ settings.organizationId ?? null,
+ )
+ : await commands.uploadExportedVideo(
+ projectPath,
+ { Initial: { pre_created_video: null } },
+ uploadChannel,
+ settings.organizationId ?? null,
+ );
+
+ if (result === "NotAuthenticated")
+ throw new Error("You need to sign in to share recordings");
+ else if (result === "PlanCheckFailed")
+ throw new Error("Failed to verify your subscription status");
+ else if (result === "UpgradeRequired")
+ throw new Error("This feature requires an upgraded plan");
+ } finally {
+ await releaseExportSession();
+ }
},
onSuccess: async () => {
await refetchMeta();
diff --git a/apps/desktop/src/utils/export.ts b/apps/desktop/src/utils/export.ts
index 98e262c7d..0fb5321ba 100644
--- a/apps/desktop/src/utils/export.ts
+++ b/apps/desktop/src/utils/export.ts
@@ -1,6 +1,18 @@
-import { Channel } from "@tauri-apps/api/core";
+import { Channel, invoke } from "@tauri-apps/api/core";
import { commands, type ExportSettings, type FramesRendered } from "./tauri";
+export async function beginExportSessionGuard() {
+ await invoke("begin_export_session");
+ let released = false;
+ return async () => {
+ if (released) return;
+ released = true;
+ await invoke("end_export_session").catch((error) => {
+ console.error("Failed to release export session guard", error);
+ });
+ };
+}
+
export function createExportTask(
projectPath: string,
settings: ExportSettings,
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 262665679..e2f1a6bbb 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -92,6 +92,12 @@ async focusCapturesPanel() : Promise<void> {
async getCurrentRecording() : Promise<JsonValue<CurrentRecording | null>> {
return await TAURI_INVOKE("get_current_recording");
},
+async beginExportSession() : Promise<void> {
+ await TAURI_INVOKE("begin_export_session");
+},
+async endExportSession() : Promise<void> {
+ await TAURI_INVOKE("end_export_session");
+},
async exportVideo(projectPath: string, progress: TAURI_CHANNEL<FramesRendered>, settings: ExportSettings) : Promise<string> {
return await TAURI_INVOKE("export_video", { projectPath, progress, settings });
},