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

reduce windows cli idle cpu (#3874)

Louis Beaumont3044b320fafb
diff --git a/Cargo.lock b/Cargo.lock
index 8893a6320..abaece52e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8127,6 +8127,7 @@ dependencies = [
"parking_lot",
"regex",
"rusqlite",
+ "screenpipe-config",
"screenpipe-core",
"screenpipe-db",
"serde",
diff --git a/crates/screenpipe-a11y/Cargo.toml b/crates/screenpipe-a11y/Cargo.toml
index 75fb166fa..e0ca189b3 100644
--- a/crates/screenpipe-a11y/Cargo.toml
+++ b/crates/screenpipe-a11y/Cargo.toml
@@ -12,6 +12,7 @@ db = ["screenpipe-db"]
[dependencies]
screenpipe-db = { path = "../screenpipe-db", optional = true }
screenpipe-core = { path = "../screenpipe-core" }
+screenpipe-config = { path = "../screenpipe-config" }
# Core
anyhow = "1.0"
tracing = "0.1"
diff --git a/crates/screenpipe-a11y/src/platform/windows_uia.rs b/crates/screenpipe-a11y/src/platform/windows_uia.rs
index 5f073b9fb..6849d2139 100644
--- a/crates/screenpipe-a11y/src/platform/windows_uia.rs
+++ b/crates/screenpipe-a11y/src/platform/windows_uia.rs
@@ -40,6 +40,8 @@ use windows::Win32::UI::WindowsAndMessaging::{
MsgWaitForMultipleObjects, PeekMessageW, TranslateMessage, MSG, PM_REMOVE, QS_ALLINPUT,
};
+const LOCKED_SCREEN_UIA_BACKOFF: Duration = Duration::from_millis(1000);
+
/// Returns true if the user has produced a mouse/keyboard event within
/// `pause_extraction_on_input_ms`. The UIA worker uses this to skip tree captures during
/// active input — the resulting tree would be stale within milliseconds anyway, and the
@@ -66,6 +68,21 @@ struct PendingFocus {
time: Instant,
}
+fn pause_uia_while_screen_locked(
+ pending_focus: &Arc<Mutex<Option<PendingFocus>>>,
+ click_queue: &Arc<Mutex<Vec<ClickElementRequest>>>,
+ last_capture_time: &mut Instant,
+) -> bool {
+ if !screenpipe_config::screen_is_locked() {
+ return false;
+ }
+
+ *pending_focus.lock() = None;
+ click_queue.lock().clear();
+ *last_capture_time = Instant::now();
+ true
+}
+
/// Click position request for ElementFromPoint
pub struct ClickElementRequest {
pub x: i32,
@@ -642,6 +659,7 @@ pub fn run_uia_thread(
let mut last_capture_time = Instant::now();
let debounce_dur = Duration::from_millis(config.tree_debounce_ms);
let interval_dur = Duration::from_millis(config.tree_capture_interval_ms);
+ let mut was_lock_paused = false;
// Capture initial focused window (no input has happened yet, so input_too_recent is a no-op)
let initial_hwnd = unsafe { GetForegroundWindow() };
@@ -677,6 +695,33 @@ pub fn run_uia_thread(
}
}
+ if pause_uia_while_screen_locked(&pending_focus, &click_queue, &mut last_capture_time) {
+ was_lock_paused = true;
+ std::thread::sleep(LOCKED_SCREEN_UIA_BACKOFF);
+ continue;
+ }
+
+ if was_lock_paused && config.capture_tree {
+ was_lock_paused = false;
+ let hwnd = unsafe { GetForegroundWindow() };
+ if !hwnd.is_invalid() {
+ capture_and_send(
+ &uia,
+ hwnd,
+ &config,
+ &tree_tx,
+ &focused_element,
+ &mut last_captured_hwnd,
+ &mut last_tree_hash,
+ &mut last_capture_time,
+ );
+ } else {
+ last_capture_time = Instant::now();
+ }
+ } else {
+ was_lock_paused = false;
+ }
+
// Defer tree captures while the user is actively typing/clicking. The captured
// tree would be stale within ms anyway, and the work would steal CPU from input
// threads. We keep `pending_focus` and don't bump `last_capture_time` so the
@@ -727,6 +772,8 @@ pub fn run_uia_thread(
&mut last_tree_hash,
&mut last_capture_time,
);
+ } else {
+ last_capture_time = Instant::now();
}
}
}
@@ -782,6 +829,10 @@ fn compute_next_timeout(
) -> u64 {
let mut min_ms: u64 = 1000; // safety ceiling
+ if !config.capture_tree {
+ return min_ms;
+ }
+
// Time until debounce fires
if let Some(ref pf) = *pending_focus.lock() {
let elapsed = pf.time.elapsed();
@@ -817,6 +868,10 @@ fn capture_and_send(
last_capture_time: &mut Instant,
) {
let capture_start = Instant::now();
+ // Mark every attempt, not just successful captures. If the focused window
+ // is filtered out or UIA capture fails, leaving the periodic timer overdue
+ // makes the worker retry immediately and spin a CPU core.
+ *last_capture_time = capture_start;
// Get window info
let (app_name, window_title, pid) = get_window_info(hwnd);
@@ -1135,6 +1190,68 @@ mod tests {
assert_eq!(root.node_count(), 4);
}
+ #[test]
+ fn test_screen_lock_pause_clears_deferred_work() {
+ struct ResetScreenLock;
+ impl Drop for ResetScreenLock {
+ fn drop(&mut self) {
+ screenpipe_config::set_screen_locked(false);
+ }
+ }
+
+ let _reset = ResetScreenLock;
+ screenpipe_config::set_screen_locked(true);
+
+ let pending_focus = Arc::new(Mutex::new(Some(PendingFocus {
+ hwnd: HWND::default(),
+ time: Instant::now(),
+ })));
+ let click_queue = Arc::new(Mutex::new(vec![ClickElementRequest {
+ x: 12,
+ y: 34,
+ timestamp: Utc::now(),
+ }]));
+ let original_capture_time = Instant::now() - Duration::from_secs(5);
+ let mut last_capture_time = original_capture_time;
+
+ assert!(pause_uia_while_screen_locked(
+ &pending_focus,
+ &click_queue,
+ &mut last_capture_time
+ ));
+ assert!(pending_focus.lock().is_none());
+ assert!(click_queue.lock().is_empty());
+ assert!(last_capture_time > original_capture_time);
+
+ screenpipe_config::set_screen_locked(false);
+ assert!(!pause_uia_while_screen_locked(
+ &pending_focus,
+ &click_queue,
+ &mut last_capture_time
+ ));
+ }
+
+ #[test]
+ fn test_compute_next_timeout_ignores_tree_work_when_capture_disabled() {
+ let pending_focus = Arc::new(Mutex::new(Some(PendingFocus {
+ hwnd: HWND::default(),
+ time: Instant::now() - Duration::from_secs(1),
+ })));
+ let mut config = UiCaptureConfig::new();
+ config.capture_tree = false;
+ config.tree_capture_interval_ms = 1;
+
+ let wait_ms = compute_next_timeout(
+ &pending_focus,
+ Duration::from_millis(10),
+ &(Instant::now() - Duration::from_secs(1)),
+ Duration::from_millis(1),
+ &config,
+ );
+
+ assert_eq!(wait_ms, 1000);
+ }
+
/// Comprehensive live test: enumerate ALL visible windows, capture each tree,
/// measure timing, verify element counts, and test hash stability.
/// Run with: cargo test --package screenpipe-accessibility test_live_all_windows -- --nocapture --ignored
diff --git a/crates/screenpipe-engine/src/server.rs b/crates/screenpipe-engine/src/server.rs
index 6b4dc1c8b..caf40be93 100644
--- a/crates/screenpipe-engine/src/server.rs
+++ b/crates/screenpipe-engine/src/server.rs
@@ -259,6 +259,14 @@ pub struct SCServer {
/// warming the hot frame cache from the DB at startup (the cache is only
/// read by the timeline streaming endpoint). Set before `start()`.
pub timeline_disabled: bool,
+ /// Advertise this instance over mDNS. Disabled for loopback-only binds
+ /// because LAN clients cannot reach those addresses and Windows may show a
+ /// firewall prompt for an otherwise local-only CLI run.
+ pub advertise_mdns: bool,
+}
+
+fn should_advertise_mdns(addr: SocketAddr) -> bool {
+ !addr.ip().is_loopback()
}
impl SCServer {
@@ -300,6 +308,7 @@ impl SCServer {
external_memory_sync: None,
high_fps_controller: None,
timeline_disabled: false,
+ advertise_mdns: should_advertise_mdns(addr),
}
}
@@ -354,9 +363,13 @@ impl SCServer {
let listener = bind_listener(self.addr).await?;
info!("Server listening on {}", self.addr);
- // Advertise via mDNS
- if let Err(e) = screenpipe_connect::mdns::advertise(self.addr.port()) {
- tracing::warn!("mdns advertisement failed (non-fatal): {}", e);
+ // Advertise via mDNS only when this server is reachable off-machine.
+ if self.advertise_mdns {
+ if let Err(e) = screenpipe_connect::mdns::advertise(self.addr.port()) {
+ tracing::warn!("mdns advertisement failed (non-fatal): {}", e);
+ }
+ } else {
+ debug!("mdns advertisement skipped for loopback-only server");
}
// Start serving
@@ -1138,3 +1151,33 @@ impl SCServer {
.layer(TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::default()))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::should_advertise_mdns;
+ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
+
+ #[test]
+ fn mdns_advertising_skips_loopback_binds() {
+ assert!(!should_advertise_mdns(SocketAddr::new(
+ IpAddr::V4(Ipv4Addr::LOCALHOST),
+ 3030,
+ )));
+ assert!(!should_advertise_mdns(SocketAddr::new(
+ IpAddr::V6(Ipv6Addr::LOCALHOST),
+ 3030,
+ )));
+ }
+
+ #[test]
+ fn mdns_advertising_runs_for_lan_binds() {
+ assert!(should_advertise_mdns(SocketAddr::new(
+ IpAddr::V4(Ipv4Addr::UNSPECIFIED),
+ 3030,
+ )));
+ assert!(should_advertise_mdns(SocketAddr::new(
+ IpAddr::V6(Ipv6Addr::UNSPECIFIED),
+ 3030,
+ )));
+ }
+}