Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(recording): require auth and stream instant uploads

Richie McIlroy9f4f92589aad
diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs
index aa293c709..a1447b90c 100644
--- a/apps/desktop-gpui/src/main_window.rs
+++ b/apps/desktop-gpui/src/main_window.rs
@@ -341,6 +341,11 @@ pub struct MainWindow {
/// is open so a large library is not walked on every home paint.
library: Option<LibraryItems>,
library_task: Option<gpui::Task<()>>,
+ incomplete_recording: Option<library::IncompleteRecordingItem>,
+ recovery_error: Option<String>,
+ recovery_pending: bool,
+ recovery_scan_task: Option<Task<()>>,
+ recovery_action_task: Option<Task<()>>,
/// `createLicenseQuery()`'s resolution, cached: reading the store file in
/// `render_plan_badge` would be I/O per paint. Refreshed on every Recents
/// rescan -- the same seam that already re-reads the library on reshow,
@@ -456,6 +461,11 @@ impl MainWindow {
recents_task: None,
library: None,
library_task: None,
+ incomplete_recording: None,
+ recovery_error: None,
+ recovery_pending: false,
+ recovery_scan_task: None,
+ recovery_action_task: None,
plan: PlanBadge::current(),
thumbnails: target_thumbnails::ThumbnailCache::default(),
display_thumbnail_task: None,
@@ -511,6 +521,24 @@ impl MainWindow {
)
});
}
+ if std::env::var("CAP_GPUI_AUTO_MIC").is_ok_and(|value| value == "1")
+ && this.microphone.is_none()
+ {
+ let selected =
+ cap_recording::feeds::microphone::MicrophoneFeed::default_device()
+ .and_then(|(name, _, _)| {
+ this.devices
+ .microphones
+ .iter()
+ .find(|microphone| microphone.name == name)
+ .cloned()
+ })
+ .or_else(|| this.devices.microphones.first().cloned());
+ if let Some(microphone) = selected {
+ tracing::info!(microphone = %microphone.name, "auto-selecting microphone");
+ this.set_microphone_selection(Some(microphone), cx);
+ }
+ }
// `CAP_GPUI_AUTO_PANEL=display|window`: open that target
// picker panel the way the chevron click does. Same reason as
// `CAP_GPUI_AUTO_CAMERA` above -- the chrome screenshots need
@@ -928,6 +956,104 @@ impl MainWindow {
}));
}
+ pub fn start_recovery_check(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.scan_incomplete_recordings(window, cx, std::time::Duration::from_secs(2));
+ }
+
+ fn scan_incomplete_recordings(
+ &mut self,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ delay: std::time::Duration,
+ ) {
+ self.recovery_scan_task = Some(cx.spawn_in(window, async move |this, cx| {
+ if !delay.is_zero() {
+ cx.background_executor().timer(delay).await;
+ }
+
+ let idle = this
+ .update_in(cx, |this, _, cx| this.session.read(cx).phase == Phase::Idle)
+ .unwrap_or(false);
+ if !idle {
+ return;
+ }
+
+ let incomplete = cx
+ .background_executor()
+ .spawn(async { library::find_incomplete_recordings() })
+ .await;
+
+ this.update_in(cx, |this, window, cx| {
+ if this.session.read(cx).phase != Phase::Idle {
+ return;
+ }
+ this.incomplete_recording = incomplete.into_iter().next();
+ if this.incomplete_recording.is_none() {
+ this.recovery_error = None;
+ }
+ cx.notify();
+ window.refresh();
+ })
+ .ok();
+ }));
+ }
+
+ fn process_incomplete_recording(
+ &mut self,
+ recover: bool,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.recovery_pending || self.session.read(cx).phase != Phase::Idle {
+ return;
+ }
+ let Some(recording) = self.incomplete_recording.clone() else {
+ return;
+ };
+
+ self.recovery_pending = true;
+ self.recovery_error = None;
+ cx.notify();
+ window.refresh();
+
+ self.recovery_action_task = Some(cx.spawn_in(window, async move |this, cx| {
+ let result = cx
+ .background_executor()
+ .spawn(async move {
+ if recover {
+ library::recover_incomplete_recording(&recording.project_path)
+ } else {
+ library::delete_recording_directory(&recording.project_path)
+ .map(|()| recording.project_path)
+ }
+ })
+ .await;
+
+ this.update_in(cx, |this, window, cx| {
+ this.recovery_pending = false;
+ match result {
+ Ok(project_path) => {
+ this.incomplete_recording = None;
+ this.recovery_error = None;
+ this.refresh_recents(window, cx);
+ this.refresh_open_library(window, cx);
+ this.scan_incomplete_recordings(window, cx, std::time::Duration::ZERO);
+ if recover {
+ cx.defer(move |cx| app_windows::open_editor(project_path, cx));
+ }
+ }
+ Err(error) => {
+ tracing::warn!(%error, "incomplete recording action failed");
+ this.recovery_error = Some(error);
+ }
+ }
+ cx.notify();
+ window.refresh();
+ })
+ .ok();
+ }));
+ }
+
/// Install a fresh scan result, releasing the previous thumbnails from the
/// sprite atlas -- the same explicit drop the camera preview does with
/// every frame it replaces.
@@ -1239,6 +1365,8 @@ impl MainWindow {
self.mode = mode;
self.target = Some(overlay.unwrap_or(TargetType::Display));
+ self.system_audio =
+ std::env::var("CAP_GPUI_AUTO_SYSTEM_AUDIO").is_ok_and(|value| value == "1");
cx.notify();
// `CAP_GPUI_AUTO_PAUSE=1`: wiggle pause/resume in the middle third, so
@@ -1339,10 +1467,20 @@ impl MainWindow {
// The overlay route: arm the mode (which opens the
// overlays), let them come up, seed what a drag or a hover
// would have produced, then press their Start button.
- if this
- .update_in(cx, |this, _window, cx| this.arm_overlay(kind, cx))
- .is_err()
- {
+ let wanted = required_window.clone();
+ let armed = this
+ .update_in(cx, |this, _window, cx| {
+ this.arm_overlay(kind, cx);
+ kind != TargetType::Window
+ || wanted.as_ref().is_none_or(|wanted| {
+ this.selected_window
+ .as_ref()
+ .is_some_and(|selected| window_matches(selected, wanted))
+ })
+ })
+ .unwrap_or(false);
+ if !armed {
+ tracing::error!("auto-record selected window is no longer available");
return;
}
cx.background_executor()
@@ -1514,6 +1652,7 @@ impl MainWindow {
let (camera_feed, mic_feed) = {
let feeds = Feeds::global(cx);
+ feeds.update(cx, |feeds, cx| feeds.resume_camera_preview(cx));
let feeds = feeds.read(cx);
(feeds.camera_actor(), feeds.mic_actor())
};
@@ -1590,7 +1729,13 @@ impl MainWindow {
label: camera.label.clone(),
});
self.camera = camera;
- Feeds::global(cx).update(cx, |feeds, cx| feeds.set_camera(selection, cx));
+ Feeds::global(cx).update(cx, |feeds, cx| {
+ let selected = selection.is_some();
+ feeds.set_camera(selection, cx);
+ if selected {
+ feeds.resume_camera_preview(cx);
+ }
+ });
cx.notify();
}
@@ -1623,6 +1768,7 @@ impl Render for MainWindow {
div()
.size_full()
+ .relative()
.flex()
.flex_col()
.overflow_hidden()
@@ -1657,10 +1803,138 @@ impl Render for MainWindow {
},
|this| this.child(self.render_recording_overlay(cx)),
)
+ .when_some(
+ self.incomplete_recording
+ .clone()
+ .filter(|_| self.session.read(cx).phase == Phase::Idle),
+ |this, recording| this.child(self.render_recovery_toast(recording, cx)),
+ )
}
}
impl MainWindow {
+ fn render_recovery_toast(
+ &self,
+ recording: library::IncompleteRecordingItem,
+ cx: &mut Context<Self>,
+ ) -> impl IntoElement {
+ let theme = self.theme;
+ let pending = self.recovery_pending;
+ let duration = recording.estimated_duration_secs.round() as u64;
+ let duration_label = if duration == 0 {
+ String::new()
+ } else if duration < 60 {
+ format!(" · ~{duration}s")
+ } else if duration.is_multiple_of(60) {
+ format!(" · ~{}m", duration / 60)
+ } else {
+ format!(" · ~{}m {}s", duration / 60, duration % 60)
+ };
+ let segments = format!(
+ "{} segment{}{}",
+ recording.segment_count,
+ if recording.segment_count == 1 {
+ ""
+ } else {
+ "s"
+ },
+ duration_label
+ );
+
+ div()
+ .absolute()
+ .bottom(px(12.))
+ .left(px(12.))
+ .right(px(12.))
+ .rounded(px(8.))
+ .border_1()
+ .border_color(theme.red_4)
+ .bg(theme.red_2)
+ .p(px(10.))
+ .shadow_md()
+ .child(
+ div()
+ .flex()
+ .flex_row()
+ .items_center()
+ .gap(px(8.))
+ .child(
+ div()
+ .flex_1()
+ .min_w_0()
+ .flex()
+ .flex_col()
+ .child(
+ div()
+ .text_size(px(10.))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(theme.red_11)
+ .child("Incomplete Recording"),
+ )
+ .child(
+ div()
+ .truncate()
+ .text_size(px(12.))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(theme.gray_12)
+ .child(recording.pretty_name),
+ )
+ .child(
+ div()
+ .text_size(px(10.))
+ .text_color(theme.gray_11)
+ .child(segments),
+ )
+ .when_some(self.recovery_error.clone(), |this, error| {
+ this.child(
+ div()
+ .mt(px(4.))
+ .text_size(px(10.))
+ .text_color(theme.red_11)
+ .child(error),
+ )
+ }),
+ )
+ .child(
+ div()
+ .flex()
+ .flex_row()
+ .flex_shrink_0()
+ .gap(px(6.))
+ .child(
+ ui::Button::plain(
+ &theme,
+ "recover-incomplete-recording",
+ ui::ButtonVariant::Primary,
+ ui::ButtonSize::Xs,
+ )
+ .label(if pending { "..." } else { "Recover" })
+ .disabled(pending)
+ .on_click(cx.listener(
+ |this, _, window, cx| {
+ this.process_incomplete_recording(true, window, cx);
+ },
+ )),
+ )
+ .child(
+ ui::Button::plain(
+ &theme,
+ "discard-incomplete-recording",
+ ui::ButtonVariant::Gray,
+ ui::ButtonSize::Xs,
+ )
+ .label("Discard")
+ .disabled(pending)
+ .on_click(cx.listener(
+ |this, _, window, cx| {
+ this.process_incomplete_recording(false, window, cx);
+ },
+ )),
+ ),
+ ),
+ )
+ }
+
fn render_header(&self, _window: &Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
@@ -2606,6 +2880,7 @@ impl MainWindow {
let studio = item.mode == library::RecordingMode::Studio;
let sharing = item.sharing.clone();
let mode = item.mode;
+ let opens_editor = item.opens_editor();
let subtitle = item.mode.label().to_string();
let actions = self.render_recording_card_actions(index, item, cx);
@@ -2617,12 +2892,12 @@ impl MainWindow {
Some(subtitle),
item.clip_count,
cx.listener(move |_, _, _window, cx| {
- if studio {
+ if studio && opens_editor {
let path = path.clone();
cx.defer(move |cx| app_windows::open_editor(path, cx));
- } else if let Some(url) = &sharing {
+ } else if !studio && let Some(url) = &sharing {
cx.open_url(url);
- } else {
+ } else if !studio {
library::open_recording_folder(&path, mode);
}
}),
@@ -2648,7 +2923,7 @@ impl MainWindow {
.px(px(8.))
.pb(px(6.))
.gap(px(4.));
- if mode == library::RecordingMode::Studio {
+ if item.opens_editor() {
let editor = path.clone();
row = row.child(self.library_action(
("lib-rec-edit", index),
@@ -4454,7 +4729,7 @@ pub fn auto_overlay_kind() -> Option<TargetType> {
}
}
-fn auto_window_title() -> Option<String> {
+pub(crate) fn auto_window_title() -> Option<String> {
std::env::var("CAP_GPUI_AUTO_WINDOW")
.ok()
.map(|value| value.trim().to_string())
@@ -4462,7 +4737,7 @@ fn auto_window_title() -> Option<String> {
}
fn window_matches(window: &crate::devices::WindowOption, title: &str) -> bool {
- window.label == title || window.label.contains(title)
+ window.label == title
}
/// `CAP_GPUI_AUTO_AREA=x,y,width,height`, the harness's stand-in for drawing a
diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rs
index b60f0b58b..1bb497e37 100644
--- a/apps/desktop-gpui/src/recording.rs
+++ b/apps/desktop-gpui/src/recording.rs
@@ -59,6 +59,7 @@ enum Handle {
pub struct ActiveRecording {
handle: Handle,
pub project_dir: PathBuf,
+ instant_upload: Option<crate::upload::InstantUpload>,
/// Recording-scoped mic mute (payload zeroing at the consumer seam; the
/// stream cadence is unaffected). `None` when the recording has no mic.
pub mic_mute: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
@@ -73,6 +74,12 @@ pub struct ActiveRecording {
}
impl ActiveRecording {
+ pub fn instant_share_url(&self) -> Option<&str> {
+ self.instant_upload
+ .as_ref()
+ .map(|upload| upload.video().link.as_str())
+ }
+
/// Stop and finalize. Returns the project directory.
///
/// Finalization mirrors the CLI's `finalize_completed`: studio projects get
@@ -121,6 +128,11 @@ impl ActiveRecording {
Handle::Studio(handle) => handle.cancel().await?,
Handle::Instant(handle) => handle.cancel().await?,
}
+ let remote_result = if let Some(upload) = self.instant_upload {
+ upload.cancel().await
+ } else {
+ Ok(())
+ };
tokio::task::spawn_blocking({
let dir = self.project_dir.clone();
move || std::fs::remove_dir_all(&dir)
@@ -128,10 +140,12 @@ impl ActiveRecording {
.await
.context("delete task")?
.with_context(|| format!("deleting {}", self.project_dir.display()))?;
+ remote_result.map_err(anyhow::Error::msg)?;
Ok(())
}
pub async fn stop(self) -> anyhow::Result<PathBuf> {
+ let mut instant_upload = self.instant_upload;
match self.handle {
Handle::Studio(handle) => {
let completed = handle.stop().await?;
@@ -163,23 +177,32 @@ impl ActiveRecording {
Handle::Instant(handle) => {
let completed = handle.stop().await?;
let project_path = completed.project_path.clone();
+ let upload = instant_upload
+ .as_mut()
+ .ok_or_else(|| anyhow!("instant recording has no upload session"))?;
+ let segmented = upload.is_segmented();
+ let segment_upload_result = upload.finish_segments().await;
let display_dir = project_path.join("content/display");
let audio_dir = project_path.join("content/audio");
let output_path = project_path.join("content/output.mp4");
- let muxed = output_path.clone();
- tokio::task::spawn_blocking(move || {
- cap_recording::recovery::RecoveryManager::finalize_instant_output(
- &display_dir,
- &audio_dir,
- &muxed,
- )
- })
- .await
- .context("instant finalize task")?
- .context("instant finalize")?;
+ if display_dir.is_dir() {
+ let muxed = output_path.clone();
+ tokio::task::spawn_blocking(move || {
+ cap_recording::recovery::RecoveryManager::finalize_instant_output(
+ &display_dir,
+ &audio_dir,
+ &muxed,
+ )
+ })
+ .await
+ .context("instant finalize task")?
+ .context("instant finalize")?;
+ } else if !output_path.is_file() {
+ return Err(anyhow!("instant recording has no finalized output"));
+ }
- persist_instant_meta(&completed)?;
+ persist_instant_meta(&completed, upload.video())?;
// The Tauri app builds the instant thumbnail by concatenating
// `content/display`'s init segment with the first media
@@ -196,6 +219,52 @@ impl ActiveRecording {
.await
.context("instant thumbnail task")?;
+ if let Err(error) = segment_upload_result {
+ persist_instant_upload_failure(&completed.project_path, &error)?;
+ return Err(anyhow!(error));
+ }
+
+ let upload_result = if segmented {
+ upload.finish_screenshot(&completed.project_path).await
+ } else {
+ crate::upload::upload_exported_video(
+ completed.project_path.clone(),
+ None,
+ |_| {},
+ Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ )
+ .await
+ .and_then(|result| match result {
+ crate::upload::UploadResult::Success(_) => Ok(()),
+ crate::upload::UploadResult::NotAuthenticated => Err(
+ "Your session has expired. Please sign in again to upload this recording."
+ .to_string(),
+ ),
+ crate::upload::UploadResult::UpgradeRequired => {
+ Err("Instant recording requires an upgraded plan.".to_string())
+ }
+ })
+ };
+ if let Err(error) = upload_result {
+ persist_instant_upload_failure(&completed.project_path, &error)?;
+ return Err(anyhow!(error));
+ }
+
+ let mut meta =
+ cap_project::RecordingMeta::load_for_project(&completed.project_path)
+ .map_err(|error| anyhow!("loading instant recording metadata: {error}"))?;
+ meta.upload = Some(cap_project::UploadMeta::Complete);
+ meta.save_for_project()
+ .map_err(|error| anyhow!("saving completed instant upload: {error}"))?;
+
+ if crate::store::GeneralSettings::load().delete_instant_recordings_after_upload {
+ let directory = completed.project_path.clone();
+ tokio::task::spawn_blocking(move || std::fs::remove_dir_all(directory))
+ .await
+ .context("instant upload cleanup task")?
+ .context("deleting uploaded instant recording")?;
+ }
+
Ok(completed.project_path)
}
}
@@ -361,7 +430,10 @@ pub fn apply_camera_blur_to_project_config(
/// `persist_instant_recording_meta` from the CLI, verbatim in behavior: without
/// this pair of files the recording plays but no Cap surface lists it.
-fn persist_instant_meta(completed: &instant_recording::CompletedRecording) -> anyhow::Result<()> {
+fn persist_instant_meta(
+ completed: &instant_recording::CompletedRecording,
+ upload: &cap_project::VideoUploadInfo,
+) -> anyhow::Result<()> {
use cap_project::{
InstantRecordingMeta, Platform, ProjectConfiguration, RecordingMeta, RecordingMetaInner,
};
@@ -380,13 +452,21 @@ fn persist_instant_meta(completed: &instant_recording::CompletedRecording) -> an
other => other.clone(),
};
+ let previous_upload = RecordingMeta::load_for_project(&completed.project_path)
+ .ok()
+ .and_then(|meta| meta.upload);
+
RecordingMeta {
platform: Some(Platform::default()),
project_path: completed.project_path.clone(),
pretty_name,
- sharing: None,
+ sharing: Some(cap_project::SharingMeta {
+ id: upload.id.clone(),
+ link: upload.link.clone(),
+ content_hash: None,
+ }),
inner: RecordingMetaInner::Instant(meta),
- upload: None,
+ upload: previous_upload,
}
.save_for_project()
.map_err(|e| anyhow!("saving instant recording meta: {e}"))?;
@@ -397,6 +477,61 @@ fn persist_instant_meta(completed: &instant_recording::CompletedRecording) -> an
Ok(())
}
+fn persist_instant_upload_failure(
+ project_path: &std::path::Path,
+ error: &str,
+) -> anyhow::Result<()> {
+ let mut meta = cap_project::RecordingMeta::load_for_project(project_path)
+ .map_err(|load_error| anyhow!("loading failed instant recording metadata: {load_error}"))?;
+ meta.upload = Some(cap_project::UploadMeta::Failed {
+ error: error.to_string(),
+ });
+ meta.save_for_project()
+ .map_err(|save_error| anyhow!("saving failed instant upload: {save_error}"))?;
+ Ok(())
+}
+
+fn persist_in_progress_instant_meta(
+ project_path: &std::path::Path,
+ video: &cap_project::VideoUploadInfo,
+ segmented: bool,
+) -> anyhow::Result<()> {
+ let upload = if segmented {
+ cap_project::UploadMeta::SegmentUpload {
+ video_id: video.id.clone(),
+ pre_created_video: video.clone(),
+ recording_dir: project_path.to_path_buf(),
+ }
+ } else {
+ cap_project::UploadMeta::MultipartUpload {
+ video_id: video.id.clone(),
+ file_path: project_path.join("content/output.mp4"),
+ pre_created_video: video.clone(),
+ recording_dir: project_path.to_path_buf(),
+ }
+ };
+ let pretty_name = project_path
+ .file_stem()
+ .and_then(|name| name.to_str())
+ .filter(|name| !name.is_empty())
+ .unwrap_or("Cap Recording")
+ .to_string();
+
+ cap_project::RecordingMeta {
+ platform: Some(cap_project::Platform::default()),
+ project_path: project_path.to_path_buf(),
+ pretty_name,
+ sharing: None,
+ inner: cap_project::RecordingMetaInner::Instant(
+ cap_project::InstantRecordingMeta::InProgress { recording: true },
+ ),
+ upload: Some(upload),
+ }
+ .save_for_project()
+ .map_err(|error| anyhow!("saving in-progress instant recording metadata: {error}"))?;
+ Ok(())
+}
+
pub async fn start(config: StartConfig) -> anyhow::Result<ActiveRecording> {
match start_attempt(config.clone()).await {
Ok(active) => Ok(active),
@@ -421,7 +556,55 @@ pub async fn start(config: StartConfig) -> anyhow::Result<ActiveRecording> {
}
async fn start_attempt(config: StartConfig) -> anyhow::Result<ActiveRecording> {
- let project_dir = create_project_dir(&config.target)?;
+ if matches!(config.target, ScreenCaptureTarget::CameraOnly) && config.camera.is_none() {
+ return Err(anyhow!("Camera-only recording requires a selected camera."));
+ }
+ if config.mode == RecordingMode::Instant && !crate::store::auth_snapshot().signed_in() {
+ return Err(anyhow!("Please sign in to use instant recording"));
+ }
+
+ let project_dir = create_project_dir(&config.target, config.mode)?;
+ let project_name = project_dir
+ .file_stem()
+ .and_then(|name| name.to_str())
+ .unwrap_or("Cap Recording")
+ .to_string();
+ let organization_id = crate::store::store_section(crate::store::RECORDING_SETTINGS)
+ .get("organizationId")
+ .and_then(serde_json::Value::as_str)
+ .filter(|organization| !organization.is_empty())
+ .map(str::to_string);
+
+ let pre_created_video = if config.mode == RecordingMode::Instant {
+ Some(
+ crate::upload::prepare_instant_upload(
+ matches!(config.target, ScreenCaptureTarget::CameraOnly),
+ project_name,
+ organization_id,
+ )
+ .await
+ .map_err(anyhow::Error::msg)?,
+ )
+ } else {
+ None
+ };
+
+ let result = start_attempt_with_upload(config, project_dir, pre_created_video.clone()).await;
+ if result.is_err()
+ && let Some(video) = pre_created_video
+ && let Err(error) = crate::upload::delete_instant_video(&video.id).await
+ {
+ tracing::error!(video_id = %video.id, "Failed to clean up instant recording: {error}");
+ return Err(anyhow!("Failed to clean up instant recording: {error}"));
+ }
+ result
+}
+
+async fn start_attempt_with_upload(
+ config: StartConfig,
+ project_dir: PathBuf,
+ pre_created_video: Option<cap_project::VideoUploadInfo>,
+) -> anyhow::Result<ActiveRecording> {
tracing::info!(dir = %project_dir.display(), "starting recording");
// The app-scoped feeds (running previews/meters, owned by `Feeds`) are
@@ -531,9 +714,7 @@ async fn start_attempt(config: StartConfig) -> anyhow::Result<ActiveRecording> {
}
excluded
};
- #[cfg(not(target_os = "macos"))]
- let excluded_windows = config.excluded_windows.clone();
-
+ let mut instant_upload = None;
let handle = match config.mode {
RecordingMode::Studio => {
let mut builder = defaults.apply_to_studio_builder(
@@ -542,7 +723,10 @@ async fn start_attempt(config: StartConfig) -> anyhow::Result<ActiveRecording> {
camera_lock.is_some(),
None,
);
- builder = builder.with_excluded_windows(excluded_windows.clone());
+ #[cfg(target_os = "macos")]
+ {
+ builder = builder.with_excluded_windows(excluded_windows.clone());
+ }
if let Some(lock) = camera_lock.clone() {
builder = builder.with_camera_feed(lock);
}
@@ -563,15 +747,18 @@ async fn start_attempt(config: StartConfig) -> anyhow::Result<ActiveRecording> {
let mut builder =
instant_recording::Actor::builder(project_dir.clone(), config.target.clone())
.with_system_audio(config.system_audio)
- .with_max_output_size(instant_max_resolution)
- .with_excluded_windows(excluded_windows.clone());
+ .with_max_output_size(instant_max_resolution);
+ #[cfg(target_os = "macos")]
+ {
+ builder = builder.with_excluded_windows(excluded_windows.clone());
+ }
if let Some(lock) = camera_lock.clone() {
builder = builder.with_camera_feed(lock);
}
if let Some(lock) = mic_lock.clone() {
builder = builder.with_mic_feed(lock);
}
- Handle::Instant(Arc::new(
+ let handle = Arc::new(
builder
.build(
#[cfg(target_os = "macos")]
@@ -579,13 +766,23 @@ async fn start_attempt(config: StartConfig) -> anyhow::Result<ActiveRecording> {
)
.await
.context("instant recording actor")?,
- ))
+ );
+ let video = pre_created_video
+ .ok_or_else(|| anyhow!("instant recording has no reserved upload"))?;
+ let segment_rx = handle.take_segment_rx();
+ persist_in_progress_instant_meta(&project_dir, &video, segment_rx.is_some())?;
+ instant_upload = Some(
+ crate::upload::start_instant_upload(video, project_dir.clone(), segment_rx)
+ .map_err(anyhow::Error::msg)?,
+ );
+ Handle::Instant(handle)
}
};
Ok(ActiveRecording {
handle,
project_dir,
+ instant_upload,
mic_mute,
_mic_feed: mic_feed,
_camera_feed: camera_feed,
@@ -764,19 +961,41 @@ pub fn delete_recording_directory(path: &std::path::Path) -> Result<(), String>
/// `format_project_name` with the default template
/// (`{target_name} ({target_kind}) {date} {time}`), then the same `:` -> `.`
/// replacement and uniquing the Tauri app applies.
-fn create_project_dir(target: &ScreenCaptureTarget) -> anyhow::Result<PathBuf> {
+fn create_project_dir(
+ target: &ScreenCaptureTarget,
+ recording_mode: RecordingMode,
+) -> anyhow::Result<PathBuf> {
let base = recordings_dir();
std::fs::create_dir_all(&base)
.with_context(|| format!("creating recordings dir {}", base.display()))?;
+ match cap_utils::disk_space::free_bytes_for_path(&base) {
+ Ok(bytes) if bytes <= cap_utils::disk_space::LOW_DISK_STOP_BYTES => {
+ return Err(anyhow!(
+ "Not enough disk space to start recording ({:.2} GB free). Free up at least {} MB and try again.",
+ bytes as f64 / 1_073_741_824.0,
+ cap_utils::disk_space::LOW_DISK_STOP_BYTES / (1024 * 1024)
+ ));
+ }
+ Ok(bytes) if bytes <= cap_utils::disk_space::LOW_DISK_WARN_BYTES => {
+ tracing::warn!(
+ bytes_remaining = bytes,
+ "Starting recording with low disk space"
+ );
+ }
+ Ok(_) => {}
+ Err(error) => tracing::warn!("Failed to check disk space before recording: {error}"),
+ }
+
let target_name = target.title().unwrap_or_else(|| "Unknown".into());
let now = chrono::Local::now();
- let name = format!(
- "{} ({}) {} {}",
- target_name,
+ let settings = crate::store::GeneralSettings::load();
+ let name = format_recording_project_name(
+ settings.default_project_name_template.as_deref(),
+ &target_name,
target.kind_str(),
- now.format("%Y-%m-%d"),
- now.format("%I.%M %p"),
+ recording_mode,
+ now,
);
// Same normalization chain as the Tauri app: colons break Finder, slashes
// break paths.
@@ -787,12 +1006,113 @@ fn create_project_dir(target: &ScreenCaptureTarget) -> anyhow::Result<PathBuf> {
Ok(base.join(filename))
}
+fn format_recording_project_name(
+ template: Option<&str>,
+ target_name: &str,
+ target_kind: &str,
+ mode: RecordingMode,
+ datetime: chrono::DateTime<chrono::Local>,
+) -> String {
+ let target_name = if target_name.chars().count() > 180 {
+ format!("{}...", target_name.chars().take(180).collect::<String>())
+ } else {
+ target_name.to_string()
+ };
+ let (recording_mode, mode) = match mode {
+ RecordingMode::Studio => ("Studio", "studio"),
+ RecordingMode::Instant => ("Instant", "instant"),
+ };
+ let formatted = template
+ .unwrap_or(crate::store::DEFAULT_PROJECT_NAME_TEMPLATE)
+ .replace("{recording_mode}", recording_mode)
+ .replace("{mode}", mode)
+ .replace("{target_kind}", target_kind)
+ .replace("{target_name}", &target_name);
+ let formatted = replace_datetime_template_token(&formatted, "date", "%Y-%m-%d", datetime);
+ let formatted = replace_datetime_template_token(&formatted, "time", "%I:%M %p", datetime);
+ replace_datetime_template_token(&formatted, "moment", "%Y-%m-%d %H:%M", datetime)
+}
+
+fn replace_datetime_template_token(
+ input: &str,
+ name: &str,
+ default_format: &str,
+ datetime: chrono::DateTime<chrono::Local>,
+) -> String {
+ let mut output = String::with_capacity(input.len());
+ let mut remaining = input;
+ let prefix = format!("{{{name}");
+
+ while let Some(start) = remaining.find(&prefix) {
+ output.push_str(&remaining[..start]);
+ let candidate = &remaining[start..];
+ let Some(end) = candidate.find('}') else {
+ output.push_str(candidate);
+ return output;
+ };
+ let token = &candidate[1..end];
+ if token == name {
+ output.push_str(&datetime.format(default_format).to_string());
+ } else if let Some(custom_format) = token.strip_prefix(&format!("{name}:")) {
+ let format = cap_utils::moment_format_to_chrono(custom_format);
+ output.push_str(&datetime.format(&format).to_string());
+ } else {
+ output.push_str(&candidate[..=end]);
+ }
+ remaining = &candidate[end + 1..];
+ }
+ output.push_str(remaining);
+ output
+}
+
#[cfg(test)]
mod tests {
use super::*;
use crate::store::BlurMode;
+ use chrono::TimeZone as _;
use serde_json::Value;
+ #[test]
+ fn recording_project_names_honor_mode_target_and_custom_datetime_formats() {
+ let timestamp = chrono::Local
+ .with_ymd_and_hms(2026, 8, 25, 14, 7, 9)
+ .single()
+ .unwrap();
+
+ assert_eq!(
+ format_recording_project_name(
+ Some(
+ "{recording_mode}-{mode}-{target_kind}-{target_name}-{date:DD/MM/YYYY}-{time:HH.mm}-{moment:YYYYMMDD_HHmmss}"
+ ),
+ "Example Window",
+ "Window",
+ RecordingMode::Instant,
+ timestamp,
+ ),
+ "Instant-instant-Window-Example Window-25/08/2026-14.07-20260825_140709"
+ );
+ }
+
+ #[test]
+ fn recording_project_names_preserve_unknown_tokens_and_limit_target_length() {
+ let timestamp = chrono::Local
+ .with_ymd_and_hms(2026, 8, 25, 9, 15, 0)
+ .single()
+ .unwrap();
+ let target = "x".repeat(200);
+
+ assert_eq!(
+ format_recording_project_name(
+ Some("{mode}-{target_name}-{unknown}"),
+ &target,
+ "Display",
+ RecordingMode::Studio,
+ timestamp,
+ ),
+ format!("studio-{}...-{{unknown}}", "x".repeat(180))
+ );
+ }
+
fn temp_project(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"cap-gpui-config-{tag}-{}-{:?}",
diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs
index efa97c47c..8063df869 100644
--- a/apps/desktop-gpui/src/session.rs
+++ b/apps/desktop-gpui/src/session.rs
@@ -210,6 +210,13 @@ impl RecordingSession {
let Some(active) = self.active.take() else {
return;
};
+ let instant_share_url = active.instant_share_url().map(ToString::to_string);
+ if let Some(link) = &instant_share_url
+ && !crate::store::GeneralSettings::load().disable_auto_open_links
+ {
+ let separator = if link.contains('?') { '&' } else { '?' };
+ cx.open_url(&format!("{link}{separator}recordingStopped=1"));
+ }
self.phase = Phase::Stopping;
cx.notify();
@@ -228,6 +235,8 @@ impl RecordingSession {
tracing::info!(dir = %project_dir.display(), "recording finished");
if this.mode() == Some(crate::recording::RecordingMode::Studio) {
this.finished_studio = Some(project_dir);
+ } else if let Some(link) = instant_share_url {
+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(link));
}
}
Ok(Err(error)) => {
diff --git a/apps/desktop-gpui/src/upload.rs b/apps/desktop-gpui/src/upload.rs
index a7f440102..b69c7d56b 100644
--- a/apps/desktop-gpui/src/upload.rs
+++ b/apps/desktop-gpui/src/upload.rs
@@ -2,9 +2,12 @@ use std::collections::HashMap;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
-use std::time::Duration;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant};
-use cap_project::{RecordingMeta, S3UploadMeta, SharingMeta, UploadMeta};
+use cap_enc_ffmpeg::segmented_stream::{SegmentCompletedEvent, SegmentMediaType};
+use cap_project::{RecordingMeta, S3UploadMeta, SharingMeta, UploadMeta, VideoUploadInfo};
+use futures_util::{StreamExt as _, stream::FuturesUnordered};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -13,6 +16,17 @@ use crate::auth::{self, AuthApiError};
const MIN_CHUNK_SIZE: u64 = 5 * 1024 * 1024;
const MAX_CHUNK_SIZE: u64 = 15 * 1024 * 1024;
+const MAX_SEGMENT_UPLOADS: usize = 6;
+const SEGMENT_URL_PREFETCH: u32 = 20;
+const SEGMENT_UPLOAD_ATTEMPTS: u32 = 3;
+const MANIFEST_UPLOAD_INTERVAL: Duration = Duration::from_secs(1);
+
+#[derive(Debug, Deserialize)]
+struct SignedUploadTarget {
+ url: String,
+ #[serde(default)]
+ headers: HashMap<String, String>,
+}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UploadResult {
@@ -21,6 +35,526 @@ pub enum UploadResult {
UpgradeRequired,
}
+pub struct InstantUpload {
+ pub video: VideoUploadInfo,
+ segment_upload: Option<tokio::task::JoinHandle<Result<(), String>>>,
+ cancel: Arc<AtomicBool>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+struct SegmentManifestEntry {
+ index: u32,
+ duration: f64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+struct SegmentUploadManifest {
+ version: u32,
+ video_init_uploaded: bool,
+ audio_init_uploaded: bool,
+ video_segments: Vec<SegmentManifestEntry>,
+ audio_segments: Vec<SegmentManifestEntry>,
+ is_complete: bool,
+}
+
+impl Default for SegmentUploadManifest {
+ fn default() -> Self {
+ Self {
+ version: 2,
+ video_init_uploaded: false,
+ audio_init_uploaded: false,
+ video_segments: Vec::new(),
+ audio_segments: Vec::new(),
+ is_complete: false,
+ }
+ }
+}
+
+impl SegmentUploadManifest {
+ fn record(&mut self, event: &SegmentCompletedEvent) {
+ match (event.is_init, event.media_type) {
+ (true, SegmentMediaType::Video) => self.video_init_uploaded = true,
+ (true, SegmentMediaType::Audio) => self.audio_init_uploaded = true,
+ (false, media_type) => {
+ let segments = match media_type {
+ SegmentMediaType::Video => &mut self.video_segments,
+ SegmentMediaType::Audio => &mut self.audio_segments,
+ };
+ if let Some(segment) = segments
+ .iter_mut()
+ .find(|segment| segment.index == event.index)
+ {
+ segment.duration = event.duration;
+ } else {
+ segments.push(SegmentManifestEntry {
+ index: event.index,
+ duration: event.duration,
+ });
+ segments.sort_unstable_by_key(|segment| segment.index);
+ }
+ }
+ }
+ }
+
+ fn has_video_content(&self) -> bool {
+ self.video_init_uploaded && !self.video_segments.is_empty()
+ }
+}
+
+pub async fn prepare_instant_upload(
+ camera_only: bool,
+ project_name: String,
+ organization_id: Option<String>,
+) -> Result<VideoUploadInfo, String> {
+ if store_auth_missing() {
+ return Err("Please sign in to use instant recording".to_string());
+ }
+
+ let recording_mode = if camera_only {
+ "desktopMP4"
+ } else {
+ "desktopSegments"
+ };
+ let config = create_or_get_video_with_mode(
+ false,
+ None,
+ Some(project_name),
+ None,
+ organization_id,
+ recording_mode,
+ )
+ .await
+ .map_err(|error| match error {
+ AuthApiError::InvalidAuthentication => {
+ "Your session has expired. Please sign in again to use instant recording.".to_string()
+ }
+ AuthApiError::UpgradeRequired => "Instant recording requires an upgraded plan.".to_string(),
+ error => format!("Could not create the shareable link: {error}"),
+ })?;
+
+ Ok(VideoUploadInfo {
+ id: config.id.clone(),
+ link: format!("{}/s/{}", auth::server_url(), config.id),
+ config,
+ })
+}
+
+pub fn start_instant_upload(
+ video: VideoUploadInfo,
+ project_path: PathBuf,
+ segment_rx: Option<std::sync::mpsc::Receiver<SegmentCompletedEvent>>,
+) -> Result<InstantUpload, String> {
+ let cancel = Arc::new(AtomicBool::new(false));
+ let segment_upload = if let Some(segment_rx) = segment_rx {
+ let (events_tx, events_rx) = flume::unbounded();
+ std::thread::Builder::new()
+ .name("gpui-instant-segments".to_string())
+ .spawn(move || {
+ while let Ok(event) = segment_rx.recv() {
+ if events_tx.send(event).is_err() {
+ break;
+ }
+ }
+ })
+ .map_err(|error| format!("Failed to start instant upload: {error}"))?;
+
+ let upload_video = video.clone();
+ let upload_cancel = cancel.clone();
+ Some(tokio::spawn(async move {
+ run_segment_upload(upload_video, project_path, events_rx, upload_cancel).await
+ }))
+ } else {
+ None
+ };
+
+ Ok(InstantUpload {
+ video,
+ segment_upload,
+ cancel,
+ })
+}
+
+impl InstantUpload {
+ pub fn video(&self) -> &VideoUploadInfo {
+ &self.video
+ }
+
+ pub fn is_segmented(&self) -> bool {
+ self.segment_upload.is_some()
+ }
+
+ pub async fn finish_segments(&mut self) -> Result<(), String> {
+ let Some(upload) = self.segment_upload.take() else {
+ return Ok(());
+ };
+ upload
+ .await
+ .map_err(|error| format!("Instant segment upload task failed: {error}"))?
+ }
+
+ pub async fn finish_screenshot(&self, project_path: &Path) -> Result<(), String> {
+ upload_screenshot(
+ &self.video.id,
+ &project_path.join("screenshots/display.jpg"),
+ )
+ .await
+ .map_err(|error| format!("Instant recording thumbnail upload failed: {error}"))
+ }
+
+ pub async fn cancel(mut self) -> Result<(), String> {
+ self.cancel.store(true, Ordering::Release);
+ if let Some(upload) = self.segment_upload.take() {
+ upload.abort();
+ }
+
+ delete_instant_video(&self.video.id).await
+ }
+}
+
+pub async fn delete_instant_video(video_id: &str) -> Result<(), String> {
+ let path = format!(
+ "/api/desktop/video/delete?videoId={}",
+ urlencoding(video_id)
+ );
+ let response = auth::authed_request(reqwest::Method::DELETE, &path, None)
+ .await
+ .map_err(|error| format!("Failed to delete instant recording: {error}"))?;
+ let status = response.status();
+ if status.is_success() || status == StatusCode::NOT_FOUND {
+ return Ok(());
+ }
+ let body = response.text().await.unwrap_or_default();
+ Err(format!(
+ "Failed to delete instant recording {video_id}: {status}: {body}"
+ ))
+}
+
+async fn run_segment_upload(
+ video: VideoUploadInfo,
+ project_path: PathBuf,
+ events: flume::Receiver<SegmentCompletedEvent>,
+ cancel: Arc<AtomicBool>,
+) -> Result<(), String> {
+ let result = upload_segments(&video.id, events, cancel.clone()).await;
+ if let Err(error) = &result
+ && !cancel.load(Ordering::Acquire)
+ && let Ok(mut meta) = RecordingMeta::load_for_project(&project_path)
+ {
+ meta.upload = Some(UploadMeta::Failed {
+ error: error.clone(),
+ });
+ if let Err(save_error) = meta.save_for_project() {
+ tracing::error!("Failed to persist instant upload failure: {save_error}");
+ }
+ }
+ result
+}
+
+async fn upload_segments(
+ video_id: &str,
+ events: flume::Receiver<SegmentCompletedEvent>,
+ cancel: Arc<AtomicBool>,
+) -> Result<(), String> {
+ let mut manifest = SegmentUploadManifest::default();
+ let mut uploads = FuturesUnordered::new();
+ let mut events_closed = false;
+ let mut last_manifest_upload: Option<Instant> = None;
+ let mut next_prefetch = SEGMENT_URL_PREFETCH + 1;
+ let signed_urls = Arc::new(Mutex::new(
+ prefetch_segment_urls(video_id, 1, SEGMENT_URL_PREFETCH)
+ .await
+ .unwrap_or_else(|error| {
+ tracing::warn!("Failed to prefetch instant upload URLs: {error}");
+ HashMap::new()
+ }),
+ ));
+
+ loop {
+ tokio::select! {
+ next_event = events.recv_async(), if !events_closed && uploads.len() < MAX_SEGMENT_UPLOADS => {
+ match next_event {
+ Ok(event) => {
+ if cancel.load(Ordering::Acquire) {
+ return Err("Instant recording upload cancelled".to_string());
+ }
+ if event.media_type == SegmentMediaType::Video
+ && event.index.saturating_add(5) >= next_prefetch
+ {
+ match prefetch_segment_urls(video_id, next_prefetch, SEGMENT_URL_PREFETCH).await {
+ Ok(urls) => {
+ signed_urls.lock().unwrap_or_else(|error| error.into_inner()).extend(urls);
+ next_prefetch = next_prefetch.saturating_add(SEGMENT_URL_PREFETCH);
+ }
+ Err(error) => tracing::warn!("Failed to extend instant upload URLs: {error}"),
+ }
+ }
+ uploads.push(upload_segment_with_retry(
+ video_id.to_string(),
+ event,
+ signed_urls.clone(),
+ cancel.clone(),
+ ));
+ }
+ Err(_) => events_closed = true,
+ }
+ }
+ Some(upload) = uploads.next(), if !uploads.is_empty() => {
+ let event = upload?;
+ manifest.record(&event);
+ if manifest.has_video_content()
+ && last_manifest_upload.is_none_or(|last| last.elapsed() >= MANIFEST_UPLOAD_INTERVAL)
+ {
+ upload_segment_manifest_with_retry(video_id, &manifest, &cancel).await?;
+ last_manifest_upload = Some(Instant::now());
+ }
+ }
+ else => break,
+ }
+ }
+
+ if cancel.load(Ordering::Acquire) {
+ return Err("Instant recording upload cancelled".to_string());
+ }
+ if !manifest.has_video_content() {
+ return Err(format!(
+ "Segment upload completed without video segments for {video_id}"
+ ));
+ }
+
+ manifest.is_complete = true;
+ upload_segment_manifest_with_retry(video_id, &manifest, &cancel).await?;
+ signal_recording_complete_with_retry(video_id, &cancel).await
+}
+
+fn prefetched_segment_paths(start: u32, count: u32) -> Vec<String> {
+ let mut subpaths = Vec::with_capacity((count as usize).saturating_mul(2).saturating_add(3));
+ if start == 1 {
+ subpaths.push("segments/video/init.mp4".to_string());
+ subpaths.push("segments/audio/init.mp4".to_string());
+ subpaths.push("segments/manifest.json".to_string());
+ }
+ for index in start..start.saturating_add(count) {
+ subpaths.push(format!("segments/video/segment_{index:03}.m4s"));
+ subpaths.push(format!("segments/audio/segment_{index:03}.m4s"));
+ }
+ subpaths
+}
+
+async fn prefetch_segment_urls(
+ video_id: &str,
+ start: u32,
+ count: u32,
+) -> Result<HashMap<String, String>, AuthApiError> {
+ #[derive(Deserialize)]
+ struct BatchResponse {
+ urls: HashMap<String, String>,
+ }
+
+ let response = auth::authed_request(
+ reqwest::Method::POST,
+ "/api/upload/signed/batch",
+ Some(json!({
+ "videoId": video_id,
+ "subpaths": prefetched_segment_paths(start, count),
+ })),
+ )
+ .await?;
+ let status = response.status();
+ if !status.is_success() {
+ let body = response.text().await.unwrap_or_default();
+ return Err(AuthApiError::Other(format!(
+ "api/upload_signed_batch/{status}: {body}"
+ )));
+ }
+ response
+ .json::<BatchResponse>()
+ .await
+ .map(|batch| batch.urls)
+ .map_err(|error| AuthApiError::Other(format!("api/upload_signed_batch/response: {error}")))
+}
+
+async fn upload_segment_with_retry(
+ video_id: String,
+ event: SegmentCompletedEvent,
+ signed_urls: Arc<Mutex<HashMap<String, String>>>,
+ cancel: Arc<AtomicBool>,
+) -> Result<SegmentCompletedEvent, String> {
+ let subpath = segment_subpath(&event);
+ let bytes = read_completed_segment(&event, &subpath, &cancel).await?;
+ let mut cached_url = signed_urls
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .remove(&subpath);
+
+ for attempt in 0..SEGMENT_UPLOAD_ATTEMPTS {
+ if cancel.load(Ordering::Acquire) {
+ return Err("Instant recording upload cancelled".to_string());
+ }
+ if attempt > 0 {
+ tokio::time::sleep(Duration::from_millis(250u64 << attempt)).await;
+ }
+
+ let result = if let Some(url) = cached_url.take() {
+ upload_signed_bytes(
+ SignedUploadTarget {
+ url,
+ headers: HashMap::new(),
+ },
+ &subpath,
+ bytes.clone(),
+ )
+ .await
+ } else {
+ presigned_put_bytes(&video_id, &subpath, bytes.clone()).await
+ };
+
+ match result {
+ Ok(()) => return Ok(event),
+ Err(AuthApiError::InvalidAuthentication) => {
+ return Err("Authentication expired while uploading the instant recording".into());
+ }
+ Err(error) if attempt + 1 == SEGMENT_UPLOAD_ATTEMPTS => {
+ return Err(format!(
+ "Failed to upload instant segment {subpath}: {error}"
+ ));
+ }
+ Err(error) => tracing::warn!(
+ subpath,
+ attempt = attempt + 1,
+ "Instant recording segment upload failed; retrying: {error}"
+ ),
+ }
+ }
+
+ Err(format!("Failed to upload instant segment {subpath}"))
+}
+
+async fn read_completed_segment(
+ event: &SegmentCompletedEvent,
+ subpath: &str,
+ cancel: &AtomicBool,
+) -> Result<Vec<u8>, String> {
+ let started = Instant::now();
+ loop {
+ if cancel.load(Ordering::Acquire) {
+ return Err("Instant recording upload cancelled".to_string());
+ }
+ let bytes = tokio::task::spawn_blocking({
+ let path = event.path.clone();
+ move || std::fs::read(path)
+ })
+ .await
+ .map_err(|error| format!("Failed to read instant segment {subpath}: {error}"))?;
+
+ match bytes {
+ Ok(bytes)
+ if !bytes.is_empty()
+ && (event.file_size == 0 || bytes.len() >= event.file_size as usize) =>
+ {
+ return Ok(bytes);
+ }
+ Ok(_) if started.elapsed() >= Duration::from_secs(10) => {
+ return Err(format!(
+ "Instant recording segment is incomplete: {subpath}"
+ ));
+ }
+ Err(error) if started.elapsed() >= Duration::from_secs(10) => {
+ return Err(format!("Failed to read instant segment {subpath}: {error}"));
+ }
+ _ => tokio::time::sleep(Duration::from_millis(50)).await,
+ }
+ }
+}
+
+fn segment_subpath(event: &SegmentCompletedEvent) -> String {
+ match (event.is_init, event.media_type) {
+ (true, SegmentMediaType::Video) => "segments/video/init.mp4".to_string(),
+ (true, SegmentMediaType::Audio) => "segments/audio/init.mp4".to_string(),
+ (false, SegmentMediaType::Video) => {
+ format!("segments/video/segment_{:03}.m4s", event.index)
+ }
+ (false, SegmentMediaType::Audio) => {
+ format!("segments/audio/segment_{:03}.m4s", event.index)
+ }
+ }
+}
+
+async fn upload_segment_manifest(
+ video_id: &str,
+ manifest: &SegmentUploadManifest,
+) -> Result<(), String> {
+ let bytes = serde_json::to_vec(manifest)
+ .map_err(|error| format!("Failed to serialize instant upload manifest: {error}"))?;
+ presigned_put_bytes(video_id, "segments/manifest.json", bytes)
+ .await
+ .map_err(|error| format!("Failed to upload instant recording manifest: {error}"))
+}
+
+async fn upload_segment_manifest_with_retry(
+ video_id: &str,
+ manifest: &SegmentUploadManifest,
+ cancel: &AtomicBool,
+) -> Result<(), String> {
+ for attempt in 0..SEGMENT_UPLOAD_ATTEMPTS {
+ if cancel.load(Ordering::Acquire) {
+ return Err("Instant recording upload cancelled".to_string());
+ }
+ match upload_segment_manifest(video_id, manifest).await {
+ Ok(()) => return Ok(()),
+ Err(error) if attempt + 1 == SEGMENT_UPLOAD_ATTEMPTS => return Err(error),
+ Err(error) => {
+ tracing::warn!(
+ attempt = attempt + 1,
+ "Instant manifest upload failed: {error}"
+ );
+ tokio::time::sleep(Duration::from_millis(250u64 << attempt)).await;
+ }
+ }
+ }
+ Err("Instant recording manifest upload failed".to_string())
+}
+
+async fn signal_recording_complete_with_retry(
+ video_id: &str,
+ cancel: &AtomicBool,
+) -> Result<(), String> {
+ for attempt in 0..SEGMENT_UPLOAD_ATTEMPTS {
+ if cancel.load(Ordering::Acquire) {
+ return Err("Instant recording upload cancelled".to_string());
+ }
+ match signal_recording_complete(video_id).await {
+ Ok(()) => return Ok(()),
+ Err(error) if attempt + 1 == SEGMENT_UPLOAD_ATTEMPTS => return Err(error),
+ Err(error) => {
+ tracing::warn!(
+ attempt = attempt + 1,
+ "Instant completion signal failed: {error}"
+ );
+ tokio::time::sleep(Duration::from_millis(250u64 << attempt)).await;
+ }
+ }
+ }
+ Err("Failed to finish instant recording upload".to_string())
+}
+
+async fn signal_recording_complete(video_id: &str) -> Result<(), String> {
+ let response = auth::authed_request(
+ reqwest::Method::POST,
+ "/api/upload/recording-complete",
+ Some(json!({ "videoId": video_id })),
+ )
+ .await
+ .map_err(|error| format!("Failed to finish instant recording upload: {error}"))?;
+ let status = response.status();
+ if status.is_success() {
+ return Ok(());
+ }
+ let body = response.text().await.unwrap_or_default();
+ Err(format!(
+ "Failed to finish instant recording upload: {status}: {body}"
+ ))
+}
+
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct UploadedPart {
@@ -199,7 +733,29 @@ async fn create_or_get_video(
meta: Option<&VideoMeta>,
organization_id: Option<String>,
) -> Result<S3UploadMeta, AuthApiError> {
- let mut path = "/api/desktop/video/create?recordingMode=desktopMP4".to_string();
+ create_or_get_video_with_mode(
+ is_screenshot,
+ video_id,
+ name,
+ meta,
+ organization_id,
+ "desktopMP4",
+ )
+ .await
+}
+
+async fn create_or_get_video_with_mode(
+ is_screenshot: bool,
+ video_id: Option<String>,
+ name: Option<String>,
+ meta: Option<&VideoMeta>,
+ organization_id: Option<String>,
+ recording_mode: &str,
+) -> Result<S3UploadMeta, AuthApiError> {
+ let mut path = format!(
+ "/api/desktop/video/create?recordingMode={}",
+ urlencoding(recording_mode)
+ );
if let Some(id) = video_id {
path.push_str(&format!("&videoId={id}"));
path.push_str("&createWithId=true");
@@ -577,13 +1133,7 @@ async fn presigned_put_bytes(
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Response {
- presigned_put_data: SignedUpload,
- }
- #[derive(Deserialize)]
- struct SignedUpload {
- url: String,
- #[serde(default)]
- headers: HashMap<String, String>,
+ presigned_put_data: SignedUploadTarget,
}
let response = auth::authed_request(
@@ -608,17 +1158,40 @@ async fn presigned_put_bytes(
.await
.map_err(|error| AuthApiError::Other(format!("api/upload_signed/response: {error}")))?
.presigned_put_data;
- let mut request = reqwest::Client::new()
- .put(target.url)
- .header("Content-Length", bytes.len())
+ upload_signed_bytes(target, subpath, bytes).await
+}
+
+async fn upload_signed_bytes(
+ target: SignedUploadTarget,
+ subpath: &str,
+ bytes: Vec<u8>,
+) -> Result<(), AuthApiError> {
+ static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
+
+ let length = bytes.len() as u64;
+ let mut request = CLIENT
+ .get_or_init(reqwest::Client::new)
+ .put(&target.url)
+ .header("Content-Length", length)
+ .header("Content-Type", upload_content_type(subpath))
+ .timeout(Duration::from_secs(5 * 60))
.body(bytes);
+ if is_google_drive_resumable_url(&target.url) && length > 0 {
+ request = request.header(
+ "Content-Range",
+ format!("bytes 0-{}/{}", length.saturating_sub(1), length),
+ );
+ }
for (name, value) in target.headers {
request = request.header(name, value);
}
- let response = request
- .send()
- .await
- .map_err(|error| AuthApiError::Other(error.to_string()))?;
+ let response = request.send().await.map_err(|error| {
+ if error.is_timeout() {
+ AuthApiError::Timeout
+ } else {
+ AuthApiError::Other(error.to_string())
+ }
+ })?;
if !response.status().is_success() {
return Err(AuthApiError::Other(format!(
"upload failed: {}",
@@ -628,6 +1201,20 @@ async fn presigned_put_bytes(
Ok(())
}
+fn upload_content_type(subpath: &str) -> &'static str {
+ if subpath.ends_with(".json") {
+ "application/json"
+ } else if subpath.ends_with(".mp4") || subpath.ends_with(".m4s") {
+ "video/mp4"
+ } else if subpath.ends_with(".png") {
+ "image/png"
+ } else if subpath.ends_with(".jpg") || subpath.ends_with(".jpeg") {
+ "image/jpeg"
+ } else {
+ "application/octet-stream"
+ }
+}
+
// ---------------------------------------------------------------------------
// Screenshot share upload
// ---------------------------------------------------------------------------
@@ -817,6 +1404,137 @@ fn urlencoding(value: &str) -> String {
mod tests {
use super::*;
+ fn segment_event(
+ index: u32,
+ duration: f64,
+ is_init: bool,
+ media_type: SegmentMediaType,
+ ) -> SegmentCompletedEvent {
+ SegmentCompletedEvent {
+ path: PathBuf::from("segment.m4s"),
+ index,
+ duration,
+ file_size: 16,
+ is_init,
+ media_type,
+ }
+ }
+
+ #[test]
+ fn segment_manifest_requires_init_and_orders_video_and_audio() {
+ let mut manifest = SegmentUploadManifest::default();
+ manifest.record(&segment_event(3, 1.5, false, SegmentMediaType::Video));
+ manifest.record(&segment_event(1, 2.0, false, SegmentMediaType::Video));
+ manifest.record(&segment_event(2, 2.0, false, SegmentMediaType::Audio));
+ manifest.record(&segment_event(1, 1.8, false, SegmentMediaType::Audio));
+
+ assert!(!manifest.has_video_content());
+ manifest.record(&segment_event(0, 0.0, true, SegmentMediaType::Video));
+ manifest.record(&segment_event(0, 0.0, true, SegmentMediaType::Audio));
+
+ assert!(manifest.has_video_content());
+ assert_eq!(
+ manifest
+ .video_segments
+ .iter()
+ .map(|segment| segment.index)
+ .collect::<Vec<_>>(),
+ vec![1, 3]
+ );
+ assert_eq!(
+ manifest
+ .audio_segments
+ .iter()
+ .map(|segment| segment.index)
+ .collect::<Vec<_>>(),
+ vec![1, 2]
+ );
+ assert!(manifest.video_init_uploaded);
+ assert!(manifest.audio_init_uploaded);
+ assert!(!manifest.is_complete);
+ }
+
+ #[test]
+ fn initial_segment_batch_prefetches_initializers_and_matching_media_pairs() {
+ let paths = prefetched_segment_paths(1, 3);
+
+ assert_eq!(paths.len(), 9);
+ assert!(paths.contains(&"segments/video/init.mp4".to_string()));
+ assert!(paths.contains(&"segments/audio/init.mp4".to_string()));
+ assert!(paths.contains(&"segments/manifest.json".to_string()));
+ assert!(paths.contains(&"segments/video/segment_001.m4s".to_string()));
+ assert!(paths.contains(&"segments/audio/segment_003.m4s".to_string()));
+ }
+
+ #[test]
+ fn subsequent_segment_batches_do_not_repeat_initializers() {
+ assert_eq!(
+ prefetched_segment_paths(21, 2),
+ vec![
+ "segments/video/segment_021.m4s",
+ "segments/audio/segment_021.m4s",
+ "segments/video/segment_022.m4s",
+ "segments/audio/segment_022.m4s",
+ ]
+ );
+ }
+
+ #[test]
+ fn segment_manifest_updates_replayed_segments_without_duplicates() {
+ let mut manifest = SegmentUploadManifest::default();
+ manifest.record(&segment_event(4, 1.0, false, SegmentMediaType::Video));
+ manifest.record(&segment_event(4, 2.5, false, SegmentMediaType::Video));
+
+ assert_eq!(
+ manifest.video_segments,
+ vec![SegmentManifestEntry {
+ index: 4,
+ duration: 2.5,
+ }]
+ );
+ }
+
+ #[test]
+ fn segment_upload_paths_match_tauri_storage_layout() {
+ assert_eq!(
+ segment_subpath(&segment_event(0, 0.0, true, SegmentMediaType::Video)),
+ "segments/video/init.mp4"
+ );
+ assert_eq!(
+ segment_subpath(&segment_event(0, 0.0, true, SegmentMediaType::Audio)),
+ "segments/audio/init.mp4"
+ );
+ assert_eq!(
+ segment_subpath(&segment_event(7, 2.0, false, SegmentMediaType::Video)),
+ "segments/video/segment_007.m4s"
+ );
+ assert_eq!(
+ segment_subpath(&segment_event(14, 2.0, false, SegmentMediaType::Audio)),
+ "segments/audio/segment_014.m4s"
+ );
+ }
+
+ #[test]
+ fn signed_upload_content_types_match_media() {
+ assert_eq!(
+ upload_content_type("segments/manifest.json"),
+ "application/json"
+ );
+ assert_eq!(upload_content_type("segments/video/init.mp4"), "video/mp4");
+ assert_eq!(
+ upload_content_type("segments/audio/segment_001.m4s"),
+ "video/mp4"
+ );
+ assert_eq!(
+ upload_content_type("screenshot/screen-capture.jpg"),
+ "image/jpeg"
+ );
+ assert_eq!(
+ upload_content_type("screenshot/screen-capture.png"),
+ "image/png"
+ );
+ }
+
#[test]
fn chunk_size_clamps() {
assert_eq!(chunk_size_for(1), MIN_CHUNK_SIZE);
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 48cdd475c..54c0d36dc 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1154,6 +1154,14 @@ fn notify_recording_start_failed(app: &AppHandle, error: &str) {
.emit(app);
}
+fn recording_start_mode_error(mode: RecordingMode, authenticated: bool) -> Option<&'static str> {
+ match mode {
+ RecordingMode::Instant if !authenticated => Some("Please sign in to use instant recording"),
+ RecordingMode::Screenshot => Some("Use take_screenshot for screenshots"),
+ RecordingMode::Studio | RecordingMode::Instant => None,
+ }
+}
+
#[derive(Serialize, Type)]
pub enum RecordingAction {
Started,
@@ -1515,6 +1523,17 @@ pub async fn start_recording(
}
}
+ let instant_auth = if matches!(inputs.mode, RecordingMode::Instant) {
+ AuthStore::get(&app).ok().flatten()
+ } else {
+ None
+ };
+ if let Some(error) = recording_start_mode_error(inputs.mode, instant_auth.is_some()) {
+ state_mtx.write().await.clear_pending_recording();
+ notify_recording_start_failed(&app, error);
+ return Err(error.to_string());
+ }
+
macro_rules! pending_try {
($expr:expr, $map_err:expr) => {
match $expr {
@@ -1625,7 +1644,7 @@ pub async fn start_recording(
let (video_upload_info, instant_mode_max_resolution) = match inputs.mode {
RecordingMode::Instant => {
- let Some(auth) = AuthStore::get(&app).ok().flatten() else {
+ let Some(auth) = instant_auth else {
let error = "Please sign in to use instant recording".to_string();
state_mtx.write().await.clear_pending_recording();
notify_recording_start_failed(&app, &error);
@@ -4238,6 +4257,30 @@ mod tests {
use super::*;
use tempfile::tempdir;
+ #[test]
+ fn recording_start_preflight_requires_authentication_for_instant_recordings() {
+ assert_eq!(
+ recording_start_mode_error(RecordingMode::Instant, false),
+ Some("Please sign in to use instant recording")
+ );
+ assert_eq!(
+ recording_start_mode_error(RecordingMode::Instant, true),
+ None
+ );
+ }
+
+ #[test]
+ fn recording_start_preflight_preserves_studio_and_rejects_screenshot_modes() {
+ assert_eq!(
+ recording_start_mode_error(RecordingMode::Studio, false),
+ None
+ );
+ assert_eq!(
+ recording_start_mode_error(RecordingMode::Screenshot, true),
+ Some("Use take_screenshot for screenshots")
+ );
+ }
+
fn click_event_with_state(time_ms: f64, down: bool) -> CursorClickEvent {
CursorClickEvent {
active_modifiers: vec![],