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(ui-events): add UI input capture as third modality (#2151)
Louis Beaumont8b1bae574ac0
diff --git a/Cargo.lock b/Cargo.lockindex 649af74a2..8e543958d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1175,6 +1175,18 @@ dependencies = ["half",]+[[package]]+name = "cidre"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aeb5b1ace98faf1a55e3631d63427f267897cfab7b65b1d5928cb0b8e6a4a194"+dependencies = [+ "cidre-macros",+ "half",+ "parking_lot",+ "tokio",+]+[[package]]name = "cidre"version = "0.13.1"@@ -1612,7 +1624,7 @@ version = "0.15.3"source = "git+https://github.com/louis030195/cpal.git?branch=main#c3eaee9cb793c90ec54da63f50908c2cb6ce95a7"dependencies = ["alsa",- "cidre",+ "cidre 0.13.1 (git+https://github.com/yury/cidre.git)","core-foundation-sys 0.8.7","coreaudio-rs","dasp_sample",@@ -6632,7 +6644,7 @@ name = "sck-rs"version = "0.1.0"source = "git+https://github.com/louis030195/sck-rs#f3667badac256c097ee616e452c9acf0708b6516"dependencies = [- "cidre",+ "cidre 0.13.1 (git+https://github.com/yury/cidre.git)","core-foundation 0.10.0","core-graphics 0.24.0","image",@@ -6654,6 +6666,25 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"+[[package]]+name = "screenpipe-accessibility"+version = "0.1.0"+dependencies = [+ "anyhow",+ "chrono",+ "cidre 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",+ "crossbeam-channel",+ "parking_lot",+ "rdev",+ "regex",+ "screenpipe-db",+ "serde",+ "serde_json",+ "tokio",+ "tracing",+ "windows 0.58.0",+]+[[package]]name = "screenpipe-audio"version = "0.3.7"@@ -6828,7 +6859,7 @@ dependencies = ["candle-nn","candle-transformers","chrono",- "cidre",+ "cidre 0.13.1 (git+https://github.com/yury/cidre.git)","clap","clap_complete","colored",@@ -6854,6 +6885,7 @@ dependencies = ["regex","reqwest 0.12.12","rust-stemmers",+ "screenpipe-accessibility","screenpipe-audio","screenpipe-core","screenpipe-db",@@ -6892,7 +6924,7 @@ dependencies = ["atspi-proxies","base64 0.22.1","chrono",- "cidre",+ "cidre 0.13.1 (git+https://github.com/yury/cidre.git)","clap","core-foundation 0.10.0","criterion",diff --git a/Cargo.toml b/Cargo.tomlindex 0b76899d3..7edd22363 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -7,6 +7,7 @@ members = ["screenpipe-integrations","screenpipe-events","screenpipe-db",+ "screenpipe-accessibility",]exclude = ["screenpipe-app-tauri/src-tauri"]resolver = "2"diff --git a/screenpipe-accessibility/Cargo.toml b/screenpipe-accessibility/Cargo.tomlnew file mode 100644index 000000000..faa5495fa--- /dev/null+++ b/screenpipe-accessibility/Cargo.toml@@ -0,0 +1,46 @@+[package]+name = "screenpipe-accessibility"+version = "0.1.0"+edition = "2021"+description = "Accessibility and UI event capture for screenpipe - keyboard, mouse, clipboard"+license = "MIT"++[features]+default = []+db = ["screenpipe-db"]++[dependencies]+screenpipe-db = { path = "../screenpipe-db", optional = true }+# Core+anyhow = "1.0"+tracing = "0.1"+chrono = { version = "0.4", features = ["serde"] }++# Serialization+serde = { version = "1.0", features = ["derive"] }+serde_json = "1.0"++# Concurrency+crossbeam-channel = "0.5"+parking_lot = "0.12"++# Regex for privacy patterns+regex = "1.10"++[target.'cfg(target_os = "macos")'.dependencies]+cidre = { version = "0.13", features = ["ax", "cg", "blocks", "ns", "app"] }++[target.'cfg(target_os = "windows")'.dependencies]+rdev = "0.5"+windows = { version = "0.58", features = [+ "Win32_Foundation",+ "Win32_System_Com",+ "Win32_System_Threading",+ "Win32_UI_Accessibility",+ "Win32_UI_WindowsAndMessaging",+ "Win32_UI_Input_KeyboardAndMouse",+ "Win32_Graphics_Gdi",+] }++[dev-dependencies]+tokio = { version = "1", features = ["rt-multi-thread", "macros"] }diff --git a/screenpipe-accessibility/src/config.rs b/screenpipe-accessibility/src/config.rsnew file mode 100644index 000000000..94a7f77cb--- /dev/null+++ b/screenpipe-accessibility/src/config.rs@@ -0,0 +1,279 @@+//! Configuration for UI event capture+//!+//! Provides settings for what to capture, privacy filters, and performance tuning.++use regex::Regex;+use serde::{Deserialize, Serialize};++/// Configuration for UI event capture+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct UiCaptureConfig {+ /// Enable UI event capture+ pub enabled: bool,++ // === Capture Settings ===+ /// Capture mouse clicks+ pub capture_clicks: bool,++ /// Capture aggregated text input+ pub capture_text: bool,++ /// Capture individual keystrokes (privacy risk - disabled by default)+ pub capture_keystrokes: bool,++ /// Capture app switches+ pub capture_app_switch: bool,++ /// Capture window focus changes+ pub capture_window_focus: bool,++ /// Capture clipboard operations+ pub capture_clipboard: bool,++ /// Capture clipboard content (privacy risk - disabled by default)+ pub capture_clipboard_content: bool,++ /// Capture element context on clicks (slower but richer)+ pub capture_context: bool,++ /// Capture mouse movement (high volume - disabled by default)+ pub capture_mouse_move: bool,++ /// Mouse move threshold in pixels (higher = fewer events)+ pub mouse_move_threshold: f64,++ /// Text aggregation timeout in milliseconds+ pub text_timeout_ms: u64,++ /// Maximum events to buffer before backpressure+ pub max_buffer_size: usize,++ // === Privacy Settings ===+ /// Auto-detect and skip password fields+ pub skip_password_fields: bool,++ /// Apply PII removal to captured text+ pub apply_pii_removal: bool,++ /// Skip secure input mode (macOS)+ pub skip_secure_input: bool,++ /// Apps to exclude from capture (case-insensitive substring match)+ pub excluded_apps: Vec<String>,++ /// Window title patterns to exclude (regex)+ #[serde(skip)]+ pub excluded_window_patterns: Vec<Regex>,++ /// Raw patterns for serialization+ pub excluded_window_pattern_strings: Vec<String>,++ // === Retention Settings ===+ /// Days to keep UI events+ pub retention_days: u32,++ /// Hours to keep clipboard content+ pub clipboard_retention_hours: u32,+}++impl Default for UiCaptureConfig {+ fn default() -> Self {+ Self {+ enabled: true,++ // Capture settings - safe defaults+ capture_clicks: true,+ capture_text: true,+ capture_keystrokes: false, // Privacy risk+ capture_app_switch: true,+ capture_window_focus: true,+ capture_clipboard: true,+ capture_clipboard_content: false, // Privacy risk+ capture_context: true,+ capture_mouse_move: false, // High volume+ mouse_move_threshold: 5.0,+ text_timeout_ms: 300,+ max_buffer_size: 10000,++ // Privacy settings - secure defaults+ skip_password_fields: true,+ apply_pii_removal: true,+ skip_secure_input: true,+ excluded_apps: vec![+ "1Password".to_string(),+ "Bitwarden".to_string(),+ "LastPass".to_string(),+ "Dashlane".to_string(),+ "KeePassXC".to_string(),+ "Keychain Access".to_string(),+ "Credential Manager".to_string(),+ ],+ excluded_window_patterns: Vec::new(),+ excluded_window_pattern_strings: vec![+ r"(?i).*password.*".to_string(),+ r"(?i).*private.*".to_string(),+ r"(?i).*incognito.*".to_string(),+ r"(?i).*secret.*".to_string(),+ ],++ // Retention+ retention_days: 30,+ clipboard_retention_hours: 24,+ }+ }+}++impl UiCaptureConfig {+ /// Create a new config with defaults+ pub fn new() -> Self {+ let mut config = Self::default();+ config.compile_patterns();+ config+ }++ /// Compile regex patterns from strings+ pub fn compile_patterns(&mut self) {+ self.excluded_window_patterns = self+ .excluded_window_pattern_strings+ .iter()+ .filter_map(|s| Regex::new(s).ok())+ .collect();+ }++ /// Check if an app should be captured+ pub fn should_capture_app(&self, app_name: &str) -> bool {+ if !self.enabled {+ return false;+ }++ let app_lower = app_name.to_lowercase();+ !self+ .excluded_apps+ .iter()+ .any(|excluded| app_lower.contains(&excluded.to_lowercase()))+ }++ /// Check if a window should be captured+ pub fn should_capture_window(&self, window_title: &str) -> bool {+ if !self.enabled {+ return false;+ }++ !self+ .excluded_window_patterns+ .iter()+ .any(|pattern| pattern.is_match(window_title))+ }++ /// Check if element appears to be a password field+ pub fn is_password_field(&self, role: Option<&str>, name: Option<&str>) -> bool {+ if !self.skip_password_fields {+ return false;+ }++ // Role-based detection+ if let Some(r) = role {+ if r == "AXSecureTextField" || r == "PasswordBox" || r.contains("Password") {+ return true;+ }+ }++ // Name-based detection+ if let Some(n) = name {+ let name_lower = n.to_lowercase();+ let password_patterns = [+ "password",+ "passwd",+ "passwort",+ "contraseña",+ "mot de passe",+ "pin",+ "secret",+ "credential",+ "passphrase",+ "master key",+ "api key",+ "access token",+ ];+ if password_patterns.iter().any(|p| name_lower.contains(p)) {+ return true;+ }+ }++ false+ }++ /// Builder pattern: set excluded apps+ pub fn with_excluded_apps(mut self, apps: Vec<String>) -> Self {+ self.excluded_apps = apps;+ self+ }++ /// Builder pattern: set capture options+ pub fn with_capture(+ mut self,+ clicks: bool,+ text: bool,+ app_switch: bool,+ clipboard: bool,+ ) -> Self {+ self.capture_clicks = clicks;+ self.capture_text = text;+ self.capture_app_switch = app_switch;+ self.capture_clipboard = clipboard;+ self+ }++ /// Builder pattern: enable mouse move capture+ pub fn with_mouse_move(mut self, enabled: bool, threshold: f64) -> Self {+ self.capture_mouse_move = enabled;+ self.mouse_move_threshold = threshold;+ self+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_default_config() {+ let config = UiCaptureConfig::new();+ assert!(config.enabled);+ assert!(config.capture_clicks);+ assert!(!config.capture_keystrokes); // Should be off by default+ assert!(!config.capture_clipboard_content); // Should be off by default+ }++ #[test]+ fn test_app_exclusion() {+ let config = UiCaptureConfig::new();+ assert!(!config.should_capture_app("1Password"));+ assert!(!config.should_capture_app("1password 7"));+ assert!(!config.should_capture_app("Bitwarden"));+ assert!(config.should_capture_app("Chrome"));+ assert!(config.should_capture_app("Visual Studio Code"));+ }++ #[test]+ fn test_window_exclusion() {+ let mut config = UiCaptureConfig::new();+ config.compile_patterns();++ assert!(!config.should_capture_window("Enter Password - Chrome"));+ assert!(!config.should_capture_window("Private Browsing - Safari"));+ assert!(!config.should_capture_window("Incognito - Chrome"));+ assert!(config.should_capture_window("GitHub - Chrome"));+ }++ #[test]+ fn test_password_field_detection() {+ let config = UiCaptureConfig::new();++ assert!(config.is_password_field(Some("AXSecureTextField"), None));+ assert!(config.is_password_field(Some("PasswordBox"), None));+ assert!(config.is_password_field(None, Some("Enter Password")));+ assert!(config.is_password_field(None, Some("API Key")));+ assert!(!config.is_password_field(Some("AXTextField"), Some("Email")));+ }+}diff --git a/screenpipe-accessibility/src/events.rs b/screenpipe-accessibility/src/events.rsnew file mode 100644index 000000000..e86a7fa33--- /dev/null+++ b/screenpipe-accessibility/src/events.rs@@ -0,0 +1,600 @@+//! UI Event types optimized for storage and AI consumption+//!+//! Events are stored as simple structs that serialize to compact JSON.+//! Based on bigbrother's event format with extensions for screenpipe integration.++use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};++/// A UI event with full context+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct UiEvent {+ /// Unique event ID (assigned by database)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub id: Option<i64>,++ /// UTC timestamp+ pub timestamp: DateTime<Utc>,++ /// Milliseconds since recording session start+ pub relative_ms: u64,++ /// Event type and data+ #[serde(flatten)]+ pub data: EventData,++ /// Application context+ #[serde(skip_serializing_if = "Option::is_none")]+ pub app_name: Option<String>,++ /// Window title+ #[serde(skip_serializing_if = "Option::is_none")]+ pub window_title: Option<String>,++ /// Browser URL (for browser windows)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub browser_url: Option<String>,++ /// Element context at event position+ #[serde(skip_serializing_if = "Option::is_none")]+ pub element: Option<ElementContext>,++ /// Associated screenshot frame ID+ #[serde(skip_serializing_if = "Option::is_none")]+ pub frame_id: Option<i64>,+}++/// Event data - tagged union for different event types+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(tag = "event_type")]+pub enum EventData {+ /// Mouse click+ #[serde(rename = "click")]+ Click {+ x: i32,+ y: i32,+ /// Button: 0=left, 1=right, 2=middle+ button: u8,+ /// Click count: 1=single, 2=double, 3=triple+ click_count: u8,+ /// Modifier keys packed: 1=shift, 2=ctrl, 4=opt, 8=cmd+ modifiers: u8,+ },++ /// Mouse move (throttled)+ #[serde(rename = "move")]+ Move { x: i32, y: i32 },++ /// Mouse scroll+ #[serde(rename = "scroll")]+ Scroll {+ x: i32,+ y: i32,+ delta_x: i16,+ delta_y: i16,+ },++ /// Key press (for shortcuts/special keys)+ #[serde(rename = "key")]+ Key {+ /// Platform-specific keycode+ key_code: u16,+ /// Modifier keys packed+ modifiers: u8,+ },++ /// Aggregated text input+ #[serde(rename = "text")]+ Text {+ /// The typed text+ content: String,+ /// Number of characters+ #[serde(skip_serializing_if = "Option::is_none")]+ char_count: Option<usize>,+ },++ /// Application activated+ #[serde(rename = "app_switch")]+ AppSwitch {+ /// Application name+ name: String,+ /// Process ID+ pid: i32,+ },++ /// Window focused+ #[serde(rename = "window_focus")]+ WindowFocus {+ /// Application name+ app: String,+ /// Window title+ #[serde(skip_serializing_if = "Option::is_none")]+ title: Option<String>,+ },++ /// Clipboard operation+ #[serde(rename = "clipboard")]+ Clipboard {+ /// Operation: 'c'=copy, 'x'=cut, 'v'=paste+ operation: char,+ /// Content preview (truncated)+ #[serde(skip_serializing_if = "Option::is_none")]+ content: Option<String>,+ },+}++/// Element context from accessibility API+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ElementContext {+ /// Accessibility role (e.g., "AXButton", "AXTextField")+ pub role: String,++ /// Element name/label+ #[serde(skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,++ /// Element value (for inputs)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub value: Option<String>,++ /// Element description+ #[serde(skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,++ /// Automation ID (Windows)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub automation_id: Option<String>,++ /// Bounding rectangle+ #[serde(skip_serializing_if = "Option::is_none")]+ pub bounds: Option<ElementBounds>,+}++/// Element bounding rectangle+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ElementBounds {+ pub x: f64,+ pub y: f64,+ pub width: f64,+ pub height: f64,+}++/// Modifier key flags+#[derive(Debug, Clone, Copy, Default)]+pub struct Modifiers(pub u8);++impl Modifiers {+ pub const SHIFT: u8 = 1 << 0;+ pub const CTRL: u8 = 1 << 1;+ pub const OPT: u8 = 1 << 2; // Alt on Windows/Linux+ pub const CMD: u8 = 1 << 3; // Win on Windows, Super on Linux+ pub const CAPS: u8 = 1 << 4;+ pub const FN: u8 = 1 << 5;++ pub fn new() -> Self {+ Self(0)+ }++ pub fn has_shift(&self) -> bool {+ self.0 & Self::SHIFT != 0+ }+ pub fn has_ctrl(&self) -> bool {+ self.0 & Self::CTRL != 0+ }+ pub fn has_opt(&self) -> bool {+ self.0 & Self::OPT != 0+ }+ pub fn has_cmd(&self) -> bool {+ self.0 & Self::CMD != 0+ }+ pub fn any_modifier(&self) -> bool {+ self.0 & (Self::CMD | Self::CTRL) != 0+ }++ #[cfg(target_os = "macos")]+ pub fn from_cg_flags(flags: u64) -> Self {+ let mut m = 0u8;+ if flags & 0x20000 != 0 {+ m |= Self::SHIFT;+ }+ if flags & 0x40000 != 0 {+ m |= Self::CTRL;+ }+ if flags & 0x80000 != 0 {+ m |= Self::OPT;+ }+ if flags & 0x100000 != 0 {+ m |= Self::CMD;+ }+ if flags & 0x10000 != 0 {+ m |= Self::CAPS;+ }+ if flags & 0x800000 != 0 {+ m |= Self::FN;+ }+ Self(m)+ }+}++impl UiEvent {+ /// Create a new click event+ pub fn click(+ timestamp: DateTime<Utc>,+ relative_ms: u64,+ x: i32,+ y: i32,+ button: u8,+ click_count: u8,+ modifiers: u8,+ ) -> Self {+ Self {+ id: None,+ timestamp,+ relative_ms,+ data: EventData::Click {+ x,+ y,+ button,+ click_count,+ modifiers,+ },+ app_name: None,+ window_title: None,+ browser_url: None,+ element: None,+ frame_id: None,+ }+ }++ /// Create a new text event+ pub fn text(timestamp: DateTime<Utc>, relative_ms: u64, content: String) -> Self {+ let char_count = Some(content.chars().count());+ Self {+ id: None,+ timestamp,+ relative_ms,+ data: EventData::Text {+ content,+ char_count,+ },+ app_name: None,+ window_title: None,+ browser_url: None,+ element: None,+ frame_id: None,+ }+ }++ /// Create an app switch event+ pub fn app_switch(timestamp: DateTime<Utc>, relative_ms: u64, name: String, pid: i32) -> Self {+ Self {+ id: None,+ timestamp,+ relative_ms,+ data: EventData::AppSwitch { name, pid },+ app_name: None,+ window_title: None,+ browser_url: None,+ element: None,+ frame_id: None,+ }+ }++ /// Get the event type as a string+ pub fn event_type(&self) -> &'static str {+ match &self.data {+ EventData::Click { .. } => "click",+ EventData::Move { .. } => "move",+ EventData::Scroll { .. } => "scroll",+ EventData::Key { .. } => "key",+ EventData::Text { .. } => "text",+ EventData::AppSwitch { .. } => "app_switch",+ EventData::WindowFocus { .. } => "window_focus",+ EventData::Clipboard { .. } => "clipboard",+ }+ }++ /// Get text content if this is a text event+ pub fn text_content(&self) -> Option<&str> {+ match &self.data {+ EventData::Text { content, .. } => Some(content),+ EventData::Clipboard {+ content: Some(c), ..+ } => Some(c),+ _ => None,+ }+ }++ /// Set element context+ pub fn with_element(mut self, element: ElementContext) -> Self {+ self.element = Some(element);+ self+ }++ /// Set app context+ pub fn with_app(mut self, app_name: String, window_title: Option<String>) -> Self {+ self.app_name = Some(app_name);+ self.window_title = window_title;+ self+ }++ /// Set frame ID+ pub fn with_frame(mut self, frame_id: i64) -> Self {+ self.frame_id = Some(frame_id);+ self+ }+}++/// Event type for database filtering+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum EventType {+ Click,+ Move,+ Scroll,+ Key,+ Text,+ AppSwitch,+ WindowFocus,+ Clipboard,+}++impl EventType {+ pub fn as_str(&self) -> &'static str {+ match self {+ EventType::Click => "click",+ EventType::Move => "move",+ EventType::Scroll => "scroll",+ EventType::Key => "key",+ EventType::Text => "text",+ EventType::AppSwitch => "app_switch",+ EventType::WindowFocus => "window_focus",+ EventType::Clipboard => "clipboard",+ }+ }++ pub fn from_str(s: &str) -> Option<Self> {+ match s {+ "click" | "c" => Some(EventType::Click),+ "move" | "m" => Some(EventType::Move),+ "scroll" | "s" => Some(EventType::Scroll),+ "key" | "k" => Some(EventType::Key),+ "text" | "t" => Some(EventType::Text),+ "app_switch" | "app" | "a" => Some(EventType::AppSwitch),+ "window_focus" | "window" | "w" => Some(EventType::WindowFocus),+ "clipboard" | "paste" | "p" => Some(EventType::Clipboard),+ _ => None,+ }+ }+}++// ============================================================================+// Database Conversion (optional feature)+// ============================================================================++#[cfg(feature = "db")]+impl UiEvent {+ /// Convert to database insert format+ pub fn to_db_insert(&self, session_id: Option<String>) -> screenpipe_db::InsertUiEvent {+ use screenpipe_db::{InsertUiEvent, UiEventType};++ let (+ event_type,+ x,+ y,+ delta_x,+ delta_y,+ button,+ click_count,+ key_code,+ modifiers,+ text_content,+ app_pid,+ ) = match &self.data {+ EventData::Click {+ x,+ y,+ button,+ click_count,+ modifiers,+ } => (+ UiEventType::Click,+ Some(*x),+ Some(*y),+ None,+ None,+ Some(*button),+ Some(*click_count),+ None,+ Some(*modifiers),+ None,+ None,+ ),+ EventData::Move { x, y } => (+ UiEventType::Move,+ Some(*x),+ Some(*y),+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ ),+ EventData::Scroll {+ x,+ y,+ delta_x,+ delta_y,+ } => (+ UiEventType::Scroll,+ Some(*x),+ Some(*y),+ Some(*delta_x),+ Some(*delta_y),+ None,+ None,+ None,+ None,+ None,+ None,+ ),+ EventData::Key {+ key_code,+ modifiers,+ } => (+ UiEventType::Key,+ None,+ None,+ None,+ None,+ None,+ None,+ Some(*key_code),+ Some(*modifiers),+ None,+ None,+ ),+ EventData::Text { content, .. } => (+ UiEventType::Text,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ Some(content.clone()),+ None,+ ),+ EventData::AppSwitch { name: _, pid } => (+ UiEventType::AppSwitch,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ Some(*pid),+ ),+ EventData::WindowFocus { app: _, title } => (+ UiEventType::WindowFocus,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ title.clone(),+ None,+ ),+ EventData::Clipboard { operation, content } => (+ UiEventType::Clipboard,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ Some(*operation as u8),+ content.clone(),+ None,+ ),+ };++ let (+ element_role,+ element_name,+ element_value,+ element_description,+ element_automation_id,+ element_bounds,+ ) = if let Some(ref elem) = self.element {+ (+ Some(elem.role.clone()),+ elem.name.clone(),+ elem.value.clone(),+ elem.description.clone(),+ elem.automation_id.clone(),+ elem.bounds.as_ref().map(|b| {+ serde_json::json!({+ "x": b.x,+ "y": b.y,+ "width": b.width,+ "height": b.height+ })+ .to_string()+ }),+ )+ } else {+ (None, None, None, None, None, None)+ };++ InsertUiEvent {+ timestamp: self.timestamp,+ session_id,+ relative_ms: self.relative_ms as i64,+ event_type,+ x,+ y,+ delta_x,+ delta_y,+ button,+ click_count,+ key_code,+ modifiers,+ text_content,+ app_name: self.app_name.clone(),+ app_pid,+ window_title: self.window_title.clone(),+ browser_url: self.browser_url.clone(),+ element_role,+ element_name,+ element_value,+ element_description,+ element_automation_id,+ element_bounds,+ frame_id: self.frame_id,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_event_serialization() {+ let event = UiEvent::click(Utc::now(), 100, 500, 300, 0, 1, 0);++ let json = serde_json::to_string(&event).unwrap();+ assert!(json.contains("\"event_type\":\"click\""));+ assert!(json.contains("\"x\":500"));+ }++ #[test]+ fn test_modifiers() {+ let mods = Modifiers(Modifiers::SHIFT | Modifiers::CMD);+ assert!(mods.has_shift());+ assert!(mods.has_cmd());+ assert!(!mods.has_ctrl());+ assert!(mods.any_modifier());+ }++ #[test]+ fn test_event_type_parsing() {+ assert_eq!(EventType::from_str("click"), Some(EventType::Click));+ assert_eq!(EventType::from_str("c"), Some(EventType::Click));+ assert_eq!(EventType::from_str("text"), Some(EventType::Text));+ assert_eq!(EventType::from_str("invalid"), None);+ }+}diff --git a/screenpipe-accessibility/src/lib.rs b/screenpipe-accessibility/src/lib.rsnew file mode 100644index 000000000..23bfcde9c--- /dev/null+++ b/screenpipe-accessibility/src/lib.rs@@ -0,0 +1,92 @@+//! screenpipe-accessibility: Cross-platform UI event capture for screenpipe+//!+//! This crate provides keyboard, mouse, and accessibility-based UI event capture+//! as a third modality for screenpipe, complementing vision (OCR) and audio.+//!+//! ## Features+//!+//! - **Mouse events**: Clicks, scrolls, movements (throttled)+//! - **Keyboard events**: Aggregated text input, hotkeys+//! - **App/Window tracking**: Application switches, window focus changes+//! - **Clipboard**: Copy/cut/paste operations+//! - **Element context**: Accessibility information for clicked elements+//!+//! ## Platform Support+//!+//! - **macOS**: Full support via CGEventTap and Accessibility APIs+//! - **Windows**: Full support via rdev and UI Automation+//! - **Linux**: Stub (planned via AT-SPI2 and XRecord)+//!+//! ## Privacy+//!+//! The crate includes built-in privacy controls:+//! - Password field detection and exclusion+//! - App/window exclusion patterns+//! - PII removal integration+//! - Configurable capture options+//!+//! ## Example+//!+//! ```rust,no_run+//! use screenpipe_accessibility::{UiRecorder, UiCaptureConfig};+//!+//! let config = UiCaptureConfig::new();+//! let recorder = UiRecorder::new(config);+//!+//! // Check permissions+//! let perms = recorder.check_permissions();+//! if !perms.all_granted() {+//! recorder.request_permissions();+//! }+//!+//! // Start capturing+//! let handle = recorder.start().unwrap();+//!+//! // Process events+//! while let Some(event) = handle.recv_timeout(std::time::Duration::from_secs(1)) {+//! println!("{:?}", event);+//! }+//!+//! handle.stop();+//! ```++pub mod config;+pub mod events;+pub mod platform;++// Re-exports+pub use config::UiCaptureConfig;+pub use events::{ElementBounds, ElementContext, EventData, EventType, Modifiers, UiEvent};+pub use platform::{PermissionStatus, RecordingHandle, UiRecorder};++/// Prelude for convenient imports+pub mod prelude {+ pub use crate::config::UiCaptureConfig;+ pub use crate::events::{ElementContext, EventData, EventType, UiEvent};+ pub use crate::platform::{PermissionStatus, RecordingHandle, UiRecorder};+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_config_defaults() {+ let config = UiCaptureConfig::new();+ assert!(config.enabled);+ assert!(config.capture_clicks);+ assert!(!config.capture_keystrokes); // Off by default for privacy+ }++ #[test]+ fn test_event_creation() {+ use chrono::Utc;++ let event = UiEvent::click(Utc::now(), 100, 500, 300, 0, 1, 0);+ assert_eq!(event.event_type(), "click");++ let event = UiEvent::text(Utc::now(), 200, "hello".to_string());+ assert_eq!(event.event_type(), "text");+ assert_eq!(event.text_content(), Some("hello"));+ }+}diff --git a/screenpipe-accessibility/src/platform/macos.rs b/screenpipe-accessibility/src/platform/macos.rsnew file mode 100644index 000000000..9d7be37e4--- /dev/null+++ b/screenpipe-accessibility/src/platform/macos.rs@@ -0,0 +1,970 @@+//! macOS UI event capture using CGEventTap and Accessibility APIs+//!+//! Based on bigbrother's implementation with screenpipe-specific enhancements.++use crate::config::UiCaptureConfig;+use crate::events::{ElementContext, EventData, Modifiers, UiEvent};+use anyhow::Result;+use chrono::Utc;+use crossbeam_channel::{bounded, Receiver, Sender};+use parking_lot::Mutex;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::thread;+use std::time::Instant;+use tracing::{debug, error};++use cidre::cg::event::access as cg_access;+use cidre::{ax, cf, cg, ns};++// Keycodes for clipboard operations (macOS)+const KEY_C: u16 = 8;+const KEY_X: u16 = 7;+const KEY_V: u16 = 9;++/// Permission status for UI capture+#[derive(Debug, Clone)]+pub struct PermissionStatus {+ pub accessibility: bool,+ pub input_monitoring: bool,+}++impl PermissionStatus {+ pub fn all_granted(&self) -> bool {+ self.accessibility && self.input_monitoring+ }+}++/// UI Event recorder for macOS+pub struct UiRecorder {+ config: UiCaptureConfig,+}++/// Handle to a running recording session+pub struct RecordingHandle {+ stop: Arc<AtomicBool>,+ events_rx: Receiver<UiEvent>,+ threads: Vec<thread::JoinHandle<()>>,+}++impl RecordingHandle {+ /// Stop the recording+ pub fn stop(self) {+ self.stop.store(true, Ordering::SeqCst);+ for t in self.threads {+ let _ = t.join();+ }+ }++ /// Check if still running+ pub fn is_running(&self) -> bool {+ !self.stop.load(Ordering::Relaxed)+ }++ /// Get the event receiver+ pub fn receiver(&self) -> &Receiver<UiEvent> {+ &self.events_rx+ }++ /// Try to receive an event without blocking+ pub fn try_recv(&self) -> Option<UiEvent> {+ self.events_rx.try_recv().ok()+ }++ /// Receive an event, blocking+ pub fn recv(&self) -> Option<UiEvent> {+ self.events_rx.recv().ok()+ }++ /// Receive with timeout+ pub fn recv_timeout(&self, timeout: std::time::Duration) -> Option<UiEvent> {+ self.events_rx.recv_timeout(timeout).ok()+ }+}++impl UiRecorder {+ /// Create a new recorder with the given config+ pub fn new(config: UiCaptureConfig) -> Self {+ Self { config }+ }++ /// Create with default config+ pub fn with_defaults() -> Self {+ Self::new(UiCaptureConfig::new())+ }++ /// Check current permission status+ pub fn check_permissions(&self) -> PermissionStatus {+ PermissionStatus {+ accessibility: ax::is_process_trusted(),+ input_monitoring: cg_access::listen_preflight(),+ }+ }++ /// Request permissions (shows system dialogs)+ pub fn request_permissions(&self) -> PermissionStatus {+ PermissionStatus {+ accessibility: ax::is_process_trusted_with_prompt(true),+ input_monitoring: cg_access::listen_request(),+ }+ }++ /// Start capturing events+ pub fn start(&self) -> Result<RecordingHandle> {+ let perms = self.check_permissions();+ if !perms.all_granted() {+ anyhow::bail!(+ "Missing permissions - accessibility: {}, input_monitoring: {}",+ perms.accessibility,+ perms.input_monitoring+ );+ }++ let (tx, rx) = bounded::<UiEvent>(self.config.max_buffer_size);+ let stop = Arc::new(AtomicBool::new(false));+ let start_time = Instant::now();++ let mut threads = Vec::new();++ // Thread 1: CGEventTap for input events+ let tx1 = tx.clone();+ let stop1 = stop.clone();+ let config1 = self.config.clone();+ threads.push(thread::spawn(move || {+ run_event_tap(tx1, stop1, start_time, config1);+ }));++ // Thread 2: App/window observer+ let tx2 = tx.clone();+ let stop2 = stop.clone();+ let config2 = self.config.clone();+ threads.push(thread::spawn(move || {+ run_app_observer(tx2, stop2, start_time, config2);+ }));++ Ok(RecordingHandle {+ stop,+ events_rx: rx,+ threads,+ })+ }+}++// ============================================================================+// Event Tap Implementation+// ============================================================================++struct TapState {+ tx: Sender<UiEvent>,+ start: Instant,+ config: UiCaptureConfig,+ last_mouse: Mutex<(f64, f64)>,+ text_buf: Mutex<TextBuffer>,+ current_app: Mutex<Option<String>>,+ current_window: Mutex<Option<String>>,+}++struct TextBuffer {+ chars: String,+ last_time: Option<Instant>,+ timeout_ms: u64,+}++impl TextBuffer {+ fn new(timeout_ms: u64) -> Self {+ Self {+ chars: String::new(),+ last_time: None,+ timeout_ms,+ }+ }++ fn push(&mut self, c: char) {+ if c == '\x08' {+ // Backspace - remove last char+ self.chars.pop();+ } else {+ self.chars.push(c);+ }+ self.last_time = Some(Instant::now());+ }++ fn flush(&mut self) -> Option<String> {+ if self.chars.is_empty() {+ return None;+ }+ let s = std::mem::take(&mut self.chars);+ self.last_time = None;+ Some(s)+ }++ fn should_flush(&self) -> bool {+ self.last_time+ .map(|t| t.elapsed().as_millis() as u64 >= self.timeout_ms)+ .unwrap_or(false)+ }+}++fn run_event_tap(+ tx: Sender<UiEvent>,+ stop: Arc<AtomicBool>,+ start: Instant,+ config: UiCaptureConfig,+) {+ // Build event mask+ let mut mask = cg::EventType::LEFT_MOUSE_DOWN.mask()+ | cg::EventType::LEFT_MOUSE_UP.mask()+ | cg::EventType::RIGHT_MOUSE_DOWN.mask()+ | cg::EventType::RIGHT_MOUSE_UP.mask()+ | cg::EventType::KEY_DOWN.mask()+ | cg::EventType::SCROLL_WHEEL.mask();++ if config.capture_mouse_move {+ mask |= cg::EventType::MOUSE_MOVED.mask()+ | cg::EventType::LEFT_MOUSE_DRAGGED.mask()+ | cg::EventType::RIGHT_MOUSE_DRAGGED.mask();+ }++ let state = Box::leak(Box::new(TapState {+ tx,+ start,+ config: config.clone(),+ last_mouse: Mutex::new((0.0, 0.0)),+ text_buf: Mutex::new(TextBuffer::new(config.text_timeout_ms)),+ current_app: Mutex::new(None),+ current_window: Mutex::new(None),+ }));++ let tap = cg::EventTap::new(+ cg::EventTapLocation::Session,+ cg::EventTapPlacement::TailAppend,+ cg::EventTapOpts::LISTEN_ONLY,+ mask,+ tap_callback,+ state as *mut TapState,+ );++ let Some(tap) = tap else {+ error!("Failed to create CGEventTap");+ return;+ };++ let Some(src) = cf::MachPort::run_loop_src(&tap, 0) else {+ error!("Failed to create run loop source");+ return;+ };++ let rl = cf::RunLoop::current();+ rl.add_src(&src, cf::RunLoopMode::default());++ debug!("Event tap started");++ while !stop.load(Ordering::Relaxed) {+ cf::RunLoop::run_in_mode(cf::RunLoopMode::default(), 0.05, true);++ // Check text buffer timeout+ let mut buf = state.text_buf.lock();+ if buf.should_flush() {+ if let Some(s) = buf.flush() {+ let event = UiEvent::text(Utc::now(), state.start.elapsed().as_millis() as u64, s);+ let _ = state.tx.try_send(event);+ }+ }+ }++ // Final flush+ let mut buf = state.text_buf.lock();+ if let Some(s) = buf.flush() {+ let event = UiEvent::text(Utc::now(), state.start.elapsed().as_millis() as u64, s);+ let _ = state.tx.try_send(event);+ }++ rl.remove_src(&src, cf::RunLoopMode::default());+ debug!("Event tap stopped");+}++extern "C" fn tap_callback(+ _proxy: *mut cg::EventTapProxy,+ event_type: cg::EventType,+ event: &mut cg::Event,+ user_info: *mut TapState,+) -> Option<&cg::Event> {+ let state = unsafe { &*user_info };+ let t = state.start.elapsed().as_millis() as u64;+ let timestamp = Utc::now();+ let loc = event.location();+ let flags = event.flags().0;+ let mods = Modifiers::from_cg_flags(flags);++ // Get current app/window context+ let app_name = state.current_app.lock().clone();+ let window_title = state.current_window.lock().clone();++ // Check if we should capture based on app/window exclusions+ if let Some(ref app) = app_name {+ if !state.config.should_capture_app(app) {+ return Some(event);+ }+ }+ if let Some(ref window) = window_title {+ if !state.config.should_capture_window(window) {+ return Some(event);+ }+ }++ match event_type {+ cg::EventType::LEFT_MOUSE_DOWN | cg::EventType::RIGHT_MOUSE_DOWN => {+ if !state.config.capture_clicks {+ return Some(event);+ }++ let btn = if event_type == cg::EventType::LEFT_MOUSE_DOWN {+ 0+ } else {+ 1+ };+ let clicks = event.field_i64(cg::EventField::MOUSE_EVENT_CLICK_STATE) as u8;++ let mut ui_event = UiEvent::click(+ timestamp,+ t,+ loc.x as i32,+ loc.y as i32,+ btn,+ clicks,+ mods.0,+ );+ ui_event.app_name = app_name.clone();+ ui_event.window_title = window_title.clone();++ let _ = state.tx.try_send(ui_event);++ // Capture element context in background+ if state.config.capture_context {+ let tx = state.tx.clone();+ let x = loc.x;+ let y = loc.y;+ let start = state.start;+ let config = state.config.clone();+ let app = app_name.clone();+ let window = window_title.clone();++ std::thread::spawn(move || {+ if let Some(element) = get_element_at_position(x, y, &config) {+ // Create a context-only event that can be associated with the click+ let ctx_event = UiEvent {+ id: None,+ timestamp: Utc::now(),+ relative_ms: start.elapsed().as_millis() as u64,+ data: EventData::Click {+ x: x as i32,+ y: y as i32,+ button: 0,+ click_count: 0, // Mark as context-only+ modifiers: 0,+ },+ app_name: app,+ window_title: window,+ browser_url: None,+ element: Some(element),+ frame_id: None,+ };+ let _ = tx.try_send(ctx_event);+ }+ });+ }+ }++ cg::EventType::MOUSE_MOVED+ | cg::EventType::LEFT_MOUSE_DRAGGED+ | cg::EventType::RIGHT_MOUSE_DRAGGED => {+ if !state.config.capture_mouse_move {+ return Some(event);+ }++ let mut last = state.last_mouse.lock();+ let dx = loc.x - last.0;+ let dy = loc.y - last.1;+ let dist = (dx * dx + dy * dy).sqrt();++ if dist >= state.config.mouse_move_threshold {+ *last = (loc.x, loc.y);+ let ui_event = UiEvent {+ id: None,+ timestamp,+ relative_ms: t,+ data: EventData::Move {+ x: loc.x as i32,+ y: loc.y as i32,+ },+ app_name,+ window_title,+ browser_url: None,+ element: None,+ frame_id: None,+ };+ let _ = state.tx.try_send(ui_event);+ }+ }++ cg::EventType::SCROLL_WHEEL => {+ let dy = event.field_i64(cg::EventField::SCROLL_WHEEL_EVENT_DELTA_AXIS1) as i16;+ let dx = event.field_i64(cg::EventField::SCROLL_WHEEL_EVENT_DELTA_AXIS2) as i16;+ if dx != 0 || dy != 0 {+ let ui_event = UiEvent {+ id: None,+ timestamp,+ relative_ms: t,+ data: EventData::Scroll {+ x: loc.x as i32,+ y: loc.y as i32,+ delta_x: dx,+ delta_y: dy,+ },+ app_name,+ window_title,+ browser_url: None,+ element: None,+ frame_id: None,+ };+ let _ = state.tx.try_send(ui_event);+ }+ }++ cg::EventType::KEY_DOWN => {+ let keycode = event.field_i64(cg::EventField::KEYBOARD_EVENT_KEYCODE) as u16;++ // Check for clipboard operations (Cmd+C, Cmd+X, Cmd+V)+ if mods.has_cmd() && !mods.has_ctrl() && state.config.capture_clipboard {+ match keycode {+ KEY_C => {+ let tx = state.tx.clone();+ let start = state.start;+ let capture_content = state.config.capture_clipboard_content;+ std::thread::spawn(move || {+ std::thread::sleep(std::time::Duration::from_millis(50));+ let content = if capture_content {+ get_clipboard().map(|s| truncate(&s, 1000))+ } else {+ None+ };+ let event = UiEvent {+ id: None,+ timestamp: Utc::now(),+ relative_ms: start.elapsed().as_millis() as u64,+ data: EventData::Clipboard {+ operation: 'c',+ content,+ },+ app_name: None,+ window_title: None,+ browser_url: None,+ element: None,+ frame_id: None,+ };+ let _ = tx.try_send(event);+ });+ }+ KEY_X => {+ let tx = state.tx.clone();+ let start = state.start;+ let capture_content = state.config.capture_clipboard_content;+ std::thread::spawn(move || {+ std::thread::sleep(std::time::Duration::from_millis(50));+ let content = if capture_content {+ get_clipboard().map(|s| truncate(&s, 1000))+ } else {+ None+ };+ let event = UiEvent {+ id: None,+ timestamp: Utc::now(),+ relative_ms: start.elapsed().as_millis() as u64,+ data: EventData::Clipboard {+ operation: 'x',+ content,+ },+ app_name: None,+ window_title: None,+ browser_url: None,+ element: None,+ frame_id: None,+ };+ let _ = tx.try_send(event);+ });+ }+ KEY_V => {+ let content = if state.config.capture_clipboard_content {+ get_clipboard().map(|s| truncate(&s, 1000))+ } else {+ None+ };+ let event = UiEvent {+ id: None,+ timestamp,+ relative_ms: t,+ data: EventData::Clipboard {+ operation: 'v',+ content,+ },+ app_name: app_name.clone(),+ window_title: window_title.clone(),+ browser_url: None,+ element: None,+ frame_id: None,+ };+ let _ = state.tx.try_send(event);+ }+ _ => {}+ }+ }++ // Record key events for shortcuts+ if mods.any_modifier() {+ let event = UiEvent {+ id: None,+ timestamp,+ relative_ms: t,+ data: EventData::Key {+ key_code: keycode,+ modifiers: mods.0,+ },+ app_name,+ window_title,+ browser_url: None,+ element: None,+ frame_id: None,+ };+ let _ = state.tx.try_send(event);+ } else if state.config.capture_text {+ // Aggregate into text buffer+ if let Some(c) = keycode_to_char(keycode, mods) {+ state.text_buf.lock().push(c);+ } else if state.config.capture_keystrokes {+ // Unknown key, record as key event+ let event = UiEvent {+ id: None,+ timestamp,+ relative_ms: t,+ data: EventData::Key {+ key_code: keycode,+ modifiers: mods.0,+ },+ app_name,+ window_title,+ browser_url: None,+ element: None,+ frame_id: None,+ };+ let _ = state.tx.try_send(event);+ }+ }+ }++ _ => {}+ }++ Some(event)+}++// ============================================================================+// App/Window Observer+// ============================================================================++fn run_app_observer(+ tx: Sender<UiEvent>,+ stop: Arc<AtomicBool>,+ start: Instant,+ config: UiCaptureConfig,+) {+ let workspace = ns::Workspace::shared();++ let mut last_app: Option<String> = None;+ let mut last_pid: i32 = 0;+ let mut last_window: Option<String> = None;++ while !stop.load(Ordering::Relaxed) {+ let apps = workspace.running_apps();+ let active_app = apps.iter().find(|app| app.is_active());++ if let Some(app) = active_app {+ let name = app+ .localized_name()+ .map(|s| s.to_string())+ .unwrap_or_else(|| "?".to_string());+ let pid = app.pid();++ // Check exclusions+ if !config.should_capture_app(&name) {+ std::thread::sleep(std::time::Duration::from_millis(100));+ continue;+ }++ let app_changed = last_app.as_ref() != Some(&name) || last_pid != pid;++ if app_changed && config.capture_app_switch {+ let event = UiEvent::app_switch(+ Utc::now(),+ start.elapsed().as_millis() as u64,+ name.clone(),+ pid,+ );+ let _ = tx.try_send(event);+ last_app = Some(name.clone());+ last_pid = pid;+ }++ // Check window change+ let window_title = get_focused_window_title(pid);++ // Check window exclusions+ let should_capture = window_title+ .as_ref()+ .map(|w| config.should_capture_window(w))+ .unwrap_or(true);++ if should_capture+ && (window_title != last_window || app_changed)+ && config.capture_window_focus+ {+ let event = UiEvent {+ id: None,+ timestamp: Utc::now(),+ relative_ms: start.elapsed().as_millis() as u64,+ data: EventData::WindowFocus {+ app: name,+ title: window_title.clone().map(|s| truncate(&s, 200)),+ },+ app_name: None,+ window_title: None,+ browser_url: None,+ element: None,+ frame_id: None,+ };+ let _ = tx.try_send(event);+ last_window = window_title;+ }+ }++ std::thread::sleep(std::time::Duration::from_millis(100));+ }+}++// ============================================================================+// Accessibility Helpers+// ============================================================================++fn get_element_at_position(x: f64, y: f64, config: &UiCaptureConfig) -> Option<ElementContext> {+ let sys = ax::UiElement::sys_wide();+ let elem = sys.element_at_pos(x as f32, y as f32).ok()?;++ let role = elem.role().ok().map(|r| {+ let s = format!("{:?}", r);+ if let Some(start) = s.find("AX") {+ let rest = &s[start..];+ let end = rest+ .find(|c| c == ')' || c == '"' || c == '}')+ .unwrap_or(rest.len());+ rest[..end].to_string()+ } else {+ "Unknown".to_string()+ }+ })?;++ // Check if this is a password field+ let name = get_string_attr(&elem, ax::attr::title())+ .or_else(|| get_string_attr(&elem, ax::attr::desc()));++ if config.is_password_field(Some(&role), name.as_deref()) {+ // Don't capture value for password fields+ return Some(ElementContext {+ role,+ name: Some("[password field]".to_string()),+ value: None,+ description: None,+ automation_id: None,+ bounds: None,+ });+ }++ let value = get_string_attr(&elem, ax::attr::value());+ let description = get_string_attr(&elem, ax::attr::desc());++ Some(ElementContext {+ role,+ name: name.map(|s| truncate(&s, 200)),+ value: value.map(|s| truncate(&s, 500)),+ description: description.map(|s| truncate(&s, 200)),+ automation_id: None,+ bounds: None,+ })+}++fn get_string_attr(elem: &ax::UiElement, attr: &ax::Attr) -> Option<String> {+ elem.attr_value(attr).ok().and_then(|v| {+ if v.get_type_id() == cf::String::type_id() {+ let s: &cf::String = unsafe { std::mem::transmute(&*v) };+ Some(s.to_string())+ } else {+ None+ }+ })+}++fn get_focused_window_title(pid: i32) -> Option<String> {+ let app = ax::UiElement::with_app_pid(pid);+ let focused = app.attr_value(ax::attr::focused_window()).ok()?;++ if focused.get_type_id() == ax::UiElement::type_id() {+ let window: &ax::UiElement = unsafe { std::mem::transmute(&*focused) };+ get_string_attr(window, ax::attr::title())+ } else {+ None+ }+}++fn get_clipboard() -> Option<String> {+ std::process::Command::new("pbpaste")+ .output()+ .ok()+ .filter(|o| o.status.success())+ .map(|o| String::from_utf8_lossy(&o.stdout).to_string())+ .filter(|s| !s.is_empty())+}++fn truncate(s: &str, max: usize) -> String {+ if s.len() <= max {+ s.to_string()+ } else {+ format!("{}...", &s[..max - 3])+ }+}++// ============================================================================+// Keycode Mapping+// ============================================================================++fn keycode_to_char(keycode: u16, mods: Modifiers) -> Option<char> {+ let shift = mods.0 & Modifiers::SHIFT != 0 || mods.0 & Modifiers::CAPS != 0;++ let c = match keycode {+ // Letters+ 0 => 'a',+ 1 => 's',+ 2 => 'd',+ 3 => 'f',+ 4 => 'h',+ 5 => 'g',+ 6 => 'z',+ 7 => 'x',+ 8 => 'c',+ 9 => 'v',+ 11 => 'b',+ 12 => 'q',+ 13 => 'w',+ 14 => 'e',+ 15 => 'r',+ 16 => 'y',+ 17 => 't',+ 31 => 'o',+ 32 => 'u',+ 34 => 'i',+ 35 => 'p',+ 37 => 'l',+ 38 => 'j',+ 40 => 'k',+ 45 => 'n',+ 46 => 'm',+ // Numbers+ 18 => {+ if shift {+ '!'+ } else {+ '1'+ }+ }+ 19 => {+ if shift {+ '@'+ } else {+ '2'+ }+ }+ 20 => {+ if shift {+ '#'+ } else {+ '3'+ }+ }+ 21 => {+ if shift {+ '$'+ } else {+ '4'+ }+ }+ 22 => {+ if shift {+ '^'+ } else {+ '6'+ }+ }+ 23 => {+ if shift {+ '%'+ } else {+ '5'+ }+ }+ 24 => {+ if shift {+ '+'+ } else {+ '='+ }+ }+ 25 => {+ if shift {+ '('+ } else {+ '9'+ }+ }+ 26 => {+ if shift {+ '&'+ } else {+ '7'+ }+ }+ 27 => {+ if shift {+ '_'+ } else {+ '-'+ }+ }+ 28 => {+ if shift {+ '*'+ } else {+ '8'+ }+ }+ 29 => {+ if shift {+ ')'+ } else {+ '0'+ }+ }+ // Punctuation+ 30 => {+ if shift {+ '}'+ } else {+ ']'+ }+ }+ 33 => {+ if shift {+ '{'+ } else {+ '['+ }+ }+ 39 => {+ if shift {+ '"'+ } else {+ '\''+ }+ }+ 41 => {+ if shift {+ ':'+ } else {+ ';'+ }+ }+ 42 => {+ if shift {+ '|'+ } else {+ '\\'+ }+ }+ 43 => {+ if shift {+ '<'+ } else {+ ','+ }+ }+ 44 => {+ if shift {+ '?'+ } else {+ '/'+ }+ }+ 47 => {+ if shift {+ '>'+ } else {+ '.'+ }+ }+ 50 => {+ if shift {+ '~'+ } else {+ '`'+ }+ }+ // Whitespace+ 36 => '\n',+ 48 => '\t',+ 49 => ' ',+ // Backspace+ 51 => '\x08',+ _ => return None,+ };++ // Handle shift for letters+ if shift && c.is_ascii_lowercase() {+ Some(c.to_ascii_uppercase())+ } else {+ Some(c)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_permission_check() {+ // This will fail without permissions, but should not panic+ let recorder = UiRecorder::with_defaults();+ let perms = recorder.check_permissions();+ // Just verify we get a result+ let _ = perms.all_granted();+ }++ #[test]+ fn test_keycode_mapping() {+ assert_eq!(keycode_to_char(0, Modifiers::new()), Some('a'));+ assert_eq!(keycode_to_char(0, Modifiers(Modifiers::SHIFT)), Some('A'));+ assert_eq!(keycode_to_char(49, Modifiers::new()), Some(' '));+ assert_eq!(keycode_to_char(36, Modifiers::new()), Some('\n'));+ }++ #[test]+ fn test_truncate() {+ assert_eq!(truncate("hello", 10), "hello");+ assert_eq!(truncate("hello world", 8), "hello...");+ }+}diff --git a/screenpipe-accessibility/src/platform/mod.rs b/screenpipe-accessibility/src/platform/mod.rsnew file mode 100644index 000000000..7e5dfb4dc--- /dev/null+++ b/screenpipe-accessibility/src/platform/mod.rs@@ -0,0 +1,90 @@+//! Platform-specific UI event capture implementations++#[cfg(target_os = "macos")]+pub mod macos;++#[cfg(target_os = "windows")]+pub mod windows;++// Re-export platform-specific types with common names+#[cfg(target_os = "macos")]+pub use macos::{PermissionStatus, RecordingHandle, UiRecorder};++#[cfg(target_os = "windows")]+pub use windows::{PermissionStatus, RecordingHandle, UiRecorder};++// Stub for unsupported platforms+#[cfg(not(any(target_os = "macos", target_os = "windows")))]+pub mod stub {+ use crate::config::UiCaptureConfig;+ use crate::events::UiEvent;+ use anyhow::Result;+ use crossbeam_channel::{bounded, Receiver};++ #[derive(Debug, Clone)]+ pub struct PermissionStatus {+ pub accessibility: bool,+ pub input_monitoring: bool,+ }++ impl PermissionStatus {+ pub fn all_granted(&self) -> bool {+ false+ }+ }++ pub struct RecordingHandle {+ events_rx: Receiver<UiEvent>,+ }++ impl RecordingHandle {+ pub fn stop(self) {}+ pub fn is_running(&self) -> bool {+ false+ }+ pub fn receiver(&self) -> &Receiver<UiEvent> {+ &self.events_rx+ }+ pub fn try_recv(&self) -> Option<UiEvent> {+ None+ }+ pub fn recv(&self) -> Option<UiEvent> {+ None+ }+ pub fn recv_timeout(&self, _: std::time::Duration) -> Option<UiEvent> {+ None+ }+ }++ pub struct UiRecorder {+ _config: UiCaptureConfig,+ }++ impl UiRecorder {+ pub fn new(config: UiCaptureConfig) -> Self {+ Self { _config: config }+ }++ pub fn with_defaults() -> Self {+ Self::new(UiCaptureConfig::new())+ }++ pub fn check_permissions(&self) -> PermissionStatus {+ PermissionStatus {+ accessibility: false,+ input_monitoring: false,+ }+ }++ pub fn request_permissions(&self) -> PermissionStatus {+ self.check_permissions()+ }++ pub fn start(&self) -> Result<RecordingHandle> {+ anyhow::bail!("UI event capture not supported on this platform")+ }+ }+}++#[cfg(not(any(target_os = "macos", target_os = "windows")))]+pub use stub::{PermissionStatus, RecordingHandle, UiRecorder};diff --git a/screenpipe-accessibility/src/platform/windows.rs b/screenpipe-accessibility/src/platform/windows.rsnew file mode 100644index 000000000..e7e34111e--- /dev/null+++ b/screenpipe-accessibility/src/platform/windows.rs@@ -0,0 +1,507 @@+//! Windows UI event capture using rdev and UI Automation+//!+//! Based on bigbrother's Windows implementation.++use crate::config::UiCaptureConfig;+use crate::events::{ElementContext, EventData, UiEvent};+use anyhow::Result;+use chrono::Utc;+use crossbeam_channel::{bounded, Receiver, Sender};+use parking_lot::Mutex;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::thread;+use std::time::Instant;+use tracing::{debug, error, warn};++use rdev::{listen, Event as RdevEvent, EventType, Key};++/// Permission status for UI capture+#[derive(Debug, Clone)]+pub struct PermissionStatus {+ pub accessibility: bool,+ pub input_monitoring: bool,+}++impl PermissionStatus {+ pub fn all_granted(&self) -> bool {+ self.accessibility && self.input_monitoring+ }+}++/// UI Event recorder for Windows+pub struct UiRecorder {+ config: UiCaptureConfig,+}++/// Handle to a running recording session+pub struct RecordingHandle {+ stop: Arc<AtomicBool>,+ events_rx: Receiver<UiEvent>,+ threads: Vec<thread::JoinHandle<()>>,+}++impl RecordingHandle {+ pub fn stop(self) {+ self.stop.store(true, Ordering::SeqCst);+ for t in self.threads {+ let _ = t.join();+ }+ }++ pub fn is_running(&self) -> bool {+ !self.stop.load(Ordering::Relaxed)+ }++ pub fn receiver(&self) -> &Receiver<UiEvent> {+ &self.events_rx+ }++ pub fn try_recv(&self) -> Option<UiEvent> {+ self.events_rx.try_recv().ok()+ }++ pub fn recv(&self) -> Option<UiEvent> {+ self.events_rx.recv().ok()+ }++ pub fn recv_timeout(&self, timeout: std::time::Duration) -> Option<UiEvent> {+ self.events_rx.recv_timeout(timeout).ok()+ }+}++impl UiRecorder {+ pub fn new(config: UiCaptureConfig) -> Self {+ Self { config }+ }++ pub fn with_defaults() -> Self {+ Self::new(UiCaptureConfig::new())+ }++ /// Windows doesn't require explicit permissions+ pub fn check_permissions(&self) -> PermissionStatus {+ PermissionStatus {+ accessibility: true,+ input_monitoring: true,+ }+ }++ pub fn request_permissions(&self) -> PermissionStatus {+ self.check_permissions()+ }++ pub fn start(&self) -> Result<RecordingHandle> {+ let (tx, rx) = bounded::<UiEvent>(self.config.max_buffer_size);+ let stop = Arc::new(AtomicBool::new(false));+ let start_time = Instant::now();++ let mut threads = Vec::new();++ // Thread 1: rdev event listener+ let tx1 = tx.clone();+ let stop1 = stop.clone();+ let config1 = self.config.clone();+ threads.push(thread::spawn(move || {+ run_rdev_listener(tx1, stop1, start_time, config1);+ }));++ // Thread 2: App/window observer+ let tx2 = tx.clone();+ let stop2 = stop.clone();+ let config2 = self.config.clone();+ threads.push(thread::spawn(move || {+ run_app_observer(tx2, stop2, start_time, config2);+ }));++ Ok(RecordingHandle {+ stop,+ events_rx: rx,+ threads,+ })+ }+}++// ============================================================================+// rdev Event Listener+// ============================================================================++struct ListenerState {+ tx: Sender<UiEvent>,+ start: Instant,+ config: UiCaptureConfig,+ last_mouse: (f64, f64),+ text_buf: String,+ last_text_time: Option<Instant>,+}++fn run_rdev_listener(+ tx: Sender<UiEvent>,+ stop: Arc<AtomicBool>,+ start: Instant,+ config: UiCaptureConfig,+) {+ let state = Arc::new(Mutex::new(ListenerState {+ tx,+ start,+ config: config.clone(),+ last_mouse: (0.0, 0.0),+ text_buf: String::new(),+ last_text_time: None,+ }));++ let state_clone = state.clone();+ let stop_clone = stop.clone();++ let callback = move |event: RdevEvent| {+ if stop_clone.load(Ordering::Relaxed) {+ return;+ }++ let mut s = state_clone.lock();+ let t = s.start.elapsed().as_millis() as u64;+ let timestamp = Utc::now();++ match event.event_type {+ EventType::ButtonPress(button) => {+ if !s.config.capture_clicks {+ return;+ }++ let (x, y) = s.last_mouse;+ let btn = match button {+ rdev::Button::Left => 0,+ rdev::Button::Right => 1,+ rdev::Button::Middle => 2,+ _ => 0,+ };++ let ui_event = UiEvent::click(timestamp, t, x as i32, y as i32, btn, 1, 0);+ let _ = s.tx.try_send(ui_event);+ }++ EventType::MouseMove { x, y } => {+ if !s.config.capture_mouse_move {+ s.last_mouse = (x, y);+ return;+ }++ let dx = x - s.last_mouse.0;+ let dy = y - s.last_mouse.1;+ let dist = (dx * dx + dy * dy).sqrt();++ if dist >= s.config.mouse_move_threshold {+ s.last_mouse = (x, y);+ let ui_event = UiEvent {+ id: None,+ timestamp,+ relative_ms: t,+ data: EventData::Move {+ x: x as i32,+ y: y as i32,+ },+ app_name: None,+ window_title: None,+ browser_url: None,+ element: None,+ frame_id: None,+ };+ let _ = s.tx.try_send(ui_event);+ } else {+ s.last_mouse = (x, y);+ }+ }++ EventType::Wheel { delta_x, delta_y } => {+ let (x, y) = s.last_mouse;+ let ui_event = UiEvent {+ id: None,+ timestamp,+ relative_ms: t,+ data: EventData::Scroll {+ x: x as i32,+ y: y as i32,+ delta_x: delta_x as i16,+ delta_y: delta_y as i16,+ },+ app_name: None,+ window_title: None,+ browser_url: None,+ element: None,+ frame_id: None,+ };+ let _ = s.tx.try_send(ui_event);+ }++ EventType::KeyPress(key) => {+ let keycode = key_to_code(&key);++ // Check text aggregation timeout first+ if let Some(last) = s.last_text_time {+ if last.elapsed().as_millis() as u64 >= s.config.text_timeout_ms+ && !s.text_buf.is_empty()+ {+ let text = std::mem::take(&mut s.text_buf);+ let ui_event = UiEvent::text(timestamp, t, text);+ let _ = s.tx.try_send(ui_event);+ s.last_text_time = None;+ }+ }++ // Try to get character for text aggregation+ if s.config.capture_text {+ if let Some(c) = key_to_char(&key) {+ if c == '\x08' {+ s.text_buf.pop();+ } else {+ s.text_buf.push(c);+ }+ s.last_text_time = Some(Instant::now());+ return; // Don't record as key event+ }+ }++ // Record as key event for special keys+ if s.config.capture_keystrokes {+ let ui_event = UiEvent {+ id: None,+ timestamp,+ relative_ms: t,+ data: EventData::Key {+ key_code: keycode,+ modifiers: 0,+ },+ app_name: None,+ window_title: None,+ browser_url: None,+ element: None,+ frame_id: None,+ };+ let _ = s.tx.try_send(ui_event);+ }+ }++ _ => {}+ }+ };++ debug!("Starting rdev listener");+ if let Err(e) = listen(callback) {+ error!("rdev listen error: {:?}", e);+ }+}++fn key_to_code(key: &Key) -> u16 {+ match key {+ Key::Alt => 0x12,+ Key::AltGr => 0x12,+ Key::Backspace => 0x08,+ Key::CapsLock => 0x14,+ Key::ControlLeft | Key::ControlRight => 0x11,+ Key::Delete => 0x2E,+ Key::DownArrow => 0x28,+ Key::End => 0x23,+ Key::Escape => 0x1B,+ Key::F1 => 0x70,+ Key::F2 => 0x71,+ Key::F3 => 0x72,+ Key::F4 => 0x73,+ Key::F5 => 0x74,+ Key::F6 => 0x75,+ Key::F7 => 0x76,+ Key::F8 => 0x77,+ Key::F9 => 0x78,+ Key::F10 => 0x79,+ Key::F11 => 0x7A,+ Key::F12 => 0x7B,+ Key::Home => 0x24,+ Key::LeftArrow => 0x25,+ Key::MetaLeft | Key::MetaRight => 0x5B,+ Key::PageDown => 0x22,+ Key::PageUp => 0x21,+ Key::Return => 0x0D,+ Key::RightArrow => 0x27,+ Key::ShiftLeft | Key::ShiftRight => 0x10,+ Key::Space => 0x20,+ Key::Tab => 0x09,+ Key::UpArrow => 0x26,+ _ => 0,+ }+}++fn key_to_char(key: &Key) -> Option<char> {+ match key {+ Key::KeyA => Some('a'),+ Key::KeyB => Some('b'),+ Key::KeyC => Some('c'),+ Key::KeyD => Some('d'),+ Key::KeyE => Some('e'),+ Key::KeyF => Some('f'),+ Key::KeyG => Some('g'),+ Key::KeyH => Some('h'),+ Key::KeyI => Some('i'),+ Key::KeyJ => Some('j'),+ Key::KeyK => Some('k'),+ Key::KeyL => Some('l'),+ Key::KeyM => Some('m'),+ Key::KeyN => Some('n'),+ Key::KeyO => Some('o'),+ Key::KeyP => Some('p'),+ Key::KeyQ => Some('q'),+ Key::KeyR => Some('r'),+ Key::KeyS => Some('s'),+ Key::KeyT => Some('t'),+ Key::KeyU => Some('u'),+ Key::KeyV => Some('v'),+ Key::KeyW => Some('w'),+ Key::KeyX => Some('x'),+ Key::KeyY => Some('y'),+ Key::KeyZ => Some('z'),+ Key::Num0 => Some('0'),+ Key::Num1 => Some('1'),+ Key::Num2 => Some('2'),+ Key::Num3 => Some('3'),+ Key::Num4 => Some('4'),+ Key::Num5 => Some('5'),+ Key::Num6 => Some('6'),+ Key::Num7 => Some('7'),+ Key::Num8 => Some('8'),+ Key::Num9 => Some('9'),+ Key::Space => Some(' '),+ Key::Return => Some('\n'),+ Key::Tab => Some('\t'),+ Key::Backspace => Some('\x08'),+ _ => None,+ }+}++// ============================================================================+// App Observer (Windows)+// ============================================================================++fn run_app_observer(+ tx: Sender<UiEvent>,+ stop: Arc<AtomicBool>,+ start: Instant,+ config: UiCaptureConfig,+) {+ use windows::Win32::Foundation::HWND;+ use windows::Win32::UI::WindowsAndMessaging::{+ GetForegroundWindow, GetWindowTextW, GetWindowThreadProcessId,+ };++ let mut last_hwnd: isize = 0;+ let mut last_title: Option<String> = None;++ while !stop.load(Ordering::Relaxed) {+ 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());++ // Check exclusions+ if !config.should_capture_app(&app_name) {+ last_hwnd = hwnd_val;+ std::thread::sleep(std::time::Duration::from_millis(100));+ continue;+ }++ 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;+ }+ }++ // Send app switch event+ if config.capture_app_switch {+ let event = UiEvent::app_switch(+ Utc::now(),+ start.elapsed().as_millis() as u64,+ app_name.clone(),+ pid as i32,+ );+ let _ = tx.try_send(event);+ }++ // 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: None,+ frame_id: None,+ };+ let _ = tx.try_send(event);+ }++ last_hwnd = hwnd_val;+ last_title = title;+ }+ }++ std::thread::sleep(std::time::Duration::from_millis(100));+ }+}++fn get_process_name(pid: u32) -> Option<String> {+ use windows::Win32::Foundation::CloseHandle;+ use windows::Win32::System::Diagnostics::ToolHelp::{+ CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,+ TH32CS_SNAPPROCESS,+ };++ unsafe {+ let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0).ok()?;++ let mut entry = PROCESSENTRY32W::default();+ entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;++ if Process32FirstW(snapshot, &mut entry).is_ok() {+ loop {+ if entry.th32ProcessID == pid {+ let name_len = entry+ .szExeFile+ .iter()+ .position(|&c| c == 0)+ .unwrap_or(entry.szExeFile.len());+ let name = String::from_utf16_lossy(&entry.szExeFile[..name_len]);+ CloseHandle(snapshot).ok();+ return Some(name);+ }++ if Process32NextW(snapshot, &mut entry).is_err() {+ break;+ }+ }+ }++ CloseHandle(snapshot).ok();+ None+ }+}diff --git a/screenpipe-app-tauri/components/settings/recording-settings.tsx b/screenpipe-app-tauri/components/settings/recording-settings.tsxindex 089747504..9d367df2a 100644--- a/screenpipe-app-tauri/components/settings/recording-settings.tsx+++ b/screenpipe-app-tauri/components/settings/recording-settings.tsx@@ -1566,6 +1566,50 @@ export function RecordingSettings() {<Separator />+ {/* UI Events (Accessibility) - macOS and Windows */}+ {(isMacOS || platform() === "windows") && (+ <div className="space-y-4">+ <div className="flex items-center gap-2 mb-2">+ <Key className="h-5 w-5" />+ <h3 className="text-lg font-semibold">UI Events (Accessibility)</h3>+ </div>++ <div className="flex items-center justify-between">+ <div className="space-y-1">+ <Label htmlFor="enableUiEvents" className="flex items-center space-x-2">+ <span>Enable UI event capture</span>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger>+ <HelpCircle className="h-4 w-4 cursor-default" />+ </TooltipTrigger>+ <TooltipContent side="right" className="max-w-xs">+ <p>+ Capture keyboard shortcuts, mouse clicks, and clipboard activity.+ {isMacOS && " Requires Accessibility and Input Monitoring permissions in System Settings."}+ {platform() === "windows" && " Uses Windows UI Automation for context capture."}+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </Label>+ <p className="text-sm text-muted-foreground">+ Track keyboard, mouse, and clipboard events for enhanced context+ </p>+ </div>+ <Switch+ id="enableUiEvents"+ checked={settings.enableUiEvents ?? false}+ onCheckedChange={(checked) =>+ handleSettingsChange({ enableUiEvents: checked }, true)+ }+ />+ </div>+ </div>+ )}++ <Separator />+{/* Window Filtering */}<div className="space-y-4"><div className="flex items-center gap-2 mb-2">diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lockindex 2f3a7f456..1e4d79a51 100755--- a/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -6733,7 +6733,7 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"[[package]]name = "screenpipe-app"-version = "2.0.192"+version = "2.0.193"dependencies = ["anyhow","async-stream",diff --git a/screenpipe-app-tauri/src-tauri/src/sidecar.rs b/screenpipe-app-tauri/src-tauri/src/sidecar.rsindex 07766e829..8f9624de7 100644--- a/screenpipe-app-tauri/src-tauri/src/sidecar.rs+++ b/screenpipe-app-tauri/src-tauri/src/sidecar.rs@@ -509,8 +509,8 @@ async fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>args.push("--adaptive-fps");}+ // Enable UI events capture (macOS and Windows)let enable_ui_events = store.enable_ui_events;-if enable_ui_events {args.push("--enable-ui-events");}diff --git a/screenpipe-audio/tests/speaker_identification.rs b/screenpipe-audio/tests/speaker_identification.rsindex 65b42e126..a2130c52b 100644--- a/screenpipe-audio/tests/speaker_identification.rs+++ b/screenpipe-audio/tests/speaker_identification.rs@@ -39,7 +39,11 @@ mod tests {// In the clone, add a new speaker (simulating a new voice detected)let speaker2_in_clone = cloned.search_speaker(embedding2.clone(), 0.5);- assert_eq!(speaker2_in_clone, Some(2), "Second speaker should be ID 2 in clone");+ assert_eq!(+ speaker2_in_clone,+ Some(2),+ "Second speaker should be ID 2 in clone"+ );// BUG: The original doesn't see the new speaker!// When cloned goes out of scope (function returns), speaker 2 is LOST@@ -102,7 +106,11 @@ mod tests {{let mut manager = shared.lock().unwrap();let speaker2_again = manager.search_speaker(embedding2.clone(), 0.5);- assert_eq!(speaker2_again, Some(2), "Same embedding should return same speaker");+ assert_eq!(+ speaker2_again,+ Some(2),+ "Same embedding should return same speaker"+ );}// Verify: shared state has both speakersdiff --git a/screenpipe-core/src/pii_removal.rs b/screenpipe-core/src/pii_removal.rsindex 24b8f2bea..21086cf79 100644--- a/screenpipe-core/src/pii_removal.rs+++ b/screenpipe-core/src/pii_removal.rs@@ -836,7 +836,9 @@ mod tests {#[test]fn test_auth_token_detection() {// Authorization headers- assert!(contains_pii("Authorization: Bearer abc123def456ghi789jkl012"));+ assert!(contains_pii(+ "Authorization: Bearer abc123def456ghi789jkl012"+ ));assert!(contains_pii("bearer eyJhbGciOiJIUzI1NiIsInR5cCI"));let result = remove_pii("Authorization: Bearer abc123def456ghi789jkl012mno");@@ -884,7 +886,10 @@ mod tests {assert!(!result.contains("eyJ"), "JWT not redacted");assert!(!result.contains("whsec_"), "Stripe key not redacted");- assert!(!result.contains("sb_publishable_"), "Supabase key not redacted");+ assert!(+ !result.contains("sb_publishable_"),+ "Supabase key not redacted"+ );assert!(!result.contains("••••"), "Password dots not redacted");}@@ -932,27 +937,37 @@ mod tests {#[test]fn test_connection_string_detection() {// PostgreSQL- assert!(contains_pii("postgres://user:password123@localhost:5432/mydb"));- assert!(contains_pii("postgresql://admin:[email protected]/prod"));+ assert!(contains_pii(+ "postgres://user:password123@localhost:5432/mydb"+ ));+ assert!(contains_pii(+ "postgresql://admin:[email protected]/prod"+ ));// MySQLassert!(contains_pii("mysql://root:[email protected]:3306/database"));// MongoDBassert!(contains_pii("mongodb://user:[email protected]/db"));- assert!(contains_pii("mongodb+srv://admin:[email protected]"));+ assert!(contains_pii(+ "mongodb+srv://admin:[email protected]"+ ));// Redisassert!(contains_pii("redis://:[email protected]:6379"));assert!(contains_pii("rediss://:[email protected]:6380"));let result = remove_pii("DATABASE_URL=postgres://user:secret@host/db");- assert!(result.contains("[CONNECTION_STRING]") || result.contains("[URL_WITH_CREDENTIALS]"));+ assert!(+ result.contains("[CONNECTION_STRING]") || result.contains("[URL_WITH_CREDENTIALS]")+ );}#[test]fn test_url_with_credentials() {- assert!(contains_pii("https://user:[email protected]/endpoint"));+ assert!(contains_pii(+ "https://user:[email protected]/endpoint"+ ));assert!(contains_pii("ftp://admin:[email protected]/files"));let result = remove_pii("API: https://apikey:[email protected]/v1");@@ -963,8 +978,12 @@ mod tests {#[test]fn test_slack_token_detection() {- assert!(contains_pii("xoxb-123456789012-1234567890123-abcdefghijklmnop"));- assert!(contains_pii("xoxp-123456789012-1234567890123-abcdefghijklmnop"));+ assert!(contains_pii(+ "xoxb-123456789012-1234567890123-abcdefghijklmnop"+ ));+ assert!(contains_pii(+ "xoxp-123456789012-1234567890123-abcdefghijklmnop"+ ));assert!(contains_pii("xapp-1-A12345678-1234567890123-abcdef"));let result = remove_pii("SLACK_TOKEN=xoxb-123456789012-1234567890123-abc");@@ -976,7 +995,9 @@ mod tests {// Discord token format: base64.timestamp.hmaclet discord_token = "MjM4NDk0NzU2NTIxMzc3Nzky.CunGFQ.wUILz7z6HoJzVeq6pyHPmVgQgV4";// Note: This is a fake token format- assert!(contains_pii("NTk0NzU2NTIxMzc3Nzk2NDEy.XQ0bXQ.vHc7MzY3NDk0NzU2NTIxMzc3Nzk"));+ assert!(contains_pii(+ "NTk0NzU2NTIxMzc3Nzk2NDEy.XQ0bXQ.vHc7MzY3NDk0NzU2NTIxMzc3Nzk"+ ));}#[test]@@ -1001,7 +1022,9 @@ mod tests {#[test]fn test_telegram_token_detection() {// Format: bot_id:secret- assert!(contains_pii("123456789:ABCdefGHIjklMNOpqrsTUVwxyz123456789"));+ assert!(contains_pii(+ "123456789:ABCdefGHIjklMNOpqrsTUVwxyz123456789"+ ));assert!(contains_pii("9876543210:abcdefghijklmnopqrstuvwxyz12345"));}diff --git a/screenpipe-core/src/sync/blob.rs b/screenpipe-core/src/sync/blob.rsindex dc5ed4c09..baf58dd4c 100644--- a/screenpipe-core/src/sync/blob.rs+++ b/screenpipe-core/src/sync/blob.rs@@ -25,6 +25,10 @@ pub enum BlobType {Transcripts,/// OCR text from screen capturesOcr,+ /// Accessibility text from screen (UI element traversal)+ Accessibility,+ /// User input events (clicks, keystrokes, clipboard)+ Input,}impl BlobType {@@ -34,6 +38,8 @@ impl BlobType {BlobType::Audio => "audio",BlobType::Transcripts => "transcripts",BlobType::Ocr => "ocr",+ BlobType::Accessibility => "accessibility",+ BlobType::Input => "input",}}}@@ -69,7 +75,10 @@ impl EncryptedBlob {/// Get search tokens as base64 strings.pub fn search_tokens_base64(&self) -> Vec<String> {- self.search_tokens.iter().map(|t| BASE64.encode(t)).collect()+ self.search_tokens+ .iter()+ .map(|t| BASE64.encode(t))+ .collect()}}diff --git a/screenpipe-core/src/sync/client.rs b/screenpipe-core/src/sync/client.rsindex d06f26eb9..8d671290f 100644--- a/screenpipe-core/src/sync/client.rs+++ b/screenpipe-core/src/sync/client.rs@@ -140,14 +140,18 @@ impl SyncClient {// For existing users, server returns the key datalet key_data = ExistingUserKeyData {- salt: response.salt.ok_or_else(|| SyncError::Key("missing salt".to_string()))?,+ salt: response+ .salt+ .ok_or_else(|| SyncError::Key("missing salt".to_string()))?,encrypted_master_key: response.encrypted_master_key.ok_or_else(|| SyncError::Key("missing encrypted_master_key".to_string()))?,master_key_nonce: response.master_key_nonce.ok_or_else(|| SyncError::Key("missing master_key_nonce".to_string()))?,- kdf_algorithm: response.kdf_algorithm.unwrap_or_else(|| "argon2id".to_string()),+ kdf_algorithm: response+ .kdf_algorithm+ .unwrap_or_else(|| "argon2id".to_string()),kdf_iterations: response.kdf_iterations.unwrap_or(3),kdf_memory: response.kdf_memory.unwrap_or(65536),key_version: response.key_version.unwrap_or(1),@@ -191,14 +195,18 @@ impl SyncClient {} else {// Existing user - derive keys from server responselet key_data = ExistingUserKeyData {- salt: response.salt.ok_or_else(|| SyncError::Key("missing salt".to_string()))?,+ salt: response+ .salt+ .ok_or_else(|| SyncError::Key("missing salt".to_string()))?,encrypted_master_key: response.encrypted_master_key.ok_or_else(|| SyncError::Key("missing encrypted_master_key".to_string()))?,master_key_nonce: response.master_key_nonce.ok_or_else(|| SyncError::Key("missing master_key_nonce".to_string()))?,- kdf_algorithm: response.kdf_algorithm.unwrap_or_else(|| "argon2id".to_string()),+ kdf_algorithm: response+ .kdf_algorithm+ .unwrap_or_else(|| "argon2id".to_string()),kdf_iterations: response.kdf_iterations.unwrap_or(3),kdf_memory: response.kdf_memory.unwrap_or(65536),key_version: response.key_version.unwrap_or(1),@@ -214,10 +222,7 @@ impl SyncClient {// =========================================================================/// Request a presigned URL for uploading a blob.- pub async fn request_upload(- &self,- metadata: &BlobMetadata,- ) -> SyncResult<UploadUrlResponse> {+ pub async fn request_upload(&self, metadata: &BlobMetadata) -> SyncResult<UploadUrlResponse> {let request = UploadRequest {blob_type: metadata.blob_type,time_start: metadata.time_start.clone(),@@ -240,17 +245,25 @@ impl SyncClient {let code = response.code.as_deref();if code == Some("QUOTA_EXCEEDED") {return Err(SyncError::QuotaExceeded(- response.error.unwrap_or_else(|| "quota exceeded".to_string()),+ response+ .error+ .unwrap_or_else(|| "quota exceeded".to_string()),));}return Err(SyncError::Server(- response.error.unwrap_or_else(|| "upload request failed".to_string()),+ response+ .error+ .unwrap_or_else(|| "upload request failed".to_string()),));}Ok(UploadUrlResponse {- blob_id: response.blob_id.ok_or_else(|| SyncError::Server("missing blob_id".to_string()))?,- upload_url: response.upload_url.ok_or_else(|| SyncError::Server("missing upload_url".to_string()))?,+ blob_id: response+ .blob_id+ .ok_or_else(|| SyncError::Server("missing blob_id".to_string()))?,+ upload_url: response+ .upload_url+ .ok_or_else(|| SyncError::Server("missing upload_url".to_string()))?,expires_in: response.expires_in.unwrap_or(300),})}@@ -285,7 +298,9 @@ impl SyncClient {if !response.success {return Err(SyncError::Server(- response.error.unwrap_or_else(|| "complete upload failed".to_string()),+ response+ .error+ .unwrap_or_else(|| "complete upload failed".to_string()),));}@@ -300,12 +315,17 @@ impl SyncClient {// =========================================================================/// Get presigned download URLs for blobs.- pub async fn get_download_urls(&self, request: DownloadRequest) -> SyncResult<Vec<DownloadBlob>> {+ pub async fn get_download_urls(+ &self,+ request: DownloadRequest,+ ) -> SyncResult<Vec<DownloadBlob>> {let response: DownloadResponse = self.post("/download", &request).await?;if !response.success {return Err(SyncError::Server(- response.error.unwrap_or_else(|| "download request failed".to_string()),+ response+ .error+ .unwrap_or_else(|| "download request failed".to_string()),));}@@ -337,7 +357,9 @@ impl SyncClient {if !response.success {return Err(SyncError::Server(- response.error.unwrap_or_else(|| "search failed".to_string()),+ response+ .error+ .unwrap_or_else(|| "search failed".to_string()),));}@@ -357,13 +379,19 @@ impl SyncClient {if !response.success {return Err(SyncError::Server(- response.error.unwrap_or_else(|| "status request failed".to_string()),+ response+ .error+ .unwrap_or_else(|| "status request failed".to_string()),));}Ok(SyncStatus {- quota: response.quota.ok_or_else(|| SyncError::Server("missing quota".to_string()))?,- stats: response.stats.ok_or_else(|| SyncError::Server("missing stats".to_string()))?,+ quota: response+ .quota+ .ok_or_else(|| SyncError::Server("missing quota".to_string()))?,+ stats: response+ .stats+ .ok_or_else(|| SyncError::Server("missing stats".to_string()))?,storage_breakdown: response.storage_breakdown,})}@@ -378,7 +406,9 @@ impl SyncClient {if !response.success {return Err(SyncError::Server(- response.error.unwrap_or_else(|| "list devices failed".to_string()),+ response+ .error+ .unwrap_or_else(|| "list devices failed".to_string()),));}@@ -392,7 +422,10 @@ impl SyncClient {let response = self.http.delete(&url)- .header("Authorization", format!("Bearer {}", self.config.auth_token))+ .header(+ "Authorization",+ format!("Bearer {}", self.config.auth_token),+ ).send().await?;@@ -403,7 +436,9 @@ impl SyncClient {code: None,});return Err(SyncError::Server(- error_body.error.unwrap_or_else(|| "remove device failed".to_string()),+ error_body+ .error+ .unwrap_or_else(|| "remove device failed".to_string()),));}@@ -421,7 +456,10 @@ impl SyncClient {let response = self.http.delete(&url)- .header("Authorization", format!("Bearer {}", self.config.auth_token))+ .header(+ "Authorization",+ format!("Bearer {}", self.config.auth_token),+ ).send().await?;@@ -432,7 +470,9 @@ impl SyncClient {code: None,});return Err(SyncError::Server(- error_body.error.unwrap_or_else(|| "delete all data failed".to_string()),+ error_body+ .error+ .unwrap_or_else(|| "delete all data failed".to_string()),));}@@ -453,7 +493,10 @@ impl SyncClient {let response = self.http.post(&url)- .header("Authorization", format!("Bearer {}", self.config.auth_token))+ .header(+ "Authorization",+ format!("Bearer {}", self.config.auth_token),+ ).header("X-Device-Id", &self.config.device_id).json(body).send()@@ -468,7 +511,10 @@ impl SyncClient {let response = self.http.get(&url)- .header("Authorization", format!("Bearer {}", self.config.auth_token))+ .header(+ "Authorization",+ format!("Bearer {}", self.config.auth_token),+ ).header("X-Device-Id", &self.config.device_id).send().await?;@@ -499,7 +545,9 @@ impl SyncClient {}if error_body.code.as_deref() == Some("QUOTA_EXCEEDED") {return Err(SyncError::QuotaExceeded(- error_body.error.unwrap_or_else(|| "quota exceeded".to_string()),+ error_body+ .error+ .unwrap_or_else(|| "quota exceeded".to_string()),));}if error_body.code.as_deref() == Some("DEVICE_LIMIT_EXCEEDED") {diff --git a/screenpipe-core/src/sync/crypto.rs b/screenpipe-core/src/sync/crypto.rsindex 3216f0cc6..e7666726d 100644--- a/screenpipe-core/src/sync/crypto.rs+++ b/screenpipe-core/src/sync/crypto.rs@@ -71,7 +71,10 @@ pub fn generate_key() -> Zeroizing<[u8; KEY_SIZE]> {////// # Returns/// A 256-bit derived key-pub fn derive_key_from_password(password: &str, salt: &[u8; SALT_SIZE]) -> SyncResult<Zeroizing<[u8; KEY_SIZE]>> {+pub fn derive_key_from_password(+ password: &str,+ salt: &[u8; SALT_SIZE],+) -> SyncResult<Zeroizing<[u8; KEY_SIZE]>> {let params = Params::new(ARGON2_MEMORY_KB,ARGON2_ITERATIONS,@@ -102,7 +105,11 @@ pub fn derive_key_from_password(password: &str, salt: &[u8; SALT_SIZE]) -> SyncR////// # Returns/// The ciphertext with authentication tag appended-pub fn encrypt(plaintext: &[u8], key: &[u8; KEY_SIZE], nonce: &[u8; NONCE_SIZE]) -> SyncResult<Vec<u8>> {+pub fn encrypt(+ plaintext: &[u8],+ key: &[u8; KEY_SIZE],+ nonce: &[u8; NONCE_SIZE],+) -> SyncResult<Vec<u8>> {let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| SyncError::Crypto(format!("invalid key: {}", e)))?;@@ -124,7 +131,11 @@ pub fn encrypt(plaintext: &[u8], key: &[u8; KEY_SIZE], nonce: &[u8; NONCE_SIZE])////// # Returns/// The decrypted plaintext, or an error if authentication fails-pub fn decrypt(ciphertext: &[u8], key: &[u8; KEY_SIZE], nonce: &[u8; NONCE_SIZE]) -> SyncResult<Vec<u8>> {+pub fn decrypt(+ ciphertext: &[u8],+ key: &[u8; KEY_SIZE],+ nonce: &[u8; NONCE_SIZE],+) -> SyncResult<Vec<u8>> {let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| SyncError::Crypto(format!("invalid key: {}", e)))?;@@ -176,7 +187,10 @@ pub fn generate_search_token(keyword: &str, key: &[u8; KEY_SIZE]) -> SyncResult<////// # Returns/// A list of unique HMAC tokens-pub fn generate_search_tokens_from_text(text: &str, key: &[u8; KEY_SIZE]) -> SyncResult<Vec<[u8; HMAC_SIZE]>> {+pub fn generate_search_tokens_from_text(+ text: &str,+ key: &[u8; KEY_SIZE],+) -> SyncResult<Vec<[u8; HMAC_SIZE]>> {let keywords = extract_keywords(text);let mut tokens = Vec::with_capacity(keywords.len());diff --git a/screenpipe-core/src/sync/manager.rs b/screenpipe-core/src/sync/manager.rsindex a0acbf113..824f5a9ec 100644--- a/screenpipe-core/src/sync/manager.rs+++ b/screenpipe-core/src/sync/manager.rs@@ -99,12 +99,8 @@ impl SyncManager {let encrypted = encrypt_blob(data, blob_type, keys, text_content)?;// Create metadata- let metadata = BlobMetadata::from_encrypted_blob(- &encrypted,- time_start,- time_end,- keys.key_version(),- );+ let metadata =+ BlobMetadata::from_encrypted_blob(&encrypted, time_start, time_end, keys.key_version());// Request upload URLlet upload_info = self.client.request_upload(&metadata).await?;@@ -230,13 +226,17 @@ impl SyncManager {Ok(SearchResult {blob_ids: response.matches.iter().map(|m| m.blob_id.clone()).collect(),- matches: response.matches.into_iter().map(|m| SearchMatchInfo {- blob_id: m.blob_id,- blob_type: m.blob_type,- time_start: m.time_start,- time_end: m.time_end,- match_count: m.match_count,- }).collect(),+ matches: response+ .matches+ .into_iter()+ .map(|m| SearchMatchInfo {+ blob_id: m.blob_id,+ blob_type: m.blob_type,+ time_start: m.time_start,+ time_end: m.time_end,+ match_count: m.match_count,+ })+ .collect(),total: response.total_matches,})}diff --git a/screenpipe-core/src/sync/service.rs b/screenpipe-core/src/sync/service.rsindex 3c9e055f4..7380f1068 100644--- a/screenpipe-core/src/sync/service.rs+++ b/screenpipe-core/src/sync/service.rs@@ -153,7 +153,13 @@ pub trait SyncDataProvider: Send + Sync {) -> SyncResult<Vec<PendingBlob>>;/// Mark data as synced.- async fn mark_synced(&self, blob_type: BlobType, time_start: &str, time_end: &str, blob_id: &str) -> SyncResult<()>;+ async fn mark_synced(+ &self,+ blob_type: BlobType,+ time_start: &str,+ time_end: &str,+ blob_id: &str,+ ) -> SyncResult<()>;}/// Data pending sync.@@ -314,7 +320,12 @@ impl SyncService {// Mark as syncedif let Err(e) = self.data_provider- .mark_synced(*blob_type, &blob.time_start, &blob.time_end, &result.blob_id)+ .mark_synced(+ *blob_type,+ &blob.time_start,+ &blob.time_end,+ &result.blob_id,+ ).await{tracing::error!("failed to mark blob as synced: {}", e);diff --git a/screenpipe-db/src/db.rs b/screenpipe-db/src/db.rsindex 8616b2077..601f3d451 100644--- a/screenpipe-db/src/db.rs+++ b/screenpipe-db/src/db.rs@@ -21,9 +21,9 @@ use futures::future::try_join_all;use crate::{text_similarity::is_similar_transcription, AudioChunksResponse, AudioDevice, AudioEntry,- AudioResult, AudioResultRaw, ContentType, DeviceType, FrameData, FrameRow, OCREntry, OCRResult,- OCRResultRaw, OcrEngine, OcrTextBlock, Order, SearchMatch, SearchResult, Speaker,- TagContentType, TextBounds, TextPosition, TimeSeriesChunk, UiContent, UiEventRecord,+ AudioResult, AudioResultRaw, ContentType, DeviceType, FrameData, FrameRow, InsertUiEvent,+ OCREntry, OCRResult, OCRResultRaw, OcrEngine, OcrTextBlock, Order, SearchMatch, SearchResult,+ Speaker, TagContentType, TextBounds, TextPosition, TimeSeriesChunk, UiContent, UiEventRecord,UiEventRow, VideoMetadata,};@@ -3162,6 +3162,208 @@ LIMIT ? OFFSET ?Ok((target_speaker.id, transcriptions_updated, embeddings_moved))}++ // ============================================================================+ // UI Events (Input Capture Modality)+ // ============================================================================++ /// Insert a UI event into the database+ pub async fn insert_ui_event(&self, event: &InsertUiEvent) -> Result<i64, sqlx::Error> {+ let text_length = event.text_content.as_ref().map(|s| s.len() as i32);++ let result = sqlx::query(+ r#"+ INSERT INTO ui_events (+ timestamp, session_id, relative_ms, event_type,+ x, y, delta_x, delta_y,+ button, click_count, key_code, modifiers,+ text_content, text_length,+ app_name, app_pid, window_title, browser_url,+ element_role, element_name, element_value, element_description,+ element_automation_id, element_bounds, frame_id+ ) VALUES (+ ?1, ?2, ?3, ?4,+ ?5, ?6, ?7, ?8,+ ?9, ?10, ?11, ?12,+ ?13, ?14,+ ?15, ?16, ?17, ?18,+ ?19, ?20, ?21, ?22,+ ?23, ?24, ?25+ )+ "#,+ )+ .bind(&event.timestamp)+ .bind(&event.session_id)+ .bind(event.relative_ms)+ .bind(event.event_type.to_string())+ .bind(event.x)+ .bind(event.y)+ .bind(event.delta_x.map(|v| v as i32))+ .bind(event.delta_y.map(|v| v as i32))+ .bind(event.button.map(|v| v as i32))+ .bind(event.click_count.map(|v| v as i32))+ .bind(event.key_code.map(|v| v as i32))+ .bind(event.modifiers.map(|v| v as i32))+ .bind(&event.text_content)+ .bind(text_length)+ .bind(&event.app_name)+ .bind(event.app_pid)+ .bind(&event.window_title)+ .bind(&event.browser_url)+ .bind(&event.element_role)+ .bind(&event.element_name)+ .bind(&event.element_value)+ .bind(&event.element_description)+ .bind(&event.element_automation_id)+ .bind(&event.element_bounds)+ .bind(event.frame_id)+ .execute(&self.pool)+ .await?;++ Ok(result.last_insert_rowid())+ }++ /// Insert multiple UI events in a batch+ pub async fn insert_ui_events_batch(+ &self,+ events: &[InsertUiEvent],+ ) -> Result<usize, sqlx::Error> {+ if events.is_empty() {+ return Ok(0);+ }++ let mut tx = self.pool.begin().await?;+ let mut count = 0;++ for event in events {+ let text_length = event.text_content.as_ref().map(|s| s.len() as i32);++ sqlx::query(+ r#"+ INSERT INTO ui_events (+ timestamp, session_id, relative_ms, event_type,+ x, y, delta_x, delta_y,+ button, click_count, key_code, modifiers,+ text_content, text_length,+ app_name, app_pid, window_title, browser_url,+ element_role, element_name, element_value, element_description,+ element_automation_id, element_bounds, frame_id+ ) VALUES (+ ?1, ?2, ?3, ?4,+ ?5, ?6, ?7, ?8,+ ?9, ?10, ?11, ?12,+ ?13, ?14,+ ?15, ?16, ?17, ?18,+ ?19, ?20, ?21, ?22,+ ?23, ?24, ?25+ )+ "#,+ )+ .bind(&event.timestamp)+ .bind(&event.session_id)+ .bind(event.relative_ms)+ .bind(event.event_type.to_string())+ .bind(event.x)+ .bind(event.y)+ .bind(event.delta_x.map(|v| v as i32))+ .bind(event.delta_y.map(|v| v as i32))+ .bind(event.button.map(|v| v as i32))+ .bind(event.click_count.map(|v| v as i32))+ .bind(event.key_code.map(|v| v as i32))+ .bind(event.modifiers.map(|v| v as i32))+ .bind(&event.text_content)+ .bind(text_length)+ .bind(&event.app_name)+ .bind(event.app_pid)+ .bind(&event.window_title)+ .bind(&event.browser_url)+ .bind(&event.element_role)+ .bind(&event.element_name)+ .bind(&event.element_value)+ .bind(&event.element_description)+ .bind(&event.element_automation_id)+ .bind(&event.element_bounds)+ .bind(event.frame_id)+ .execute(&mut *tx)+ .await?;++ count += 1;+ }++ tx.commit().await?;+ debug!("Inserted {} UI events in batch", count);+ Ok(count)+ }++ /// Get recent UI events for a specific app+ pub async fn get_recent_ui_events_by_app(+ &self,+ app_name: &str,+ limit: u32,+ ) -> Result<Vec<UiEventRecord>, sqlx::Error> {+ let rows: Vec<UiEventRow> = sqlx::query_as(+ r#"+ SELECT *+ FROM ui_events+ WHERE app_name = ?+ ORDER BY timestamp DESC+ LIMIT ?+ "#,+ )+ .bind(app_name)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?;++ Ok(rows.into_iter().map(UiEventRecord::from).collect())+ }++ /// Get text events (aggregated keystrokes) for semantic search+ pub async fn search_ui_text_events(+ &self,+ query: &str,+ start_time: Option<DateTime<Utc>>,+ end_time: Option<DateTime<Utc>>,+ limit: u32,+ ) -> Result<Vec<UiEventRecord>, sqlx::Error> {+ let mut conditions = vec!["event_type = 'text'".to_string()];++ if let Some(start) = start_time {+ conditions.push(format!(+ "timestamp >= '{}'",+ start.format("%Y-%m-%d %H:%M:%S")+ ));+ }+ if let Some(end) = end_time {+ conditions.push(format!(+ "timestamp <= '{}'",+ end.format("%Y-%m-%d %H:%M:%S")+ ));+ }++ let where_clause = conditions.join(" AND ");++ let sql = format!(+ r#"+ SELECT ui_events.*+ FROM ui_events_fts+ JOIN ui_events ON ui_events_fts.rowid = ui_events.id+ WHERE ui_events_fts MATCH ?+ AND {}+ ORDER BY ui_events.timestamp DESC+ LIMIT ?+ "#,+ where_clause+ );++ let rows: Vec<UiEventRow> = sqlx::query_as(&sql)+ .bind(query)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?;++ Ok(rows.into_iter().map(UiEventRecord::from).collect())+ }}pub fn find_matching_positions(blocks: &[OcrTextBlock], query: &str) -> Vec<TextPosition> {diff --git a/screenpipe-db/src/migrations/20250201000000_add_accessibility_and_input_tables.sql b/screenpipe-db/src/migrations/20250201000000_add_accessibility_and_input_tables.sqlnew file mode 100644index 000000000..8afc56d6a--- /dev/null+++ b/screenpipe-db/src/migrations/20250201000000_add_accessibility_and_input_tables.sql@@ -0,0 +1,161 @@+-- Add accessibility table (replaces ui_monitoring with better name and sync support)+-- and ui_events table for input capture++-- =============================================================================+-- ACCESSIBILITY TABLE (screen content from accessibility APIs)+-- =============================================================================++CREATE TABLE IF NOT EXISTS accessibility (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ app_name TEXT NOT NULL,+ window_name TEXT NOT NULL,+ text_content TEXT NOT NULL,+ browser_url TEXT,+ -- Sync columns+ sync_id TEXT,+ machine_id TEXT,+ synced_at DATETIME+);++-- Indexes for accessibility+CREATE INDEX IF NOT EXISTS idx_accessibility_timestamp ON accessibility(timestamp);+CREATE INDEX IF NOT EXISTS idx_accessibility_app_name ON accessibility(app_name);+CREATE INDEX IF NOT EXISTS idx_accessibility_window_name ON accessibility(window_name);+CREATE INDEX IF NOT EXISTS idx_accessibility_sync_id ON accessibility(sync_id);+CREATE INDEX IF NOT EXISTS idx_accessibility_synced_at ON accessibility(synced_at);+CREATE INDEX IF NOT EXISTS idx_accessibility_unsynced ON accessibility(synced_at) WHERE synced_at IS NULL;++-- FTS for accessibility+CREATE VIRTUAL TABLE IF NOT EXISTS accessibility_fts USING fts5(+ text_content,+ app_name,+ window_name,+ content='accessibility',+ content_rowid='id',+ tokenize='unicode61'+);++-- Triggers for accessibility FTS+CREATE TRIGGER IF NOT EXISTS accessibility_ai AFTER INSERT ON accessibility BEGIN+ INSERT INTO accessibility_fts(rowid, text_content, app_name, window_name)+ VALUES (NEW.id, NEW.text_content, NEW.app_name, NEW.window_name);+END;++CREATE TRIGGER IF NOT EXISTS accessibility_ad AFTER DELETE ON accessibility BEGIN+ INSERT INTO accessibility_fts(accessibility_fts, rowid, text_content, app_name, window_name)+ VALUES('delete', OLD.id, OLD.text_content, OLD.app_name, OLD.window_name);+END;++CREATE TRIGGER IF NOT EXISTS accessibility_au AFTER UPDATE ON accessibility BEGIN+ INSERT INTO accessibility_fts(accessibility_fts, rowid, text_content, app_name, window_name)+ VALUES('delete', OLD.id, OLD.text_content, OLD.app_name, OLD.window_name);+ INSERT INTO accessibility_fts(rowid, text_content, app_name, window_name)+ VALUES (NEW.id, NEW.text_content, NEW.app_name, NEW.window_name);+END;++-- Junction table for accessibility and tags+CREATE TABLE IF NOT EXISTS accessibility_tags (+ accessibility_id INTEGER NOT NULL,+ tag_id INTEGER NOT NULL,+ PRIMARY KEY (accessibility_id, tag_id),+ FOREIGN KEY (accessibility_id) REFERENCES accessibility(id) ON DELETE CASCADE,+ FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE+);++CREATE INDEX IF NOT EXISTS idx_accessibility_tags_accessibility_id ON accessibility_tags(accessibility_id);+CREATE INDEX IF NOT EXISTS idx_accessibility_tags_tag_id ON accessibility_tags(tag_id);++-- =============================================================================+-- UI_EVENTS TABLE (user input actions: clicks, keystrokes, clipboard)+-- =============================================================================++CREATE TABLE IF NOT EXISTS ui_events (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ session_id TEXT,+ relative_ms INTEGER NOT NULL DEFAULT 0,+ event_type TEXT NOT NULL, -- click, move, scroll, key, text, app_switch, window_focus, clipboard+ -- Position+ x INTEGER,+ y INTEGER,+ delta_x INTEGER,+ delta_y INTEGER,+ -- Mouse/key+ button INTEGER,+ click_count INTEGER,+ key_code INTEGER,+ modifiers INTEGER,+ -- Text content+ text_content TEXT,+ text_length INTEGER,+ -- App context+ app_name TEXT,+ app_pid INTEGER,+ window_title TEXT,+ browser_url TEXT,+ -- Element context (from accessibility APIs)+ element_role TEXT,+ element_name TEXT,+ element_value TEXT,+ element_description TEXT,+ element_automation_id TEXT,+ element_bounds TEXT, -- JSON: {"x":0,"y":0,"width":100,"height":50}+ -- Frame correlation+ frame_id INTEGER,+ -- Sync columns+ sync_id TEXT,+ machine_id TEXT,+ synced_at DATETIME+);++-- Indexes for ui_events+CREATE INDEX IF NOT EXISTS idx_ui_events_timestamp ON ui_events(timestamp);+CREATE INDEX IF NOT EXISTS idx_ui_events_event_type ON ui_events(event_type);+CREATE INDEX IF NOT EXISTS idx_ui_events_app_name ON ui_events(app_name);+CREATE INDEX IF NOT EXISTS idx_ui_events_session_id ON ui_events(session_id);+CREATE INDEX IF NOT EXISTS idx_ui_events_frame_id ON ui_events(frame_id);+CREATE INDEX IF NOT EXISTS idx_ui_events_sync_id ON ui_events(sync_id);+CREATE INDEX IF NOT EXISTS idx_ui_events_synced_at ON ui_events(synced_at);+CREATE INDEX IF NOT EXISTS idx_ui_events_unsynced ON ui_events(synced_at) WHERE synced_at IS NULL;++-- FTS for ui_events (searchable text content)+CREATE VIRTUAL TABLE IF NOT EXISTS ui_events_fts USING fts5(+ text_content,+ app_name,+ window_title,+ element_name,+ content='ui_events',+ content_rowid='id',+ tokenize='unicode61'+);++-- Triggers for ui_events FTS+CREATE TRIGGER IF NOT EXISTS ui_events_ai AFTER INSERT ON ui_events BEGIN+ INSERT INTO ui_events_fts(rowid, text_content, app_name, window_title, element_name)+ VALUES (NEW.id, NEW.text_content, NEW.app_name, NEW.window_title, NEW.element_name);+END;++CREATE TRIGGER IF NOT EXISTS ui_events_ad AFTER DELETE ON ui_events BEGIN+ INSERT INTO ui_events_fts(ui_events_fts, rowid, text_content, app_name, window_title, element_name)+ VALUES('delete', OLD.id, OLD.text_content, OLD.app_name, OLD.window_title, OLD.element_name);+END;++CREATE TRIGGER IF NOT EXISTS ui_events_au AFTER UPDATE ON ui_events BEGIN+ INSERT INTO ui_events_fts(ui_events_fts, rowid, text_content, app_name, window_title, element_name)+ VALUES('delete', OLD.id, OLD.text_content, OLD.app_name, OLD.window_title, OLD.element_name);+ INSERT INTO ui_events_fts(rowid, text_content, app_name, window_title, element_name)+ VALUES (NEW.id, NEW.text_content, NEW.app_name, NEW.window_title, NEW.element_name);+END;++-- =============================================================================+-- ADD SYNC COLUMNS TO UI_MONITORING (for backwards compatibility)+-- =============================================================================++ALTER TABLE ui_monitoring ADD COLUMN sync_id TEXT;+ALTER TABLE ui_monitoring ADD COLUMN machine_id TEXT;+ALTER TABLE ui_monitoring ADD COLUMN synced_at DATETIME;++CREATE INDEX IF NOT EXISTS idx_ui_monitoring_sync_id ON ui_monitoring(sync_id);+CREATE INDEX IF NOT EXISTS idx_ui_monitoring_synced_at ON ui_monitoring(synced_at);+CREATE INDEX IF NOT EXISTS idx_ui_monitoring_unsynced ON ui_monitoring(synced_at) WHERE synced_at IS NULL;diff --git a/screenpipe-db/src/migrations/20250201000000_create_ui_events.sql b/screenpipe-db/src/migrations/20250201000000_create_ui_events.sqlnew file mode 100644index 000000000..f9f799b0a--- /dev/null+++ b/screenpipe-db/src/migrations/20250201000000_create_ui_events.sql@@ -0,0 +1,98 @@+-- UI Events table for storing keyboard, mouse, and accessibility events+-- This is the third modality alongside OCR (vision) and audio++CREATE TABLE IF NOT EXISTS ui_events (+ id INTEGER PRIMARY KEY AUTOINCREMENT,++ -- Timing+ timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ session_id TEXT, -- UUID for recording session+ relative_ms INTEGER NOT NULL, -- ms since session start++ -- Event type+ event_type TEXT NOT NULL, -- click, move, scroll, key, text, app_switch, window_focus, clipboard++ -- Position data (for mouse events)+ x INTEGER,+ y INTEGER,+ delta_x INTEGER, -- scroll/drag delta+ delta_y INTEGER,++ -- Mouse/key data+ button INTEGER, -- 0=left, 1=right, 2=middle+ click_count INTEGER DEFAULT 1, -- 1=single, 2=double+ key_code INTEGER,+ modifiers INTEGER, -- packed: 1=shift, 2=ctrl, 4=opt, 8=cmd++ -- Text content+ text_content TEXT,+ text_length INTEGER, -- Denormalized for queries++ -- App/Window context+ app_name TEXT,+ app_pid INTEGER,+ window_title TEXT,+ browser_url TEXT,++ -- Element context (from accessibility)+ element_role TEXT, -- AXButton, AXTextField, etc.+ element_name TEXT, -- Accessible name/label+ element_value TEXT, -- Current value (for inputs)+ element_description TEXT,+ element_automation_id TEXT, -- Windows automation ID+ element_bounds TEXT, -- JSON: {"x":0,"y":0,"width":100,"height":50}++ -- Frame correlation+ frame_id INTEGER,+ FOREIGN KEY (frame_id) REFERENCES frames(id)+);++-- FTS index for semantic search+CREATE VIRTUAL TABLE IF NOT EXISTS ui_events_fts USING fts5(+ text_content,+ app_name,+ window_title,+ element_name,+ element_value,+ content='ui_events',+ content_rowid='id',+ tokenize='porter unicode61'+);++-- Performance indexes+CREATE INDEX IF NOT EXISTS idx_ui_events_timestamp ON ui_events(timestamp DESC);+CREATE INDEX IF NOT EXISTS idx_ui_events_type ON ui_events(event_type);+CREATE INDEX IF NOT EXISTS idx_ui_events_app ON ui_events(app_name);+CREATE INDEX IF NOT EXISTS idx_ui_events_role ON ui_events(element_role);+CREATE INDEX IF NOT EXISTS idx_ui_events_frame ON ui_events(frame_id);++-- Compound index for common queries+CREATE INDEX IF NOT EXISTS idx_ui_events_app_type_time+ ON ui_events(app_name, event_type, timestamp DESC);++-- FTS sync triggers+CREATE TRIGGER IF NOT EXISTS ui_events_ai AFTER INSERT ON ui_events BEGIN+ INSERT INTO ui_events_fts(rowid, text_content, app_name, window_title, element_name, element_value)+ VALUES (new.id, new.text_content, new.app_name, new.window_title, new.element_name, new.element_value);+END;++CREATE TRIGGER IF NOT EXISTS ui_events_ad AFTER DELETE ON ui_events BEGIN+ INSERT INTO ui_events_fts(ui_events_fts, rowid, text_content, app_name, window_title, element_name, element_value)+ VALUES ('delete', old.id, old.text_content, old.app_name, old.window_title, old.element_name, old.element_value);+END;++CREATE TRIGGER IF NOT EXISTS ui_events_au AFTER UPDATE ON ui_events BEGIN+ INSERT INTO ui_events_fts(ui_events_fts, rowid, text_content, app_name, window_title, element_name, element_value)+ VALUES ('delete', old.id, old.text_content, old.app_name, old.window_title, old.element_name, old.element_value);+ INSERT INTO ui_events_fts(rowid, text_content, app_name, window_title, element_name, element_value)+ VALUES (new.id, new.text_content, new.app_name, new.window_title, new.element_name, new.element_value);+END;++-- Daily stats table for dashboard+CREATE TABLE IF NOT EXISTS ui_event_stats (+ date DATE NOT NULL,+ app_name TEXT NOT NULL,+ event_type TEXT NOT NULL,+ count INTEGER DEFAULT 0,+ PRIMARY KEY (date, app_name, event_type)+);diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex 0664e8e25..f5a5060a4 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -19,6 +19,7 @@ screenpipe-vision = { path = "../screenpipe-vision" }screenpipe-audio = { path = "../screenpipe-audio" }screenpipe-core = { path = "../screenpipe-core", features = ["security", "cloud-sync"] }screenpipe-db = { path = "../screenpipe-db" }+screenpipe-accessibility = { path = "../screenpipe-accessibility", features = ["db"], optional = true }killport = { version = "1.1.0" }# Image processing@@ -128,7 +129,7 @@ tokio-tungstenite = "0.24"criterion = { workspace = true }[features]-default = []+default = ["ui-events"]metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]mkl = ["candle/mkl", "candle-nn/mkl", "candle-transformers/mkl"]@@ -136,6 +137,7 @@ llm = []experimental = []debug-console = ["console-subscriber"]adaptive-fps = ["screenpipe-vision/adaptive-fps"]+ui-events = ["screenpipe-accessibility"][[bin]]name = "screenpipe"diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 34d443bc3..42fef0bff 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -24,11 +24,11 @@ use screenpipe_server::{},handle_index_command,pipe_manager::PipeInfo,- start_continuous_recording,+ start_continuous_recording, start_sleep_monitor, start_ui_recording,vision_manager::{start_monitor_watcher, stop_monitor_watcher, VisionManager, VisionManagerConfig,},- watch_pid, PipeManager, ResourceMonitor, SCServer, start_sleep_monitor,+ watch_pid, PipeManager, ResourceMonitor, SCServer,};use screenpipe_vision::monitor::list_monitors;use serde::Deserialize;@@ -743,6 +743,8 @@ async fn main() -> anyhow::Result<()> {let ignored_windows_clone = cli.ignored_windows.clone();let included_windows_clone = cli.included_windows.clone();let realtime_audio_devices_clone = realtime_audio_devices.clone();+ // Create UI recorder config early before cli is moved+ let ui_recorder_config = cli.to_ui_recorder_config();let fps = if cli.fps.is_finite() && cli.fps > 0.0 {cli.fps@@ -1208,6 +1210,23 @@ async fn main() -> anyhow::Result<()> {}}+ // Start UI event recording+ let ui_recorder_handle = {+ if ui_recorder_config.enabled {+ info!("starting UI event capture");+ match start_ui_recording(db.clone(), ui_recorder_config).await {+ Ok(handle) => Some(handle),+ Err(e) => {+ error!("failed to start UI event recording: {}", e);+ None+ }+ }+ } else {+ debug!("UI event capture is disabled");+ None+ }+ };+let server_future = server.start(cli.enable_frame_cache);pin_mut!(server_future);@@ -1264,10 +1283,20 @@ async fn main() -> anyhow::Result<()> {_ = ctrl_c_future => {info!("received ctrl+c, initiating shutdown");audio_manager.shutdown().await?;+ // Stop UI recorder if running+ if let Some(ref handle) = ui_recorder_handle {+ info!("stopping UI event capture");+ handle.stop();+ }let _ = shutdown_tx.send(());}}+ // Wait for UI recorder to finish+ if let Some(handle) = ui_recorder_handle {+ handle.join().await;+ }+tokio::task::block_in_place(|| {drop(pipes_runtime);drop(vision_runtime);diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rsindex d36b3056a..6e1347ef1 100644--- a/screenpipe-server/src/cli.rs+++ b/screenpipe-server/src/cli.rs@@ -334,6 +334,23 @@ impl Cli {generate(shell, &mut cmd, "screenpipe", &mut std::io::stdout());Ok(())}++ /// Create UI recorder configuration from CLI arguments+ #[cfg(feature = "ui-events")]+ pub fn to_ui_recorder_config(&self) -> crate::ui_recorder::UiRecorderConfig {+ // Use sensible defaults - the single enable_ui_events flag controls everything+ let mut config = crate::ui_recorder::UiRecorderConfig::default();+ config.enabled = self.enable_ui_events;+ // Reuse ignored_windows for UI exclusion+ config.excluded_windows = self.ignored_windows.clone();+ config+ }++ /// Create UI recorder configuration (stub when ui-events feature is disabled)+ #[cfg(not(feature = "ui-events"))]+ pub fn to_ui_recorder_config(&self) -> crate::ui_recorder::UiRecorderConfig {+ crate::ui_recorder::UiRecorderConfig { enabled: false }+ }}#[derive(Subcommand)]diff --git a/screenpipe-server/src/cloud_search.rs b/screenpipe-server/src/cloud_search.rsindex b3b2768f7..2b36fec75 100644--- a/screenpipe-server/src/cloud_search.rs+++ b/screenpipe-server/src/cloud_search.rs@@ -96,7 +96,11 @@ impl CloudSearchClient {}/// Get cloud search metadata (for including in search responses).- pub async fn get_metadata(&self, query: &str, time_range: Option<TimeRange>) -> CloudSearchMetadata {+ pub async fn get_metadata(+ &self,+ query: &str,+ time_range: Option<TimeRange>,+ ) -> CloudSearchMetadata {let enabled = self.is_enabled().await;let status = if !enabled {@@ -112,7 +116,10 @@ impl CloudSearchClient {cloud_search_available: enabled && matches!(status, CloudStatus::Available),cloud_has_relevant_data: time_range.is_some(), // Assume cloud has data if time range specifiedcloud_query_hint: if enabled && !query.is_empty() {- Some(format!("Add include_cloud=true to include cloud results for '{}'", query))+ Some(format!(+ "Add include_cloud=true to include cloud results for '{}'",+ query+ ))} else {None},@@ -227,13 +234,16 @@ mod tests {#[tokio::test]async fn test_cloud_search_returns_disabled_status() {let client = CloudSearchClient::new();- let result = client.search(CloudSearchParams {- query: "test".to_string(),- content_type: CloudContentType::All,- time_range: None,- limit: 10,- offset: 0,- }).await.unwrap();+ let result = client+ .search(CloudSearchParams {+ query: "test".to_string(),+ content_type: CloudContentType::All,+ time_range: None,+ limit: 10,+ offset: 0,+ })+ .await+ .unwrap();assert!(result.items.is_empty());assert_eq!(result.cloud_status, CloudStatus::Disabled);diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex 7a24c4376..c92467fd3 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -1,24 +1,25 @@mod add;pub mod analytics;mod auto_destruct;-pub mod sleep_monitor;pub mod chunking;pub mod cli;pub mod cloud_search;pub mod core;-pub mod sync_provider;pub mod filtering;pub mod pipe_manager;mod resource_monitor;mod server;+pub mod sleep_monitor;+pub mod sync_provider;pub mod text_embeds;+pub mod ui_events_api;+pub mod ui_recorder;mod video;pub mod video_cache;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};@@ -32,6 +33,8 @@ pub use server::HealthCheckResponse;pub use server::PaginatedResponse;pub use server::SCServer;pub use server::{api_list_monitors, MonitorInfo};+pub use sleep_monitor::start_sleep_monitor;pub use video::{FrameWriteInfo, FrameWriteTracker, VideoCapture};pub mod embedding;pub use cloud_search::{CloudSearchClient, CloudSearchMetadata, CloudStatus};+pub use ui_recorder::{start_ui_recording, UiRecorderConfig, UiRecorderHandle};diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 7648dc568..16ea89f12 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -487,9 +487,10 @@ pub(crate) async fn search(SearchResult::OCR(ocr) => !is_screenpipe_app(&ocr.app_name),SearchResult::Audio(_) => true, // Audio doesn't have app_nameSearchResult::UI(ui) => !is_screenpipe_app(&ui.app_name),- SearchResult::Input(input) => {- input.app_name.as_ref().map_or(true, |app| !is_screenpipe_app(app))- }+ SearchResult::Input(input) => input+ .app_name+ .as_ref()+ .map_or(true, |app| !is_screenpipe_app(app)),}).map(|result| match result {SearchResult::OCR(ocr) => ContentItem::OCR(OCRContent {@@ -1407,6 +1408,9 @@ impl SCServer {// Build the main router with all routesRouter::new().merge(server.into_router())+ // UI Events API routes+ .route("/ui-events", get(ui_events_search_handler))+ .route("/ui-events/stats", get(ui_events_stats_handler))// NOTE: websockerts and sse is not supported by openapi so we move it down here.route("/stream/frames", get(stream_frames_handler)).route("/ws/events", get(ws_events_handler))@@ -3227,7 +3231,11 @@ pub async fn get_next_valid_frame(let forward = query.direction.to_lowercase() != "backward";// Get candidate frames from database- let candidates = match state.db.get_frames_near(query.frame_id, forward, query.limit).await {+ let candidates = match state+ .db+ .get_frames_near(query.frame_id, forward, query.limit)+ .await+ {Ok(frames) => frames,Err(e) => {error!("Failed to get frames near {}: {}", query.frame_id, e);@@ -3853,6 +3861,34 @@ async fn send_batch(buffer.clear();Ok(())}++// UI Events API handlers+async fn ui_events_search_handler(+ State(state): State<Arc<AppState>>,+ Query(params): Query<crate::ui_events_api::UiEventsQuery>,+) -> Result<Json<crate::ui_events_api::UiEventsResponse>, (StatusCode, String)> {+ match crate::ui_events_api::search_ui_events_handler(state.db.clone(), params).await {+ Ok(response) => Ok(Json(response)),+ Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e)),+ }+}++async fn ui_events_stats_handler(+ State(state): State<Arc<AppState>>,+ Query(params): Query<crate::ui_events_api::UiEventsQuery>,+) -> Result<Json<Vec<crate::ui_events_api::UiEventStats>>, (StatusCode, String)> {+ match crate::ui_events_api::get_ui_event_stats_handler(+ state.db.clone(),+ params.start_time,+ params.end_time,+ )+ .await+ {+ Ok(stats) => Ok(Json(stats)),+ Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e)),+ }+}+async fn stream_frames_handler(ws: WebSocketUpgrade,State(state): State<Arc<AppState>>,diff --git a/screenpipe-server/src/sync_provider.rs b/screenpipe-server/src/sync_provider.rsindex 654bfffbc..1012804c5 100644--- a/screenpipe-server/src/sync_provider.rs+++ b/screenpipe-server/src/sync_provider.rs@@ -33,6 +33,12 @@ pub struct SyncChunk {/// Audio transcription records#[serde(default)]pub transcriptions: Vec<TranscriptionRecord>,+ /// Accessibility records (UI element text)+ #[serde(default)]+ pub accessibility_records: Vec<AccessibilityRecord>,+ /// UI event records (user input actions)+ #[serde(default)]+ pub ui_events: Vec<UiEventSyncRecord>,}/// Frame record for sync@@ -69,8 +75,37 @@ pub struct TranscriptionRecord {pub speaker_id: Option<i64>,}+/// Accessibility record for sync (UI element text from accessibility APIs)+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AccessibilityRecord {+ pub sync_id: String,+ pub timestamp: String,+ pub app_name: String,+ pub window_name: String,+ pub text_content: String,+ pub browser_url: Option<String>,+}++/// UI event record for sync (user input actions)+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct UiEventSyncRecord {+ pub sync_id: String,+ pub timestamp: String,+ pub event_type: String,+ pub app_name: Option<String>,+ pub window_title: Option<String>,+ pub browser_url: Option<String>,+ pub text_content: Option<String>,+ pub x: Option<i32>,+ pub y: Option<i32>,+ pub key_code: Option<i32>,+ pub modifiers: Option<i32>,+ pub element_role: Option<String>,+ pub element_name: Option<String>,+}+/// Current schema version for sync chunks-const SCHEMA_VERSION: u32 = 1;+const SCHEMA_VERSION: u32 = 2;/// Data provider implementation for screenpipe database.pub struct ScreenpipeSyncProvider {@@ -132,7 +167,8 @@ impl ScreenpipeSyncProvider {let mut frame_records = Vec::new();let mut frame_sync_map = std::collections::HashMap::new();- for (id, timestamp, offset_index, app_name, window_name, browser_url, device_name) in frames {+ for (id, timestamp, offset_index, app_name, window_name, browser_url, device_name) in frames+ {let sync_id = Uuid::new_v4().to_string();frame_sync_map.insert(id, sync_id.clone());@@ -152,12 +188,14 @@ impl ScreenpipeSyncProvider {let ocr_records: Vec<OcrRecord> = ocr_results.into_iter().filter_map(|(frame_id, text, focused)| {- frame_sync_map.get(&frame_id).map(|frame_sync_id| OcrRecord {- sync_id: Uuid::new_v4().to_string(),- frame_sync_id: frame_sync_id.clone(),- text,- focused,- })+ frame_sync_map+ .get(&frame_id)+ .map(|frame_sync_id| OcrRecord {+ sync_id: Uuid::new_v4().to_string(),+ frame_sync_id: frame_sync_id.clone(),+ text,+ focused,+ })}).collect();@@ -169,6 +207,8 @@ impl ScreenpipeSyncProvider {frames: frame_records,ocr_records,transcriptions: Vec::new(),+ accessibility_records: Vec::new(),+ ui_events: Vec::new(),};Ok(Some((chunk, time_start, time_end)))@@ -204,14 +244,16 @@ impl ScreenpipeSyncProvider {let records: Vec<TranscriptionRecord> = transcriptions.into_iter()- .map(|(_, timestamp, transcription, device, is_input, speaker_id)| TranscriptionRecord {- sync_id: Uuid::new_v4().to_string(),- timestamp,- transcription,- device,- is_input_device: is_input,- speaker_id,- })+ .map(+ |(_, timestamp, transcription, device, is_input, speaker_id)| TranscriptionRecord {+ sync_id: Uuid::new_v4().to_string(),+ timestamp,+ transcription,+ device,+ is_input_device: is_input,+ speaker_id,+ },+ ).collect();let chunk = SyncChunk {@@ -222,6 +264,160 @@ impl ScreenpipeSyncProvider {frames: Vec::new(),ocr_records: Vec::new(),transcriptions: records,+ accessibility_records: Vec::new(),+ ui_events: Vec::new(),+ };++ Ok(Some((chunk, time_start, time_end)))+ }++ /// Get unsynced accessibility records.+ async fn get_unsynced_accessibility_chunk(+ &self,+ limit: usize,+ ) -> SyncResult<Option<(SyncChunk, String, String)>> {+ let pool = &self.db.pool;++ let records: Vec<(i64, String, String, String, String, Option<String>)> = sqlx::query_as(+ r#"+ SELECT id, timestamp, app_name, window_name, text_content, browser_url+ FROM accessibility+ WHERE synced_at IS NULL+ ORDER BY timestamp ASC+ LIMIT ?+ "#,+ )+ .bind(limit as i64)+ .fetch_all(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to query accessibility: {}", e)))?;++ if records.is_empty() {+ return Ok(None);+ }++ let time_start = records.first().map(|r| r.1.clone()).unwrap();+ let time_end = records.last().map(|r| r.1.clone()).unwrap();++ let accessibility_records: Vec<AccessibilityRecord> = records+ .into_iter()+ .map(+ |(_, timestamp, app_name, window_name, text_content, browser_url)| {+ AccessibilityRecord {+ sync_id: Uuid::new_v4().to_string(),+ timestamp,+ app_name,+ window_name,+ text_content,+ browser_url,+ }+ },+ )+ .collect();++ let chunk = SyncChunk {+ schema_version: SCHEMA_VERSION,+ machine_id: self.machine_id.clone(),+ time_start: time_start.clone(),+ time_end: time_end.clone(),+ frames: Vec::new(),+ ocr_records: Vec::new(),+ transcriptions: Vec::new(),+ accessibility_records,+ ui_events: Vec::new(),+ };++ Ok(Some((chunk, time_start, time_end)))+ }++ /// Get unsynced UI events (user input actions).+ async fn get_unsynced_input_chunk(+ &self,+ limit: usize,+ ) -> SyncResult<Option<(SyncChunk, String, String)>> {+ let pool = &self.db.pool;++ let records: Vec<(+ i64,+ String,+ String,+ Option<String>,+ Option<String>,+ Option<String>,+ Option<String>,+ Option<i32>,+ Option<i32>,+ Option<i32>,+ Option<i32>,+ Option<String>,+ Option<String>,+ )> = sqlx::query_as(+ r#"+ SELECT id, timestamp, event_type, app_name, window_title, browser_url,+ text_content, x, y, key_code, modifiers, element_role, element_name+ FROM ui_events+ WHERE synced_at IS NULL+ ORDER BY timestamp ASC+ LIMIT ?+ "#,+ )+ .bind(limit as i64)+ .fetch_all(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to query ui_events: {}", e)))?;++ if records.is_empty() {+ return Ok(None);+ }++ let time_start = records.first().map(|r| r.1.clone()).unwrap();+ let time_end = records.last().map(|r| r.1.clone()).unwrap();++ let ui_events: Vec<UiEventSyncRecord> = records+ .into_iter()+ .map(+ |(+ _,+ timestamp,+ event_type,+ app_name,+ window_title,+ browser_url,+ text_content,+ x,+ y,+ key_code,+ modifiers,+ element_role,+ element_name,+ )| UiEventSyncRecord {+ sync_id: Uuid::new_v4().to_string(),+ timestamp,+ event_type,+ app_name,+ window_title,+ browser_url,+ text_content,+ x,+ y,+ key_code,+ modifiers,+ element_role,+ element_name,+ },+ )+ .collect();++ let chunk = SyncChunk {+ schema_version: SCHEMA_VERSION,+ machine_id: self.machine_id.clone(),+ time_start: time_start.clone(),+ time_end: time_end.clone(),+ frames: Vec::new(),+ ocr_records: Vec::new(),+ transcriptions: Vec::new(),+ accessibility_records: Vec::new(),+ ui_events,};Ok(Some((chunk, time_start, time_end)))@@ -242,20 +438,24 @@ impl ScreenpipeSyncProvider {imported_frames: 0,imported_ocr: 0,imported_transcriptions: 0,- skipped: chunk.frames.len() + chunk.ocr_records.len() + chunk.transcriptions.len(),+ imported_accessibility: 0,+ imported_ui_events: 0,+ skipped: chunk.frames.len()+ + chunk.ocr_records.len()+ + chunk.transcriptions.len()+ + chunk.accessibility_records.len()+ + chunk.ui_events.len(),});}// Import framesfor frame in &chunk.frames {// Check if already exists- let exists: Option<(i64,)> = sqlx::query_as(- "SELECT id FROM frames WHERE sync_id = ?"- )- .bind(&frame.sync_id)- .fetch_optional(pool)- .await- .map_err(|e| SyncError::Database(format!("failed to check frame: {}", e)))?;+ let exists: Option<(i64,)> = sqlx::query_as("SELECT id FROM frames WHERE sync_id = ?")+ .bind(&frame.sync_id)+ .fetch_optional(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to check frame: {}", e)))?;if exists.is_some() {skipped += 1;@@ -269,7 +469,7 @@ impl ScreenpipeSyncProvider {VALUES ('cloud://' || ?, ?, ?, ?)ON CONFLICT DO NOTHINGRETURNING id- "#+ "#,).bind(&frame.sync_id).bind(&frame.device_name)@@ -313,7 +513,7 @@ impl ScreenpipeSyncProvider {let frame_sync_ids: Vec<String> = chunk.frames.iter().map(|f| f.sync_id.clone()).collect();let frame_id_map: std::collections::HashMap<String, i64> = if !frame_sync_ids.is_empty() {sqlx::query_as::<_, (String, i64)>(- "SELECT sync_id, id FROM frames WHERE sync_id IN (SELECT value FROM json_each(?))"+ "SELECT sync_id, id FROM frames WHERE sync_id IN (SELECT value FROM json_each(?))",).bind(serde_json::to_string(&frame_sync_ids).unwrap()).fetch_all(pool)@@ -329,13 +529,12 @@ impl ScreenpipeSyncProvider {for ocr in &chunk.ocr_records {if let Some(&frame_id) = frame_id_map.get(&ocr.frame_sync_id) {// Check if already exists- let exists: Option<(i64,)> = sqlx::query_as(- "SELECT 1 FROM ocr_text WHERE sync_id = ?"- )- .bind(&ocr.sync_id)- .fetch_optional(pool)- .await- .map_err(|e| SyncError::Database(format!("failed to check OCR: {}", e)))?;+ let exists: Option<(i64,)> =+ sqlx::query_as("SELECT 1 FROM ocr_text WHERE sync_id = ?")+ .bind(&ocr.sync_id)+ .fetch_optional(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to check OCR: {}", e)))?;if exists.is_some() {skipped += 1;@@ -346,7 +545,7 @@ impl ScreenpipeSyncProvider {r#"INSERT INTO ocr_text (frame_id, text, focused, sync_id, synced_at)VALUES (?, ?, ?, ?, ?)- "#+ "#,).bind(frame_id).bind(&ocr.text)@@ -366,13 +565,14 @@ impl ScreenpipeSyncProvider {// Import transcriptionsfor trans in &chunk.transcriptions {// Check if already exists- let exists: Option<(i64,)> = sqlx::query_as(- "SELECT 1 FROM audio_transcriptions WHERE sync_id = ?"- )- .bind(&trans.sync_id)- .fetch_optional(pool)- .await- .map_err(|e| SyncError::Database(format!("failed to check transcription: {}", e)))?;+ let exists: Option<(i64,)> =+ sqlx::query_as("SELECT 1 FROM audio_transcriptions WHERE sync_id = ?")+ .bind(&trans.sync_id)+ .fetch_optional(pool)+ .await+ .map_err(|e| {+ SyncError::Database(format!("failed to check transcription: {}", e))+ })?;if exists.is_some() {skipped += 1;@@ -385,7 +585,7 @@ impl ScreenpipeSyncProvider {INSERT INTO audio_chunks (file_path, device_name, sync_id, machine_id)VALUES ('cloud://' || ?, ?, ?, ?)RETURNING id- "#+ "#,).bind(&trans.sync_id).bind(&trans.device)@@ -416,10 +616,97 @@ impl ScreenpipeSyncProvider {imported_transcriptions += 1;}+ // Import accessibility records+ let mut imported_accessibility = 0;+ for acc in &chunk.accessibility_records {+ // Check if already exists+ let exists: Option<(i64,)> =+ sqlx::query_as("SELECT 1 FROM accessibility WHERE sync_id = ?")+ .bind(&acc.sync_id)+ .fetch_optional(pool)+ .await+ .map_err(|e| {+ SyncError::Database(format!("failed to check accessibility: {}", e))+ })?;++ if exists.is_some() {+ skipped += 1;+ continue;+ }++ sqlx::query(+ r#"+ INSERT INTO accessibility (timestamp, app_name, window_name, text_content, browser_url, sync_id, machine_id, synced_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ "#+ )+ .bind(&acc.timestamp)+ .bind(&acc.app_name)+ .bind(&acc.window_name)+ .bind(&acc.text_content)+ .bind(&acc.browser_url)+ .bind(&acc.sync_id)+ .bind(&chunk.machine_id)+ .bind(Utc::now().to_rfc3339())+ .execute(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to insert accessibility: {}", e)))?;++ imported_accessibility += 1;+ }++ // Import UI events+ let mut imported_ui_events = 0;+ for event in &chunk.ui_events {+ // Check if already exists+ let exists: Option<(i64,)> =+ sqlx::query_as("SELECT 1 FROM ui_events WHERE sync_id = ?")+ .bind(&event.sync_id)+ .fetch_optional(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to check ui_event: {}", e)))?;++ if exists.is_some() {+ skipped += 1;+ continue;+ }++ sqlx::query(+ r#"+ INSERT INTO ui_events (timestamp, event_type, app_name, window_title, browser_url,+ text_content, x, y, key_code, modifiers, element_role, element_name,+ sync_id, machine_id, synced_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ "#,+ )+ .bind(&event.timestamp)+ .bind(&event.event_type)+ .bind(&event.app_name)+ .bind(&event.window_title)+ .bind(&event.browser_url)+ .bind(&event.text_content)+ .bind(event.x)+ .bind(event.y)+ .bind(event.key_code)+ .bind(event.modifiers)+ .bind(&event.element_role)+ .bind(&event.element_name)+ .bind(&event.sync_id)+ .bind(&chunk.machine_id)+ .bind(Utc::now().to_rfc3339())+ .execute(pool)+ .await+ .map_err(|e| SyncError::Database(format!("failed to insert ui_event: {}", e)))?;++ imported_ui_events += 1;+ }+Ok(ImportResult {imported_frames,imported_ocr,imported_transcriptions,+ imported_accessibility,+ imported_ui_events,skipped,})}@@ -441,7 +728,7 @@ impl ScreenpipeSyncProvider {r#"UPDATE frames SET synced_at = ?WHERE timestamp >= ? AND timestamp <= ? AND synced_at IS NULL- "#+ "#,).bind(&now).bind(time_start)@@ -455,14 +742,48 @@ impl ScreenpipeSyncProvider {r#"UPDATE audio_transcriptions SET synced_at = ?WHERE timestamp >= ? AND timestamp <= ? AND synced_at IS NULL- "#+ "#,).bind(&now).bind(time_start).bind(time_end).execute(pool).await- .map_err(|e| SyncError::Database(format!("failed to mark transcriptions synced: {}", e)))?;+ .map_err(|e| {+ SyncError::Database(format!("failed to mark transcriptions synced: {}", e))+ })?;+ }+ BlobType::Accessibility => {+ sqlx::query(+ r#"+ UPDATE accessibility SET synced_at = ?+ WHERE timestamp >= ? AND timestamp <= ? AND synced_at IS NULL+ "#,+ )+ .bind(&now)+ .bind(time_start)+ .bind(time_end)+ .execute(pool)+ .await+ .map_err(|e| {+ SyncError::Database(format!("failed to mark accessibility synced: {}", e))+ })?;+ }+ BlobType::Input => {+ sqlx::query(+ r#"+ UPDATE ui_events SET synced_at = ?+ WHERE timestamp >= ? AND timestamp <= ? AND synced_at IS NULL+ "#,+ )+ .bind(&now)+ .bind(time_start)+ .bind(time_end)+ .execute(pool)+ .await+ .map_err(|e| {+ SyncError::Database(format!("failed to mark ui_events synced: {}", e))+ })?;}_ => {}}@@ -482,6 +803,19 @@ impl ScreenpipeSyncProvider {text_parts.push(trans.transcription.clone());}+ for acc in &chunk.accessibility_records {+ text_parts.push(acc.text_content.clone());+ }++ for event in &chunk.ui_events {+ if let Some(text) = &event.text_content {+ text_parts.push(text.clone());+ }+ if let Some(app) = &event.app_name {+ text_parts.push(app.clone());+ }+ }+text_parts.join(" ")}}@@ -496,14 +830,17 @@ impl SyncDataProvider for ScreenpipeSyncProvider {let chunk_result = match blob_type {BlobType::Ocr => self.get_unsynced_ocr_chunk(limit).await?,BlobType::Transcripts => self.get_unsynced_transcriptions_chunk(limit).await?,+ BlobType::Accessibility => self.get_unsynced_accessibility_chunk(limit).await?,+ BlobType::Input => self.get_unsynced_input_chunk(limit).await?,_ => return Ok(Vec::new()),};match chunk_result {Some((chunk, time_start, time_end)) => {let text_content = Self::get_chunk_text(&chunk);- let data = serde_json::to_vec(&chunk)- .map_err(|e| SyncError::Database(format!("failed to serialize chunk: {}", e)))?;+ let data = serde_json::to_vec(&chunk).map_err(|e| {+ SyncError::Database(format!("failed to serialize chunk: {}", e))+ })?;Ok(vec![PendingBlob {data,@@ -527,7 +864,8 @@ impl SyncDataProvider for ScreenpipeSyncProvider {time_end: &str,_blob_id: &str,) -> SyncResult<()> {- self.mark_records_synced(blob_type, time_start, time_end).await+ self.mark_records_synced(blob_type, time_start, time_end)+ .await}}@@ -537,6 +875,8 @@ pub struct ImportResult {pub imported_frames: usize,pub imported_ocr: usize,pub imported_transcriptions: usize,+ pub imported_accessibility: usize,+ pub imported_ui_events: usize,pub skipped: usize,}@@ -568,6 +908,8 @@ mod tests {focused: true,}],transcriptions: Vec::new(),+ accessibility_records: Vec::new(),+ ui_events: Vec::new(),};let json = serde_json::to_string(&chunk).unwrap();diff --git a/screenpipe-server/src/ui_events_api.rs b/screenpipe-server/src/ui_events_api.rsnew file mode 100644index 000000000..9b5b32251--- /dev/null+++ b/screenpipe-server/src/ui_events_api.rs@@ -0,0 +1,124 @@+//! UI Events API endpoints+//!+//! Provides REST API endpoints for querying UI events (clicks, keystrokes, etc.)++use chrono::{DateTime, Utc};+use screenpipe_db::{DatabaseManager, UiEventRecord};+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use tracing::error;++/// Query parameters for UI events search+#[derive(Debug, Deserialize)]+pub struct UiEventsQuery {+ /// Search query (text content, app name, etc.)+ #[serde(default)]+ pub q: Option<String>,+ /// Filter by event type (click, text, scroll, key, app_switch, window_focus, clipboard)+ #[serde(default)]+ pub event_type: Option<String>,+ /// Filter by app name+ #[serde(default)]+ pub app_name: Option<String>,+ /// Filter by window title+ #[serde(default)]+ pub window_name: Option<String>,+ /// Start time (ISO 8601)+ #[serde(default)]+ pub start_time: Option<DateTime<Utc>>,+ /// End time (ISO 8601)+ #[serde(default)]+ pub end_time: Option<DateTime<Utc>>,+ /// Maximum number of results (default 50)+ #[serde(default = "default_limit")]+ pub limit: u32,+ /// Offset for pagination (default 0)+ #[serde(default)]+ pub offset: u32,+}++fn default_limit() -> u32 {+ 50+}++/// UI Events response+#[derive(Debug, Serialize)]+pub struct UiEventsResponse {+ pub data: Vec<UiEventRecord>,+ pub pagination: PaginationInfo,+}++#[derive(Debug, Serialize)]+pub struct PaginationInfo {+ pub limit: u32,+ pub offset: u32,+ pub total: usize,+}++#[derive(Debug, Serialize)]+pub struct UiEventStats {+ pub app_name: String,+ pub event_type: String,+ pub count: i64,+}++/// Search UI events handler - called from main server router+pub async fn search_ui_events_handler(+ db: Arc<DatabaseManager>,+ params: UiEventsQuery,+) -> Result<UiEventsResponse, String> {+ match db+ .search_ui_events(+ params.q.as_deref(),+ params.event_type.as_deref(),+ params.app_name.as_deref(),+ params.window_name.as_deref(),+ params.start_time,+ params.end_time,+ params.limit,+ params.offset,+ )+ .await+ {+ Ok(events) => {+ let count = events.len();+ Ok(UiEventsResponse {+ data: events,+ pagination: PaginationInfo {+ limit: params.limit,+ offset: params.offset,+ total: count,+ },+ })+ }+ Err(e) => {+ error!("Failed to search UI events: {}", e);+ Err(format!("Failed to search UI events: {}", e))+ }+ }+}++/// Get UI event statistics - called from main server router+pub async fn get_ui_event_stats_handler(+ db: Arc<DatabaseManager>,+ start_time: Option<DateTime<Utc>>,+ end_time: Option<DateTime<Utc>>,+) -> Result<Vec<UiEventStats>, String> {+ match db.get_ui_event_stats(start_time, end_time).await {+ Ok(stats) => {+ let result: Vec<UiEventStats> = stats+ .into_iter()+ .map(|(app, event_type, count)| UiEventStats {+ app_name: app,+ event_type,+ count,+ })+ .collect();+ Ok(result)+ }+ Err(e) => {+ error!("Failed to get UI event stats: {}", e);+ Err(format!("Failed to get UI event stats: {}", e))+ }+ }+}diff --git a/screenpipe-server/src/ui_recorder.rs b/screenpipe-server/src/ui_recorder.rsnew file mode 100644index 000000000..4cbf16c67--- /dev/null+++ b/screenpipe-server/src/ui_recorder.rs@@ -0,0 +1,286 @@+//! UI Event Recording Integration+//!+//! Integrates screenpipe-accessibility capture with the server's recording loop.++#[cfg(feature = "ui-events")]+use anyhow::Result;+#[cfg(feature = "ui-events")]+use screenpipe_accessibility::{UiCaptureConfig, UiRecorder};+#[cfg(feature = "ui-events")]+use screenpipe_db::{DatabaseManager, InsertUiEvent};+#[cfg(feature = "ui-events")]+use std::sync::atomic::{AtomicBool, Ordering};+#[cfg(feature = "ui-events")]+use std::sync::Arc;+#[cfg(feature = "ui-events")]+use std::time::Duration;+#[cfg(feature = "ui-events")]+use tracing::{debug, error, info, warn};+#[cfg(feature = "ui-events")]+use uuid::Uuid;++/// Configuration for UI event capture+#[cfg(feature = "ui-events")]+#[derive(Debug, Clone)]+pub struct UiRecorderConfig {+ /// Enable UI event capture+ pub enabled: bool,+ /// Capture mouse clicks+ pub capture_clicks: bool,+ /// Capture mouse movements (throttled)+ pub capture_mouse_move: bool,+ /// Capture text input (aggregated)+ pub capture_text: bool,+ /// Capture individual keystrokes (privacy sensitive)+ pub capture_keystrokes: bool,+ /// Capture clipboard operations+ pub capture_clipboard: bool,+ /// Capture clipboard content (privacy sensitive)+ pub capture_clipboard_content: bool,+ /// Capture app switches+ pub capture_app_switch: bool,+ /// Capture window focus changes+ pub capture_window_focus: bool,+ /// Capture element context via accessibility+ pub capture_context: bool,+ /// Additional apps to exclude+ pub excluded_apps: Vec<String>,+ /// Window patterns to exclude+ pub excluded_windows: Vec<String>,+ /// Batch size for database inserts+ pub batch_size: usize,+ /// Batch timeout in milliseconds+ pub batch_timeout_ms: u64,+}++#[cfg(feature = "ui-events")]+impl Default for UiRecorderConfig {+ fn default() -> Self {+ Self {+ enabled: false, // Opt-in by default+ capture_clicks: true,+ capture_mouse_move: false,+ capture_text: true,+ capture_keystrokes: false,+ capture_clipboard: true,+ capture_clipboard_content: false,+ capture_app_switch: true,+ capture_window_focus: true,+ capture_context: true,+ excluded_apps: Vec::new(),+ excluded_windows: Vec::new(),+ batch_size: 100,+ batch_timeout_ms: 1000,+ }+ }+}++#[cfg(feature = "ui-events")]+impl UiRecorderConfig {+ /// Convert to screenpipe-ui config+ pub fn to_ui_config(&self) -> UiCaptureConfig {+ let mut config = UiCaptureConfig::new();+ config.enabled = self.enabled;+ config.capture_clicks = self.capture_clicks;+ config.capture_mouse_move = self.capture_mouse_move;+ config.capture_text = self.capture_text;+ config.capture_keystrokes = self.capture_keystrokes;+ config.capture_clipboard = self.capture_clipboard;+ config.capture_clipboard_content = self.capture_clipboard_content;+ config.capture_app_switch = self.capture_app_switch;+ config.capture_window_focus = self.capture_window_focus;+ config.capture_context = self.capture_context;++ // Add excluded apps+ for app in &self.excluded_apps {+ config.excluded_apps.push(app.to_lowercase());+ }++ // Add excluded window patterns+ for pattern in &self.excluded_windows {+ if let Ok(re) = regex::Regex::new(pattern) {+ config.excluded_window_patterns.push(re);+ }+ }++ config+ }+}++/// Handle for managing the UI recorder+#[cfg(feature = "ui-events")]+pub struct UiRecorderHandle {+ stop_flag: Arc<AtomicBool>,+ task_handle: Option<tokio::task::JoinHandle<()>>,+}++#[cfg(feature = "ui-events")]+impl UiRecorderHandle {+ /// Stop the UI recorder+ pub fn stop(&self) {+ self.stop_flag.store(true, Ordering::SeqCst);+ }++ /// Check if still running+ pub fn is_running(&self) -> bool {+ !self.stop_flag.load(Ordering::Relaxed)+ }++ /// Wait for the recorder to stop+ pub async fn join(self) {+ if let Some(handle) = self.task_handle {+ let _ = handle.await;+ }+ }+}++/// Start UI event recording+#[cfg(feature = "ui-events")]+pub async fn start_ui_recording(+ db: Arc<DatabaseManager>,+ config: UiRecorderConfig,+) -> Result<UiRecorderHandle> {+ if !config.enabled {+ info!("UI event capture is disabled");+ return Ok(UiRecorderHandle {+ stop_flag: Arc::new(AtomicBool::new(true)),+ task_handle: None,+ });+ }++ let ui_config = config.to_ui_config();+ let recorder = UiRecorder::new(ui_config);++ // Check permissions+ let perms = recorder.check_permissions();+ if !perms.all_granted() {+ warn!(+ "UI capture permissions not granted - accessibility: {}, input_monitoring: {}",+ perms.accessibility, perms.input_monitoring+ );+ warn!("Requesting permissions...");+ let perms = recorder.request_permissions();+ if !perms.all_granted() {+ error!("UI capture permissions denied. UI event recording will be disabled.");+ return Ok(UiRecorderHandle {+ stop_flag: Arc::new(AtomicBool::new(true)),+ task_handle: None,+ });+ }+ }++ info!("Starting UI event capture");++ let stop_flag = Arc::new(AtomicBool::new(false));+ let stop_flag_clone = stop_flag.clone();+ let batch_size = config.batch_size;+ let batch_timeout = Duration::from_millis(config.batch_timeout_ms);++ // Start the recording+ let handle = match recorder.start() {+ Ok(h) => h,+ Err(e) => {+ error!("Failed to start UI recorder: {}", e);+ return Err(e);+ }+ };++ // Spawn the event processing task+ let task_handle = tokio::spawn(async move {+ let session_id = Uuid::new_v4().to_string();+ info!("UI recording session started: {}", session_id);++ let mut batch: Vec<InsertUiEvent> = Vec::with_capacity(batch_size);+ let mut last_flush = std::time::Instant::now();++ loop {+ if stop_flag_clone.load(Ordering::Relaxed) {+ break;+ }++ // Try to receive events with timeout+ match handle.recv_timeout(Duration::from_millis(100)) {+ Some(event) => {+ let db_event = event.to_db_insert(Some(session_id.clone()));+ batch.push(db_event);++ // Flush if batch is full+ if batch.len() >= batch_size {+ flush_batch(&db, &mut batch).await;+ last_flush = std::time::Instant::now();+ }+ }+ None => {+ // Timeout - check if we should flush+ if !batch.is_empty() && last_flush.elapsed() >= batch_timeout {+ flush_batch(&db, &mut batch).await;+ last_flush = std::time::Instant::now();+ }+ }+ }+ }++ // Final flush+ if !batch.is_empty() {+ flush_batch(&db, &mut batch).await;+ }++ handle.stop();+ info!("UI recording session ended: {}", session_id);+ });++ Ok(UiRecorderHandle {+ stop_flag,+ task_handle: Some(task_handle),+ })+}++#[cfg(feature = "ui-events")]+async fn flush_batch(db: &Arc<DatabaseManager>, batch: &mut Vec<InsertUiEvent>) {+ if batch.is_empty() {+ return;+ }++ match db.insert_ui_events_batch(batch).await {+ Ok(inserted) => {+ debug!("Flushed {} UI events to database", inserted);+ }+ Err(e) => {+ error!("Failed to insert UI events batch: {}", e);+ }+ }+ batch.clear();+}++// Stub implementations when ui-events feature is disabled+#[cfg(not(feature = "ui-events"))]+pub struct UiRecorderConfig {+ pub enabled: bool,+}++#[cfg(not(feature = "ui-events"))]+impl Default for UiRecorderConfig {+ fn default() -> Self {+ Self { enabled: false }+ }+}++#[cfg(not(feature = "ui-events"))]+pub struct UiRecorderHandle;++#[cfg(not(feature = "ui-events"))]+impl UiRecorderHandle {+ pub fn stop(&self) {}+ pub fn is_running(&self) -> bool {+ false+ }+ pub async fn join(self) {}+}++#[cfg(not(feature = "ui-events"))]+pub async fn start_ui_recording(+ _db: std::sync::Arc<screenpipe_db::DatabaseManager>,+ _config: UiRecorderConfig,+) -> anyhow::Result<UiRecorderHandle> {+ Ok(UiRecorderHandle)+}diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex 3bdb3a2bd..eca2bb5e5 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -787,16 +787,10 @@ mod tests {/// Helper to create a synthetic PNG image of given dimensionsfn create_test_png(width: u32, height: u32) -> Vec<u8> {- let img: ImageBuffer<Rgba<u8>, Vec<u8>> =- ImageBuffer::from_fn(width, height, |x, y| {- // Create a simple gradient pattern for visual verification- Rgba([- (x % 256) as u8,- (y % 256) as u8,- ((x + y) % 256) as u8,- 255,- ])- });+ let img: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::from_fn(width, height, |x, y| {+ // Create a simple gradient pattern for visual verification+ Rgba([(x % 256) as u8, (y % 256) as u8, ((x + y) % 256) as u8, 255])+ });let mut buffer = Vec::new();let mut cursor = Cursor::new(&mut buffer);@@ -809,10 +803,14 @@ mod tests {async fn get_video_dimensions(video_path: &str) -> Result<(u32, u32), anyhow::Error> {let output = Command::new("ffprobe").args([- "-v", "error",- "-select_streams", "v:0",- "-show_entries", "stream=width,height",- "-of", "csv=s=x:p=0",+ "-v",+ "error",+ "-select_streams",+ "v:0",+ "-show_entries",+ "stream=width,height",+ "-of",+ "csv=s=x:p=0",video_path,]).output()@@ -851,7 +849,11 @@ mod tests {drop(stdin);let output = child.wait_with_output().await.expect("FFmpeg failed");- assert!(output.status.success(), "FFmpeg exited with error: {:?}", String::from_utf8_lossy(&output.stderr));+ assert!(+ output.status.success(),+ "FFmpeg exited with error: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );// Verify output dimensions are even (1920x1080)let (width, height) = get_video_dimensions(output_str)@@ -885,7 +887,11 @@ mod tests {drop(stdin);let output = child.wait_with_output().await.expect("FFmpeg failed");- assert!(output.status.success(), "FFmpeg exited with error: {:?}", String::from_utf8_lossy(&output.stderr));+ assert!(+ output.status.success(),+ "FFmpeg exited with error: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );let (width, height) = get_video_dimensions(output_str).await@@ -917,7 +923,11 @@ mod tests {drop(stdin);let output = child.wait_with_output().await.expect("FFmpeg failed");- assert!(output.status.success(), "FFmpeg exited with error: {:?}", String::from_utf8_lossy(&output.stderr));+ assert!(+ output.status.success(),+ "FFmpeg exited with error: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );let (width, height) = get_video_dimensions(output_str).await@@ -951,7 +961,11 @@ mod tests {drop(stdin);let output = child.wait_with_output().await.expect("FFmpeg failed");- assert!(output.status.success(), "FFmpeg exited with error: {:?}", String::from_utf8_lossy(&output.stderr));+ assert!(+ output.status.success(),+ "FFmpeg exited with error: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );let (width, height) = get_video_dimensions(output_str).await@@ -983,7 +997,11 @@ mod tests {drop(stdin);let output = child.wait_with_output().await.expect("FFmpeg failed");- assert!(output.status.success(), "FFmpeg exited with error: {:?}", String::from_utf8_lossy(&output.stderr));+ assert!(+ output.status.success(),+ "FFmpeg exited with error: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );let (width, height) = get_video_dimensions(output_str).awaitdiff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rsindex 70138a07e..313f91463 100644--- a/screenpipe-server/tests/tags_test.rs+++ b/screenpipe-server/tests/tags_test.rs@@ -152,6 +152,9 @@ async fn test_add_tags_and_search() {ContentItem::UI(_) => {unreachable!()}+ ContentItem::Input(_) => {+ unreachable!()+ }}}}@@ -352,6 +355,9 @@ async fn test_search_by_multiple_tags() {ContentItem::UI(_) => {panic!("UI content should not be included in the results");}+ ContentItem::Input(_) => {+ panic!("Input content should not be included in the results");+ }}}}