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: graceful DRM pause without killing the server (#2876)

Ezra Ellette3d9f0e8bba33
diff --git a/.gitignore b/.gitignore
index 2788cbb8a..fba87642f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -78,3 +78,4 @@ crates/screenpipe-audio/openblas-0.3.31-x64.zip
crates/screenpipe-audio/openblas-0.3.31-woa64-dll.zip
apps/screenpipe-app-tauri/src-tauri/openblas/
apps/screenpipe-app-tauri/src-tauri/mlx.metallib
+.serena/
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
index bb6c574c0..1656a7610 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
@@ -315,6 +315,11 @@ pub async fn start_embedded_server(
let vm_clone = vision_manager.clone();
let shutdown_rx = shutdown_tx_clone.subscribe();
+ let audio_manager_for_drm = if !config.disable_audio {
+ Some((*audio_manager).clone())
+ } else {
+ None
+ };
tokio::spawn(async move {
let mut shutdown_rx = shutdown_rx;
@@ -326,8 +331,8 @@ pub async fn start_embedded_server(
}
info!("VisionManager started successfully");
- // Start MonitorWatcher for dynamic detection
- if let Err(e) = start_monitor_watcher(vm_clone.clone()).await {
+ // Start MonitorWatcher for dynamic detection (with audio DRM pause support)
+ if let Err(e) = start_monitor_watcher(vm_clone.clone(), audio_manager_for_drm).await {
error!("Failed to start monitor watcher: {:?}", e);
}
info!("Monitor watcher started - will detect connect/disconnect");
@@ -347,11 +352,20 @@ pub async fn start_embedded_server(
// Start audio recording
if !config.disable_audio {
let audio_manager_clone = audio_manager.clone();
+ let drm_pause = config.pause_on_drm_content;
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(1)).await;
if let Err(e) = audio_manager_clone.start().await {
error!("Failed to start audio manager: {}", e);
}
+ // If DRM content was already focused at launch, the DRM callback
+ // fired before audio was ready. Stop the output device now so we
+ // don't hold an SCK session while DRM is active.
+ if drm_pause && screenpipe_engine::drm_detector::drm_content_paused() {
+ if let Err(e) = audio_manager_clone.stop_output_devices().await {
+ warn!("failed to stop SCK audio after late DRM detection: {:?}", e);
+ }
+ }
});
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/health.rs b/apps/screenpipe-app-tauri/src-tauri/src/health.rs
index de7b96d39..1540dcf39 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/health.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/health.rs
@@ -313,9 +313,6 @@ pub async fn start_health_check(app: tauri::AppHandle) -> Result<()> {
let mut consecutive_failures: u32 = 0;
let mut consecutive_unhealthy: u32 = 0;
- // DRM pause state — tracked here because engine memory is lost on stop_screenpipe
- let mut drm_stopped = false;
- let mut drm_stop_time: Option<Instant> = None;
// Capture stall detection state
let mut consecutive_audio_stall: u32 = 0;
@@ -477,58 +474,9 @@ pub async fn start_health_check(app: tauri::AppHandle) -> Result<()> {
}
// ── DRM content pause / resume ──
- // When the engine detects DRM streaming content (Netflix, etc.),
- // stop the entire recording pipeline — exactly like the "stop recording"
- // button. This fully releases ScreenCaptureKit so DRM doesn't black out.
- //
- // IMPORTANT: Stop and start are serialized — we never emit start in the
- // same iteration as stop, and we enforce a cooldown between DRM stop and
- // DRM resume to prevent the rapid stop/start race that killed the server.
- if let Ok(ref health) = health_result {
- if health.drm_content_paused && !drm_stopped {
- info!("DRM content detected — calling stop_screenpipe to fully release screen recording");
- let _ = app.emit("shortcut-stop-recording", ());
- drm_stopped = true;
- drm_stop_time = Some(Instant::now());
- // Skip resume check this iteration — let the stop complete first
- }
- }
- // Auto-resume: when server is down due to DRM, poll the focused app.
- // Wait at least 5s after stop to let shutdown complete before attempting restart.
- if drm_stopped {
- let stop_elapsed = drm_stop_time.map(|t| t.elapsed()).unwrap_or_default();
- if stop_elapsed < Duration::from_secs(5) {
- debug!(
- "DRM stop cooldown: {:.1}s elapsed, waiting for 5s before resume check",
- stop_elapsed.as_secs_f64()
- );
- } else {
- let should_resume = tokio::task::spawn_blocking(|| {
- // poll_drm_clear returns true = still DRM, false = cleared
- !screenpipe_engine::drm_detector::poll_drm_clear()
- })
- .await
- .unwrap_or(false);
- if should_resume {
- info!("DRM content no longer focused — auto-restarting recording");
- let _ = app.emit("shortcut-start-recording", ());
- drm_stopped = false;
- drm_stop_time = None;
- // Give the server time to start before checking health again
- last_restart_triggered = Some(Instant::now());
- }
- }
- }
- // Clear drm_stopped if server came back and DRM flag is no longer set
- // (e.g. user manually started recording or toggled the setting off)
- if drm_stopped && health_result.is_ok() {
- if let Ok(ref health) = health_result {
- if !health.drm_content_paused {
- drm_stopped = false;
- drm_stop_time = None;
- }
- }
- }
+ // DRM pause/resume is handled internally by the engine's monitor_watcher:
+ // it stops/restarts VisionManager + AudioManager without killing the server.
+ // The health endpoint still reports drm_content_paused for UI purposes.
// ── Capture stall detection ──
// Only check when the server is responding (status == Recording),
diff --git a/crates/screenpipe-audio/src/audio_manager/manager.rs b/crates/screenpipe-audio/src/audio_manager/manager.rs
index 57cbfd47e..d90fe9f1b 100644
--- a/crates/screenpipe-audio/src/audio_manager/manager.rs
+++ b/crates/screenpipe-audio/src/audio_manager/manager.rs
@@ -95,6 +95,9 @@ pub struct AudioManager {
on_transcription_insert: Option<crate::transcription::AudioInsertCallback>,
/// Unified transcription engine. Set after model loading in start_audio_receiver_handler.
engine: Arc<RwLock<Option<TranscriptionEngine>>>,
+ /// Output devices temporarily stopped due to DRM content detection.
+ /// Stored so they can be restarted when DRM clears.
+ drm_stopped_devices: Arc<RwLock<Vec<AudioDevice>>>,
}
/// Result of checking / restarting the two central handler tasks.
@@ -155,6 +158,7 @@ impl AudioManager {
transcription_paused: Arc::new(AtomicBool::new(false)),
on_transcription_insert: None,
engine: Arc::new(RwLock::new(None)),
+ drm_stopped_devices: Arc::new(RwLock::new(Vec::new())),
};
Ok(manager)
@@ -332,6 +336,18 @@ impl AudioManager {
}
pub async fn start_device(&self, device: &AudioDevice) -> Result<()> {
+ // Don't restart devices that are paused due to DRM content detection.
+ // The monitor watcher will call start_output_devices() when DRM clears.
+ if self
+ .drm_stopped_devices
+ .read()
+ .await
+ .iter()
+ .any(|d| d == device)
+ {
+ return Ok(());
+ }
+
if let Err(e) = self.device_manager.start_device(device).await {
let err_str = e.to_string();
@@ -770,6 +786,69 @@ impl AudioManager {
self.options.read().await.enabled_devices.clone()
}
+ /// Stop all SCK-based (Output) audio devices for DRM pause.
+ /// Input (microphone) devices are left running. Unlike `stop_device()`,
+ /// this does NOT remove devices from `enabled_devices` since DRM pause
+ /// is temporary.
+ pub async fn stop_output_devices(&self) -> Result<()> {
+ use crate::core::device::DeviceType;
+
+ let output_devices: Vec<AudioDevice> = self
+ .current_devices()
+ .into_iter()
+ .filter(|d| d.device_type == DeviceType::Output)
+ .collect();
+
+ if output_devices.is_empty() {
+ return Ok(());
+ }
+
+ info!(
+ "DRM: stopping {} output (SCK) audio device(s)",
+ output_devices.len()
+ );
+
+ for device in &output_devices {
+ // Stop the underlying stream
+ if let Err(e) = self.device_manager.stop_device(device).await {
+ warn!("DRM: failed to stop audio device {}: {:?}", device, e);
+ }
+
+ // Abort the recording task
+ if let Some(pair) = self.recording_handles.get(device) {
+ pair.value().lock().await.abort();
+ }
+ self.recording_handles.remove(device);
+ }
+
+ // Store stopped devices for later restart
+ *self.drm_stopped_devices.write().await = output_devices;
+
+ Ok(())
+ }
+
+ /// Restart SCK-based (Output) audio devices after DRM clears.
+ pub async fn start_output_devices(&self) -> Result<()> {
+ let devices = std::mem::take(&mut *self.drm_stopped_devices.write().await);
+
+ if devices.is_empty() {
+ return Ok(());
+ }
+
+ info!(
+ "DRM: restarting {} output (SCK) audio device(s)",
+ devices.len()
+ );
+
+ for device in &devices {
+ if let Err(e) = self.start_device(device).await {
+ warn!("DRM: failed to restart audio device {}: {:?}", device, e);
+ }
+ }
+
+ Ok(())
+ }
+
/// Returns a reference to the meeting detector, if batch mode is active.
pub fn meeting_detector(&self) -> Option<&Arc<MeetingDetector>> {
self.meeting_detector.as_ref()
@@ -1192,6 +1271,7 @@ impl Drop for AudioManager {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::core::device::{AudioDevice, DeviceType};
#[test]
fn test_central_handler_restart_result_defaults() {
@@ -1201,4 +1281,105 @@ mod tests {
assert!(result.recording_error.is_none());
assert!(result.transcription_error.is_none());
}
+
+ // ── DRM stopped devices tracking tests ─────────────────────
+
+ #[tokio::test]
+ async fn test_drm_stopped_devices_initially_empty() {
+ let devices: Arc<RwLock<Vec<AudioDevice>>> = Arc::new(RwLock::new(Vec::new()));
+ assert!(devices.read().await.is_empty());
+ }
+
+ #[tokio::test]
+ async fn test_drm_stopped_devices_stores_output_only() {
+ let drm_stopped = Arc::new(RwLock::new(Vec::new()));
+
+ let input = AudioDevice::new("MacBook Pro Mic".to_string(), DeviceType::Input);
+ let output = AudioDevice::new("System Audio".to_string(), DeviceType::Output);
+ let all_devices = vec![input.clone(), output.clone()];
+
+ // Simulate stop_output_devices: filter for Output only
+ let output_devices: Vec<AudioDevice> = all_devices
+ .into_iter()
+ .filter(|d| d.device_type == DeviceType::Output)
+ .collect();
+
+ *drm_stopped.write().await = output_devices;
+
+ let stopped = drm_stopped.read().await;
+ assert_eq!(stopped.len(), 1);
+ assert_eq!(stopped[0].name, "System Audio");
+ assert_eq!(stopped[0].device_type, DeviceType::Output);
+ }
+
+ #[tokio::test]
+ async fn test_drm_stopped_devices_start_clears_list() {
+ let drm_stopped = Arc::new(RwLock::new(vec![AudioDevice::new(
+ "System Audio".to_string(),
+ DeviceType::Output,
+ )]));
+
+ // Simulate start_output_devices: take and clear
+ let devices = std::mem::take(&mut *drm_stopped.write().await);
+ assert_eq!(devices.len(), 1);
+ assert!(drm_stopped.read().await.is_empty());
+ }
+
+ #[tokio::test]
+ async fn test_drm_guard_blocks_restart_of_paused_device() {
+ let drm_stopped = Arc::new(RwLock::new(vec![AudioDevice::new(
+ "System Audio".to_string(),
+ DeviceType::Output,
+ )]));
+
+ let device_to_start = AudioDevice::new("System Audio".to_string(), DeviceType::Output);
+
+ // Simulate the guard check in start_device
+ let is_drm_blocked = drm_stopped
+ .read()
+ .await
+ .iter()
+ .any(|d| d == &device_to_start);
+
+ assert!(
+ is_drm_blocked,
+ "start_device should be blocked for a DRM-paused device"
+ );
+ }
+
+ #[tokio::test]
+ async fn test_drm_guard_allows_input_devices() {
+ let drm_stopped = Arc::new(RwLock::new(vec![AudioDevice::new(
+ "System Audio".to_string(),
+ DeviceType::Output,
+ )]));
+
+ let mic = AudioDevice::new("MacBook Pro Mic".to_string(), DeviceType::Input);
+
+ let is_drm_blocked = drm_stopped.read().await.iter().any(|d| d == &mic);
+
+ assert!(
+ !is_drm_blocked,
+ "input devices should not be blocked by DRM guard"
+ );
+ }
+
+ #[tokio::test]
+ async fn test_drm_guard_allows_after_clear() {
+ let drm_stopped = Arc::new(RwLock::new(vec![AudioDevice::new(
+ "System Audio".to_string(),
+ DeviceType::Output,
+ )]));
+
+ // Simulate start_output_devices clearing the list
+ let _ = std::mem::take(&mut *drm_stopped.write().await);
+
+ let device = AudioDevice::new("System Audio".to_string(), DeviceType::Output);
+ let is_drm_blocked = drm_stopped.read().await.iter().any(|d| d == &device);
+
+ assert!(
+ !is_drm_blocked,
+ "after DRM clears, device should not be blocked"
+ );
+ }
}
diff --git a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
index cbb7ee8e6..ca3687909 100644
--- a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
+++ b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
@@ -793,6 +793,11 @@ async fn main() -> anyhow::Result<()> {
let trigger_tx = vision_manager.trigger_sender();
let vm_clone = vision_manager.clone();
+ let audio_manager_for_drm = if !config.disable_audio {
+ Some((*audio_manager).clone())
+ } else {
+ None
+ };
let shutdown_tx_clone2 = shutdown_tx_clone.clone();
let runtime = &tokio::runtime::Handle::current();
let h = runtime.spawn(async move {
@@ -804,8 +809,8 @@ async fn main() -> anyhow::Result<()> {
return;
}
- // Start MonitorWatcher for dynamic detection
- if let Err(e) = start_monitor_watcher(vm_clone.clone()).await {
+ // Start MonitorWatcher for dynamic detection (with audio DRM pause support)
+ if let Err(e) = start_monitor_watcher(vm_clone.clone(), audio_manager_for_drm).await {
error!("Failed to start monitor watcher: {:?}", e);
}
@@ -948,6 +953,10 @@ async fn main() -> anyhow::Result<()> {
"│ vision disabled │ {:<34} │",
record_args.disable_vision
);
+ println!(
+ "│ pause on DRM content │ {:<34} │",
+ record_args.pause_on_drm_content
+ );
println!(
"│ audio engine │ {:<34} │",
format!("{:?}", warning_audio_transcription_engine_clone)
@@ -1143,9 +1152,18 @@ async fn main() -> anyhow::Result<()> {
// start recording after all this text
if !config.disable_audio {
let audio_manager_clone = audio_manager.clone();
+ let drm_pause = config.pause_on_drm_content;
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(10)).await;
audio_manager_clone.start().await.unwrap();
+ // If DRM content was already focused at launch, the DRM callback
+ // fired before audio was ready. Stop the output device now so we
+ // don't hold an SCK session while DRM is active.
+ if drm_pause && screenpipe_engine::drm_detector::drm_content_paused() {
+ if let Err(e) = audio_manager_clone.stop_output_devices().await {
+ tracing::warn!("failed to stop SCK audio after late DRM detection: {:?}", e);
+ }
+ }
});
}
diff --git a/crates/screenpipe-engine/src/cli/mod.rs b/crates/screenpipe-engine/src/cli/mod.rs
index 9a38c0025..c9f2bd666 100644
--- a/crates/screenpipe-engine/src/cli/mod.rs
+++ b/crates/screenpipe-engine/src/cli/mod.rs
@@ -339,6 +339,10 @@ pub struct RecordArgs {
/// Override the machine ID for this device
#[arg(long)]
pub sync_machine_id: Option<String>,
+
+ /// Pause screen and audio capture when DRM content (Netflix, Disney+, etc.) is detected
+ #[arg(long, default_value_t = false)]
+ pub pause_on_drm_content: bool,
}
impl RecordArgs {
@@ -402,6 +406,7 @@ impl RecordArgs {
video_quality: self.video_quality.clone(),
analytics_enabled: !self.disable_telemetry,
ignore_incognito_windows: true,
+ pause_on_drm_content: self.pause_on_drm_content,
..screenpipe_config::RecordingSettings::default()
}
}
@@ -687,3 +692,63 @@ pub fn get_or_create_machine_id(override_id: Option<String>) -> String {
screenpipe_core::sync::get_or_create_machine_id()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use clap::Parser;
+
+ #[test]
+ fn test_pause_on_drm_content_default_false() {
+ let cli = Cli::try_parse_from(["screenpipe", "record"]).unwrap();
+ match cli.command {
+ Command::Record(args) => {
+ assert!(!args.pause_on_drm_content, "default should be false");
+ }
+ _ => panic!("expected Record command"),
+ }
+ }
+
+ #[test]
+ fn test_pause_on_drm_content_flag_sets_true() {
+ let cli =
+ Cli::try_parse_from(["screenpipe", "record", "--pause-on-drm-content"]).unwrap();
+ match cli.command {
+ Command::Record(args) => {
+ assert!(args.pause_on_drm_content, "flag should set to true");
+ }
+ _ => panic!("expected Record command"),
+ }
+ }
+
+ #[test]
+ fn test_pause_on_drm_content_flows_to_recording_settings() {
+ let cli =
+ Cli::try_parse_from(["screenpipe", "record", "--pause-on-drm-content"]).unwrap();
+ match cli.command {
+ Command::Record(args) => {
+ let settings = args.to_recording_settings();
+ assert!(
+ settings.pause_on_drm_content,
+ "flag should propagate to RecordingSettings"
+ );
+ }
+ _ => panic!("expected Record command"),
+ }
+ }
+
+ #[test]
+ fn test_pause_on_drm_content_absent_flows_false() {
+ let cli = Cli::try_parse_from(["screenpipe", "record"]).unwrap();
+ match cli.command {
+ Command::Record(args) => {
+ let settings = args.to_recording_settings();
+ assert!(
+ !settings.pause_on_drm_content,
+ "absent flag should be false in settings"
+ );
+ }
+ _ => panic!("expected Record command"),
+ }
+ }
+}
diff --git a/crates/screenpipe-engine/src/drm_detector.rs b/crates/screenpipe-engine/src/drm_detector.rs
index 6f24d52de..39cfc2814 100644
--- a/crates/screenpipe-engine/src/drm_detector.rs
+++ b/crates/screenpipe-engine/src/drm_detector.rs
@@ -853,4 +853,77 @@ mod tests {
DRM_CONTENT_PAUSED.store(false, Ordering::SeqCst);
}
+
+ // ── check_and_update_drm_state tests ─────────────────────────
+
+ #[test]
+ fn test_check_and_update_drm_state_sets_flag_on_drm_app() {
+ DRM_CONTENT_PAUSED.store(false, Ordering::SeqCst);
+ let result = check_and_update_drm_state(true, Some("Netflix"), None);
+ assert!(result, "should return true for DRM app");
+ assert!(drm_content_paused(), "global flag should be set");
+ DRM_CONTENT_PAUSED.store(false, Ordering::SeqCst);
+ }
+
+ #[test]
+ fn test_check_and_update_drm_state_sets_flag_on_drm_url() {
+ DRM_CONTENT_PAUSED.store(false, Ordering::SeqCst);
+ let result =
+ check_and_update_drm_state(true, Some("Chrome"), Some("https://netflix.com/watch"));
+ assert!(result, "should return true for DRM URL");
+ assert!(drm_content_paused(), "global flag should be set");
+ DRM_CONTENT_PAUSED.store(false, Ordering::SeqCst);
+ }
+
+ #[test]
+ fn test_check_and_update_drm_state_clears_flag_on_non_drm() {
+ DRM_CONTENT_PAUSED.store(true, Ordering::SeqCst);
+ let result =
+ check_and_update_drm_state(true, Some("Finder"), Some("https://google.com"));
+ assert!(!result, "should return false for non-DRM content");
+ assert!(
+ !drm_content_paused(),
+ "global flag should be cleared"
+ );
+ DRM_CONTENT_PAUSED.store(false, Ordering::SeqCst);
+ }
+
+ #[test]
+ fn test_check_and_update_drm_state_noop_when_disabled() {
+ DRM_CONTENT_PAUSED.store(false, Ordering::SeqCst);
+ let result = check_and_update_drm_state(false, Some("Netflix"), None);
+ assert!(!result, "should return false when feature is disabled");
+ assert!(
+ !drm_content_paused(),
+ "global flag should stay false when disabled"
+ );
+ }
+
+ #[test]
+ fn test_check_and_update_drm_state_clears_flag_when_disabled() {
+ // If the flag was somehow set and the feature is disabled, it should clear
+ DRM_CONTENT_PAUSED.store(true, Ordering::SeqCst);
+ let result = check_and_update_drm_state(false, Some("Netflix"), None);
+ assert!(!result);
+ assert!(
+ !drm_content_paused(),
+ "disabling the feature should clear any existing DRM pause"
+ );
+ }
+
+ #[test]
+ fn test_check_and_update_drm_state_none_app_preserves_current() {
+ // When app_name is None (empty string), check_and_update_drm_state
+ // preserves the current flag rather than clearing it (unknown = keep state).
+ DRM_CONTENT_PAUSED.store(false, Ordering::SeqCst);
+ let result = check_and_update_drm_state(true, None, None);
+ // With flag=false and no DRM info, it returns false (current state)
+ assert!(!result, "should return false when flag was false and app unknown");
+
+ DRM_CONTENT_PAUSED.store(true, Ordering::SeqCst);
+ let result = check_and_update_drm_state(true, None, None);
+ // With flag=true and no DRM info, it preserves true (unknown = keep)
+ assert!(result, "should return true when flag was true and app unknown");
+ DRM_CONTENT_PAUSED.store(false, Ordering::SeqCst);
+ }
}
diff --git a/crates/screenpipe-engine/src/vision_manager/manager.rs b/crates/screenpipe-engine/src/vision_manager/manager.rs
index 5571b248a..fcb4552df 100644
--- a/crates/screenpipe-engine/src/vision_manager/manager.rs
+++ b/crates/screenpipe-engine/src/vision_manager/manager.rs
@@ -196,6 +196,17 @@ impl VisionManager {
}
}
+ // Aborting capture tasks does NOT release sck_rs's global SCStream handles.
+ // Explicitly tear them down so macOS sees no active ScreenCaptureKit usage.
+ #[cfg(target_os = "macos")]
+ {
+ screenpipe_screen::stream_invalidation::invalidate_streams();
+ // MonitorStream::drop spawns a detached thread to call stream.stop().
+ // Give those threads time to complete so the OS tears down the SCK session
+ // and the purple recording dot disappears.
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ }
+
let mut status = self.status.write().await;
*status = VisionManagerStatus::Stopped;
@@ -338,8 +349,17 @@ impl VisionManager {
// Abort the task
handle.abort();
- // Wait for it to finish
- let _ = handle.await;
+ // Wait for it to finish with a timeout — if the capture task is stuck
+ // in a spawn_blocking AX tree walk, cancellation can be delayed.
+ match tokio::time::timeout(std::time::Duration::from_secs(3), handle).await {
+ Ok(_) => {}
+ Err(_) => {
+ warn!(
+ "monitor {} capture task did not finish within 3s after abort, moving on",
+ monitor_id
+ );
+ }
+ }
Ok(())
} else {
@@ -394,3 +414,82 @@ impl VisionManager {
self.stop().await
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Verify that stop_monitor completes promptly when the task finishes normally.
+ #[tokio::test]
+ async fn test_stop_monitor_normal_task() {
+ let tasks: Arc<DashMap<u32, JoinHandle<()>>> = Arc::new(DashMap::new());
+ let handle = tokio::spawn(async {
+ // Task that finishes quickly
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ });
+ tasks.insert(1, handle);
+
+ // Simulate stop_monitor logic
+ if let Some((_, handle)) = tasks.remove(&1) {
+ handle.abort();
+ let result =
+ tokio::time::timeout(std::time::Duration::from_secs(3), handle).await;
+ // Should complete well before 3s
+ assert!(result.is_ok(), "normal task should finish within timeout");
+ }
+ }
+
+ /// Verify that stop_monitor doesn't hang on a slow task — the 3s timeout fires.
+ #[tokio::test]
+ async fn test_stop_monitor_timeout_on_slow_task() {
+ let tasks: Arc<DashMap<u32, JoinHandle<()>>> = Arc::new(DashMap::new());
+ let handle = tokio::spawn(async {
+ // Simulate a task stuck in spawn_blocking-like work.
+ // We use a long sleep; abort won't cancel it instantly in all cases.
+ tokio::task::spawn_blocking(|| {
+ std::thread::sleep(std::time::Duration::from_secs(30));
+ })
+ .await
+ .ok();
+ });
+ tasks.insert(1, handle);
+
+ if let Some((_, handle)) = tasks.remove(&1) {
+ handle.abort();
+ let start = std::time::Instant::now();
+ let result =
+ tokio::time::timeout(std::time::Duration::from_secs(3), handle).await;
+ let elapsed = start.elapsed();
+
+ // The timeout should fire around 3s, not 30s
+ assert!(
+ elapsed < std::time::Duration::from_secs(5),
+ "should not wait for the full 30s task, elapsed: {:?}",
+ elapsed
+ );
+ // The result is either Ok (abort completed) or Err (timeout). Either is acceptable —
+ // the important thing is we didn't hang.
+ let _ = result;
+ }
+ }
+
+ /// Verify that an already-finished task completes instantly on stop_monitor.
+ #[tokio::test]
+ async fn test_stop_monitor_already_finished() {
+ let tasks: Arc<DashMap<u32, JoinHandle<()>>> = Arc::new(DashMap::new());
+ let handle = tokio::spawn(async {});
+ // Let it finish
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ tasks.insert(1, handle);
+
+ if let Some((_, handle)) = tasks.remove(&1) {
+ handle.abort();
+ let result =
+ tokio::time::timeout(std::time::Duration::from_secs(3), handle).await;
+ assert!(
+ result.is_ok(),
+ "already-finished task should resolve instantly"
+ );
+ }
+ }
+}
diff --git a/crates/screenpipe-engine/src/vision_manager/monitor_watcher.rs b/crates/screenpipe-engine/src/vision_manager/monitor_watcher.rs
index 92e7b9157..2b86d3865 100644
--- a/crates/screenpipe-engine/src/vision_manager/monitor_watcher.rs
+++ b/crates/screenpipe-engine/src/vision_manager/monitor_watcher.rs
@@ -19,8 +19,13 @@ use crate::drm_detector;
static MONITOR_WATCHER: Lazy<Mutex<Option<JoinHandle<()>>>> = Lazy::new(|| Mutex::new(None));
-/// Start the monitor watcher that polls for monitor changes
-pub async fn start_monitor_watcher(vision_manager: Arc<VisionManager>) -> anyhow::Result<()> {
+/// Start the monitor watcher that polls for monitor changes.
+/// When `audio_manager` is provided, SCK-based (output) audio devices are also
+/// stopped/restarted alongside vision during DRM pause/resume.
+pub async fn start_monitor_watcher(
+ vision_manager: Arc<VisionManager>,
+ audio_manager: Option<screenpipe_audio::audio_manager::AudioManager>,
+) -> anyhow::Result<()> {
// Stop existing watcher if any
stop_monitor_watcher().await?;
@@ -66,6 +71,11 @@ pub async fn start_monitor_watcher(vision_manager: Arc<VisionManager>) -> anyhow
if let Err(e) = vision_manager.stop().await {
warn!("failed to stop vision manager for DRM pause: {:?}", e);
}
+ if let Some(ref am) = audio_manager {
+ if let Err(e) = am.stop_output_devices().await {
+ warn!("failed to stop SCK audio for DRM pause: {:?}", e);
+ }
+ }
drm_stopped = true;
}
// Poll focused app (Accessibility API only, no SCK) to detect
@@ -85,6 +95,11 @@ pub async fn start_monitor_watcher(vision_manager: Arc<VisionManager>) -> anyhow
if let Err(e) = vision_manager.start().await {
warn!("failed to restart vision manager after DRM pause: {:?}", e);
}
+ if let Some(ref am) = audio_manager {
+ if let Err(e) = am.start_output_devices().await {
+ warn!("failed to restart SCK audio after DRM clear: {:?}", e);
+ }
+ }
drm_stopped = false;
// Re-populate known_monitors after restart
if let Ok(monitors) = list_monitors_detailed().await {