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

perf: reduce Windows idle CPU — event-driven hooks, caching, RegexSet

louis030195d2c9d1fb863f
diff --git a/crates/screenpipe-a11y/src/platform/windows.rs b/crates/screenpipe-a11y/src/platform/windows.rs
index febff92d5..630a6ebad 100644
--- a/crates/screenpipe-a11y/src/platform/windows.rs
+++ b/crates/screenpipe-a11y/src/platform/windows.rs
@@ -26,11 +26,17 @@ use windows::Win32::UI::Input::KeyboardAndMouse::{
};
use windows::Win32::UI::WindowsAndMessaging::{
CallNextHookEx, DispatchMessageW, GetForegroundWindow, GetMessageW, GetWindowTextW,
- GetWindowThreadProcessId, SetWindowsHookExW, TranslateMessage, UnhookWindowsHookEx, HC_ACTION,
- HHOOK, KBDLLHOOKSTRUCT, MSG, MSLLHOOKSTRUCT, WH_KEYBOARD_LL, WH_MOUSE_LL, WM_KEYDOWN, WM_KEYUP,
- WM_LBUTTONDOWN, WM_MBUTTONDOWN, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_RBUTTONDOWN, WM_SYSKEYDOWN,
- WM_SYSKEYUP, WM_XBUTTONDOWN,
+ GetWindowThreadProcessId, PostThreadMessageW, SetTimer, SetWindowsHookExW, TranslateMessage,
+ UnhookWindowsHookEx, EVENT_SYSTEM_FOREGROUND, HC_ACTION, HHOOK, KBDLLHOOKSTRUCT, MSG,
+ MSLLHOOKSTRUCT, WH_KEYBOARD_LL, WH_MOUSE_LL, WINEVENT_OUTOFCONTEXT,
+ WINEVENT_SKIPOWNPROCESS, WM_KEYDOWN, WM_KEYUP, WM_LBUTTONDOWN, WM_MBUTTONDOWN,
+ WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_QUIT, WM_RBUTTONDOWN, WM_SYSKEYDOWN, WM_SYSKEYUP,
+ WM_TIMER, WM_XBUTTONDOWN,
};
+use windows::Win32::UI::Accessibility::{
+ SetWinEventHook, UnhookWinEvent, HWINEVENTHOOK,
+};
+use windows::Win32::System::Threading::GetCurrentThreadId;
/// Permission status for UI capture
#[derive(Debug, Clone)]
@@ -1083,9 +1089,133 @@ fn get_clipboard_text() -> Option<String> {
}
// ============================================================================
-// App Observer (Windows)
+// App Observer (Windows) — event-driven via SetWinEventHook
// ============================================================================
+/// Thread-local state for the app observer WinEvent callback.
+struct AppObserverState {
+ tx: Sender<UiEvent>,
+ start: Instant,
+ config: UiCaptureConfig,
+ current_app: Arc<Mutex<Option<String>>>,
+ current_window: Arc<Mutex<Option<String>>>,
+ focused_element: Arc<Mutex<Option<ElementContext>>>,
+ last_hwnd: isize,
+ last_title: Option<String>,
+}
+
+thread_local! {
+ static APP_OBSERVER_STATE: std::cell::RefCell<Option<Box<AppObserverState>>> = const { std::cell::RefCell::new(None) };
+}
+
+/// Timer ID for the safety-net periodic check.
+const APP_OBSERVER_TIMER_ID: usize = 1;
+
+/// Process a foreground window change in the app observer.
+fn process_foreground_change(state: &mut AppObserverState) {
+ unsafe {
+ let hwnd = GetForegroundWindow();
+ let hwnd_val = hwnd.0 as isize;
+
+ if hwnd_val == state.last_hwnd {
+ return;
+ }
+
+ // Get window title
+ let mut title_buf = [0u16; 512];
+ let len = GetWindowTextW(hwnd, &mut title_buf);
+ let title = if len > 0 {
+ Some(String::from_utf16_lossy(&title_buf[..len as usize]))
+ } else {
+ None
+ };
+
+ // Get process ID
+ let mut pid: u32 = 0;
+ GetWindowThreadProcessId(hwnd, Some(&mut pid));
+
+ // Get process name
+ let app_name = get_process_name(pid).unwrap_or_else(|| "Unknown".to_string());
+
+ // Check exclusions
+ if !state.config.should_capture_app(&app_name) {
+ state.last_hwnd = hwnd_val;
+ return;
+ }
+
+ if let Some(ref t) = title {
+ if !state.config.should_capture_window(t) {
+ state.last_hwnd = hwnd_val;
+ return;
+ }
+ }
+
+ // Update shared state for event listener thread
+ *state.current_app.lock() = Some(app_name.clone());
+ *state.current_window.lock() = title.clone();
+
+ // Get focused element context from UIA thread
+ let element = if state.config.capture_context {
+ state.focused_element.lock().clone()
+ } else {
+ None
+ };
+
+ // Send app switch event
+ if state.config.capture_app_switch {
+ let mut event = UiEvent::app_switch(
+ Utc::now(),
+ state.start.elapsed().as_millis() as u64,
+ app_name.clone(),
+ pid as i32,
+ );
+ event.element = element.clone();
+ let _ = state.tx.try_send(event);
+ }
+
+ // Send window focus event
+ if state.config.capture_window_focus && title != state.last_title {
+ let event = UiEvent {
+ id: None,
+ timestamp: Utc::now(),
+ relative_ms: state.start.elapsed().as_millis() as u64,
+ data: EventData::WindowFocus {
+ app: app_name,
+ title: title.clone(),
+ },
+ app_name: None,
+ window_title: None,
+ browser_url: None,
+ element,
+ frame_id: None,
+ };
+ let _ = state.tx.try_send(event);
+ }
+
+ state.last_hwnd = hwnd_val;
+ state.last_title = title;
+ }
+}
+
+/// WinEvent callback for EVENT_SYSTEM_FOREGROUND changes.
+unsafe extern "system" fn foreground_event_proc(
+ _hook: HWINEVENTHOOK,
+ _event: u32,
+ _hwnd: HWND,
+ _id_object: i32,
+ _id_child: i32,
+ _event_thread: u32,
+ _event_time: u32,
+) {
+ APP_OBSERVER_STATE.with(|state| {
+ if let Ok(mut guard) = state.try_borrow_mut() {
+ if let Some(ref mut s) = *guard {
+ process_foreground_change(s);
+ }
+ }
+ });
+}
+
fn run_app_observer(
tx: Sender<UiEvent>,
stop: Arc<AtomicBool>,
@@ -1095,98 +1225,120 @@ fn run_app_observer(
current_window: Arc<Mutex<Option<String>>>,
focused_element: Arc<Mutex<Option<ElementContext>>>,
) {
- let mut last_hwnd: isize = 0;
- let mut last_title: Option<String> = None;
+ // Initialize thread-local state
+ APP_OBSERVER_STATE.with(|state| {
+ *state.borrow_mut() = Some(Box::new(AppObserverState {
+ tx,
+ start,
+ config,
+ current_app,
+ current_window,
+ focused_element,
+ last_hwnd: 0,
+ last_title: None,
+ }));
+ });
- while !stop.load(Ordering::Relaxed) {
+ // Save thread ID so the stop logic can post WM_QUIT
+ let thread_id = unsafe { GetCurrentThreadId() };
+
+ // Spawn a watcher that posts WM_QUIT when stop is signaled
+ let stop_clone = stop.clone();
+ thread::spawn(move || {
+ while !stop_clone.load(Ordering::Relaxed) {
+ std::thread::sleep(std::time::Duration::from_millis(200));
+ }
unsafe {
- let hwnd = GetForegroundWindow();
- let hwnd_val = hwnd.0 as isize;
-
- if hwnd_val != last_hwnd {
- // Get window title
- let mut title_buf = [0u16; 512];
- let len = GetWindowTextW(hwnd, &mut title_buf);
- let title = if len > 0 {
- Some(String::from_utf16_lossy(&title_buf[..len as usize]))
- } else {
- None
- };
-
- // Get process ID
- let mut pid: u32 = 0;
- GetWindowThreadProcessId(hwnd, Some(&mut pid));
-
- // Get process name
- let app_name = get_process_name(pid).unwrap_or_else(|| "Unknown".to_string());
+ let _ = PostThreadMessageW(thread_id, WM_QUIT, WPARAM(0), LPARAM(0));
+ }
+ });
- // Check exclusions
- if !config.should_capture_app(&app_name) {
- last_hwnd = hwnd_val;
- std::thread::sleep(std::time::Duration::from_millis(100));
- continue;
- }
+ unsafe {
+ // Register WinEvent hook for foreground window changes (event-driven, no polling)
+ let hook = SetWinEventHook(
+ EVENT_SYSTEM_FOREGROUND,
+ EVENT_SYSTEM_FOREGROUND,
+ None,
+ Some(foreground_event_proc),
+ 0,
+ 0,
+ WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
+ );
+
+ // Safety-net timer: re-check foreground every 2s in case a hook event was missed
+ SetTimer(HWND::default(), APP_OBSERVER_TIMER_ID, 2000, None);
+
+ // Process initial foreground window
+ APP_OBSERVER_STATE.with(|state| {
+ if let Some(ref mut s) = *state.borrow_mut() {
+ process_foreground_change(s);
+ }
+ });
+
+ // Block on message pump (wakes only on events/timer, no busy-polling)
+ let mut msg = MSG::default();
+ loop {
+ let ret = GetMessageW(&mut msg, HWND::default(), 0, 0);
+ if ret.0 <= 0 {
+ break; // WM_QUIT or error
+ }
- if let Some(ref t) = title {
- if !config.should_capture_window(t) {
- last_hwnd = hwnd_val;
- std::thread::sleep(std::time::Duration::from_millis(100));
- continue;
+ // Handle timer messages as a safety-net foreground check
+ if msg.message == WM_TIMER && msg.wParam.0 == APP_OBSERVER_TIMER_ID {
+ APP_OBSERVER_STATE.with(|state| {
+ if let Ok(mut guard) = state.try_borrow_mut() {
+ if let Some(ref mut s) = *guard {
+ process_foreground_change(s);
+ }
}
- }
+ });
+ }
- // Update shared state for event listener thread
- *current_app.lock() = Some(app_name.clone());
- *current_window.lock() = title.clone();
-
- // Get focused element context from UIA thread
- let element = if config.capture_context {
- focused_element.lock().clone()
- } else {
- None
- };
-
- // Send app switch event
- if config.capture_app_switch {
- let mut event = UiEvent::app_switch(
- Utc::now(),
- start.elapsed().as_millis() as u64,
- app_name.clone(),
- pid as i32,
- );
- event.element = element.clone();
- let _ = tx.try_send(event);
- }
+ let _ = TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
- // Send window focus event
- if config.capture_window_focus && title != last_title {
- let event = UiEvent {
- id: None,
- timestamp: Utc::now(),
- relative_ms: start.elapsed().as_millis() as u64,
- data: EventData::WindowFocus {
- app: app_name,
- title: title.clone(),
- },
- app_name: None,
- window_title: None,
- browser_url: None,
- element,
- frame_id: None,
- };
- let _ = tx.try_send(event);
- }
+ // Cleanup
+ if !hook.is_invalid() {
+ let _ = UnhookWinEvent(hook);
+ }
+ }
- last_hwnd = hwnd_val;
- last_title = title;
+ debug!("App observer stopped");
+}
+
+/// Cached PID→process name mapping with TTL to avoid CreateToolhelp32Snapshot on every lookup.
+static PROCESS_NAME_CACHE: std::sync::OnceLock<Mutex<std::collections::HashMap<u32, (String, Instant)>>> = std::sync::OnceLock::new();
+
+fn process_name_cache() -> &'static Mutex<std::collections::HashMap<u32, (String, Instant)>> {
+ PROCESS_NAME_CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()))
+}
+
+pub(crate) fn get_process_name(pid: u32) -> Option<String> {
+ let now = Instant::now();
+ // Check cache first
+ {
+ let cache = process_name_cache().lock();
+ if let Some((name, cached_at)) = cache.get(&pid) {
+ if now.duration_since(*cached_at) < std::time::Duration::from_secs(60) {
+ return Some(name.clone());
}
}
-
- std::thread::sleep(std::time::Duration::from_millis(100));
}
+ // Cache miss — do the expensive lookup
+ let name = get_process_name_uncached(pid)?;
+ {
+ let mut cache = process_name_cache().lock();
+ // Evict if too large
+ if cache.len() > 200 {
+ cache.clear();
+ }
+ cache.insert(pid, (name.clone(), now));
+ }
+ Some(name)
}
-pub(crate) fn get_process_name(pid: u32) -> Option<String> {
+fn get_process_name_uncached(pid: u32) -> Option<String> {
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
diff --git a/crates/screenpipe-a11y/src/platform/windows_uia.rs b/crates/screenpipe-a11y/src/platform/windows_uia.rs
index 9345ce0cd..a49a6fb53 100644
--- a/crates/screenpipe-a11y/src/platform/windows_uia.rs
+++ b/crates/screenpipe-a11y/src/platform/windows_uia.rs
@@ -36,8 +36,8 @@ use windows::Win32::UI::Accessibility::{
UIA_PROPERTY_ID,
};
use windows::Win32::UI::WindowsAndMessaging::{
- DispatchMessageW, GetForegroundWindow, GetWindowTextW, GetWindowThreadProcessId, PeekMessageW,
- TranslateMessage, MSG, PM_REMOVE,
+ DispatchMessageW, GetForegroundWindow, GetWindowTextW, GetWindowThreadProcessId,
+ MsgWaitForMultipleObjects, PeekMessageW, QS_ALLINPUT, TranslateMessage, MSG, PM_REMOVE,
};
/// Shared state for pending focus changes (set by COM handler, read by UIA thread)
@@ -699,8 +699,18 @@ pub fn run_uia_thread(
}
}
- // Sleep to avoid busy-waiting (50ms = responsive but low CPU)
- std::thread::sleep(Duration::from_millis(50));
+ // Block until a Windows message arrives or a computed timeout elapses.
+ // This replaces the old 50ms sleep-poll: the thread stays asleep until
+ // something actually needs to happen (COM event, debounce, or re-capture).
+ let wait_ms = compute_next_timeout(&pending_focus, debounce_dur, &last_capture_time, interval_dur, &config);
+ unsafe {
+ MsgWaitForMultipleObjects(
+ None,
+ false,
+ wait_ms as u32,
+ QS_ALLINPUT,
+ );
+ }
}
// Cleanup
@@ -709,6 +719,43 @@ pub fn run_uia_thread(
debug!("UIA worker thread stopped");
}
+/// Compute the next timeout for MsgWaitForMultipleObjects.
+/// Returns the minimum of:
+/// - Time until debounce fires (if pending focus exists)
+/// - Time until periodic re-capture
+/// - Max 1000ms safety ceiling
+fn compute_next_timeout(
+ pending_focus: &Arc<Mutex<Option<PendingFocus>>>,
+ debounce_dur: Duration,
+ last_capture_time: &Instant,
+ interval_dur: Duration,
+ config: &UiCaptureConfig,
+) -> u64 {
+ let mut min_ms: u64 = 1000; // safety ceiling
+
+ // Time until debounce fires
+ if let Some(ref pf) = *pending_focus.lock() {
+ let elapsed = pf.time.elapsed();
+ if elapsed >= debounce_dur {
+ return 0; // Ready now
+ }
+ let remaining = (debounce_dur - elapsed).as_millis() as u64;
+ min_ms = min_ms.min(remaining);
+ }
+
+ // Time until periodic re-capture
+ if config.tree_capture_interval_ms > 0 {
+ let elapsed = last_capture_time.elapsed();
+ if elapsed >= interval_dur {
+ return 0; // Ready now
+ }
+ let remaining = (interval_dur - elapsed).as_millis() as u64;
+ min_ms = min_ms.min(remaining);
+ }
+
+ min_ms.max(1) // avoid 0 (which means infinite in Win32)
+}
+
/// Capture a window tree and send it through the channel if it changed.
fn capture_and_send(
uia: &UiaContext,
diff --git a/crates/screenpipe-core/src/pii_removal.rs b/crates/screenpipe-core/src/pii_removal.rs
index d0bfbd8aa..346cb38f3 100644
--- a/crates/screenpipe-core/src/pii_removal.rs
+++ b/crates/screenpipe-core/src/pii_removal.rs
@@ -1,5 +1,5 @@
use lazy_static::lazy_static;
-use regex::Regex;
+use regex::{Regex, RegexSet};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@@ -135,6 +135,12 @@ lazy_static! {
static ref PASSWORD_CONTEXT_PATTERN: Regex = Regex::new(
r"(?i)((?:master\s+)?(?:password|passcode|passphrase|pin|secret\s*key|unlock\s*code|security\s*code)[\s]*[:=][\s]*)(\S+)"
).unwrap();
+
+ // RegexSet for fast "any PII present?" check — single DFA pass over the text.
+ // Most captures have zero PII so this avoids running 27 individual replace_all calls.
+ static ref PII_REGEX_SET: RegexSet = RegexSet::new(
+ PII_PATTERNS.iter().map(|(re, _)| re.as_str())
+ ).unwrap();
}
/// Represents a region in an image that contains PII and should be redacted
@@ -153,15 +159,21 @@ pub struct PiiRegion {
}
pub fn remove_pii(text: &str) -> String {
- let mut sanitized = text.to_string();
+ // Fast path: single RegexSet DFA pass checks all patterns at once.
+ // Most captured text has zero PII, so we avoid 27 individual replace_all calls.
+ let matches: Vec<usize> = PII_REGEX_SET.matches(text).into_iter().collect();
+ if matches.is_empty() {
+ return text.to_string();
+ }
// First, handle password context specially - preserve the keyword, redact only the value
- sanitized = PASSWORD_CONTEXT_PATTERN
- .replace_all(&sanitized, "$1[PASSWORD]")
+ let mut sanitized = PASSWORD_CONTEXT_PATTERN
+ .replace_all(text, "$1[PASSWORD]")
.to_string();
- // Then apply other PII patterns (skip PASSWORD_CONTEXT as it's already handled)
- for (pattern, replacement) in PII_PATTERNS.iter() {
+ // Only run replace_all for patterns that actually matched
+ for idx in matches {
+ let (pattern, replacement) = &PII_PATTERNS[idx];
if *replacement == "PASSWORD_CONTEXT" {
continue; // Already handled above
}
@@ -194,12 +206,7 @@ pub fn remove_pii_from_text_json(
/// Check if a given text contains PII
pub fn contains_pii(text: &str) -> bool {
- for (pattern, _) in PII_PATTERNS.iter() {
- if pattern.is_match(text) {
- return true;
- }
- }
- false
+ PII_REGEX_SET.is_match(text)
}
/// Get the PII type for a given text, if any
diff --git a/crates/screenpipe-engine/src/meeting_detector.rs b/crates/screenpipe-engine/src/meeting_detector.rs
index 841adb28c..9f8efc5d0 100644
--- a/crates/screenpipe-engine/src/meeting_detector.rs
+++ b/crates/screenpipe-engine/src/meeting_detector.rs
@@ -401,7 +401,7 @@ impl MeetingUiScanner {
let app_name = get_app_name_for_pid(pid).unwrap_or_else(|| format!("pid:{}", pid));
let max_depth = self.max_depth;
let scan_timeout = self.scan_timeout;
- let signals = profile.call_signals.clone();
+ let precomputed = PrecomputedSignal::from_signals(&profile.call_signals);
let min_required = profile.min_signals_required;
// Wrap in catch_unwind to survive cidre/ObjC FFI panics
@@ -440,7 +440,7 @@ impl MeetingUiScanner {
// Walk this window's AX tree looking for signals
walk_for_signals(
- window, &signals, 0, max_depth, &start, scan_timeout,
+ window, &precomputed, 0, max_depth, &start, scan_timeout,
&mut found, min_required,
);
@@ -555,10 +555,13 @@ impl MeetingUiScanner {
///
/// This is a standalone function (not a method) so it can be called recursively
/// without borrowing `self`. It is only compiled on macOS.
+///
+/// Uses `PrecomputedSignal` to avoid per-signal `.to_lowercase()` allocations.
+/// Lowercases node title/desc/identifier ONCE per node, not once per signal.
#[cfg(target_os = "macos")]
fn walk_for_signals(
elem: &cidre::ax::UiElement,
- signals: &[CallSignal],
+ signals: &[PrecomputedSignal],
depth: usize,
max_depth: usize,
start: &Instant,
@@ -582,16 +585,21 @@ fn walk_for_signals(
let desc = get_ax_string_attr(elem, cidre::ax::attr::desc());
let identifier = get_ax_identifier(elem);
- // Check each signal against this element
- for signal in signals {
- if check_signal_match(
- signal,
+ // Lowercase node fields ONCE, not once per signal
+ let title_lower = title.as_deref().map(|t| t.to_lowercase());
+ let desc_lower = desc.as_deref().map(|d| d.to_lowercase());
+ let ident_lower = identifier.as_deref().map(|i| i.to_lowercase());
+
+ // Check each signal against this element using precomputed lowercase
+ for ps in signals {
+ if check_signal_match_precomputed(
+ ps,
&role_str,
- title.as_deref(),
- desc.as_deref(),
- identifier.as_deref(),
+ title_lower.as_deref(),
+ desc_lower.as_deref(),
+ ident_lower.as_deref(),
) {
- let label = format_signal_match(signal, &role_str, title.as_deref(), desc.as_deref());
+ let label = format_signal_match(&ps.signal, &role_str, title.as_deref(), desc.as_deref());
if !found.contains(&label) {
found.push(label);
}
@@ -628,7 +636,38 @@ fn walk_for_signals(
}
}
+/// A signal with pre-lowercased match strings to avoid per-node allocations.
+struct PrecomputedSignal {
+ signal: CallSignal,
+ /// Pre-lowercased match string (the substring to search for).
+ lower: String,
+}
+
+impl PrecomputedSignal {
+ fn from_signals(signals: &[CallSignal]) -> Vec<PrecomputedSignal> {
+ signals
+ .iter()
+ .map(|s| {
+ let lower = match s {
+ CallSignal::AutomationId(id) => id.to_string(), // exact match, no lowercase needed
+ CallSignal::AutomationIdContains(substr) => substr.to_lowercase(),
+ CallSignal::KeyboardShortcut(shortcut) => shortcut.to_lowercase(),
+ CallSignal::RoleWithName { name_contains, .. } => name_contains.to_lowercase(),
+ };
+ PrecomputedSignal {
+ signal: s.clone(),
+ lower,
+ }
+ })
+ .collect()
+ }
+}
+
/// Check if a [`CallSignal`] matches the given element properties.
+///
+/// `title` and `desc` are expected to be raw (not lowercased) for the original
+/// `check_signal_match` entry point. For the optimized hot path, use
+/// `check_signal_match_precomputed` with pre-lowercased values.
fn check_signal_match(
signal: &CallSignal,
role: &str,
@@ -677,6 +716,39 @@ fn check_signal_match(
}
}
+/// Optimized signal match using pre-lowercased signal strings and pre-lowercased node fields.
+/// Avoids per-signal and per-node `.to_lowercase()` allocations on the hot path.
+fn check_signal_match_precomputed(
+ ps: &PrecomputedSignal,
+ role: &str,
+ title_lower: Option<&str>,
+ desc_lower: Option<&str>,
+ identifier_lower: Option<&str>,
+) -> bool {
+ match &ps.signal {
+ CallSignal::AutomationId(id) => {
+ // exact match (not lowercased — automation IDs are case-sensitive)
+ identifier_lower.map_or(false, |ident| ident == *id)
+ }
+ CallSignal::AutomationIdContains(_) => {
+ identifier_lower.map_or(false, |ident| ident.contains(&ps.lower[..]))
+ }
+ CallSignal::KeyboardShortcut(_) => {
+ let in_desc = desc_lower.map_or(false, |d| d.contains(&ps.lower[..]));
+ let in_title = title_lower.map_or(false, |t| t.contains(&ps.lower[..]));
+ in_desc || in_title
+ }
+ CallSignal::RoleWithName { role: r, .. } => {
+ if role != *r {
+ return false;
+ }
+ let in_title = title_lower.map_or(false, |t| t.contains(&ps.lower[..]));
+ let in_desc = desc_lower.map_or(false, |d| d.contains(&ps.lower[..]));
+ in_title || in_desc
+ }
+ }
+}
+
/// Format a human-readable label for a matched signal (used in debug logging).
fn format_signal_match(
signal: &CallSignal,
diff --git a/crates/screenpipe-screen/src/monitor.rs b/crates/screenpipe-screen/src/monitor.rs
index a85b8c19c..f288fd8d2 100644
--- a/crates/screenpipe-screen/src/monitor.rs
+++ b/crates/screenpipe-screen/src/monitor.rs
@@ -74,6 +74,10 @@ pub struct SafeMonitor {
cached_sck: Option<SckMonitor>,
#[cfg(target_os = "macos")]
cached_xcap: Option<XcapMonitor>,
+ /// Cached index position in XcapMonitor::all() to avoid linear search on every capture.
+ /// Monitor IDs are stable during a session, so we try the cached index first (O(1)).
+ #[cfg(not(target_os = "macos"))]
+ cached_monitor_index: Arc<std::sync::Mutex<Option<usize>>>,
}
#[derive(Clone, Debug)]
@@ -188,6 +192,7 @@ impl SafeMonitor {
Self {
monitor_id,
monitor_data,
+ cached_monitor_index: Arc::new(std::sync::Mutex::new(None)),
}
}
@@ -277,13 +282,29 @@ impl SafeMonitor {
#[cfg(not(target_os = "macos"))]
pub async fn capture_image(&self) -> Result<DynamicImage> {
let monitor_id = self.monitor_id;
+ let cached_idx = self.cached_monitor_index.clone();
let image = tokio::task::spawn_blocking(move || -> Result<DynamicImage> {
- let monitor = XcapMonitor::all()
- .map_err(Error::from)?
- .into_iter()
- .find(|m| m.id().unwrap_or(0) == monitor_id)
- .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?;
+ let monitors = XcapMonitor::all().map_err(Error::from)?;
+
+ // Try cached index first (O(1) vs O(n))
+ let monitor = {
+ let idx = cached_idx.lock().unwrap();
+ idx.and_then(|i| monitors.get(i))
+ .filter(|m| m.id().unwrap_or(0) == monitor_id)
+ }
+ .or_else(|| {
+ // Cache miss — linear search and cache result
+ let found = monitors
+ .iter()
+ .enumerate()
+ .find(|(_, m)| m.id().unwrap_or(0) == monitor_id);
+ if let Some((i, _)) = found {
+ *cached_idx.lock().unwrap() = Some(i);
+ }
+ found.map(|(_, m)| m)
+ })
+ .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?;
if monitor.width().unwrap_or(0) == 0 || monitor.height().unwrap_or(0) == 0 {
return Err(anyhow::anyhow!("Invalid monitor dimensions"));
@@ -390,6 +411,8 @@ impl SafeMonitor {
.map_err(|e| anyhow::anyhow!("refresh task panicked: {}", e))??;
self.monitor_data = Arc::new(refreshed);
+ // Invalidate cached index — monitor list may have changed
+ *self.cached_monitor_index.lock().unwrap() = None;
tracing::debug!("Refreshed monitor {} metadata", self.monitor_id);
Ok(())
}
@@ -711,6 +734,8 @@ mod tests {
cached_sck: None,
#[cfg(target_os = "macos")]
cached_xcap: None,
+ #[cfg(not(target_os = "macos"))]
+ cached_monitor_index: Arc::new(std::sync::Mutex::new(None)),
}
}