Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(search): use accessibility tree bounding boxes for keyword search highlights

Louis Beaumont5327ca09559f
diff --git a/apps/screenpipe-app-tauri/components/rewind/thumbnail-highlight-overlay.tsx b/apps/screenpipe-app-tauri/components/rewind/thumbnail-highlight-overlay.tsx
index 631510d10..f0a5d39ea 100644
--- a/apps/screenpipe-app-tauri/components/rewind/thumbnail-highlight-overlay.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/thumbnail-highlight-overlay.tsx
@@ -22,7 +22,9 @@ export const ThumbnailHighlightOverlay = memo(function ThumbnailHighlightOverlay
frameId,
highlightTerms,
}: ThumbnailHighlightOverlayProps) {
- const { textPositions } = useFrameOcrData(frameId);
+ const { textPositions } = useFrameOcrData(frameId, {
+ query: highlightTerms.length > 0 ? highlightTerms.join(" ") : undefined,
+ });
const highlights = useMemo(() => {
if (!highlightTerms.length || !textPositions.length) return [];
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-frame-ocr-data.ts b/apps/screenpipe-app-tauri/lib/hooks/use-frame-ocr-data.ts
index 1d23f6c25..7dd657739 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-frame-ocr-data.ts
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-frame-ocr-data.ts
@@ -27,6 +27,8 @@ interface UseFrameOcrDataOptions {
autoFetch?: boolean;
/** Cache size limit (number of frames to cache) */
cacheSize?: number;
+ /** Search query — when provided, only positions matching this term are returned */
+ query?: string;
}
interface UseFrameOcrDataReturn {
@@ -98,7 +100,7 @@ export function useFrameOcrData(
frameId: number | null,
options: UseFrameOcrDataOptions = {}
): UseFrameOcrDataReturn {
- const { autoFetch = true } = options;
+ const { autoFetch = true, query } = options;
const [textPositions, setTextPositions] = useState<TextPosition[]>([]);
const [isLoading, setIsLoading] = useState(false);
@@ -116,8 +118,9 @@ export function useFrameOcrData(
return;
}
- // Check cache first
- const cached = globalOcrCache.get(frameId);
+ // Use a composite cache key: frameId + query (so filtered and unfiltered results are cached separately)
+ const cacheKey = query ? frameId * 100000 + query.length : frameId;
+ const cached = globalOcrCache.get(cacheKey);
if (cached !== undefined) {
setTextPositions(cached);
setError(null);
@@ -143,10 +146,10 @@ export function useFrameOcrData(
try {
// Step 1: GET — check if OCR data already exists in DB
- const response = await fetch(
- `http://localhost:3030/frames/${frameId}/ocr`,
- { signal: controller.signal }
- );
+ const ocrUrl = query
+ ? `http://localhost:3030/frames/${frameId}/ocr?query=${encodeURIComponent(query)}`
+ : `http://localhost:3030/frames/${frameId}/ocr`;
+ const response = await fetch(ocrUrl, { signal: controller.signal });
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
@@ -159,7 +162,7 @@ export function useFrameOcrData(
if (data.text_positions.length > 0) {
// OCR data exists — use it directly
- globalOcrCache.set(frameId, data.text_positions);
+ globalOcrCache.set(cacheKey, data.text_positions);
if (!controller.signal.aborted) {
setTextPositions(data.text_positions);
lastFetchedRef.current = frameId;
@@ -193,7 +196,7 @@ export function useFrameOcrData(
}
const ocrData: FrameOcrResponse = await ocrResponse.json();
- globalOcrCache.set(capturedFrameId, ocrData.text_positions);
+ globalOcrCache.set(cacheKey, ocrData.text_positions);
if (!controller.signal.aborted) {
setTextPositions(ocrData.text_positions);
@@ -225,7 +228,7 @@ export function useFrameOcrData(
setIsLoading(false);
}
}
- }, [frameId]);
+ }, [frameId, query]);
// Auto-fetch when frameId changes
useEffect(() => {
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index 0c096b47d..4ac78ab8a 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -4362,7 +4362,7 @@ impl DatabaseManager {
// the entire result set, hiding results from other apps.
format!(
r#"
-SELECT id, timestamp, url, app_name, window_name, ocr_text, text_json FROM (
+SELECT id, timestamp, url, app_name, window_name, ocr_text, text_json, accessibility_tree_json FROM (
SELECT
f.id,
f.timestamp,
@@ -4371,6 +4371,7 @@ SELECT id, timestamp, url, app_name, window_name, ocr_text, text_json FROM (
COALESCE(f.window_name, o.window_name, '') as window_name,
COALESCE(f.full_text, o.text, f.accessibility_text, '') as ocr_text,
o.text_json,
+ f.accessibility_tree_json,
ROW_NUMBER() OVER (
PARTITION BY COALESCE(f.app_name, o.app_name, '')
ORDER BY f.timestamp {order_dir}, {relevance} DESC
@@ -4398,7 +4399,8 @@ SELECT
COALESCE(f.app_name, o.app_name) as app_name,
COALESCE(f.window_name, o.window_name) as window_name,
COALESCE(f.full_text, o.text, f.accessibility_text, '') as ocr_text,
- o.text_json
+ o.text_json,
+ f.accessibility_tree_json
FROM frames f
LEFT JOIN ocr_text o ON f.id = o.frame_id
WHERE {}
@@ -4441,7 +4443,7 @@ LIMIT ? OFFSET ?
Ok(rows
.iter()
.map(|row| {
- let positions = if !query.is_empty() {
+ let mut positions = if !query.is_empty() {
let ocr_blocks: Vec<OcrTextBlock> =
serde_json::from_str(&row.text_json).unwrap_or_default();
find_matching_positions(&ocr_blocks, query)
@@ -4449,6 +4451,14 @@ LIMIT ? OFFSET ?
Vec::new()
};
+ // Fallback: when OCR yields no positions, search accessibility
+ // tree nodes for the query and use their bounding boxes
+ if positions.is_empty() && !query.is_empty() {
+ if let Some(tree_json) = &row.accessibility_tree_json {
+ positions = find_matching_a11y_positions(tree_json, query);
+ }
+ }
+
SearchMatch {
frame_id: row.id,
timestamp: row.timestamp,
@@ -5816,6 +5826,63 @@ pub fn find_matching_positions(blocks: &[OcrTextBlock], query: &str) -> Vec<Text
.collect()
}
+/// 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> {
+ let nodes: Vec<serde_json::Value> = match serde_json::from_str(tree_json) {
+ Ok(n) => n,
+ Err(_) => return Vec::new(),
+ };
+
+ let query_lower = query.to_lowercase();
+ let query_words: Vec<&str> = query_lower.split_whitespace().collect();
+
+ let mut matches: Vec<TextPosition> = nodes
+ .iter()
+ .filter_map(|n| {
+ let text = n.get("text")?.as_str()?;
+ if text.trim().is_empty() {
+ return 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;
+ }
+ let b = n.get("bounds")?;
+ let left = b.get("left")?.as_f64()? as f32;
+ let top = b.get("top")?.as_f64()? as f32;
+ let width = b.get("width")?.as_f64()? as f32;
+ let height = b.get("height")?.as_f64()? as f32;
+ // Skip nodes with zero/negative bounds or unreasonably tiny bounds
+ if width <= 0.001 || height <= 0.001 {
+ return None;
+ }
+ Some(TextPosition {
+ text: text.to_string(),
+ confidence: 1.0,
+ bounds: TextBounds {
+ left,
+ top,
+ width,
+ height,
+ },
+ })
+ })
+ .collect();
+
+ // Deduplicate: if multiple nodes have the same text, keep the one with the largest area
+ matches.sort_by(|a, b| {
+ let area_a = a.bounds.width * a.bounds.height;
+ let area_b = b.bounds.width * b.bounds.height;
+ area_b.partial_cmp(&area_a).unwrap_or(std::cmp::Ordering::Equal)
+ });
+ matches.dedup_by(|a, b| a.text == b.text);
+
+ matches
+}
+
fn calculate_confidence(positions: &[TextPosition]) -> f32 {
if positions.is_empty() {
return 0.0;
diff --git a/crates/screenpipe-db/src/lib.rs b/crates/screenpipe-db/src/lib.rs
index 4a01fab3d..129d6f2f1 100644
--- a/crates/screenpipe-db/src/lib.rs
+++ b/crates/screenpipe-db/src/lib.rs
@@ -8,7 +8,7 @@ pub mod text_similarity;
mod types;
mod video_db;
-pub use db::{parse_all_text_positions, DatabaseManager, DeleteTimeRangeResult};
+pub use db::{find_matching_a11y_positions, parse_all_text_positions, DatabaseManager, DeleteTimeRangeResult};
pub use migration_worker::{
create_migration_worker, MigrationCommand, MigrationConfig, MigrationResponse, MigrationStatus,
MigrationWorker,
diff --git a/crates/screenpipe-db/src/types.rs b/crates/screenpipe-db/src/types.rs
index af0b1a898..9f95a332d 100644
--- a/crates/screenpipe-db/src/types.rs
+++ b/crates/screenpipe-db/src/types.rs
@@ -376,6 +376,8 @@ pub struct FrameRow {
pub window_name: String,
pub ocr_text: String,
pub text_json: String,
+ /// Accessibility tree JSON — used as fallback for bounding boxes when OCR text_json is empty
+ pub accessibility_tree_json: Option<String>,
}
/// Lightweight frame row for grouped search — skips text/text_json columns.
diff --git a/crates/screenpipe-engine/src/routes/frames.rs b/crates/screenpipe-engine/src/routes/frames.rs
index 427b61d30..b0272efc5 100644
--- a/crates/screenpipe-engine/src/routes/frames.rs
+++ b/crates/screenpipe-engine/src/routes/frames.rs
@@ -643,6 +643,14 @@ pub struct FrameOcrResponse {
pub text_positions: Vec<TextPosition>,
}
+/// Optional query parameter for filtering text positions by search term.
+#[derive(Debug, Deserialize, OaSchema)]
+pub struct FrameOcrQuery {
+ /// When provided, only return text positions matching this search term.
+ /// Without this, the a11y fallback returns ALL text nodes (hundreds of them).
+ pub query: Option<String>,
+}
+
/// Get OCR text positions with bounding boxes for a specific frame.
/// Falls back to accessibility tree node bounds when no OCR data exists.
/// Both OCR and accessibility bounds are normalized to 0-1 relative to the
@@ -651,6 +659,7 @@ pub struct FrameOcrResponse {
pub async fn get_frame_ocr_data(
State(state): State<Arc<AppState>>,
Path(frame_id): Path<i64>,
+ Query(params): Query<FrameOcrQuery>,
) -> Result<JsonResponse<FrameOcrResponse>, (StatusCode, JsonResponse<Value>)> {
// Get OCR data (bounding boxes from Apple Vision)
let mut text_positions = match state.db.get_frame_text_positions(frame_id).await {
@@ -706,10 +715,16 @@ pub async fn get_frame_ocr_data(
}
}
- // Pure a11y fallback for frames with no OCR — grab all text nodes with bounds
+ // Pure a11y fallback for frames with no OCR — use accessibility tree bounding boxes.
+ // When a query param is provided, only return nodes matching the search term.
+ // Without a query, return all nodes (for text selection overlay).
if text_positions.is_empty() {
if let Ok((_, Some(tree_json))) = state.db.get_frame_accessibility_data(frame_id).await {
- if let Ok(nodes) = serde_json::from_str::<Vec<serde_json::Value>>(&tree_json) {
+ if let Some(query) = &params.query {
+ // Filtered: use the same matching logic as keyword search
+ text_positions = screenpipe_db::find_matching_a11y_positions(&tree_json, query);
+ } else if let Ok(nodes) = serde_json::from_str::<Vec<serde_json::Value>>(&tree_json) {
+ // Unfiltered: return all nodes (existing behavior for text selection)
text_positions = nodes
.iter()
.filter_map(|n| {
diff --git a/crates/screenpipe-engine/src/routes/search.rs b/crates/screenpipe-engine/src/routes/search.rs
index a8d6e087b..14a3513dd 100644
--- a/crates/screenpipe-engine/src/routes/search.rs
+++ b/crates/screenpipe-engine/src/routes/search.rs
@@ -496,6 +496,9 @@ pub(crate) async fn keyword_search_handler(
let filtered: Vec<_> = matches
.into_iter()
.filter(|m| !m.app_name.to_lowercase().contains("screenpipe"))
+ // Drop results with no text_positions — the user can't see where
+ // the match is on the screenshot, so showing them is misleading
+ .filter(|m| !m.text_positions.is_empty() || query.query.is_empty())
.collect();
Ok(JsonResponse(json!(filtered)))