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
fix(timeline): tight per-word search highlights
Louis Beaumont7e829fd336a6
diff --git a/apps/screenpipe-app-tauri/components/text-overlay.tsx b/apps/screenpipe-app-tauri/components/text-overlay.tsxindex b46d16dc9..6c4fc059d 100644--- a/apps/screenpipe-app-tauri/components/text-overlay.tsx+++ b/apps/screenpipe-app-tauri/components/text-overlay.tsx@@ -285,7 +285,10 @@ export const TextOverlay = memo(function TextOverlay({if (blockWidth <= 0 || blockHeight <= 0) continue;// Skip if this highlight largely overlaps an existing one- // (OCR + accessibility can return near-identical bounding boxes)+ // (OCR + accessibility can return near-identical bounding boxes).+ // Compare against the smaller of the two areas so a tight word box+ // inside a paragraph-sized one isn't suppressed when both match.+ const thisArea = blockWidth * blockHeight;const isDuplicate = result.some(existing => {const overlapLeft = Math.max(existing.left, blockLeft);const overlapTop = Math.max(existing.top, blockTop);@@ -293,8 +296,9 @@ export const TextOverlay = memo(function TextOverlay({const overlapBottom = Math.min(existing.top + existing.height, blockTop + blockHeight);if (overlapRight <= overlapLeft || overlapBottom <= overlapTop) return false;const overlapArea = (overlapRight - overlapLeft) * (overlapBottom - overlapTop);- const thisArea = blockWidth * blockHeight;- return overlapArea > thisArea * 0.5;+ const existingArea = existing.width * existing.height;+ const minArea = Math.min(thisArea, existingArea);+ return overlapArea > minArea * 0.7;});if (isDuplicate) continue;@@ -355,9 +359,10 @@ export const TextOverlay = memo(function TextOverlay({top: hl.top,width: hl.width,height: hl.height,- backgroundColor: "rgba(250, 204, 21, 0.35)",- border: "1px solid rgba(250, 204, 21, 0.7)",- borderRadius: "2px",+ backgroundColor: "rgba(250, 204, 21, 0.22)",+ border: "1px solid rgba(250, 204, 21, 0.85)",+ borderRadius: "3px",+ boxShadow: "0 0 6px rgba(250, 204, 21, 0.45)",}}/>))}diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rsindex 78a334989..e53c3b103 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -7715,29 +7715,83 @@ pub fn find_matching_positions(blocks: &[OcrTextBlock], query: &str) -> Vec<Text.filter_map(|block| {let text_lower = block.text.to_lowercase();- // Check for exact match or any word match- let matches = text_lower.contains(&query_lower)- || query_words.iter().any(|&word| text_lower.contains(word));-- if matches {- // Stored coords are already screen space (top-left origin); use as-is.- Some(TextPosition {- text: block.text.clone(),- confidence: block.conf.parse::<f32>().unwrap_or(0.0),- bounds: TextBounds {- left: block.left.parse::<f32>().unwrap_or(0.0),- top: block.top.parse::<f32>().unwrap_or(0.0),- width: block.width.parse::<f32>().unwrap_or(0.0),- height: block.height.parse::<f32>().unwrap_or(0.0),- },- })+ // Pick the needle that's actually in the text (full query or first matching word)+ // so legacy paragraph-level OCR rows can be narrowed to where the term appears.+ let needle = if text_lower.contains(&query_lower) {+ Some(query_lower.as_str())} else {- None- }+ query_words+ .iter()+ .copied()+ .find(|w| text_lower.contains(*w))+ }?;++ // Stored coords are already screen space (top-left origin); use as-is.+ let left = block.left.parse::<f32>().unwrap_or(0.0);+ let top = block.top.parse::<f32>().unwrap_or(0.0);+ let width = block.width.parse::<f32>().unwrap_or(0.0);+ let height = block.height.parse::<f32>().unwrap_or(0.0);++ let (n_left, n_width) =+ narrow_bbox_to_needle(&block.text, &text_lower, needle, left, width, height);++ Some(TextPosition {+ text: block.text.clone(),+ confidence: block.conf.parse::<f32>().unwrap_or(0.0),+ bounds: TextBounds {+ left: n_left,+ top,+ width: n_width,+ height,+ },+ })}).collect()}+/// Narrow a single-line-ish bbox to the sub-rect where `needle` appears within `text`.+/// Returns (new_left, new_width). Falls back to the original bbox when the element+/// looks multi-line (text doesn't fit within a single line at the bbox's aspect ratio),+/// because proportional narrowing only makes sense for single-line elements.+fn narrow_bbox_to_needle(+ text: &str,+ text_lower: &str,+ needle: &str,+ left: f32,+ width: f32,+ height: f32,+) -> (f32, f32) {+ let text_len = text.chars().count();+ if text_len == 0 || height <= 0.0 {+ return (left, width);+ }+ // Estimate single-line capacity from aspect ratio: avg proportional-font char width+ // is ~0.55 * line height. With 1.6x slack to tolerate variable fonts/spacing.+ let aspect = width / height;+ let chars_per_line_est = (aspect / 0.55) * 1.6;+ if (text_len as f32) > chars_per_line_est {+ // Likely multi-line — leave bbox alone, otherwise we'd draw a thin sliver+ // across all lines which is more confusing than a full element rect.+ return (left, width);+ }++ let Some(byte_offset) = text_lower.find(needle) else {+ return (left, width);+ };+ let char_offset = text_lower[..byte_offset].chars().count();+ let needle_chars = needle.chars().count();+ if needle_chars == 0 {+ return (left, width);+ }+ let frac_start = char_offset as f32 / text_len as f32;+ let frac_width = needle_chars as f32 / text_len as f32;+ let new_left = left + frac_start * width;+ // Floor at half the line height so very short queries (single chars) still draw.+ let min_w = (height * 0.5).min(width);+ let new_width = (frac_width * width).max(min_w);+ (new_left, new_width)+}+/// Search accessibility tree JSON nodes for a query and return matching positions./// Used as fallback when OCR text_json has no bounding boxes for a frame.pub fn find_matching_a11y_positions(tree_json: &str, query: &str) -> Vec<TextPosition> {@@ -7757,11 +7811,18 @@ pub fn find_matching_a11y_positions(tree_json: &str, query: &str) -> Vec<TextPosreturn None;}let text_lower = text.to_lowercase();- let is_match = text_lower.contains(&query_lower)- || query_words.iter().any(|&word| text_lower.contains(word));- if !is_match {- return None;- }+ // Find which needle (full query or first matching word) is present, so we can+ // narrow the bbox to roughly where it appears in the element's text instead of+ // highlighting the whole AX element rect.+ let needle = if text_lower.contains(&query_lower) {+ Some(query_lower.as_str())+ } else {+ query_words+ .iter()+ .copied()+ .find(|w| text_lower.contains(*w))+ };+ let needle = needle?;let b = n.get("bounds")?;let left = b.get("left")?.as_f64()? as f32;let top = b.get("top")?.as_f64()? as f32;@@ -7771,13 +7832,16 @@ pub fn find_matching_a11y_positions(tree_json: &str, query: &str) -> Vec<TextPosif width <= 0.001 || height <= 0.001 {return None;}++ let (n_left, n_width) = narrow_bbox_to_needle(text, &text_lower, needle, left, width, height);+Some(TextPosition {text: text.to_string(),confidence: 1.0,bounds: TextBounds {- left,+ left: n_left,top,- width,+ width: n_width,height,},})diff --git a/crates/screenpipe-screen/src/apple.rs b/crates/screenpipe-screen/src/apple.rsindex 84748076f..36055f13b 100644--- a/crates/screenpipe-screen/src/apple.rs+++ b/crates/screenpipe-screen/src/apple.rs@@ -75,6 +75,33 @@ extern "C" fn release_callback(_refcon: *mut c_void, _data_ptr: *const *const c_// Implement your release logic here}+#[cfg(target_os = "macos")]+fn utf16_word_ranges(s: &str) -> Vec<(usize, usize, String)> {+ let mut out = Vec::new();+ let mut utf16_pos: usize = 0;+ let mut word_start: Option<usize> = None;+ let mut word_buf = String::new();++ for c in s.chars() {+ let c_utf16 = c.len_utf16();+ if c.is_whitespace() {+ if let Some(start) = word_start.take() {+ out.push((start, utf16_pos - start, std::mem::take(&mut word_buf)));+ }+ } else {+ if word_start.is_none() {+ word_start = Some(utf16_pos);+ }+ word_buf.push(c);+ }+ utf16_pos += c_utf16;+ }+ if let Some(start) = word_start.take() {+ out.push((start, utf16_pos - start, word_buf));+ }+ out+}+#[cfg(target_os = "macos")]pub fn perform_ocr_apple(image: &DynamicImage,@@ -165,39 +192,70 @@ pub fn perform_ocr_apple(};let text = observation_result.string();let confidence = observation_result.confidence() as f64;- let Ok(bbox_result) =- observation_result.bounding_box_for_range(ns::Range::new(0, text.len()))- else {- // Skip bounding box if it fails, still capture the text- overall_confidence += confidence;- ocr_text.push_str(text.to_string().as_str());+ let s = text.to_string();+ if s.is_empty() {return;- };- let bbox = bbox_result.bounding_box();- let x = bbox.origin.x;- let y_vision = bbox.origin.y; // Vision: bottom-left origin, Y up- let height = bbox.size.height;- let width = bbox.size.width;- // Convert to top-left origin (same as other OCR engines) so pipeline/DB stay consistent- let top = 1.0 - y_vision - height;-- ocr_results_vec.push(serde_json::json!({- "level": "0",- "page_num": "0",- "block_num": "0",- "par_num": "0",- "line_num": "0",- "word_num": "0",- "left": x.to_string(),- "top": top.to_string(),- "width": width.to_string(),- "height": height.to_string(),- "conf": confidence.to_string(),- "text": text.to_string(),- }));+ }overall_confidence += confidence;- ocr_text.push_str(text.to_string().as_str());+ ocr_text.push_str(&s);++ // Apple Vision groups multiple words/lines into one observation. Tokenize+ // by whitespace and emit one record per word with its own bbox so the+ // timeline search highlight can be tight on the matched word.+ // bounding_box_for_range expects an NSRange in UTF-16 code units, not+ // Rust byte offsets — walk chars summing len_utf16() to build the offsets.+ let word_ranges = utf16_word_ranges(&s);+ if word_ranges.is_empty() {+ return;+ }++ let emit_record =+ |ocr_results_vec: &mut Vec<serde_json::Value>,+ word_text: &str,+ word_num: usize,+ utf16_start: usize,+ utf16_len: usize| {+ let Ok(bbox_result) = observation_result+ .bounding_box_for_range(ns::Range::new(utf16_start, utf16_len))+ else {+ return;+ };+ let bbox = bbox_result.bounding_box();+ let x = bbox.origin.x;+ let y_vision = bbox.origin.y; // Vision: bottom-left origin, Y up+ let height = bbox.size.height;+ let width = bbox.size.width;+ // Convert to top-left origin (same as other OCR engines)+ let top = 1.0 - y_vision - height;++ ocr_results_vec.push(serde_json::json!({+ "level": "5",+ "page_num": "0",+ "block_num": "0",+ "par_num": "0",+ "line_num": "0",+ "word_num": word_num.to_string(),+ "left": x.to_string(),+ "top": top.to_string(),+ "width": width.to_string(),+ "height": height.to_string(),+ "conf": confidence.to_string(),+ "text": word_text.to_string(),+ }));+ };++ for (i, (utf16_start, utf16_len, word_text)) in+ word_ranges.iter().enumerate()+ {+ emit_record(+ &mut ocr_results_vec,+ word_text,+ i + 1,+ *utf16_start,+ *utf16_len,+ );+ }});let json_output_string =