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

feat(server): add macOS sleep/wake monitor for telemetry

Louis Beaumont4923546c2a29
diff --git a/Cargo.lock b/Cargo.lock
index b0f6c34f4..649af74a2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6828,6 +6828,7 @@ dependencies = [
"candle-nn",
"candle-transformers",
"chrono",
+ "cidre",
"clap",
"clap_complete",
"colored",
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index da782a237..0664e8e25 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -153,3 +153,6 @@ windows = { version = "0.58", features = [
"Win32_System_Threading",
"Win32_Foundation",
] }
+
+[target.'cfg(target_os = "macos")'.dependencies]
+cidre = { git = "https://github.com/yury/cidre.git", features = ["ns"] }
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index d71485fa5..34d443bc3 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -28,7 +28,7 @@ use screenpipe_server::{
vision_manager::{
start_monitor_watcher, stop_monitor_watcher, VisionManager, VisionManagerConfig,
},
- watch_pid, PipeManager, ResourceMonitor, SCServer,
+ watch_pid, PipeManager, ResourceMonitor, SCServer, start_sleep_monitor,
};
use screenpipe_vision::monitor::list_monitors;
use serde::Deserialize;
@@ -698,6 +698,10 @@ async fn main() -> anyhow::Result<()> {
// Initialize analytics for API tracking
analytics::init(!cli.disable_telemetry);
+ // Start sleep/wake monitor for telemetry (macOS only)
+ // This tracks sleep/wake events and checks if recording is degraded after wake
+ start_sleep_monitor();
+
let db = Arc::new(
DatabaseManager::new(&format!("{}/db.sqlite", local_data_dir.to_string_lossy()))
.await
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index 1ca382a4d..7a24c4376 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -1,6 +1,7 @@
mod add;
pub mod analytics;
mod auto_destruct;
+pub mod sleep_monitor;
pub mod chunking;
pub mod cli;
pub mod cloud_search;
@@ -17,6 +18,7 @@ pub mod video_utils;
pub mod vision_manager;
pub use add::handle_index_command;
pub use auto_destruct::watch_pid;
+pub use sleep_monitor::start_sleep_monitor;
pub use axum::Json as JsonResponse;
pub use cli::Cli;
pub use core::{record_video, start_continuous_recording};
diff --git a/screenpipe-server/src/sleep_monitor.rs b/screenpipe-server/src/sleep_monitor.rs
new file mode 100644
index 000000000..17d1ffb7a
--- /dev/null
+++ b/screenpipe-server/src/sleep_monitor.rs
@@ -0,0 +1,206 @@
+//! macOS Sleep/Wake Monitor
+//!
+//! Listens for system sleep and wake events using NSWorkspace notifications.
+//! Currently only tracks these events with PostHog analytics to validate
+//! the hypothesis that sleep/wake events cause recording degradation.
+//!
+//! Future work: Trigger component reinitialization on wake events.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::time::Duration;
+use tracing::{debug, error, info, warn};
+
+use crate::analytics::capture_event_nonblocking;
+use serde_json::json;
+
+/// Tracks whether the system is currently in a "post-wake" state
+static RECENTLY_WOKE: AtomicBool = AtomicBool::new(false);
+
+/// Returns true if the system recently woke from sleep (within last 30 seconds)
+pub fn recently_woke_from_sleep() -> bool {
+ RECENTLY_WOKE.load(Ordering::SeqCst)
+}
+
+/// Start the sleep/wake monitor on macOS
+/// This sets up NSWorkspace notification observers for sleep and wake events.
+#[cfg(target_os = "macos")]
+pub fn start_sleep_monitor() {
+ use cidre::ns;
+
+ info!("Starting macOS sleep/wake monitor");
+
+ std::thread::spawn(|| {
+ // We need to run this on a thread with a run loop
+ // cidre's notification center requires the main run loop or a dedicated one
+
+ let result = std::panic::catch_unwind(|| {
+ // Get the shared workspace - cidre returns Retained<Workspace> directly
+ let workspace = ns::Workspace::shared();
+
+ // Get the workspace's notification center
+ let mut notification_center: cidre::arc::Retained<ns::NotificationCenter> =
+ workspace.notification_center();
+
+ // Subscribe to will_sleep notification
+ let will_sleep_name = ns::workspace::notification::will_sleep();
+ let _sleep_guard = notification_center.add_observer_guard(
+ will_sleep_name,
+ None,
+ None,
+ |_notification| {
+ info!("System is going to sleep");
+ on_will_sleep();
+ },
+ );
+
+ // Subscribe to did_wake notification
+ let did_wake_name = ns::workspace::notification::did_wake();
+ let _wake_guard = notification_center.add_observer_guard(
+ did_wake_name,
+ None,
+ None,
+ |_notification| {
+ info!("System woke from sleep");
+ on_did_wake();
+ },
+ );
+
+ // Subscribe to screens_did_sleep notification
+ let screens_sleep_name = ns::workspace::notification::screens_did_sleep();
+ let _screens_sleep_guard = notification_center.add_observer_guard(
+ screens_sleep_name,
+ None,
+ None,
+ |_notification| {
+ debug!("Screens went to sleep");
+ },
+ );
+
+ // Subscribe to screens_did_wake notification
+ let screens_wake_name = ns::workspace::notification::screens_did_wake();
+ let _screens_wake_guard = notification_center.add_observer_guard(
+ screens_wake_name,
+ None,
+ None,
+ |_notification| {
+ debug!("Screens woke up");
+ },
+ );
+
+ debug!("Sleep/wake notification observers registered successfully");
+
+ // Run the run loop to receive notifications
+ // This will block forever, which is fine since we're in a dedicated thread
+ ns::RunLoop::current().run();
+ });
+
+ if let Err(e) = result {
+ error!("Sleep monitor panicked: {:?}", e);
+ }
+ });
+}
+
+/// Called when system is about to sleep
+fn on_will_sleep() {
+ capture_event_nonblocking(
+ "system_will_sleep",
+ json!({
+ "platform": "macos",
+ }),
+ );
+}
+
+/// Called when system wakes from sleep
+fn on_did_wake() {
+ // Mark that we recently woke
+ RECENTLY_WOKE.store(true, Ordering::SeqCst);
+
+ // Spawn a task to check recording health after a short delay
+ // This gives the system time to stabilize after wake
+ tokio::spawn(async {
+ // Wait 5 seconds for system to stabilize
+ tokio::time::sleep(Duration::from_secs(5)).await;
+
+ // Check if recording is healthy
+ let (audio_healthy, vision_healthy) = check_recording_health().await;
+
+ capture_event_nonblocking(
+ "system_did_wake",
+ json!({
+ "platform": "macos",
+ "audio_healthy_after_wake": audio_healthy,
+ "vision_healthy_after_wake": vision_healthy,
+ "check_delay_secs": 5,
+ }),
+ );
+
+ if !audio_healthy || !vision_healthy {
+ warn!(
+ "Recording degraded after wake: audio={}, vision={}",
+ audio_healthy, vision_healthy
+ );
+ }
+
+ // Clear the recently woke flag after 30 seconds
+ tokio::time::sleep(Duration::from_secs(25)).await;
+ RECENTLY_WOKE.store(false, Ordering::SeqCst);
+ });
+}
+
+/// Check if audio and vision recording are healthy
+/// Returns (audio_healthy, vision_healthy)
+async fn check_recording_health() -> (bool, bool) {
+ // Try to hit the local health endpoint
+ let client = reqwest::Client::new();
+
+ match client
+ .get("http://localhost:3030/health")
+ .timeout(Duration::from_secs(5))
+ .send()
+ .await
+ {
+ Ok(response) => {
+ if let Ok(json) = response.json::<serde_json::Value>().await {
+ let frame_status = json
+ .get("frame_status")
+ .and_then(|v| v.as_str())
+ .unwrap_or("unknown");
+ let audio_status = json
+ .get("audio_status")
+ .and_then(|v| v.as_str())
+ .unwrap_or("unknown");
+
+ let vision_healthy = frame_status == "ok" || frame_status == "healthy";
+ let audio_healthy = audio_status == "ok" || audio_status == "healthy";
+
+ (audio_healthy, vision_healthy)
+ } else {
+ (false, false)
+ }
+ }
+ Err(e) => {
+ warn!("Failed to check health after wake: {}", e);
+ (false, false)
+ }
+ }
+}
+
+/// No-op on non-macOS platforms
+#[cfg(not(target_os = "macos"))]
+pub fn start_sleep_monitor() {
+ debug!("Sleep monitor is only available on macOS");
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_recently_woke_flag() {
+ assert!(!recently_woke_from_sleep());
+ RECENTLY_WOKE.store(true, Ordering::SeqCst);
+ assert!(recently_woke_from_sleep());
+ RECENTLY_WOKE.store(false, Ordering::SeqCst);
+ assert!(!recently_woke_from_sleep());
+ }
+}