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
feat(a11y): add --prioritize-input-latency to reduce input lag during a11y capture
nakagawa9c6f43f7f9fa
diff --git a/crates/screenpipe-a11y/src/config.rs b/crates/screenpipe-a11y/src/config.rsindex 78bd0998d..9e0b64839 100644--- a/crates/screenpipe-a11y/src/config.rs+++ b/crates/screenpipe-a11y/src/config.rs@@ -110,6 +110,61 @@ pub struct UiCaptureConfig {/// How often to walk the AX tree#[serde(skip)]pub tree_walk_interval: Duration,++ /// Prioritize input latency over event metadata completeness. Opt-in master switch+ /// for three coordinated optimizations (all active only when this is true):+ /// 1. `mouse_hook_proc` / `keyboard_hook_proc` blocking locks → `try_lock` (fall back to None on contention)+ /// 2. UIA worker / app observer threads run at lower OS priority (see `extraction_thread_priority`)+ /// 3. UIA worker skips tree captures during a short window after any input (see `pause_extraction_on_input_ms`)+ /// Intended for environments where users perceive mouse/keyboard lag and prefer+ /// responsiveness over event completeness.+ pub prioritize_input_latency: bool,++ /// OS thread priority applied to a11y extraction threads (UIA worker, app observer)+ /// when `prioritize_input_latency` is true. Lower values let user input threads+ /// preempt extraction more aggressively. Ignored when `prioritize_input_latency` is false.+ pub extraction_thread_priority: ExtractionThreadPriority,++ /// Skip UIA tree captures within this many milliseconds after the most recent+ /// mouse/keyboard input. 0 disables the skip (default 150ms when+ /// `prioritize_input_latency` is true). Ignored when `prioritize_input_latency` is false.+ /// Captures right after input are typically stale within ms anyway, so skipping+ /// costs little signal while yielding CPU to input threads.+ pub pause_extraction_on_input_ms: u64,+}++/// OS thread priority for a11y extraction threads.+/// Maps to Windows `SetThreadPriority` constants; on non-Windows platforms this+/// is recorded but currently has no effect.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ExtractionThreadPriority {+ Normal,+ BelowNormal,+ Lowest,+ Idle,+}++impl Default for ExtractionThreadPriority {+ fn default() -> Self {+ Self::BelowNormal+ }+}++impl std::str::FromStr for ExtractionThreadPriority {+ type Err = String;+ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s.to_ascii_lowercase().as_str() {+ "normal" => Ok(Self::Normal),+ "below_normal" | "below-normal" | "belownormal" => Ok(Self::BelowNormal),+ "lowest" => Ok(Self::Lowest),+ "idle" => Ok(Self::Idle),+ other => Err(format!(+ "invalid extraction thread priority '{}': expected normal|below_normal|lowest|idle",+ other+ )),+ }+ }}impl Default for UiCaptureConfig {@@ -167,6 +222,11 @@ impl Default for UiCaptureConfig {// Tree walkerenable_tree_walker: true,tree_walk_interval: Duration::from_secs(3),++ // Opt-in. Default false preserves existing behavior.+ prioritize_input_latency: false,+ extraction_thread_priority: ExtractionThreadPriority::BelowNormal,+ pause_extraction_on_input_ms: 150,}}}diff --git a/crates/screenpipe-a11y/src/lib.rs b/crates/screenpipe-a11y/src/lib.rsindex d7be5a7ee..6df64ab88 100644--- a/crates/screenpipe-a11y/src/lib.rs+++ b/crates/screenpipe-a11y/src/lib.rs@@ -68,7 +68,7 @@ pub mod tree;// Re-exportspub use activity_feed::{ActivityFeed, ActivityKind, CaptureParams};-pub use config::UiCaptureConfig;+pub use config::{ExtractionThreadPriority, UiCaptureConfig};pub use events::{AccessibilityNode, ElementBounds, ElementContext, EventData, EventType, Modifiers, UiEvent,WindowTreeSnapshot,@@ -78,7 +78,7 @@ pub use platform::{PermissionStatus, RecordingHandle, UiRecorder};/// Prelude for convenient importspub mod prelude {pub use crate::activity_feed::{ActivityFeed, ActivityKind, CaptureParams};- pub use crate::config::UiCaptureConfig;+ pub use crate::config::{ExtractionThreadPriority, UiCaptureConfig};pub use crate::events::{AccessibilityNode, ElementContext, EventData, EventType, UiEvent, WindowTreeSnapshot,};diff --git a/crates/screenpipe-a11y/src/platform/windows.rs b/crates/screenpipe-a11y/src/platform/windows.rsindex 512ed8327..84f681c1b 100644--- a/crates/screenpipe-a11y/src/platform/windows.rs+++ b/crates/screenpipe-a11y/src/platform/windows.rs@@ -3,24 +3,28 @@//! Uses low-level Windows hooks for keyboard and mouse input capture.use crate::activity_feed::{ActivityFeed, ActivityKind};-use crate::config::UiCaptureConfig;+use crate::config::{ExtractionThreadPriority, UiCaptureConfig};use crate::events::{ElementContext, EventData, UiEvent, WindowTreeSnapshot};use anyhow::Result;use chrono::Utc;use crossbeam_channel::{bounded, Receiver, Sender};use parking_lot::Mutex;use screenpipe_core::pii_removal::remove_pii;-use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::Arc;use std::thread;use std::time::Instant;-use tracing::{debug, error};+use tracing::{debug, error, warn};use super::windows_uia::{self, ClickElementRequest};use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, WPARAM};use windows::Win32::System::LibraryLoader::GetModuleHandleW;-use windows::Win32::System::Threading::GetCurrentThreadId;+use windows::Win32::System::Threading::{+ GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY,+ THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST,+ THREAD_PRIORITY_NORMAL,+};use windows::Win32::UI::Accessibility::{SetWinEventHook, UnhookWinEvent, HWINEVENTHOOK};use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyState, VK_CAPITAL, VK_CONTROL, VK_LCONTROL, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MENU,@@ -35,6 +39,29 @@ use windows::Win32::UI::WindowsAndMessaging::{WM_RBUTTONDOWN, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_TIMER, WM_XBUTTONDOWN,};+/// Lower the current thread's OS priority so user input threads (mouse/keyboard hook,+/// foreground app) get scheduled preferentially. Called from a11y extraction threads+/// at thread start when `prioritize_input_latency` is on, to mitigate input lag caused+/// by a11y extraction threads monopolizing CPU.+pub(crate) fn apply_extraction_thread_priority(priority: ExtractionThreadPriority) {+ let level: THREAD_PRIORITY = match priority {+ ExtractionThreadPriority::Normal => THREAD_PRIORITY_NORMAL,+ ExtractionThreadPriority::BelowNormal => THREAD_PRIORITY_BELOW_NORMAL,+ ExtractionThreadPriority::Lowest => THREAD_PRIORITY_LOWEST,+ ExtractionThreadPriority::Idle => THREAD_PRIORITY_IDLE,+ };+ unsafe {+ let handle = GetCurrentThread();+ match SetThreadPriority(handle, level) {+ Ok(()) => debug!("extraction thread priority set to {:?}", priority),+ Err(e) => warn!(+ "SetThreadPriority({:?}) failed: {:?} — falling back to default priority",+ priority, e+ ),+ }+ }+}+/// Permission status for UI capture#[derive(Debug, Clone)]pub struct PermissionStatus {@@ -171,6 +198,11 @@ impl UiRecorder {let click_queue = Arc::new(Mutex::new(Vec::<ClickElementRequest>::new()));let focused_element = Arc::new(Mutex::new(None::<ElementContext>));+ // Most recent input timestamp (ms since start), used by the UIA worker to skip+ // tree captures during/just after user input when prioritize_input_latency is on.+ // 0 = no input observed yet.+ let last_input_at_ms = Arc::new(AtomicU64::new(0));+// Thread 1: Native Windows hooks for input eventslet tx1 = tx.clone();let stop1 = stop.clone();@@ -180,6 +212,7 @@ impl UiRecorder {let feed1 = activity_feed.clone();let click_queue1 = click_queue.clone();let focused_element1 = focused_element.clone();+ let last_input_at_ms1 = last_input_at_ms.clone();threads.push(thread::spawn(move || {run_native_hooks(tx1,@@ -191,6 +224,7 @@ impl UiRecorder {feed1,click_queue1,focused_element1,+ last_input_at_ms1,);}));@@ -219,6 +253,7 @@ impl UiRecorder {let config3 = self.config.clone();let click_queue3 = click_queue.clone();let focused_element3 = focused_element.clone();+ let last_input_at_ms3 = last_input_at_ms.clone();threads.push(thread::spawn(move || {windows_uia::run_uia_thread(tree_tx,@@ -227,6 +262,8 @@ impl UiRecorder {focused_element3,stop3,config3,+ start_time,+ last_input_at_ms3,);}));@@ -303,6 +340,10 @@ struct HookState {focused_element: Arc<Mutex<Option<ElementContext>>>,/// Clipboard operations deferred from the LL hook to the message loop.pending_clipboard: Vec<PendingClipboard>,+ /// Shared timestamp (ms since start) of the most recent input event.+ /// Updated unconditionally at the top of mouse_hook_proc / keyboard_hook_proc so the UIA+ /// worker can defer tree captures while the user is actively typing/clicking/scrolling.+ last_input_at_ms: Arc<AtomicU64>,}// Thread-local storage for hook state@@ -326,6 +367,7 @@ fn run_native_hooks(activity_feed: Option<ActivityFeed>,click_queue: Arc<Mutex<Vec<ClickElementRequest>>>,focused_element: Arc<Mutex<Option<ElementContext>>>,+ last_input_at_ms: Arc<AtomicU64>,) {debug!("Starting native Windows hooks");@@ -344,6 +386,7 @@ fn run_native_hooks(click_queue,focused_element,pending_clipboard: Vec::new(),+ last_input_at_ms,}));});@@ -487,6 +530,13 @@ unsafe extern "system" fn keyboard_hook_proc(code: i32, wparam: WPARAM, lparam:return;};if let Some(ref mut s) = *guard {+ // Record latest input timestamp unconditionally so the UIA worker can defer+ // extraction while the user is typing. Cheap (one atomic store).+ if is_key_down || is_key_up {+ s.last_input_at_ms+ .store(s.start.elapsed().as_millis() as u64, Ordering::Relaxed);+ }+// Record activityif let Some(ref feed) = s.activity_feed {if is_key_down {@@ -505,8 +555,22 @@ unsafe extern "system" fn keyboard_hook_proc(code: i32, wparam: WPARAM, lparam:let t = s.start.elapsed().as_millis() as u64;let mods = get_modifier_state();- let app_name = s.current_app.lock().clone();- let window_title = s.current_window.lock().clone();+ // try_lock when prioritize_input_latency is set, mirroring mouse_hook_proc:+ // avoid stalling the OS message queue if these locks are contended.+ let (app_name, window_title) = if s.config.prioritize_input_latency {+ (+ s.current_app.try_lock().map(|g| g.clone()).unwrap_or(None),+ s.current_window+ .try_lock()+ .map(|g| g.clone())+ .unwrap_or(None),+ )+ } else {+ (+ s.current_app.lock().clone(),+ s.current_window.lock().clone(),+ )+ };// Check exclusionsif !s.config.should_capture_target(@@ -612,6 +676,12 @@ unsafe extern "system" fn mouse_hook_proc(code: i32, wparam: WPARAM, lparam: LPAreturn;};if let Some(ref mut s) = *guard {+ // Record latest input timestamp unconditionally for all mouse messages+ // (move/click/wheel). Cheap atomic store, lets the UIA worker know the user+ // is actively driving the UI so it can defer captures.+ s.last_input_at_ms+ .store(s.start.elapsed().as_millis() as u64, Ordering::Relaxed);+// Fast path for WM_MOUSEMOVE — no mutex locks to avoid blocking// the system-wide mouse input pipeline (critical for RDP cursor rendering)if msg == WM_MOUSEMOVE {@@ -660,12 +730,27 @@ unsafe extern "system" fn mouse_hook_proc(code: i32, wparam: WPARAM, lparam: LPAreturn;}- // Slow path for clicks/scroll — these are infrequent, mutex locks OK+ // Slow path for clicks/scroll — these are infrequent, mutex locks OK.+ // When prioritize_input_latency is set, switch the blocking locks to try_lock.+ // Falls back to None if contended so the hook returns fast and Windows can+ // dispatch the next mouse event without delay.let timestamp = Utc::now();let t = s.start.elapsed().as_millis() as u64;- let app_name = s.current_app.lock().clone();- let window_title = s.current_window.lock().clone();+ let (app_name, window_title) = if s.config.prioritize_input_latency {+ (+ s.current_app.try_lock().map(|g| g.clone()).unwrap_or(None),+ s.current_window+ .try_lock()+ .map(|g| g.clone())+ .unwrap_or(None),+ )+ } else {+ (+ s.current_app.lock().clone(),+ s.current_window.lock().clone(),+ )+ };// Check exclusionsif !s.config.should_capture_target(@@ -693,9 +778,17 @@ unsafe extern "system" fn mouse_hook_proc(code: i32, wparam: WPARAM, lparam: LPA_ => 0,};- // Attach focused element context (approximate, fast)+ // Attach focused element context (approximate, fast).+ // try_lock when prioritize_input_latency is set.let element = if s.config.capture_context {- s.focused_element.lock().clone()+ if s.config.prioritize_input_latency {+ s.focused_element+ .try_lock()+ .map(|g| g.clone())+ .unwrap_or(None)+ } else {+ s.focused_element.lock().clone()+ }} else {None};@@ -709,9 +802,17 @@ unsafe extern "system" fn mouse_hook_proc(code: i32, wparam: WPARAM, lparam: LPA// Queue ElementFromPoint request for precise element contextif s.config.capture_context {- s.click_queue- .lock()- .push(ClickElementRequest { x, y, timestamp });+ // try_lock when prioritize_input_latency is set. If contended,+ // skip queueing — better than stalling the hook.+ if s.config.prioritize_input_latency {+ if let Some(mut q) = s.click_queue.try_lock() {+ q.push(ClickElementRequest { x, y, timestamp });+ }+ } else {+ s.click_queue+ .lock()+ .push(ClickElementRequest { x, y, timestamp });+ }}}@@ -1210,6 +1311,12 @@ fn run_app_observer(current_window: Arc<Mutex<Option<String>>>,focused_element: Arc<Mutex<Option<ElementContext>>>,) {+ // Lower OS thread priority so user input threads can preempt. The app observer+ // does some UIAutomation work on focus changes — let it yield to input.+ if config.prioritize_input_latency {+ apply_extraction_thread_priority(config.extraction_thread_priority);+ }+// Initialize thread-local stateAPP_OBSERVER_STATE.with(|state| {*state.borrow_mut() = Some(Box::new(AppObserverState {@@ -1409,6 +1516,7 @@ mod tests {click_queue: Arc::new(parking_lot::Mutex::new(Vec::new())),focused_element: Arc::new(parking_lot::Mutex::new(None)),pending_clipboard: Vec::new(),+ last_input_at_ms: Arc::new(AtomicU64::new(0)),}}diff --git a/crates/screenpipe-a11y/src/platform/windows_uia.rs b/crates/screenpipe-a11y/src/platform/windows_uia.rsindex b424d44e8..5f073b9fb 100644--- a/crates/screenpipe-a11y/src/platform/windows_uia.rs+++ b/crates/screenpipe-a11y/src/platform/windows_uia.rs@@ -14,7 +14,7 @@ use crossbeam_channel::Sender;use parking_lot::Mutex;use std::collections::hash_map::DefaultHasher;use std::hash::{Hash, Hasher};-use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::Arc;use std::time::{Duration, Instant};use tracing::{debug, error, trace, warn};@@ -40,6 +40,26 @@ use windows::Win32::UI::WindowsAndMessaging::{MsgWaitForMultipleObjects, PeekMessageW, TranslateMessage, MSG, PM_REMOVE, QS_ALLINPUT,};+/// 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+/// extraction work would compete with input threads for CPU, contributing to perceived lag.+fn input_too_recent(+ config: &UiCaptureConfig,+ start_time: Instant,+ last_input_at_ms: &AtomicU64,+) -> bool {+ if !config.prioritize_input_latency || config.pause_extraction_on_input_ms == 0 {+ return false;+ }+ let last_input = last_input_at_ms.load(Ordering::Relaxed);+ if last_input == 0 {+ return false;+ }+ let now_ms = start_time.elapsed().as_millis() as u64;+ now_ms.saturating_sub(last_input) < config.pause_extraction_on_input_ms+}+/// Shared state for pending focus changes (set by COM handler, read by UIA thread)struct PendingFocus {hwnd: HWND,@@ -520,9 +540,18 @@ pub fn run_uia_thread(focused_element: Arc<Mutex<Option<ElementContext>>>,stop: Arc<AtomicBool>,config: UiCaptureConfig,+ start_time: Instant,+ last_input_at_ms: Arc<AtomicU64>,) {debug!("UIA worker thread starting");+ // Lower OS thread priority so user input threads can preempt. The UIA worker is+ // the heaviest a11y consumer — letting it yield to input is the highest-value+ // piece of the prioritize_input_latency bundle.+ if config.prioritize_input_latency {+ super::windows::apply_extraction_thread_priority(config.extraction_thread_priority);+ }+// Initialize COM (STA for event handler delivery)unsafe {let hr = CoInitializeEx(None, COINIT_APARTMENTTHREADED);@@ -614,7 +643,7 @@ pub fn run_uia_thread(let debounce_dur = Duration::from_millis(config.tree_debounce_ms);let interval_dur = Duration::from_millis(config.tree_capture_interval_ms);- // Capture initial focused window+ // Capture initial focused window (no input has happened yet, so input_too_recent is a no-op)let initial_hwnd = unsafe { GetForegroundWindow() };if !initial_hwnd.is_invalid() {capture_and_send(@@ -629,6 +658,14 @@ pub fn run_uia_thread();}+ // Compute the cooldown for shortening MsgWaitForMultipleObjects timeout when input is recent.+ // We want to wake up shortly after the input window expires to retry the deferred capture.+ let input_pause_dur_ms = if config.prioritize_input_latency {+ config.pause_extraction_on_input_ms+ } else {+ 0+ };+// Main loop: pump messages + process eventslet mut msg = MSG::default();while !stop.load(Ordering::Relaxed) {@@ -640,8 +677,14 @@ pub fn run_uia_thread(}}+ // 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+ // capture is retried on the next loop once input pauses.+ let skip_capture = input_too_recent(&config, start_time, &last_input_at_ms);+// Check for pending focus change (debounced)- if config.capture_tree {+ if config.capture_tree && !skip_capture {let should_capture = {let pending = pending_focus.lock();if let Some(ref pf) = *pending {@@ -702,13 +745,18 @@ pub fn run_uia_thread(// 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(+ let mut wait_ms = compute_next_timeout(&pending_focus,debounce_dur,&last_capture_time,interval_dur,&config,);+ // If we just skipped a capture due to recent input, cap the wait so we wake up+ // shortly after the input cooldown expires and can retry the capture.+ if skip_capture && input_pause_dur_ms > 0 {+ wait_ms = wait_ms.min(input_pause_dur_ms);+ }unsafe {MsgWaitForMultipleObjects(None, false, wait_ms as u32, QS_ALLINPUT);}@@ -1529,6 +1577,8 @@ mod tests {let config2 = config.clone();let click_queue2 = click_queue.clone();let focused_element2 = focused_element.clone();+ let start_time = Instant::now();+ let last_input_at_ms = Arc::new(AtomicU64::new(0));let thread = std::thread::spawn(move || {run_uia_thread(@@ -1538,6 +1588,8 @@ mod tests {focused_element2,stop2,config2,+ start_time,+ last_input_at_ms,);});@@ -1636,6 +1688,7 @@ mod tests {let cpu_before = get_process_cpu_time();let wall_start = std::time::Instant::now();+ let last_input_at_ms = Arc::new(AtomicU64::new(0));let thread = std::thread::spawn(move || {run_uia_thread(@@ -1645,6 +1698,8 @@ mod tests {focused_element2,stop2,config2,+ wall_start,+ last_input_at_ms,);});diff --git a/crates/screenpipe-a11y/src/platform/windows_uia_tests.rs b/crates/screenpipe-a11y/src/platform/windows_uia_tests.rsindex 608a3dbb1..b053aabb1 100644--- a/crates/screenpipe-a11y/src/platform/windows_uia_tests.rs+++ b/crates/screenpipe-a11y/src/platform/windows_uia_tests.rs@@ -15,7 +15,7 @@ use crate::platform::windows_uia::{self, ClickElementRequest, UiaContext};use crossbeam_channel::bounded;use parking_lot::Mutex;use std::process::{Child, Command};-use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::Arc;use std::time::{Duration, Instant};@@ -529,6 +529,8 @@ fn test_full_pipeline_with_app() {let config2 = config.clone();let click_queue2 = click_queue.clone();let focused_element2 = focused_element.clone();+ let start_time = Instant::now();+ let last_input_at_ms = Arc::new(AtomicU64::new(0));let thread = std::thread::spawn(move || {windows_uia::run_uia_thread(tree_tx,@@ -537,6 +539,8 @@ fn test_full_pipeline_with_app() {focused_element2,stop2,config2,+ start_time,+ last_input_at_ms,);});diff --git a/crates/screenpipe-config/src/recording.rs b/crates/screenpipe-config/src/recording.rsindex 972530427..9f4084b3a 100644--- a/crates/screenpipe-config/src/recording.rs+++ b/crates/screenpipe-config/src/recording.rs@@ -193,6 +193,28 @@ pub struct RecordingSettings {#[serde(rename = "minCaptureIntervalMs", default)]pub min_capture_interval_ms: Option<u64>,+ /// Prioritize mouse/keyboard input latency over a11y event completeness.+ /// Opt-in master switch for the three coordinated optimizations defined on+ /// `UiCaptureConfig.prioritize_input_latency`.+ #[serde(rename = "prioritizeInputLatency", default)]+ pub prioritize_input_latency: bool,++ /// OS thread priority for a11y extraction threads when `prioritize_input_latency`+ /// is true. Values: "normal" / "below_normal" / "lowest" / "idle".+ #[serde(+ rename = "extractionThreadPriority",+ default = "default_extraction_thread_priority"+ )]+ pub extraction_thread_priority: String,++ /// Skip UIA tree captures within this many ms after the most recent input.+ /// 0 disables. Ignored when `prioritize_input_latency` is false.+ #[serde(+ rename = "pauseExtractionOnInputMs",+ default = "default_pause_extraction_on_input_ms"+ )]+ pub pause_extraction_on_input_ms: u64,+// ── Filters ────────────────────────────────────────────────────────/// Window titles to exclude from capture.#[serde(rename = "ignoredWindows")]@@ -442,6 +464,9 @@ impl Default for RecordingSettings {visual_check_interval_ms: None,visual_change_threshold: None,min_capture_interval_ms: None,+ prioritize_input_latency: false,+ extraction_thread_priority: default_extraction_thread_priority(),+ pause_extraction_on_input_ms: default_pause_extraction_on_input_ms(),ignored_windows: vec![],included_windows: vec![],ignored_urls: vec![],@@ -496,6 +521,14 @@ fn default_max_snapshot_width() -> u32 {1920}+fn default_extraction_thread_priority() -> String {+ "below_normal".to_string()+}++fn default_pause_extraction_on_input_ms() -> u64 {+ 150+}+fn default_pii_backend() -> String {"local".to_string()}diff --git a/crates/screenpipe-engine/src/cli/mod.rs b/crates/screenpipe-engine/src/cli/mod.rsindex 1f6803cf7..7081680bf 100644--- a/crates/screenpipe-engine/src/cli/mod.rs+++ b/crates/screenpipe-engine/src/cli/mod.rs@@ -428,6 +428,28 @@ pub struct RecordArgs {#[arg(long)]pub min_capture_interval_ms: Option<u64>,+ /// Prioritize mouse/keyboard input latency over a11y event metadata completeness.+ /// When enabled, three opt-in optimizations are activated together:+ /// 1. mouse/keyboard hook locks switch to try_lock (contended → app_name/window=None)+ /// 2. a11y extraction threads self-deprioritize via SetThreadPriority+ /// 3. UIA tree captures are skipped within N ms after the most recent input+ /// Fine-tune via --extraction-thread-priority and --pause-extraction-on-input-ms.+ #[arg(long, default_value_t = false)]+ pub prioritize_input_latency: bool,++ /// OS thread priority for a11y extraction threads when --prioritize-input-latency is set.+ /// Lower values yield CPU more aggressively to user input threads. Ignored otherwise.+ /// Values: "normal" / "below_normal" / "lowest" / "idle".+ #[arg(long, default_value = "below_normal")]+ pub extraction_thread_priority: String,++ /// Skip UIA tree captures within this many ms after the most recent mouse/keyboard input.+ /// 0 disables. Ignored when --prioritize-input-latency is off.+ /// Captures immediately after input are likely to be stale (next input is imminent),+ /// so skipping costs little data and frees CPU for input responsiveness.+ #[arg(long, default_value_t = 150)]+ pub pause_extraction_on_input_ms: u64,+/// Enable cloud sync#[arg(long, default_value_t = false)]pub enable_sync: bool,@@ -701,6 +723,9 @@ impl RecordArgs {visual_check_interval_ms: self.visual_check_interval_ms,visual_change_threshold: self.visual_change_threshold,min_capture_interval_ms: self.min_capture_interval_ms,+ prioritize_input_latency: self.prioritize_input_latency,+ extraction_thread_priority: self.extraction_thread_priority.clone(),+ pause_extraction_on_input_ms: self.pause_extraction_on_input_ms,analytics_enabled: !self.disable_telemetry,ignore_incognito_windows: true,pause_on_drm_content: self.pause_on_drm_content,diff --git a/crates/screenpipe-engine/src/recording_config.rs b/crates/screenpipe-engine/src/recording_config.rsindex eafa3cc65..cd5979977 100644--- a/crates/screenpipe-engine/src/recording_config.rs+++ b/crates/screenpipe-engine/src/recording_config.rs@@ -152,6 +152,14 @@ pub struct RecordingConfig {pub visual_change_threshold: Option<f64>,pub min_capture_interval_ms: Option<u64>,+ /// Prioritize input latency over a11y event completeness.+ /// See `RecordingSettings.prioritize_input_latency` for details.+ pub prioritize_input_latency: bool,+ /// A11y extraction thread priority ("normal"/"below_normal"/"lowest"/"idle").+ pub extraction_thread_priority: String,+ /// Skip UIA tree captures within this many ms after the most recent input.+ pub pause_extraction_on_input_ms: u64,+/// Require authentication for remote (non-localhost) API access./// When true, requests from other devices must include/// `Authorization: Bearer <SCREENPIPE_API_KEY>`.@@ -295,6 +303,9 @@ impl RecordingConfig {visual_check_interval_ms: settings.visual_check_interval_ms,visual_change_threshold: settings.visual_change_threshold,min_capture_interval_ms: settings.min_capture_interval_ms,+ prioritize_input_latency: settings.prioritize_input_latency,+ extraction_thread_priority: settings.extraction_thread_priority.clone(),+ pause_extraction_on_input_ms: settings.pause_extraction_on_input_ms,// LAN exposure is opt-in. We force `api_auth` on whenever// `listen_on_lan` is true so a user can never accidentally// publish an unauthenticated API on their local network. The@@ -323,6 +334,11 @@ impl RecordingConfig {included_windows: self.included_windows.clone(),capture_clipboard: !self.disable_clipboard_capture,capture_clipboard_content: !self.disable_clipboard_capture,+ // Input-latency tuning. `extraction_thread_priority` is parsed from its+ // string form; an unrecognized value falls back to the enum default.+ prioritize_input_latency: self.prioritize_input_latency,+ extraction_thread_priority: self.extraction_thread_priority.parse().unwrap_or_default(),+ pause_extraction_on_input_ms: self.pause_extraction_on_input_ms,..Default::default()}}diff --git a/crates/screenpipe-engine/src/ui_recorder.rs b/crates/screenpipe-engine/src/ui_recorder.rsindex 4110e2faa..a6a087007 100644--- a/crates/screenpipe-engine/src/ui_recorder.rs+++ b/crates/screenpipe-engine/src/ui_recorder.rs@@ -7,7 +7,7 @@//! Integrates screenpipe-a11y capture with the server's recording loop.use anyhow::Result;-use screenpipe_a11y::{UiCaptureConfig, UiRecorder};+use screenpipe_a11y::{ExtractionThreadPriority, UiCaptureConfig, UiRecorder};use screenpipe_db::{DatabaseManager, InsertUiEvent};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;@@ -58,6 +58,15 @@ pub struct UiRecorderConfig {pub tree_walk_interval_ms: u64,/// Record input events to DB (false = still capture for wake signal but don't write)pub record_input_events: bool,+ /// Prioritize input latency over event metadata completeness.+ /// Maps to `UiCaptureConfig.prioritize_input_latency`. See that field for details.+ pub prioritize_input_latency: bool,+ /// OS thread priority for a11y extraction threads (UIA worker, app observer)+ /// when `prioritize_input_latency` is true. Ignored otherwise.+ pub extraction_thread_priority: ExtractionThreadPriority,+ /// Skip UIA tree captures within this many ms after the most recent+ /// mouse/keyboard input. 0 disables. Ignored when `prioritize_input_latency` is false.+ pub pause_extraction_on_input_ms: u64,}impl Default for UiRecorderConfig {@@ -83,6 +92,9 @@ impl Default for UiRecorderConfig {enable_tree_walker: true,tree_walk_interval_ms: 3000,record_input_events: true,+ prioritize_input_latency: false,+ extraction_thread_priority: ExtractionThreadPriority::BelowNormal,+ pause_extraction_on_input_ms: 150,}}}@@ -102,6 +114,9 @@ impl UiRecorderConfig {config.capture_window_focus = self.capture_window_focus;config.capture_scroll = self.capture_scroll;config.capture_context = self.capture_context;+ config.prioritize_input_latency = self.prioritize_input_latency;+ config.extraction_thread_priority = self.extraction_thread_priority;+ config.pause_extraction_on_input_ms = self.pause_extraction_on_input_ms;// Add excluded appsfor app in &self.excluded_apps {