Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(engine): de-flake sleep_monitor wake/lock flag tests (global-state pollution) (#4795)

Ezra Elletted86960c714c9
diff --git a/crates/screenpipe-engine/src/sleep_monitor.rs b/crates/screenpipe-engine/src/sleep_monitor.rs
index 9d31e41bc..cffd1fe55 100644
--- a/crates/screenpipe-engine/src/sleep_monitor.rs
+++ b/crates/screenpipe-engine/src/sleep_monitor.rs
@@ -698,8 +698,26 @@ pub fn start_sleep_monitor() {
mod tests {
use super::*;
+ /// `RECENTLY_WOKE` / `RECENTLY_WOKE_SEQ` are process-global, and
+ /// `mark_recently_woke` arms them with a 30s-delayed clear thread. Tests
+ /// that touch them must hold this lock so they can't interleave under the
+ /// parallel test runner.
+ static RECENTLY_WOKE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+ /// Neutralize any pending delayed clear (by bumping the seq) and reset the
+ /// flag, giving the caller a clean baseline regardless of what earlier
+ /// tests left behind.
+ fn reset_recently_woke() {
+ RECENTLY_WOKE_SEQ.fetch_add(1, Ordering::SeqCst);
+ RECENTLY_WOKE.store(false, Ordering::SeqCst);
+ }
+
#[test]
fn test_recently_woke_flag() {
+ let _guard = RECENTLY_WOKE_TEST_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ reset_recently_woke();
assert!(!recently_woke_from_sleep());
RECENTLY_WOKE.store(true, Ordering::SeqCst);
assert!(recently_woke_from_sleep());
@@ -709,6 +727,12 @@ mod tests {
#[test]
fn test_screen_is_locked_flag() {
+ // SCREEN_IS_LOCKED is process-global and the capture path mirrors the
+ // REAL machine lock state into it (event_driven_capture stores true
+ // when it resolves loginwindow as the frontmost app). Running the
+ // suite while the screen is actually locked leaves it armed — reset
+ // for a hermetic baseline.
+ SCREEN_IS_LOCKED.store(false, Ordering::SeqCst);
assert!(!screen_is_locked());
SCREEN_IS_LOCKED.store(true, Ordering::SeqCst);
assert!(screen_is_locked());
@@ -812,10 +836,13 @@ mod tests {
#[cfg(target_os = "macos")]
#[tokio::test]
async fn test_on_did_wake_sets_audio_invalidation() {
+ let _guard = RECENTLY_WOKE_TEST_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
// Clear stale flags
let _ = screenpipe_audio::stream_invalidation::take();
let _ = screenpipe_screen::stream_invalidation::take();
- RECENTLY_WOKE.store(false, Ordering::SeqCst);
+ reset_recently_woke();
let handle = tokio::runtime::Handle::current();
on_did_wake(&handle);
@@ -837,6 +864,10 @@ mod tests {
!screenpipe_audio::stream_invalidation::take(),
"Audio flag should be cleared after take()"
);
+
+ // Don't leak the armed flag (and its pending 30s clear thread) to
+ // whatever test runs next.
+ reset_recently_woke();
}
/// A screen-unlock transition must arm the permission-monitor wake grace,