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(permissions): grace permission monitor on screen unlock / display reconfig (CLI-WH) (#4625)
Ezra Elletted72ad2541e25
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-permission-monitor.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-permission-monitor.tsxindex 22113c1e2..22c2ff38f 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-permission-monitor.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/use-permission-monitor.tsx@@ -15,6 +15,10 @@ interface PermissionLostPayload {microphone: boolean;accessibility: boolean;browser_automation?: boolean;+ // Diagnostic context from the engine emission site ("poll", or the raw+ // ScreenCaptureKit error string for the eager path). Lets us tell a real+ // revoke from an un-graced transient in telemetry. May be absent.+ reason?: string | null;}interface PermissionNeededPayload {@@ -38,7 +42,7 @@ export function usePermissionMonitor() {if (skipPaths.some((p) => pathname?.startsWith(p))) return;const unlisten = listen<PermissionLostPayload>("permission-lost", async (event) => {- const { screen_recording, microphone, accessibility, browser_automation } = event.payload;+ const { screen_recording, microphone, accessibility, browser_automation, reason } = event.payload;if (hasShownRef.current) return;@@ -54,6 +58,7 @@ export function usePermissionMonitor() {microphone_lost: microphone,accessibility_lost: accessibility,browser_automation_lost: browser_automation,+ reason: reason ?? null,});try {diff --git a/apps/screenpipe-app-tauri/src-tauri/src/engine_events/permission.rs b/apps/screenpipe-app-tauri/src-tauri/src/engine_events/permission.rsindex 168ba89a3..d0a953468 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/engine_events/permission.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/engine_events/permission.rs@@ -48,6 +48,11 @@ fn handle_lost(app: &AppHandle, data: &Value) {}info!(event = %data, "permission-lost (from engine)");+ // Diagnostic context from the emission site ("poll", or the raw+ // ScreenCaptureKit error string for the eager path). Forwarded to+ // telemetry so a residual loss can be explained (real revoke vs a+ // transient we haven't yet graced). Absent → null.+ let reason = data.get("reason").and_then(|v| v.as_str());// Shape the payload to match what the Tauri webview already listens for.// Existing recovery modal expects `screen_recording` / `microphone` /// `accessibility` booleans.@@ -56,6 +61,7 @@ fn handle_lost(app: &AppHandle, data: &Value) {"microphone": kind == "microphone","accessibility": kind == "accessibility","browser_automation": false,+ "reason": reason,});if let Err(e) = app.emit("permission-lost", payload) {warn!("failed to emit permission-lost: {}", e);diff --git a/crates/screenpipe-engine/src/permission_monitor.rs b/crates/screenpipe-engine/src/permission_monitor.rsindex defdd6e4a..667a44888 100644--- a/crates/screenpipe-engine/src/permission_monitor.rs+++ b/crates/screenpipe-engine/src/permission_monitor.rs@@ -215,6 +215,16 @@ pub fn notify_wake() {);}+/// Returns `true` while the wake grace period is active (permission-loss+/// emissions are currently suppressed). Diagnostic/test accessor — lets the+/// sleep monitor's unit tests assert that an unlock/display-reconfig actually+/// armed the grace without waiting out [`WAKE_GRACE`].+#[allow(dead_code)] // consumed by sleep_monitor's (test-only) unlock-grace assertion+pub(crate) fn wake_grace_active() -> bool {+ let state = STATE.lock().unwrap_or_else(|e| e.into_inner());+ matches!(state.wake_grace_until, Some(until) if Instant::now() < until)+}+async fn run() {let mut ticker = tokio::time::interval(POLL_INTERVAL);// First tick fires immediately — skip it, we already seeded state.diff --git a/crates/screenpipe-engine/src/sleep_monitor.rs b/crates/screenpipe-engine/src/sleep_monitor.rsindex 16375bc06..9d31e41bc 100644--- a/crates/screenpipe-engine/src/sleep_monitor.rs+++ b/crates/screenpipe-engine/src/sleep_monitor.rs@@ -189,6 +189,26 @@ fn check_screen_locked_cgsession() -> bool {}}+/// Shared handling for a screen-unlock transition.+///+/// Invalidates persistent SCStream handles so the capture loop recreates them+/// with fresh frames, AND arms the permission-monitor wake grace. The grace is+/// the load-bearing part: re-creating an SCStream transiently reports `denied`+/// before ScreenCaptureKit re-registers, which the eager permission detector+/// would otherwise surface as a spurious `permission_lost`. That false positive+/// is the dominant cause of the recurring screen-recording permission-loss+/// telemetry — users lock/unlock several times a day. System *wake* already+/// arms this grace via [`mark_recently_woke`]; unlock did not, until now.+///+/// Also wakes any `monitor_watcher` parked on [`SCREEN_UNLOCK_NOTIFY`] so it+/// re-scans immediately instead of waiting for its poll tick.+#[cfg(target_os = "macos")]+fn handle_screen_unlock_transition() {+ screenpipe_screen::stream_invalidation::request();+ crate::permission_monitor::notify_wake();+ SCREEN_UNLOCK_NOTIFY.notify_one();+}+/// Start the sleep/wake monitor on macOS/// This sets up NSWorkspace notification observers for sleep and wake events,/// plus a polling thread that checks `CGSessionCopyCurrentDictionary` every@@ -283,12 +303,11 @@ pub fn start_sleep_monitor() {let was_locked = SCREEN_IS_LOCKED.swap(false, Ordering::SeqCst);screenpipe_config::set_screen_locked(false);if was_locked {- // State change logged via safety-net poll below if needed.- // Request invalidation of persistent SCStream handles so- // the capture loop recreates them with fresh frames.- #[cfg(target_os = "macos")]- screenpipe_screen::stream_invalidation::request();- SCREEN_UNLOCK_NOTIFY.notify_one();+ // Recreate the SCStream with fresh frames AND arm the+ // permission-monitor grace (re-creation transiently reports+ // `denied`). catch_unwind: never let a panic unwind across the+ // C boundary — this runs in a CFNotificationCenter callback.+ let _ = std::panic::catch_unwind(handle_screen_unlock_transition);}}@@ -348,9 +367,7 @@ pub fn start_sleep_monitor() {info!("Screen locked (CGSession safety-net poll)");} else {info!("Screen unlocked (CGSession safety-net poll)");- #[cfg(target_os = "macos")]- screenpipe_screen::stream_invalidation::request();- SCREEN_UNLOCK_NOTIFY.notify_one();+ handle_screen_unlock_transition();}}});@@ -396,6 +413,11 @@ pub fn start_sleep_monitor() {#[cfg(target_os = "macos")]screenpipe_screen::stream_invalidation::request();screenpipe_audio::stream_invalidation::request();+ // SCStream re-creation after a reconfiguration transiently reports+ // `denied`; arm the permission-monitor grace so it isn't surfaced+ // as a false permission_lost. catch_unwind: never unwind across the+ // C boundary (this runs in a CGDisplay reconfiguration callback).+ let _ = std::panic::catch_unwind(crate::permission_monitor::notify_wake);// Wake any waiters (e.g. monitor_watcher) so they re-scan the// monitor list immediately instead of waiting on a poll timer.DISPLAY_RECONFIG_NOTIFY.notify_one();@@ -531,9 +553,7 @@ fn on_did_wake(handle: &tokio::runtime::Handle) {screenpipe_config::set_screen_locked(locked);if was_locked && !locked {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();+ handle_screen_unlock_transition();}// Resume DB write queue now that the system is stable.@@ -819,6 +839,20 @@ mod tests {);}+ /// A screen-unlock transition must arm the permission-monitor wake grace,+ /// so the SCStream re-creation it triggers does not surface as a spurious+ /// `permission_lost`. This is the #1 cause of recurring screen-recording+ /// permission-loss telemetry (users lock/unlock several times a day).+ #[cfg(target_os = "macos")]+ #[test]+ fn test_screen_unlock_arms_permission_wake_grace() {+ handle_screen_unlock_transition();+ assert!(+ crate::permission_monitor::wake_grace_active(),+ "screen unlock must arm the permission-monitor wake grace"+ );+ }+/// 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")]