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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(capture): recover vision capture after a locked-screen startup (#3705)
Divanshu47be89046fca
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/capture_session.rs b/apps/screenpipe-app-tauri/src-tauri/src/capture_session.rsindex 95a73e4b9..2dc3136ff 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/capture_session.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/capture_session.rs@@ -96,17 +96,16 @@ impl CaptureSession {None};- // Await VisionManager::start inline so its Err can propagate back to- // start_capture. Previously this was inside a detached `tokio::spawn`,- // which returned the outer `Ok(Self)` before the spawn even ran — so- // a silent failure (e.g. stale allowlist matching zero monitors) left- // a "dead" CaptureSession parked in RecordingState.capture and every- // subsequent tray click short-circuited on is_some().- vision_manager.start().await.map_err(|e| {- error!("Failed to start VisionManager: {:?}", e);- format!("Failed to start VisionManager: {e}")- })?;- info!("VisionManager started successfully");+ // A failed initial start() (e.g. 0 monitors while screen is locked at boot)+ // is recoverable — the monitor watcher below retries on unlock/topology change.+ // Don't propagate the error; keep the session alive so the watcher can run.+ match vision_manager.start().await {+ Ok(()) => info!("VisionManager started successfully"),+ Err(e) => {+ warn!("VisionManager initial start failed ({e}); monitor watcher will retry");+ crate::health::set_recording_status(crate::health::RecordingStatus::Starting);+ }+ }// Long-running parts (monitor watcher + shutdown handler) stay in the// spawn — they're fire-and-forget by design.diff --git a/crates/screenpipe-engine/src/sleep_monitor.rs b/crates/screenpipe-engine/src/sleep_monitor.rsindex 1454f22fb..16375bc06 100644--- a/crates/screenpipe-engine/src/sleep_monitor.rs+++ b/crates/screenpipe-engine/src/sleep_monitor.rs@@ -26,7 +26,6 @@ use tracing::{debug, error, info, warn};use crate::analytics::capture_event_nonblocking;#[cfg(target_os = "macos")]use serde_json::json;-#[cfg(target_os = "macos")]use tokio::sync::Notify;/// Tracks whether the system is currently in a "post-wake" state@@ -50,6 +49,15 @@ static SCREEN_IS_LOCKED: AtomicBool = AtomicBool::new(false);#[cfg(target_os = "macos")]static DISPLAY_RECONFIG_NOTIFY: Notify = Notify::const_new();+/// Fired on every locked → unlocked transition. Lets the monitor watcher retry+/// start() immediately rather than waiting for the next poll tick.+/// Same notify_one single-consumer semantics as DISPLAY_RECONFIG_NOTIFY.+static SCREEN_UNLOCK_NOTIFY: Notify = Notify::const_new();++pub fn screen_unlock_notify() -> &'static Notify {+ &SCREEN_UNLOCK_NOTIFY+}+/// Set to `true` once `CGDisplayRegisterReconfigurationCallback` has been/// registered successfully. If registration fails (rare CG error path),/// callers should fall back to shorter polling instead of relying on the@@ -280,6 +288,7 @@ pub fn start_sleep_monitor() {// the capture loop recreates them with fresh frames.#[cfg(target_os = "macos")]screenpipe_screen::stream_invalidation::request();+ SCREEN_UNLOCK_NOTIFY.notify_one();}}@@ -341,6 +350,7 @@ pub fn start_sleep_monitor() {info!("Screen unlocked (CGSession safety-net poll)");#[cfg(target_os = "macos")]screenpipe_screen::stream_invalidation::request();+ SCREEN_UNLOCK_NOTIFY.notify_one();}}});@@ -523,6 +533,7 @@ fn on_did_wake(handle: &tokio::runtime::Handle) {info!("Screen unlocked after wake (CGSession safety-net cleared SCREEN_IS_LOCKED)");#[cfg(target_os = "macos")]screenpipe_screen::stream_invalidation::request();+ SCREEN_UNLOCK_NOTIFY.notify_one();}// Resume DB write queue now that the system is stable.@@ -716,6 +727,44 @@ mod tests {.expect("waiter task should not panic");}+ #[tokio::test]+ async fn test_screen_unlock_notify_wakes_waiter() {+ // buffered permit resolves immediately+ screen_unlock_notify().notify_one();+ tokio::time::timeout(+ std::time::Duration::from_millis(50),+ screen_unlock_notify().notified(),+ )+ .await+ .expect("buffered permit should resolve immediately");++ // parked waiter woken by subsequent notify+ let waiter = tokio::spawn(async { screen_unlock_notify().notified().await });+ tokio::task::yield_now().await;+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ screen_unlock_notify().notify_one();+ tokio::time::timeout(std::time::Duration::from_millis(50), waiter)+ .await+ .expect("parked waiter should wake")+ .expect("waiter task should not panic");+ }++ #[tokio::test]+ async fn test_stale_permit_drain_then_block() {+ let notify = std::sync::Arc::new(Notify::const_new());+ notify.notify_one();++ // timeout(0) drains the buffered permit without blocking+ let drained =+ tokio::time::timeout(std::time::Duration::from_millis(0), notify.notified()).await;+ assert!(drained.is_ok(), "should consume the buffered permit");++ // no permit left — next wait must block+ let fresh =+ tokio::time::timeout(std::time::Duration::from_millis(30), notify.notified()).await;+ assert!(fresh.is_err(), "should block after drain");+ }+#[cfg(target_os = "macos")]#[test]fn test_display_reconfig_callback_registered_default_false() {diff --git a/crates/screenpipe-engine/src/vision_manager/monitor_watcher.rs b/crates/screenpipe-engine/src/vision_manager/monitor_watcher.rsindex 66aeebf86..8dcdf12ea 100644--- a/crates/screenpipe-engine/src/vision_manager/monitor_watcher.rs+++ b/crates/screenpipe-engine/src/vision_manager/monitor_watcher.rs@@ -183,8 +183,23 @@ pub async fn start_monitor_watcher(}// ── Normal monitor polling ──────────────────────────────────────- // If stopped (e.g. no monitors after undock/wake), retry start()+ // If stopped (e.g. no monitors after undock/wake), retry start().if vision_manager.status().await != VisionManagerStatus::Running {+ #[cfg(target_os = "macos")]+ {+ let unlock = crate::sleep_monitor::screen_unlock_notify();+ // Drain any permit buffered while we were Running so we don't+ // wake instantly on a stale signal.+ let _ = tokio::time::timeout(Duration::from_millis(0), unlock.notified()).await;+ // Race unlock against the 5s backstop.+ if tokio::time::timeout(Duration::from_secs(5), unlock.notified())+ .await+ .is_ok()+ {+ info!("screen unlocked — retrying VisionManager start immediately");+ }+ }+ #[cfg(not(target_os = "macos"))]tokio::time::sleep(Duration::from_secs(5)).await;match vision_manager.start().await {Ok(()) => {