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(audio): force-restart audio devices after sleep/wake and display changes

Louis Beaumont48d31ffaaeda
diff --git a/crates/screenpipe-audio/src/audio_manager/device_monitor.rs b/crates/screenpipe-audio/src/audio_manager/device_monitor.rs
index 15113787c..064f15e97 100644
--- a/crates/screenpipe-audio/src/audio_manager/device_monitor.rs
+++ b/crates/screenpipe-audio/src/audio_manager/device_monitor.rs
@@ -200,6 +200,27 @@ pub async fn start_device_monitor(
loop {
if audio_manager.status().await == AudioManagerStatus::Running {
+ // Check if sleep/wake or display reconfiguration requested
+ // audio stream invalidation. Force-cycle all running devices
+ // to recover from silent CoreAudio stream failures.
+ if crate::stream_invalidation::take() {
+ info!("[DEVICE_RECOVERY] audio stream invalidation requested (wake/display change), restarting all devices");
+ let enabled = audio_manager.enabled_devices().await;
+ for device_name in &enabled {
+ if let Ok(device) = parse_audio_device(device_name) {
+ // Gracefully stop the recording: signals is_running=false,
+ // tears down the cpal stream, then aborts the task handle.
+ // Does NOT remove from enabled_devices so restart picks it up.
+ let _ = audio_manager.stop_device_recording(&device).await;
+ }
+ disconnected_devices.insert(device_name.clone());
+ }
+ // Let CoreAudio settle after wake before the reconnect
+ // logic kicks in on the next loop iteration
+ sleep(Duration::from_secs(2)).await;
+ continue;
+ }
+
let currently_available_devices = device_manager.devices().await;
if currently_available_devices.is_empty() {
warn!("[DEVICE_RECOVERY] device list returned empty (transient SCK failure?), skipping availability checks this cycle");
diff --git a/crates/screenpipe-audio/src/audio_manager/manager.rs b/crates/screenpipe-audio/src/audio_manager/manager.rs
index 71d402044..ee1954ced 100644
--- a/crates/screenpipe-audio/src/audio_manager/manager.rs
+++ b/crates/screenpipe-audio/src/audio_manager/manager.rs
@@ -339,7 +339,8 @@ impl AudioManager {
/// Stop a device's recording without removing it from enabled_devices.
/// Idempotent — safe to call on already-stopped devices.
- async fn stop_device_recording(&self, device: &AudioDevice) -> Result<()> {
+ /// Used by device monitor for force-cycling devices after sleep/wake.
+ pub async fn stop_device_recording(&self, device: &AudioDevice) -> Result<()> {
// Signal the recording loop to stop BEFORE aborting the handle,
// so it exits cleanly without triggering "stream dead" warnings.
if let Some(is_running) = self.device_manager.is_running_mut(device) {
diff --git a/crates/screenpipe-audio/src/lib.rs b/crates/screenpipe-audio/src/lib.rs
index 902050298..e25668592 100644
--- a/crates/screenpipe-audio/src/lib.rs
+++ b/crates/screenpipe-audio/src/lib.rs
@@ -22,3 +22,52 @@ mod device;
pub mod idle_detector;
pub mod meeting_detector;
mod segmentation;
+
+/// Flag to request invalidation of audio streams after sleep/wake or display
+/// reconfiguration. Set by `sleep_monitor` (CFNotification callback thread),
+/// consumed by the device monitor loop so that audio devices are force-cycled
+/// (stop + restart) to recover from silent CoreAudio stream failures.
+pub mod stream_invalidation {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ static NEEDS_INVALIDATION: AtomicBool = AtomicBool::new(false);
+
+ /// Request that all audio streams be invalidated and restarted.
+ /// Safe to call from any thread (including CFNotification callbacks).
+ pub fn request() {
+ NEEDS_INVALIDATION.store(true, Ordering::SeqCst);
+ }
+
+ /// Check and clear the invalidation flag. If `true`, the caller should
+ /// force-restart all running audio devices.
+ pub fn take() -> bool {
+ NEEDS_INVALIDATION.swap(false, Ordering::SeqCst)
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ #[test]
+ fn take_returns_false_when_no_request() {
+ // Clear any leftover state from other tests
+ let _ = take();
+ assert!(!take());
+ }
+
+ #[test]
+ fn request_then_take_returns_true_once() {
+ request();
+ assert!(take(), "first take after request should return true");
+ assert!(!take(), "second take should return false (flag cleared)");
+ }
+
+ #[test]
+ fn multiple_requests_coalesce() {
+ request();
+ request();
+ request();
+ assert!(take(), "take should return true");
+ assert!(!take(), "flag should be cleared after single take");
+ }
+ }
+}
diff --git a/crates/screenpipe-engine/src/sleep_monitor.rs b/crates/screenpipe-engine/src/sleep_monitor.rs
index 55ab1552f..3e5824129 100644
--- a/crates/screenpipe-engine/src/sleep_monitor.rs
+++ b/crates/screenpipe-engine/src/sleep_monitor.rs
@@ -343,8 +343,10 @@ pub fn start_sleep_monitor() {
return;
}
// Display topology changed — invalidate cached SCStream handles
+ // and audio streams (CoreAudio can go silent after display changes)
#[cfg(target_os = "macos")]
screenpipe_screen::stream_invalidation::request();
+ screenpipe_audio::stream_invalidation::request();
}
unsafe {
@@ -449,6 +451,11 @@ fn on_did_wake(handle: &tokio::runtime::Handle) {
#[cfg(target_os = "macos")]
screenpipe_screen::stream_invalidation::request();
+ // Invalidate audio streams so the device monitor force-restarts all
+ // audio devices. CoreAudio streams can go silent after sleep/wake
+ // without triggering error callbacks.
+ screenpipe_audio::stream_invalidation::request();
+
// Spawn a task on the captured tokio runtime handle to check recording
// health after a short delay. We can't use bare tokio::spawn() here
// because this callback runs on an NSRunLoop thread, not a tokio thread.
@@ -631,4 +638,79 @@ mod tests {
assert!(!is_wake_gap(Duration::from_secs(20), poll));
assert!(is_wake_gap(Duration::from_secs(21), poll));
}
+
+ /// Verifies that on_did_wake sets the audio stream invalidation flag.
+ /// This is the core of the fix — when macOS fires the wake notification,
+ /// on_did_wake must set both vision AND audio invalidation flags.
+ #[cfg(target_os = "macos")]
+ #[tokio::test]
+ async fn test_on_did_wake_sets_audio_invalidation() {
+ // Clear stale flags
+ let _ = screenpipe_audio::stream_invalidation::take();
+ let _ = screenpipe_screen::stream_invalidation::take();
+ RECENTLY_WOKE.store(false, Ordering::SeqCst);
+
+ let handle = tokio::runtime::Handle::current();
+ on_did_wake(&handle);
+
+ assert!(
+ recently_woke_from_sleep(),
+ "RECENTLY_WOKE should be set after on_did_wake"
+ );
+ assert!(
+ screenpipe_audio::stream_invalidation::take(),
+ "Audio stream invalidation flag must be set after wake"
+ );
+ assert!(
+ screenpipe_screen::stream_invalidation::take(),
+ "Vision stream invalidation flag must be set after wake"
+ );
+ // Flags should be cleared after take()
+ assert!(
+ !screenpipe_audio::stream_invalidation::take(),
+ "Audio flag should be cleared after take()"
+ );
+ }
+
+ /// Manual test: lock your screen (Cmd+Ctrl+Q), wait 2-3s, unlock.
+ /// Run with: cargo test -p screenpipe-engine --lib -- test_screen_lock_unlock --ignored --nocapture
+ #[cfg(target_os = "macos")]
+ #[tokio::test]
+ #[ignore = "requires manual screen lock/unlock"]
+ async fn test_screen_lock_unlock() {
+ SCREEN_IS_LOCKED.store(false, Ordering::SeqCst);
+
+ start_sleep_monitor();
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
+
+ eprintln!("============================================");
+ eprintln!(" LOCK YOUR SCREEN NOW (Cmd+Ctrl+Q),");
+ eprintln!(" wait 2-3s, then UNLOCK it.");
+ eprintln!(" You have 60 seconds.");
+ eprintln!("============================================");
+
+ let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(60);
+ let mut saw_locked = false;
+ let mut saw_unlocked_after_lock = false;
+
+ while tokio::time::Instant::now() < deadline {
+ if !saw_locked && screen_is_locked() {
+ saw_locked = true;
+ eprintln!("[OK] Screen lock detected");
+ }
+ if saw_locked && !screen_is_locked() {
+ saw_unlocked_after_lock = true;
+ eprintln!("[OK] Screen unlock detected after lock");
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(200)).await;
+ }
+
+ assert!(saw_locked, "Screen lock was NOT detected — did you lock the screen?");
+ assert!(saw_unlocked_after_lock, "Screen unlock was NOT detected after lock");
+
+ eprintln!("============================================");
+ eprintln!(" LOCK/UNLOCK DETECTION PASSED");
+ eprintln!("============================================");
+ }
}