Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(cli): improve macOS shareable content acquisition for recording

Richie McIlroya313a697e4f7
diff --git a/apps/cli/src/record.rs b/apps/cli/src/record.rs
index 417fb27a5..04617847f 100644
--- a/apps/cli/src/record.rs
+++ b/apps/cli/src/record.rs
@@ -22,6 +22,7 @@ use std::{
time::{Duration, Instant},
};
use tokio::io::AsyncBufReadExt;
+use tracing::debug;
use uuid::Uuid;
use crate::{
@@ -219,7 +220,9 @@ async fn foreground_inner(params: RecordParams, format: OutputFormat) -> Result<
path: &path_display,
},
) {
- let _ = actor.stop().await;
+ if let Ok(completed) = actor.stop().await {
+ let _ = finalize_completed(completed).await;
+ }
return Err(error);
}
@@ -494,16 +497,11 @@ impl RecordStopArgs {
recording_meta_exists: session.recording_meta_exists.unwrap_or(true),
},
)?;
- session::cleanup(&id);
+ cleanup_session(&id, &session.path);
return Ok(());
}
session::request_stop(&id)?;
- // The stop file is the authoritative cross-platform stop signal; only also SIGTERM a live pid
- // so a recycled pid belonging to an unrelated process is never signalled.
- if session::process_alive(session.pid) {
- session::terminate(session.pid);
- }
let deadline = Instant::now() + Duration::from_secs_f64(self.timeout.max(0.0));
loop {
@@ -517,11 +515,11 @@ impl RecordStopArgs {
recording_meta_exists: current.recording_meta_exists.unwrap_or(true),
},
)?;
- session::cleanup(&id);
+ cleanup_session(&id, &current.path);
return Ok(());
}
SessionStatus::Error => {
- session::cleanup(&id);
+ cleanup_session(&id, &current.path);
return Err(current
.error
.unwrap_or_else(|| "recording failed".to_string()));
@@ -542,7 +540,7 @@ impl RecordStopArgs {
return fail_dead_session(current, error);
}
- session::cleanup(&id);
+ cleanup_session(&id, &current.path);
return emit_record_event(
format,
&RecordEvent::Stopped {
@@ -553,6 +551,9 @@ impl RecordStopArgs {
}
if Instant::now() >= deadline {
+ if session::process_alive(current.pid) {
+ session::terminate(current.pid);
+ }
return Err(format!(
"timed out after {}s waiting for recording '{id}' to stop",
self.timeout
@@ -564,6 +565,13 @@ impl RecordStopArgs {
}
}
+fn cleanup_session(id: &str, project_path: &Path) {
+ if let Err(error) = session::archive_log(id, project_path) {
+ debug!("{error}");
+ }
+ session::cleanup(id);
+}
+
fn fail_dead_session(session: Session, error: String) -> Result<(), String> {
let _ = session::write_session(&Session {
status: SessionStatus::Error,
@@ -725,6 +733,8 @@ async fn start_recording(
target: ScreenCaptureTarget,
path: PathBuf,
) -> Result<ActorHandle, String> {
+ #[cfg(target_os = "macos")]
+ let target_for_shareable_content = target.clone();
let mut studio_builder = studio_recording::Actor::builder(path.clone(), target.clone())
.with_system_audio(params.system_audio);
let mut instant_builder =
@@ -806,11 +816,9 @@ async fn start_recording(
builder
.build(
#[cfg(target_os = "macos")]
- Some(cap_recording::SendableShareableContent::from(
- cidre::sc::ShareableContent::current()
- .await
- .map_err(|e| format!("Failed to read shareable content: {e}"))?,
- )),
+ Some(
+ acquire_shareable_content_for_target(&target_for_shareable_content).await?,
+ ),
)
.await
.map(ActorHandle::Studio)
@@ -828,11 +836,9 @@ async fn start_recording(
builder
.build(
#[cfg(target_os = "macos")]
- Some(cap_recording::SendableShareableContent::from(
- cidre::sc::ShareableContent::current()
- .await
- .map_err(|e| format!("Failed to read shareable content: {e}"))?,
- )),
+ Some(
+ acquire_shareable_content_for_target(&target_for_shareable_content).await?,
+ ),
)
.await
.map(ActorHandle::Instant)
@@ -841,15 +847,87 @@ async fn start_recording(
}
}
+#[cfg(target_os = "macos")]
+async fn acquire_shareable_content_for_target(
+ target: &ScreenCaptureTarget,
+) -> Result<cap_recording::SendableShareableContent, String> {
+ let mut available_display_ids = Vec::new();
+
+ for attempt in 0..3 {
+ let shareable_content = read_shareable_content().await?;
+ available_display_ids = shareable_content_display_ids(&shareable_content);
+
+ if !shareable_content_missing_target_display(target, &shareable_content) {
+ return Ok(shareable_content);
+ }
+
+ if attempt < 2 {
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ }
+ }
+
+ let requested_display = target
+ .display()
+ .map(|display| display.id().to_string())
+ .unwrap_or_else(|| "none".to_string());
+ Err(format!(
+ "ScreenCaptureKit shareable content missing target display {requested_display}. Available display ids: {available_display_ids:?}"
+ ))
+}
+
+#[cfg(target_os = "macos")]
+async fn read_shareable_content() -> Result<cap_recording::SendableShareableContent, String> {
+ let content = cidre::sc::ShareableContent::current()
+ .await
+ .map_err(|e| format!("Failed to read shareable content: {e}"))?;
+ if !content.displays().is_empty() {
+ return Ok(cap_recording::SendableShareableContent::from(content));
+ }
+
+ let process_content = cidre::sc::ShareableContent::current_process()
+ .await
+ .map_err(|e| format!("Failed to read current-process shareable content: {e}"))?;
+ if !process_content.displays().is_empty() {
+ return Ok(cap_recording::SendableShareableContent::from(
+ process_content,
+ ));
+ }
+
+ Ok(cap_recording::SendableShareableContent::from(content))
+}
+
+#[cfg(target_os = "macos")]
+fn shareable_content_missing_target_display(
+ target: &ScreenCaptureTarget,
+ shareable_content: &cap_recording::SendableShareableContent,
+) -> bool {
+ match target.display() {
+ Some(display) => display
+ .raw_handle()
+ .as_sc(shareable_content.retained())
+ .is_none(),
+ None => false,
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn shareable_content_display_ids(
+ shareable_content: &cap_recording::SendableShareableContent,
+) -> Vec<String> {
+ shareable_content
+ .retained()
+ .displays()
+ .iter()
+ .map(|display| display.display_id().0.to_string())
+ .collect()
+}
+
/// Wait for the stop trigger, then finalize the recording. A panic between start and stop would
/// otherwise drop the actor without writing recording-meta.json (`ActorHandle` has no `Drop`),
/// leaving an unrecoverable .cap; catch it and best-effort finalize so the recording is recoverable.
///
-/// Studio recordings are fragmented for crash recovery, so a graceful stop leaves the display track
-/// as a directory of fragments with status `NeedsRemux`. We then run the shared
-/// `RecoveryManager::remux_if_needed` — the same remux the desktop runs after stop — so the `.cap`
-/// is immediately exportable instead of `cap export`/`cap upload` failing to open a fragment
-/// directory as a video.
+/// Studio recordings are fragmented while recording, so a graceful stop finalizes those fragments
+/// before the `.cap` is returned.
async fn finalize(
actor: ActorHandle,
duration: Option<f64>,
@@ -884,7 +962,7 @@ async fn finalize_completed(completed: CompletedRecording) -> Result<CompletedRe
})
.await
.map_err(|e| format!("recording finalize task failed: {e}"))?
- .map_err(|e| format!("Failed to remux recording: {e}"))?;
+ .map_err(|e| format!("Failed to finalize recording: {e}"))?;
}
CompletedRecording::Instant(recording) => {
finalize_instant_output(recording.project_path.clone()).await?;