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: fuzzy dedup via SimHash + browser URL capture in accessibility
Louis Beaumont56b242eaad3f
diff --git a/crates/screenpipe-accessibility/src/tree/cache.rs b/crates/screenpipe-accessibility/src/tree/cache.rsindex ea01cdcb3..d307928d1 100644--- a/crates/screenpipe-accessibility/src/tree/cache.rs+++ b/crates/screenpipe-accessibility/src/tree/cache.rs@@ -9,18 +9,24 @@use std::collections::HashMap;use std::time::{Duration, Instant};-use super::TreeSnapshot;+use super::{hamming_distance, TreeSnapshot};const MAX_ENTRIES: usize = 100;const DEFAULT_TTL: Duration = Duration::from_secs(60);-/// Cache entry tracking the last stored content hash for a window.+/// Hamming distance threshold for fuzzy dedup: if distance <= this, content is "similar enough" to skip.+/// Real accessibility text is typically hundreds of words; scrolling changes ~10-20% of content,+/// which corresponds to roughly 5-10 bit differences in a 64-bit SimHash.+const SIMHASH_THRESHOLD: u32 = 10;++/// Cache entry tracking the last stored simhash for a window.struct CacheEntry {- content_hash: u64,+ simhash: u64,last_stored: Instant,}-/// Content-hash dedup cache keyed on (app_name, window_name).+/// Fuzzy-dedup cache keyed on (app_name, window_name).+/// Uses SimHash with Hamming distance to detect near-duplicate content.pub struct TreeCache {entries: HashMap<(String, String), CacheEntry>,ttl: Duration,@@ -35,12 +41,13 @@ impl TreeCache {}}- /// Check if a snapshot should be stored (hash differs or TTL expired).+ /// Check if a snapshot should be stored (content differs enough or TTL expired).+ /// Uses SimHash hamming distance for fuzzy comparison.pub fn should_store(&self, snapshot: &TreeSnapshot) -> bool {let key = (snapshot.app_name.clone(), snapshot.window_name.clone());match self.entries.get(&key) {Some(entry) => {- entry.content_hash != snapshot.content_hash+ hamming_distance(entry.simhash, snapshot.simhash) > SIMHASH_THRESHOLD|| entry.last_stored.elapsed() >= self.ttl}None => true,@@ -48,12 +55,12 @@ impl TreeCache {}/// Record that a snapshot was stored.- pub fn record_store(&mut self, app_name: &str, window_name: &str, content_hash: u64) {+ pub fn record_store(&mut self, app_name: &str, window_name: &str, simhash: u64) {let key = (app_name.to_string(), window_name.to_string());self.entries.insert(key,CacheEntry {- content_hash,+ simhash,last_stored: Instant::now(),},);@@ -97,40 +104,106 @@ mod tests {node_count: 1,walk_duration: Duration::from_millis(10),content_hash: TreeSnapshot::compute_hash(text),+ simhash: TreeSnapshot::compute_simhash(text),}}#[test]- fn test_cache_dedup_same_hash() {+ fn test_cache_dedup_same_content() {let mut cache = TreeCache::new();- let snap = make_snapshot("Chrome", "Tab 1", "hello world");+ let snap = make_snapshot("Chrome", "Tab 1", "hello world foo bar baz");assert!(cache.should_store(&snap));- cache.record_store(&snap.app_name, &snap.window_name, snap.content_hash);+ cache.record_store(&snap.app_name, &snap.window_name, snap.simhash);// Same content — should NOT storeassert!(!cache.should_store(&snap));}#[test]- fn test_cache_different_hash() {+ fn test_cache_fuzzy_rejects_similar() {let mut cache = TreeCache::new();- let snap1 = make_snapshot("Chrome", "Tab 1", "hello world");- cache.record_store(&snap1.app_name, &snap1.window_name, snap1.content_hash);+ let base_text = "Welcome to the documentation site\n\+ Getting started with the framework\n\+ Installation guide for new users\n\+ Configure your development environment\n\+ Set up the database connection\n\+ Create your first application\n\+ Understanding the project structure\n\+ Working with models and controllers\n\+ Routing and middleware configuration\n\+ Authentication and authorization setup\n\+ Testing your application thoroughly\n\+ Deployment best practices guide\n\+ Performance optimization techniques\n\+ Monitoring and logging setup\n\+ Troubleshooting common issues here\n\+ Community support and resources\n\+ Contributing to the project\n\+ License and copyright information";+ let snap1 = make_snapshot("Chrome", "Tab 1", base_text);+ cache.record_store(&snap1.app_name, &snap1.window_name, snap1.simhash);++ // Scroll: last 2 lines change+ let scrolled_text = "Welcome to the documentation site\n\+ Getting started with the framework\n\+ Installation guide for new users\n\+ Configure your development environment\n\+ Set up the database connection\n\+ Create your first application\n\+ Understanding the project structure\n\+ Working with models and controllers\n\+ Routing and middleware configuration\n\+ Authentication and authorization setup\n\+ Testing your application thoroughly\n\+ Deployment best practices guide\n\+ Performance optimization techniques\n\+ Monitoring and logging setup\n\+ Troubleshooting common issues here\n\+ Community support and resources\n\+ Frequently asked questions page\n\+ API reference documentation here";+ let snap2 = make_snapshot("Chrome", "Tab 1", scrolled_text);+ assert!(+ !cache.should_store(&snap2),+ "fuzzy dedup should reject similar content (hamming dist: {})",+ super::hamming_distance(snap1.simhash, snap2.simhash)+ );+ }- let snap2 = make_snapshot("Chrome", "Tab 1", "different content");- assert!(cache.should_store(&snap2));+ #[test]+ fn test_cache_accepts_different() {+ let mut cache = TreeCache::new();+ let snap1 = make_snapshot(+ "Chrome",+ "Tab 1",+ "the quick brown fox jumps over the lazy dog and runs through the forest \+ chasing rabbits while the sun sets behind the mountains creating beautiful colors",+ );+ cache.record_store(&snap1.app_name, &snap1.window_name, snap1.simhash);++ let snap2 = make_snapshot(+ "Chrome",+ "Tab 1",+ "rust programming language provides memory safety without garbage collection \+ enabling developers to build reliable and efficient software systems today",+ );+ assert!(+ cache.should_store(&snap2),+ "different content should be stored (hamming dist: {})",+ super::hamming_distance(snap1.simhash, snap2.simhash)+ );}#[test]- fn test_cache_ttl_expiry() {+ fn test_cache_ttl_overrides_similarity() {let mut cache = TreeCache {entries: HashMap::new(),ttl: Duration::from_millis(0), // immediate expiry};- let snap = make_snapshot("Chrome", "Tab 1", "hello world");- cache.record_store(&snap.app_name, &snap.window_name, snap.content_hash);+ let snap = make_snapshot("Chrome", "Tab 1", "hello world foo bar baz");+ cache.record_store(&snap.app_name, &snap.window_name, snap.simhash);// Even same hash — TTL expired so should storestd::thread::sleep(Duration::from_millis(1));@@ -151,10 +224,10 @@ mod tests {#[test]fn test_cache_different_windows() {let mut cache = TreeCache::new();- let snap1 = make_snapshot("Chrome", "Tab 1", "content A");- let snap2 = make_snapshot("Chrome", "Tab 2", "content A");+ let snap1 = make_snapshot("Chrome", "Tab 1", "content A foo bar baz");+ let snap2 = make_snapshot("Chrome", "Tab 2", "content A foo bar baz");- cache.record_store(&snap1.app_name, &snap1.window_name, snap1.content_hash);+ cache.record_store(&snap1.app_name, &snap1.window_name, snap1.simhash);// Different window — separate cache entry, should storeassert!(cache.should_store(&snap2));diff --git a/crates/screenpipe-accessibility/src/tree/macos.rs b/crates/screenpipe-accessibility/src/tree/macos.rsindex a0284a6f8..c4b8cea47 100644--- a/crates/screenpipe-accessibility/src/tree/macos.rs+++ b/crates/screenpipe-accessibility/src/tree/macos.rs@@ -8,9 +8,144 @@ use super::{TreeSnapshot, TreeWalkerConfig, TreeWalkerPlatform};use anyhow::Result;use chrono::Utc;use cidre::{ax, cf, ns};+use std::process::Command;use std::time::Instant;use tracing::debug;+/// Known browser app names (lowercase). Matches vision crate's list.+const BROWSER_NAMES: &[&str] = &[+ "chrome",+ "firefox",+ "safari",+ "edge",+ "brave",+ "arc",+ "chromium",+ "vivaldi",+ "opera",+ "zen",+ "brave browser",+ "google chrome",+ "microsoft edge",+];++/// Check if the app (lowercase name) is a known browser.+fn is_browser(app_lower: &str) -> bool {+ BROWSER_NAMES.iter().any(|b| app_lower.contains(b))+}++/// Extract the browser URL from the focused window using AX APIs.+/// Tries AXDocument first (works for Safari, Chrome, etc.), then+/// AppleScript for Arc, then falls back to shallow AXTextField walk.+fn extract_browser_url(+ window: &ax::UiElement,+ app_name: &str,+ window_name: &str,+) -> Option<String> {+ // Tier 1: AXDocument attribute on the window+ if let Some(url) = get_string_attr(window, ax::attr::document()) {+ if url.starts_with("http://") || url.starts_with("https://") {+ return Some(url);+ }+ }++ // Tier 2: For Arc, use AppleScript (AXDocument may not be set)+ let app_lower = app_name.to_lowercase();+ if app_lower.contains("arc") {+ if let Some(url) = get_arc_url(window_name) {+ return Some(url);+ }+ }++ // Tier 3: Shallow walk for AXTextField with URL-like value+ if let Some(url) = find_url_in_children(window, 0, 5) {+ return Some(url);+ }++ None+}++/// Get Arc browser's current URL via AppleScript.+/// Cross-checks the returned title against window_name to avoid stale results.+fn get_arc_url(window_name: &str) -> Option<String> {+ let script = r#"tell application "Arc"+ set currentTab to active tab of front window+ set tabURL to URL of currentTab+ set tabTitle to title of currentTab+ return tabTitle & "\n" & tabURL+ end tell"#;++ let output = Command::new("osascript")+ .arg("-e")+ .arg(script)+ .output()+ .ok()?;++ if !output.status.success() {+ return None;+ }++ let result = String::from_utf8_lossy(&output.stdout).trim().to_string();+ let mut lines = result.lines();+ let title = lines.next()?;+ let url = lines.next()?;++ // Cross-check: window title should contain the tab title (or vice versa)+ let window_lower = window_name.to_lowercase();+ let title_lower = title.to_lowercase();+ if !window_lower.contains(&title_lower) && !title_lower.contains(&window_lower) {+ // Title mismatch — may be stale+ return None;+ }++ if url.starts_with("http://") || url.starts_with("https://") {+ Some(url.to_string())+ } else {+ None+ }+}++/// Shallow walk of AX children to find a text field containing a URL.+fn find_url_in_children(elem: &ax::UiElement, depth: usize, max_depth: usize) -> Option<String> {+ if depth >= max_depth {+ return None;+ }++ let children = elem.children().ok()?;+ for i in 0..children.len() {+ let child = &children[i];+ let _ = child.set_messaging_timeout_secs(0.1);++ if let Ok(role) = child.role() {+ let role_str = role.to_string();+ if role_str == "AXTextField" || role_str == "AXComboBox" {+ if let Some(val) = get_string_attr(child, ax::attr::value()) {+ if looks_like_url(&val) {+ return Some(val);+ }+ }+ }+ }++ // Recurse+ if let Some(url) = find_url_in_children(child, depth + 1, max_depth) {+ return Some(url);+ }+ }+ None+}++/// Heuristic: does this string look like a URL?+fn looks_like_url(s: &str) -> bool {+ let trimmed = s.trim();+ if trimmed.is_empty() || trimmed.contains(' ') {+ return false;+ }+ trimmed.starts_with("http://")+ || trimmed.starts_with("https://")+ || (trimmed.contains('.') && !trimmed.starts_with('.') && trimmed.len() > 4)+}+/// macOS tree walker using cidre's AX bindings.pub struct MacosTreeWalker {config: TreeWalkerConfig,@@ -133,14 +268,23 @@ impl TreeWalkerPlatform for MacosTreeWalker {};let content_hash = TreeSnapshot::compute_hash(&text_content);+ let simhash = TreeSnapshot::compute_simhash(&text_content);let walk_duration = start.elapsed();+ // Extract browser URL (runs after tree walk to avoid affecting walk timeout)+ let browser_url = if is_browser(&app_lower) {+ extract_browser_url(window, &app_name, &window_name)+ } else {+ None+ };+debug!(- "tree walk: app={}, window={}, nodes={}, text_len={}, duration={:?}",+ "tree walk: app={}, window={}, nodes={}, text_len={}, url={:?}, duration={:?}",app_name,window_name,state.node_count,text_content.len(),+ browser_url,walk_duration);@@ -148,11 +292,12 @@ impl TreeWalkerPlatform for MacosTreeWalker {app_name,window_name,text_content,- browser_url: None,+ browser_url,timestamp: Utc::now(),node_count: state.node_count,walk_duration,content_hash,+ simhash,}))}}@@ -374,6 +519,37 @@ mod tests {assert_eq!(buf, "hello\nworld"); // empty/whitespace skipped}+ #[test]+ fn test_is_browser() {+ assert!(is_browser("google chrome"));+ assert!(is_browser("safari"));+ assert!(is_browser("firefox"));+ assert!(is_browser("arc"));+ assert!(is_browser("brave browser"));+ assert!(is_browser("microsoft edge"));+ assert!(is_browser("vivaldi"));+ assert!(is_browser("opera"));+ assert!(is_browser("zen"));+ assert!(is_browser("chromium"));+ assert!(!is_browser("finder"));+ assert!(!is_browser("terminal"));+ assert!(!is_browser("textedit"));+ assert!(!is_browser("visual studio code"));+ assert!(!is_browser("screenpipe"));+ }++ #[test]+ fn test_looks_like_url() {+ assert!(looks_like_url("https://example.com"));+ assert!(looks_like_url("http://localhost:3000"));+ assert!(looks_like_url("example.com"));+ assert!(looks_like_url("docs.rs"));+ assert!(!looks_like_url(""));+ assert!(!looks_like_url("hello world"));+ assert!(!looks_like_url(".hidden"));+ assert!(!looks_like_url("abc"));+ }+#[test]#[cfg(target_os = "macos")]fn test_walk_focused_window_returns_result() {diff --git a/crates/screenpipe-accessibility/src/tree/mod.rs b/crates/screenpipe-accessibility/src/tree/mod.rsindex ec4ce9f16..59dc5bda8 100644--- a/crates/screenpipe-accessibility/src/tree/mod.rs+++ b/crates/screenpipe-accessibility/src/tree/mod.rs@@ -29,6 +29,8 @@ pub struct TreeSnapshot {pub node_count: usize,pub walk_duration: Duration,pub content_hash: u64,+ /// Locality-sensitive hash for fuzzy dedup (similar text → small hamming distance).+ pub simhash: u64,}impl TreeSnapshot {@@ -38,6 +40,50 @@ impl TreeSnapshot {text.hash(&mut hasher);hasher.finish()}++ /// Compute a SimHash (locality-sensitive hash) for fuzzy dedup.+ /// Uses word-level 3-shingles: similar texts produce hashes with small Hamming distance.+ pub fn compute_simhash(text: &str) -> u64 {+ let words: Vec<&str> = text.split_whitespace().collect();+ if words.is_empty() {+ return 0;+ }++ // Accumulator for each bit position+ let mut bits = [0i32; 64];++ // Generate 3-shingles (or fewer if text is short)+ let shingle_size = 3.min(words.len());+ for window in words.windows(shingle_size) {+ let mut hasher = DefaultHasher::new();+ for w in window {+ w.hash(&mut hasher);+ }+ let hash = hasher.finish();++ for i in 0..64 {+ if (hash >> i) & 1 == 1 {+ bits[i] += 1;+ } else {+ bits[i] -= 1;+ }+ }+ }++ // Convert accumulator to hash: bit is 1 if sum > 0+ let mut result: u64 = 0;+ for i in 0..64 {+ if bits[i] > 0 {+ result |= 1 << i;+ }+ }+ result+ }+}++/// Hamming distance between two 64-bit hashes (number of differing bits).+pub fn hamming_distance(a: u64, b: u64) -> u32 {+ (a ^ b).count_ones()}/// Configuration for the tree walker.@@ -137,4 +183,92 @@ mod tests {assert_eq!(config.walk_timeout, Duration::from_millis(100));assert_eq!(config.max_text_length, 50_000);}++ #[test]+ fn test_simhash_identical() {+ let h1 = TreeSnapshot::compute_simhash("the quick brown fox jumps over the lazy dog");+ let h2 = TreeSnapshot::compute_simhash("the quick brown fox jumps over the lazy dog");+ assert_eq!(hamming_distance(h1, h2), 0);+ }++ #[test]+ fn test_simhash_similar() {+ // Realistic page content — scrolling changes a few lines out of many+ let base = "Welcome to the documentation site\n\+ Getting started with the framework\n\+ Installation guide for new users\n\+ Configure your development environment\n\+ Set up the database connection\n\+ Create your first application\n\+ Understanding the project structure\n\+ Working with models and controllers\n\+ Routing and middleware configuration\n\+ Authentication and authorization setup\n\+ Testing your application thoroughly\n\+ Deployment best practices guide\n\+ Performance optimization techniques\n\+ Monitoring and logging setup\n\+ Troubleshooting common issues here\n\+ Community support and resources\n\+ Contributing to the project\n\+ License and copyright information";+ // Scroll: last 2 lines change, rest stays the same+ let scrolled = "Welcome to the documentation site\n\+ Getting started with the framework\n\+ Installation guide for new users\n\+ Configure your development environment\n\+ Set up the database connection\n\+ Create your first application\n\+ Understanding the project structure\n\+ Working with models and controllers\n\+ Routing and middleware configuration\n\+ Authentication and authorization setup\n\+ Testing your application thoroughly\n\+ Deployment best practices guide\n\+ Performance optimization techniques\n\+ Monitoring and logging setup\n\+ Troubleshooting common issues here\n\+ Community support and resources\n\+ Frequently asked questions page\n\+ API reference documentation here";+ let h1 = TreeSnapshot::compute_simhash(base);+ let h2 = TreeSnapshot::compute_simhash(scrolled);+ let dist = hamming_distance(h1, h2);+ assert!(+ dist <= 10,+ "similar texts (scroll) should have hamming distance <= 10, got {}",+ dist+ );+ }++ #[test]+ fn test_simhash_different() {+ let h1 = TreeSnapshot::compute_simhash(+ "the quick brown fox jumps over the lazy dog and runs through the forest \+ chasing rabbits while the sun sets behind the mountains creating beautiful colors",+ );+ let h2 = TreeSnapshot::compute_simhash(+ "rust programming language provides memory safety without garbage collection \+ enabling developers to build reliable and efficient software systems today",+ );+ let dist = hamming_distance(h1, h2);+ assert!(+ dist > 10,+ "very different texts should have hamming distance > 10, got {}",+ dist+ );+ }++ #[test]+ fn test_simhash_empty() {+ assert_eq!(TreeSnapshot::compute_simhash(""), 0);+ assert_eq!(TreeSnapshot::compute_simhash(" "), 0);+ }++ #[test]+ fn test_hamming_distance() {+ assert_eq!(hamming_distance(0, 0), 0);+ assert_eq!(hamming_distance(0b1111, 0b0000), 4);+ assert_eq!(hamming_distance(u64::MAX, 0), 64);+ }}diff --git a/crates/screenpipe-accessibility/src/tree/windows.rs b/crates/screenpipe-accessibility/src/tree/windows.rsindex 2a996c1f9..df225a6e3 100644--- a/crates/screenpipe-accessibility/src/tree/windows.rs+++ b/crates/screenpipe-accessibility/src/tree/windows.rs@@ -198,6 +198,7 @@ impl TreeWalkerPlatform for WindowsTreeWalker {let node_count = root.node_count();let content_hash = TreeSnapshot::compute_hash(&text_buffer);+ let simhash = TreeSnapshot::compute_simhash(&text_buffer);let walk_duration = start.elapsed();debug!(@@ -218,6 +219,7 @@ impl TreeWalkerPlatform for WindowsTreeWalker {node_count,walk_duration,content_hash,+ simhash,}))}}diff --git a/crates/screenpipe-accessibility/tests/e2e_tree_walker.rs b/crates/screenpipe-accessibility/tests/e2e_tree_walker.rsindex 0d5ee1e80..abd65491c 100644--- a/crates/screenpipe-accessibility/tests/e2e_tree_walker.rs+++ b/crates/screenpipe-accessibility/tests/e2e_tree_walker.rs@@ -262,11 +262,11 @@ mod e2e {println!(" First walk: app={}, hash={}, text_len={}",snap.app_name,- snap.content_hash,+ snap.simhash,snap.text_content.len());assert!(cache.should_store(&snap), "first walk should store");- cache.record_store(&snap.app_name, &snap.window_name, snap.content_hash);+ cache.record_store(&snap.app_name, &snap.window_name, snap.simhash);// Walk again immediately — no user interaction, content should be stablelet snap2 = walker.walk_focused_window().unwrap();@@ -439,7 +439,7 @@ mod e2e {match walker.walk_focused_window() {Ok(Some(snap)) => {if cache.should_store(&snap) {- cache.record_store(&snap.app_name, &snap.window_name, snap.content_hash);+ cache.record_store(&snap.app_name, &snap.window_name, snap.simhash);stored += 1;} else {deduped += 1;diff --git a/crates/screenpipe-server/src/ui_recorder.rs b/crates/screenpipe-server/src/ui_recorder.rsindex 1b27fc86d..7655dad03 100644--- a/crates/screenpipe-server/src/ui_recorder.rs+++ b/crates/screenpipe-server/src/ui_recorder.rs@@ -500,7 +500,7 @@ fn run_tree_walker(cache.record_store(&snap.app_name,&snap.window_name,- snap.content_hash,+ snap.simhash,);metrics.walks_stored += 1;}