Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Make Tauri commands and export flow resilient
Richie McIlroy30a06d8a1f2a
diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rsindex a370f0d1b..ad57c7d8c 100644--- a/apps/desktop/src-tauri/src/editor_window.rs+++ b/apps/desktop/src-tauri/src/editor_window.rs@@ -253,9 +253,17 @@ impl<'de, R: Runtime> CommandArg<'de, R> for WindowEditorInstance {let Some(instances) = window.try_state::<EditorInstances>() else {return Err("editor instance registry unavailable".into());};- let instance = futures::executor::block_on(instances.0.read());- let Some(instance) = instance.get(window.label()).cloned() else {+ // Avoid `futures::executor::block_on` on a tokio RwLock here. That can deadlock or+ // panic when the IPC handler runs from inside the tokio runtime (release builds hit+ // this path much more aggressively than dev builds and silently terminate the process).+ // `try_read` is sync and never blocks; if the lock is contended we surface a transient+ // error and let the frontend retry.+ let Ok(instance_guard) = instances.0.try_read() else {+ return Err("editor instance registry busy".into());+ };++ let Some(instance) = instance_guard.get(window.label()).cloned() else {return Err("editor instance unavailable".into());};@@ -291,8 +299,10 @@ impl<'de, R: Runtime> CommandArg<'de, R> for OptionalWindowEditorInstance {return Ok(Self(None));};- let instance = futures::executor::block_on(instances.0.read());- Ok(Self(instance.get(window.label()).cloned()))+ match instances.0.try_read() {+ Ok(instance_guard) => Ok(Self(instance_guard.get(window.label()).cloned())),+ Err(_) => Ok(Self(None)),+ }}}diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 078b19f73..26f5c2ca6 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -118,6 +118,8 @@ use crate::{upload::InstantMultipartUpload,};use exit_shutdown::{AppExitAction, app_exit_action, collect_device_inventory, run_while_active};+use futures::FutureExt;+use std::panic::AssertUnwindSafe;type FinalizingRecordingsMap =std::collections::HashMap<PathBuf, (watch::Sender<bool>, watch::Receiver<bool>)>;@@ -2235,7 +2237,11 @@ fn find_first_segment(dir: &std::path::Path) -> Option<PathBuf> {#[specta::specta]#[instrument(skip(app))]async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(), String> {- println!("Attempting to copy file from {src} to {dst}");+ run_command_safely("copy_file_to_path", copy_file_to_path_inner(app, src, dst)).await+}++async fn copy_file_to_path_inner(app: AppHandle, src: String, dst: String) -> Result<(), String> {+ info!(%src, %dst, "Attempting to copy file");let is_screenshot = src.contains("screenshots/");let is_gif = src.ends_with(".gif") || dst.ends_with(".gif");@@ -2248,7 +2254,11 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(if !is_screenshot && !is_gif && !is_valid_video(src_path) {let mut attempts = 0;while attempts < 10 {- std::thread::sleep(std::time::Duration::from_secs(1));+ // Replaced `std::thread::sleep` with `tokio::time::sleep` — the previous version+ // blocked the tokio worker for up to 10 seconds, which on release builds with+ // smaller worker pools could starve the runtime and cause unrelated tasks to time+ // out (including window/IPC events).+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;if is_valid_video(src_path) {break;}@@ -2300,7 +2310,7 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(continue;}- println!("Successfully copied {bytes} bytes from {src} to {dst}");+ info!(bytes, %src, %dst, "Successfully copied file");notifications::send_notification(&app,@@ -2323,12 +2333,15 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(}}- eprintln!(- "Failed to copy file from {} to {} after {} attempts. Last error: {}",- src,- dst,- MAX_ATTEMPTS,- last_error.as_ref().unwrap()+ let last_error_message = last_error+ .as_deref()+ .unwrap_or("Maximum retry attempts exceeded");+ error!(+ %src,+ %dst,+ attempts = MAX_ATTEMPTS,+ error = %last_error_message,+ "Failed to copy file after retries");notifications::send_notification(@@ -3079,6 +3092,18 @@ async fn save_file_dialog(app: AppHandle,file_name: String,file_type: String,+) -> Result<Option<String>, String> {+ run_command_safely(+ "save_file_dialog",+ save_file_dialog_inner(app, file_name, file_type),+ )+ .await+}++async fn save_file_dialog_inner(+ app: AppHandle,+ file_name: String,+ file_type: String,) -> Result<Option<String>, String> {use tauri_plugin_dialog::DialogExt;@@ -3102,7 +3127,12 @@ async fn save_file_dialog(info!(file_name, name, extension, "Showing save file dialog");- let (tx, rx) = std::sync::mpsc::channel();+ // Use `tokio::sync::oneshot` so the async runtime worker yields while the native dialog+ // is open instead of being parked by a synchronous `std::sync::mpsc` receive. The+ // previous version blocked a runtime worker for the lifetime of the dialog which, in+ // release builds with fewer/active workers, could starve other tasks and let an unrelated+ // exit event slip through before the export session guard incremented.+ let (tx, rx) = tokio::sync::oneshot::channel();app.dialog().file()@@ -3117,7 +3147,7 @@ async fn save_file_dialog();});- match rx.recv() {+ match rx.await {Ok(result) => {info!(path = ?result, "Save file dialog completed");Ok(result)@@ -4538,6 +4568,19 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {if app_is_exiting(app) {return;}+ // If a webview crashes mid-export (memory pressure, GPU teardown, etc.) we+ // get a Destroyed event for the editor window. Tearing down camera/mic+ // feeds and editor registry entries here would race the running export+ // sidecar and could trigger Tauri's "last window closed" exit path. Skip+ // cleanup entirely while an export is active — the regular Destroyed flow+ // will run again when the export completes if the window is still gone.+ if export::export_session_active() {+ warn!(+ window = label,+ "Skipping Destroyed cleanup during active export"+ );+ return;+ }if let Ok(window_id) = CapWindowId::from_str(label) {if matches!(window_id, CapWindowId::Camera) {tracing::warn!("Camera window Destroyed event received!");@@ -4826,6 +4869,32 @@ pub(crate) fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> Str}}+// Catches panics inside an async Tauri command body so a single bad code path can't+// unwind through the IPC dispatcher and terminate the whole desktop process. This is+// particularly important for commands that participate in the export flow because the+// sidecar architecture relies on the desktop app remaining alive to babysit the worker.+async fn run_command_safely<T, F>(command_name: &'static str, fut: F) -> Result<T, String>+where+ F: std::future::Future<Output = Result<T, String>>,+{+ match AssertUnwindSafe(fut).catch_unwind().await {+ Ok(result) => result,+ Err(panic) => {+ let message = panic_payload_message(&*panic);+ error!(+ command = command_name,+ panic = %message,+ "Suppressed panic in Tauri command"+ );+ sentry::capture_message(+ &format!("Tauri command '{command_name}' panicked: {message}"),+ sentry::Level::Error,+ );+ Err(format!("{command_name} failed unexpectedly"))+ }+ }+}+fn emit_app_event_safely<E>(app: &AppHandle, event: E)whereE: Event + Serialize + Clone,diff --git a/apps/desktop/src/routes/editor/ExportPage.tsx b/apps/desktop/src/routes/editor/ExportPage.tsxindex aee09fef1..6023d5e83 100644--- a/apps/desktop/src/routes/editor/ExportPage.tsx+++ b/apps/desktop/src/routes/editor/ExportPage.tsx@@ -31,7 +31,7 @@ import { createSignInMutation } from "~/utils/auth";import {beginExportSessionGuard,createExportTask,- createExportToFileTask,+ exportVideoToFile,} from "~/utils/export";import { createSelectedOrganization } from "~/utils/organization-branding";import {@@ -588,23 +588,22 @@ export function ExportPage() {customBpp,forceFfmpegDecoder(),);- const { promise, cancel } = createExportToFileTask(+ const savePath = await exportVideoToFile(projectPath,exportSettings,`${meta().prettyName}.${extension}`,extension,+ () => {+ setExportState(reconcile({ action: "save", type: "starting" }));+ },+ () => {+ setExportState({ action: "save", type: "copying" });+ },(progress) => {if (isCancelled()) throw new SilentError("Cancelled");setExportState({ type: "rendering", progress });},);- cancelCurrentExport = cancel;-- setExportState(reconcile({ action: "save", type: "starting" }));-- const savePath = await promise.finally(() => {- if (cancelCurrentExport === cancel) cancelCurrentExport = null;- });if (isCancelled()) throw new SilentError("Cancelled");diff --git a/apps/desktop/src/utils/export.ts b/apps/desktop/src/utils/export.tsindex 5583828bb..873d5dc8f 100644--- a/apps/desktop/src/utils/export.ts+++ b/apps/desktop/src/utils/export.ts@@ -1,13 +1,13 @@-import { Channel, invoke } from "@tauri-apps/api/core";+import { Channel } from "@tauri-apps/api/core";import { commands, type ExportSettings, type FramesRendered } from "./tauri";export async function beginExportSessionGuard() {- await invoke("begin_export_session");+ await commands.beginExportSession();let released = false;return async () => {if (released) return;released = true;- await invoke("end_export_session").catch((error) => {+ await commands.endExportSession().catch((error) => {console.error("Failed to release export session guard", error);});};@@ -59,16 +59,50 @@ export function createExportToFileTask().__TAURI_INTERNALS__;internals?.unregisterCallback?.(progress.id);};- const promise = invoke<string>("export_video_to_file", {- projectPath,- progress,- settings,- fileName,- fileType,- }).finally(cancel);+ const promise = (async () => {+ const releaseExportSession = await beginExportSessionGuard();+ try {+ const savePath = await commands.saveFileDialog(fileName, fileType);+ if (!savePath) throw new Error("Save dialog cancelled");++ const outputPath = await commands.exportVideo(+ projectPath,+ progress,+ settings,+ );+ await commands.copyFileToPath(outputPath, savePath);+ return savePath;+ } finally {+ await releaseExportSession();+ }+ })().finally(cancel);return { promise, cancel };}+export async function exportVideoToFile(+ projectPath: string,+ settings: ExportSettings,+ fileName: string,+ fileType: string,+ onStart: () => void,+ onCopying: () => void,+ onProgress: (progress: FramesRendered) => void,+) {+ const releaseExportSession = await beginExportSessionGuard();+ try {+ const savePath = await commands.saveFileDialog(fileName, fileType);+ if (!savePath) throw new Error("Save dialog cancelled");++ onStart();+ const videoPath = await exportVideo(projectPath, settings, onProgress);+ onCopying();+ await commands.copyFileToPath(videoPath, savePath);+ return savePath;+ } finally {+ await releaseExportSession();+ }+}+export async function exportVideo(projectPath: string,settings: ExportSettings,diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex e2f1a6bbb..42e988ad3 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -101,6 +101,9 @@ async endExportSession() : Promise<void> {async exportVideo(projectPath: string, progress: TAURI_CHANNEL<FramesRendered>, settings: ExportSettings) : Promise<string> {return await TAURI_INVOKE("export_video", { projectPath, progress, settings });},+async exportVideoToFile(projectPath: string, progress: TAURI_CHANNEL<FramesRendered>, settings: ExportSettings, fileName: string, fileType: string) : Promise<string> {+ return await TAURI_INVOKE("export_video_to_file", { projectPath, progress, settings, fileName, fileType });+},async getExportEstimates(path: string, settings: ExportSettings) : Promise<ExportEstimates> {return await TAURI_INVOKE("get_export_estimates", { path, settings });},