diff --git a/.github/workflows/instant-reliability.yml b/.github/workflows/instant-reliability.yml index f3213417d7e..a0655c46e40 100644 --- a/.github/workflows/instant-reliability.yml +++ b/.github/workflows/instant-reliability.yml @@ -6,8 +6,7 @@ name: Instant reliability (real app) # followed by Recover. Each case checks what reached the mock server and what # was left on disk, so a regression that loses a recording, deletes one with # media, or leaves an empty video behind fails here. The Linux job runs the -# cases whose expectations hold there on Xvfb: Linux keeps a cancelled or -# crashed start's files and video rather than deleting them. +# same cases on Xvfb, recording another app's window. on: pull_request: @@ -262,7 +261,8 @@ jobs: CAP_GPUI_AUTO_OVERLAY=window CAP_GPUI_AUTO_WINDOW=xmessage \ dbus-run-session -- "$(cat "$RUNNER_TEMP/test-binary")" --ignored --test-threads=1 --nocapture \ real_app_instant_recording_uploads_and_verifies real_app_recovered_recording_uploads \ - real_app_start_cue_waits_for_a_slow_server_video + real_app_start_cue_waits_for_a_slow_server_video real_app_cancelled_start_deletes_its_video \ + real_app_crashes_never_delete_a_recording_with_media - name: Upload sandboxes if: failure() diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rs index 1cf1b8a6ecd..c9658a5c016 100644 --- a/apps/desktop-gpui/src/recording.rs +++ b/apps/desktop-gpui/src/recording.rs @@ -118,6 +118,9 @@ pub(crate) struct InstantAttempt(Arc); #[cfg(target_os = "linux")] struct InstantAttemptInner { lifecycle: Mutex>, + /// The server video and folder of a start still being built. A cancelled + /// start drops the build before it can clean up, so the attempt does it. + video: Mutex>, cancelled: tokio::sync::watch::Sender, startup: tokio::sync::watch::Sender, } @@ -136,6 +139,7 @@ impl InstantAttempt { pub fn new() -> Self { Self(Arc::new(InstantAttemptInner { lifecycle: Mutex::new(None), + video: Mutex::new(None), cancelled: tokio::sync::watch::channel(false).0, startup: tokio::sync::watch::channel(StartupState::Unstarted).0, })) @@ -313,9 +317,14 @@ where if result.is_err() { attempt.cancel(); let lifecycle = attempt.0.lifecycle.lock().unwrap().clone(); - if let Some(lifecycle) = lifecycle { - lifecycle.wait_for_quiescence().await; - } + let joined = match lifecycle { + Some(lifecycle) => { + lifecycle.wait_for_quiescence().await + == instant_recording::InstantQuiescence::Joined + } + None => true, + }; + discard_unstarted_video(&attempt, joined).await; } if let Err(Ok(active)) = sender.send(result) { let _ = cleanup(active).await; @@ -1123,21 +1132,32 @@ impl ActiveRecording { /// delete and restart flows. Deleting a directory this app just created is /// app behavior, same as the Tauri delete button. pub async fn cancel_and_delete(self) -> anyhow::Result<()> { - self.cancel_and_delete_with_query(None).await + self.cancel_and_delete_with_query(None, false).await } /// `cancel_and_delete` for a start that was superseded before it began, - /// telling the server why its Instant video is deleted. - #[cfg(not(target_os = "linux"))] + /// telling the server why its Instant video is deleted. On Linux a start + /// that wrote media by the time capture stopped keeps it, as after a crash. pub(crate) async fn discard_cancelled_start(self) -> anyhow::Result<()> { + #[cfg(target_os = "linux")] + if !matches!(self.handle, Handle::Instant(_)) { + return self.cancel_preserving().await; + } let query = crate::upload::instant_cleanup::delete_query( crate::upload::instant_cleanup::CleanupReason::StartCancelled, None, ); - self.cancel_and_delete_with_query(query).await + self.cancel_and_delete_with_query(query, cfg!(target_os = "linux")) + .await } - async fn cancel_and_delete_with_query(self, query: Option) -> anyhow::Result<()> { + /// `keep_media`: once capture has stopped, a folder holding media is kept + /// as a stopped recording with its server video instead of being deleted. + async fn cancel_and_delete_with_query( + self, + query: Option, + keep_media: bool, + ) -> anyhow::Result<()> { if let Some(gate) = &self.start_gate { gate.arm(); } @@ -1167,9 +1187,15 @@ impl ActiveRecording { Handle::Instant(handle) => { #[cfg(target_os = "linux")] { - let (_, result) = + let (joined, result) = joined_instant_result(handle.lifecycle(), handle.cancel()).await; - result + if joined { + result + } else { + Err(anyhow!( + "Instant capture cleanup is unconfirmed; local files preserved" + )) + } } #[cfg(not(target_os = "linux"))] { @@ -1185,6 +1211,26 @@ impl ActiveRecording { } return Err(error); } + #[cfg(target_os = "linux")] + if keep_media && crate::upload::instant_cleanup::project_holds_media(&self.project_dir) { + let mut upload = match self.instant_upload.as_ref() { + Some(upload) => Some(upload.lock().await), + None => None, + }; + let upload = upload.as_deref_mut().and_then(Option::as_mut); + if let Some(upload) = upload { + upload.abort_segments().await; + return persist_preserved_instant_stop( + &self.project_dir, + Some(upload.metadata_lock()), + true, + Ok(()), + ); + } + return persist_preserved_instant_stop(&self.project_dir, None, true, Ok(())); + } + #[cfg(not(target_os = "linux"))] + let _ = keep_media; let mut upload = match self.instant_upload.as_ref() { Some(upload) => upload.lock().await.take(), None => None, @@ -2137,6 +2183,35 @@ pub async fn start(config: StartConfig) -> anyhow::Result { .await } +/// The server video of a start whose build was dropped: deleted with its +/// folder when capture stopped without writing media, as a cancelled start is +/// on macOS and Windows. Otherwise the cleanup journal keeps it for the sweep, +/// which never deletes a recording that holds media. +#[cfg(target_os = "linux")] +async fn discard_unstarted_video(attempt: &InstantAttempt, joined: bool) { + use crate::upload::instant_cleanup::{self, CleanupReason}; + let Some((video_id, project_dir)) = attempt.0.video.lock().unwrap().take() else { + return; + }; + if !joined || instant_cleanup::project_holds_media(&project_dir) { + instant_cleanup::abandon(&video_id, CleanupReason::StartCancelled, None); + return; + } + let query = instant_cleanup::delete_query(CleanupReason::StartCancelled, None); + match crate::upload::delete_instant_video_with_query(&video_id, query.as_deref()).await { + Ok(()) => { + instant_cleanup::resolved(&video_id); + if let Err(error) = tokio::fs::remove_dir_all(&project_dir).await { + tracing::warn!(%error, path = %project_dir.display(), "Could not remove a cancelled start's folder"); + } + } + Err(error) => { + tracing::warn!(%error, video_id, "Could not delete a cancelled start's video"); + instant_cleanup::abandon(&video_id, CleanupReason::StartCancelled, None); + } + } +} + #[cfg(target_os = "linux")] pub(crate) fn start_tracked( config: StartConfig, @@ -2145,7 +2220,7 @@ pub(crate) fn start_tracked( owned_instant_start( attempt.clone(), start_internal(config, Some(attempt)), - ActiveRecording::cancel_preserving, + ActiveRecording::discard_cancelled_start, ) } @@ -2188,6 +2263,10 @@ async fn start_internal( .await .map_err(anyhow::Error::msg)?; crate::upload::instant_cleanup::begin(&video.id, &project_dir); + #[cfg(target_os = "linux")] + if let Some(attempt) = &attempt { + *attempt.0.video.lock().unwrap() = Some((video.id.clone(), project_dir.clone())); + } Some(video) } else { None @@ -2226,10 +2305,18 @@ async fn start_internal( Err(error) => { instant_cleanup::abandon(&video.id, CleanupReason::StartFailed, Some(cause)); tracing::error!(video_id = %video.id, "Failed to clean up instant recording: {error}"); + #[cfg(target_os = "linux")] + if let Some(attempt) = &attempt { + attempt.0.video.lock().unwrap().take(); + } return Err(anyhow!("Failed to clean up instant recording: {error}")); } } } + #[cfg(target_os = "linux")] + if let Some(attempt) = &attempt { + attempt.0.video.lock().unwrap().take(); + } result } diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs index c30faff40e9..20ef9f7ecc3 100644 --- a/apps/desktop-gpui/src/session.rs +++ b/apps/desktop-gpui/src/session.rs @@ -990,9 +990,6 @@ impl RecordingSession { if let Some(previous) = previous { let _ = previous.await; } - #[cfg(target_os = "linux")] - let discarded = active.cancel_preserving().await; - #[cfg(not(target_os = "linux"))] let discarded = active.discard_cancelled_start().await; match discarded { Ok(()) => { diff --git a/apps/desktop-gpui/src/upload/instant_cleanup.rs b/apps/desktop-gpui/src/upload/instant_cleanup.rs index 1e1fcd71ea9..fc58e1f0c8d 100644 --- a/apps/desktop-gpui/src/upload/instant_cleanup.rs +++ b/apps/desktop-gpui/src/upload/instant_cleanup.rs @@ -353,11 +353,8 @@ fn abandon_at( /// Records a pre-created Instant video before capture starts, so a crash, /// panic or aborted discard during startup still gets its server copy -/// deleted on the next sweep. Linux keeps its own startup cleanup contract. +/// deleted on the next sweep. pub(crate) fn begin(video_id: &str, project_dir: &Path) { - if cfg!(target_os = "linux") { - return; - } let Some(owner_id) = current_owner_id() else { return; }; @@ -372,16 +369,10 @@ pub(crate) fn begin(video_id: &str, project_dir: &Path) { } pub(crate) fn started(video_id: &str) { - if cfg!(target_os = "linux") { - return; - } remove_at(&journal_path(), video_id); } pub(crate) fn resolved(video_id: &str) { - if cfg!(target_os = "linux") { - return; - } remove_at(&journal_path(), video_id); } @@ -390,16 +381,10 @@ pub(crate) fn resolved(video_id: &str) { /// removed and delete the uploaded video. False when the entry is still there, /// so the caller keeps the local copy. pub(crate) fn forget_verified(video_id: &str) -> bool { - if cfg!(target_os = "linux") { - return true; - } forget_at(&journal_path(), video_id) } pub(crate) fn abandon(video_id: &str, reason: CleanupReason, cause: Option) { - if cfg!(target_os = "linux") { - return; - } let identity = current_owner_id().map(|owner| (auth::server_url(), owner)); abandon_at(&journal_path(), video_id, reason, cause, identity, now()); } @@ -433,6 +418,12 @@ fn meta_claims(meta: &RecordingMeta, video_id: &str) -> bool { || upload_meta_video_id(meta) == Some(video_id) } +/// Whether a recording folder holds media a crash or a cancelled start must +/// not delete. +pub(crate) fn project_holds_media(project: &Path) -> bool { + has_recorded_media(&project.join("content"), MEDIA_SCAN_DEPTH) +} + /// True when the folder holds recorded media, or when part of it cannot be /// read: media that cannot be checked counts as present. Only a missing folder /// counts as empty. A segment still named `.m4s.tmp` counts too, since a crash @@ -732,6 +723,18 @@ async fn sweep(path: &Path, session: &str, now: i64, backend: &impl SweepBackend summary } +/// Whether the sweep keeps an entry's server video while its folder holds +/// media. A crashed start's folder may have recorded before the crash; on +/// Linux a cancelled start that wrote media keeps it too +/// (`ActiveRecording::discard_cancelled_start`), so its video must stay. +fn guards_media(reason: CleanupReason) -> bool { + match reason { + CleanupReason::Interrupted => true, + CleanupReason::StartCancelled => cfg!(target_os = "linux"), + CleanupReason::StartFailed => false, + } +} + struct LiveSweep; impl SweepBackend for LiveSweep { @@ -741,13 +744,13 @@ impl SweepBackend for LiveSweep { async fn protected(&self, entry: &Entry) -> bool { let video_id = entry.video_id.clone(); - let interrupted = entry.effective_reason() == CleanupReason::Interrupted; + let guards_media = guards_media(entry.effective_reason()); let start_project = entry.project_dir.clone(); tokio::task::spawn_blocking(move || { locally_protected( &crate::library::known_recordings_dirs(), &video_id, - interrupted, + guards_media, start_project.as_deref(), ) }) @@ -809,9 +812,6 @@ async fn run() { } pub(crate) fn init(cx: &mut gpui::App) { - if cfg!(target_os = "linux") { - return; - } session_id(); launched_at(); gpui_tokio::Tokio::spawn(cx, run()).detach(); @@ -1355,6 +1355,29 @@ mod tests { assert!(!locally_protected(&[recordings], "video", false, None)); } + #[test] + fn a_cancelled_start_guards_media_where_it_keeps_it() { + assert!(guards_media(CleanupReason::Interrupted)); + assert!(!guards_media(CleanupReason::StartFailed)); + assert_eq!( + guards_media(CleanupReason::StartCancelled), + cfg!(target_os = "linux") + ); + let fixture = Fixture::new(); + let recordings = fixture.recordings(); + let project = write_project(&recordings, "cancelled.cap", "video", in_progress()); + std::fs::write(project.join("content/display/segment_001.m4s"), b"media").unwrap(); + assert_eq!( + locally_protected( + &[recordings], + "video", + guards_media(CleanupReason::StartCancelled), + Some(&project), + ), + cfg!(target_os = "linux") + ); + } + #[cfg(unix)] #[test] fn media_that_cannot_be_read_protects_an_interrupted_start() {