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: escape FTS5 queries to prevent 500 errors on special characters
Louis Beaumontfb31f225e054
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rsindex 54113cd14..b45a337ac 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -1743,17 +1743,17 @@ impl DatabaseManager {if let Some(app) = app_name {if !app.is_empty() {- frame_fts_parts.push(format!("app_name:{}", app));+ frame_fts_parts.push(format!("app_name:\"{}\"", app.replace('"', "")));}}if let Some(window) = window_name {if !window.is_empty() {- frame_fts_parts.push(format!("window_name:{}", window));+ frame_fts_parts.push(format!("window_name:\"{}\"", window.replace('"', "")));}}if let Some(browser) = browser_url {if !browser.is_empty() {- frame_fts_parts.push(format!("browser_url:{}", browser));+ frame_fts_parts.push(format!("browser_url:\"{}\"", browser.replace('"', "")));}}if let Some(is_focused) = focused {@@ -1761,7 +1761,7 @@ impl DatabaseManager {}if let Some(frame_name) = frame_name {if !frame_name.is_empty() {- frame_fts_parts.push(format!("name:{}", frame_name));+ frame_fts_parts.push(format!("name:\"{}\"", frame_name.replace('"', "")));}}@@ -1845,7 +1845,7 @@ impl DatabaseManager {.bind(if query.trim().is_empty() {None} else {- Some(query)+ Some(crate::text_normalizer::sanitize_fts5_query(query))}).bind(limit).bind(offset)@@ -1957,7 +1957,8 @@ impl DatabaseManager {// bind parameters in the same order as added to the where clauseif !query.is_empty() {- query_builder = query_builder.bind(query);+ query_builder =+ query_builder.bind(crate::text_normalizer::sanitize_fts5_query(query));}if let Some(start) = start_time {query_builder = query_builder.bind(start);@@ -2290,24 +2291,24 @@ impl DatabaseManager {// Split query parts between frame metadata and OCR contentif !query.is_empty() {- ocr_fts_parts.push(query.to_owned()); // Just use the query directly- ui_fts_parts.push(query.to_owned());+ ocr_fts_parts.push(crate::text_normalizer::sanitize_fts5_query(query));+ ui_fts_parts.push(crate::text_normalizer::sanitize_fts5_query(query));}if let Some(app) = app_name {if !app.is_empty() {- frame_fts_parts.push(format!("app_name:{}", app));- ui_fts_parts.push(format!("app_name:\"{}\"", app));+ frame_fts_parts.push(format!("app_name:\"{}\"", app.replace('"', "")));+ ui_fts_parts.push(format!("app_name:\"{}\"", app.replace('"', "")));}}if let Some(window) = window_name {if !window.is_empty() {- frame_fts_parts.push(format!("window_name:{}", window));- ui_fts_parts.push(format!("window_name:\"{}\"", window));+ frame_fts_parts.push(format!("window_name:\"{}\"", window.replace('"', "")));+ ui_fts_parts.push(format!("window_name:\"{}\"", window.replace('"', "")));}}if let Some(browser) = browser_url {if !browser.is_empty() {- frame_fts_parts.push(format!("browser_url:{}", browser));+ frame_fts_parts.push(format!("browser_url:\"{}\"", browser.replace('"', "")));}}if let Some(is_focused) = focused {@@ -2394,6 +2395,51 @@ impl DatabaseManager {"audio_transcriptions_fts MATCH ?1"}),+ ContentType::Input => {+ // Count ui_events using parameterized LIKE queries+ let mut conditions = Vec::new();+ let mut bind_values: Vec<String> = Vec::new();++ if !query.is_empty() {+ conditions.push(+ "(text_content LIKE '%' || ? || '%' OR app_name LIKE '%' || ? || '%' OR window_title LIKE '%' || ? || '%')"+ .to_string(),+ );+ bind_values.push(query.to_owned());+ bind_values.push(query.to_owned());+ bind_values.push(query.to_owned());+ }+ if let Some(app) = app_name {+ if !app.is_empty() {+ conditions.push("app_name LIKE '%' || ? || '%'".to_string());+ bind_values.push(app.to_owned());+ }+ }+ if let Some(window) = window_name {+ if !window.is_empty() {+ conditions.push("window_title LIKE '%' || ? || '%'".to_string());+ bind_values.push(window.to_owned());+ }+ }++ let where_part = if conditions.is_empty() {+ "1=1".to_string()+ } else {+ conditions.join(" AND ")+ };++ let input_sql = format!(+ "SELECT COUNT(*) FROM ui_events WHERE {} AND (? IS NULL OR timestamp >= ?) AND (? IS NULL OR timestamp <= ?)",+ where_part+ );+ let mut qb = sqlx::query_scalar::<_, i64>(&input_sql);+ for val in &bind_values {+ qb = qb.bind(val);+ }+ qb = qb.bind(start_time).bind(start_time).bind(end_time).bind(end_time);+ let count: i64 = qb.fetch_one(&self.pool).await?;+ return Ok(count as usize);+ }_ => return Ok(0),};@@ -2426,8 +2472,13 @@ impl DatabaseManager {.await?}ContentType::Audio => {+ let sanitized_audio = if query.is_empty() {+ "*".to_owned()+ } else {+ crate::text_normalizer::sanitize_fts5_query(query)+ };let mut query_builder = sqlx::query_scalar(&sql)- .bind(if query.is_empty() { "*" } else { query })+ .bind(&sanitized_audio).bind(start_time).bind(end_time).bind(min_length.map(|l| l as i64))@@ -2438,17 +2489,7 @@ impl DatabaseManager {}query_builder.fetch_one(&self.pool).await?}- _ => {- sqlx::query_scalar(&sql)- .bind(query)- .bind(start_time)- .bind(end_time)- .bind(min_length.map(|l| l as i64))- .bind(max_length.map(|l| l as i64))- .bind(json_array)- .fetch_one(&self.pool)- .await?- }+ _ => return Ok(0),};Ok(count as usize)@@ -2957,13 +2998,13 @@ impl DatabaseManager {// combine search aspects into single fts querylet mut fts_parts = Vec::new();if !query.is_empty() {- fts_parts.push(query.to_owned());+ fts_parts.push(crate::text_normalizer::sanitize_fts5_query(query));}if let Some(app) = app_name {- fts_parts.push(format!("app:{}", app));+ fts_parts.push(format!("app:\"{}\"", app.replace('"', "")));}if let Some(window) = window_name {- fts_parts.push(format!("window:{}", window));+ fts_parts.push(format!("window:\"{}\"", window.replace('"', "")));}let combined_query = fts_parts.join(" ");@@ -3037,13 +3078,13 @@ impl DatabaseManager {) -> Result<Vec<UiContent>, sqlx::Error> {let mut fts_parts = Vec::new();if !query.is_empty() {- fts_parts.push(query.to_owned());+ fts_parts.push(crate::text_normalizer::sanitize_fts5_query(query));}if let Some(app) = app_name {- fts_parts.push(format!("app_name:{}", app));+ fts_parts.push(format!("app_name:\"{}\"", app.replace('"', "")));}if let Some(window) = window_name {- fts_parts.push(format!("window_name:{}", window));+ fts_parts.push(format!("window_name:\"{}\"", window.replace('"', "")));}let combined_query = fts_parts.join(" ");@@ -3116,28 +3157,35 @@ impl DatabaseManager {offset: u32,) -> Result<Vec<UiEventRecord>, sqlx::Error> {let mut conditions = vec!["1=1".to_string()];+ let mut bind_values: Vec<String> = Vec::new();if let Some(q) = query {if !q.is_empty() {- conditions.push(format!(- "(text_content LIKE '%{}%' OR app_name LIKE '%{}%' OR window_title LIKE '%{}%')",- q, q, q- ));+ conditions.push(+ "(text_content LIKE '%' || ? || '%' OR app_name LIKE '%' || ? || '%' OR window_title LIKE '%' || ? || '%')"+ .to_string(),+ );+ bind_values.push(q.to_owned());+ bind_values.push(q.to_owned());+ bind_values.push(q.to_owned());}}if let Some(et) = event_type {if !et.is_empty() {- conditions.push(format!("event_type = '{}'", et));+ conditions.push("event_type = ?".to_string());+ bind_values.push(et.to_owned());}}if let Some(app) = app_name {if !app.is_empty() {- conditions.push(format!("app_name LIKE '%{}%'", app));+ conditions.push("app_name LIKE '%' || ? || '%'".to_string());+ bind_values.push(app.to_owned());}}if let Some(window) = window_name {if !window.is_empty() {- conditions.push(format!("window_title LIKE '%{}%'", window));+ conditions.push("window_title LIKE '%' || ? || '%'".to_string());+ bind_values.push(window.to_owned());}}@@ -3155,16 +3203,22 @@ impl DatabaseManager {frame_idFROM ui_eventsWHERE {}- AND (?1 IS NULL OR timestamp >= ?1)- AND (?2 IS NULL OR timestamp <= ?2)+ AND (? IS NULL OR timestamp >= ?)+ AND (? IS NULL OR timestamp <= ?)ORDER BY timestamp DESC- LIMIT ?3 OFFSET ?4+ LIMIT ? OFFSET ?"#,where_clause);- let rows: Vec<UiEventRow> = sqlx::query_as(&sql)+ let mut query_builder = sqlx::query_as::<_, UiEventRow>(&sql);+ for val in &bind_values {+ query_builder = query_builder.bind(val);+ }+ let rows: Vec<UiEventRow> = query_builder.bind(start_time)+ .bind(start_time)+ .bind(end_time).bind(end_time).bind(limit).bind(offset)@@ -3860,7 +3914,7 @@ impl DatabaseManager {// Use intelligent query expansion for compound wordscrate::text_normalizer::expand_search_query(query)} else {- query.to_string()+ crate::text_normalizer::sanitize_fts5_query(query)};conditions.push("f.id IN (SELECT frame_id FROM ocr_text_fts WHERE text MATCH ? ORDER BY rank LIMIT 5000)",@@ -4044,7 +4098,7 @@ LIMIT ? OFFSET ?let fts_match = if fuzzy_match {crate::text_normalizer::expand_search_query(query)} else {- query.to_string()+ crate::text_normalizer::sanitize_fts5_query(query)};conditions.push("f.id IN (SELECT frame_id FROM ocr_text_fts WHERE text MATCH ? ORDER BY rank LIMIT 5000)",diff --git a/crates/screenpipe-db/src/lib.rs b/crates/screenpipe-db/src/lib.rsindex 2440a118f..4a01fab3d 100644--- a/crates/screenpipe-db/src/lib.rs+++ b/crates/screenpipe-db/src/lib.rs@@ -13,5 +13,5 @@ pub use migration_worker::{create_migration_worker, MigrationCommand, MigrationConfig, MigrationResponse, MigrationStatus,MigrationWorker,};-pub use text_normalizer::expand_search_query;+pub use text_normalizer::{expand_search_query, sanitize_fts5_query};pub use types::*;diff --git a/crates/screenpipe-db/src/text_normalizer.rs b/crates/screenpipe-db/src/text_normalizer.rsindex 05cbb0638..181ac27b0 100644--- a/crates/screenpipe-db/src/text_normalizer.rs+++ b/crates/screenpipe-db/src/text_normalizer.rs@@ -31,12 +31,42 @@ fn split_compound(text: &str) -> String {result.into_owned()}+/// Sanitize a query string for safe use in FTS5 MATCH expressions.+///+/// Wraps each whitespace-delimited token in double quotes so that+/// special characters (dots, parens, colons, etc.) are treated as+/// literal text rather than FTS5 operators.+///+/// # Example+/// ```+/// use screenpipe_db::text_normalizer::sanitize_fts5_query;+///+/// assert_eq!(sanitize_fts5_query("100.100.0.42"), r#""100.100.0.42""#);+/// assert_eq!(sanitize_fts5_query("hello world"), r#""hello" "world""#);+/// ```+pub fn sanitize_fts5_query(query: &str) -> String {+ query+ .split_whitespace()+ .filter_map(|token| {+ let cleaned = token.replace('"', "");+ if cleaned.is_empty() {+ return None;+ }+ Some(format!("\"{}\"", cleaned))+ })+ .collect::<Vec<_>>()+ .join(" ")+}+/// Expand a search query to improve recall on compound words.////// Takes a user query and returns an expanded FTS5 query that searches for:/// 1. The original term (with prefix matching)/// 2. Split parts of compound words (with prefix matching)///+/// All tokens are quoted to safely handle special characters (dots, parens, etc.)+/// in FTS5.+////// This catches cases where OCR concatenated words like "ActivityPerformance"/// when the user searches for "activity" or "performance".///@@ -44,11 +74,11 @@ fn split_compound(text: &str) -> String {/// ```/// use screenpipe_db::text_normalizer::expand_search_query;///-/// // Single word - just adds prefix matching-/// assert_eq!(expand_search_query("test"), "test*");+/// // Single word - quoted with prefix matching+/// assert_eq!(expand_search_query("test"), r#""test"*"#);////// // Compound word - expands to catch parts-/// assert_eq!(expand_search_query("proStart"), "(proStart* OR pro* OR Start*)");+/// assert_eq!(expand_search_query("proStart"), r#"("proStart"* OR "pro"* OR "Start"*)"#);/// ```pub fn expand_search_query(query: &str) -> String {let query = query.trim();@@ -60,22 +90,23 @@ pub fn expand_search_query(query: &str) -> String {let expanded_terms: Vec<String> = query.split_whitespace().flat_map(|word| {- let split = split_compound(word);+ let cleaned = word.replace('"', "");+ let split = split_compound(&cleaned);let parts: Vec<&str> = split.split_whitespace().collect();if parts.len() > 1 {// Word was split - include original and parts with prefix matching- let mut terms = vec![format!("{}*", word)];+ let mut terms = vec![format!("\"{}\"*", cleaned)];for part in parts {if part.len() >= 2 {// Only add parts with 2+ chars to avoid noise- terms.push(format!("{}*", part));+ terms.push(format!("\"{}\"*", part));}}terms} else {- // No split needed - just add prefix matching- vec![format!("{}*", word)]+ // No split needed - just add quoted prefix matching+ vec![format!("\"{}\"*", cleaned)]}}).collect();@@ -114,21 +145,52 @@ mod tests {assert_eq!(split_compound("hello world"), "hello world");}+ #[test]+ fn test_sanitize_fts5_simple() {+ assert_eq!(sanitize_fts5_query("hello"), r#""hello""#);+ assert_eq!(sanitize_fts5_query("hello world"), r#""hello" "world""#);+ }++ #[test]+ fn test_sanitize_fts5_dots() {+ assert_eq!(sanitize_fts5_query("100.100.0.42"), r#""100.100.0.42""#);+ }++ #[test]+ fn test_sanitize_fts5_special_chars() {+ assert_eq!(sanitize_fts5_query("foo(bar)"), r#""foo(bar)""#);+ assert_eq!(sanitize_fts5_query("C++"), r#""C++""#);+ }++ #[test]+ fn test_sanitize_fts5_strips_quotes() {+ assert_eq!(+ sanitize_fts5_query(r#"he said "hello""#),+ r#""he" "said" "hello""#+ );+ }++ #[test]+ fn test_sanitize_fts5_empty() {+ assert_eq!(sanitize_fts5_query(""), "");+ assert_eq!(sanitize_fts5_query(" "), "");+ }+#[test]fn test_expand_simple_query() {- assert_eq!(expand_search_query("test"), "test*");- assert_eq!(expand_search_query("hello"), "hello*");+ assert_eq!(expand_search_query("test"), r#""test"*"#);+ assert_eq!(expand_search_query("hello"), r#""hello"*"#);}#[test]fn test_expand_compound_query() {assert_eq!(expand_search_query("proStart"),- "(proStart* OR pro* OR Start*)"+ r#"("proStart"* OR "pro"* OR "Start"*)"#);assert_eq!(expand_search_query("ActivityPerformance"),- "(ActivityPerformance* OR Activity* OR Performance*)"+ r#"("ActivityPerformance"* OR "Activity"* OR "Performance"*)"#);}@@ -136,14 +198,17 @@ mod tests {fn test_expand_number_boundary() {assert_eq!(expand_search_query("test123"),- "(test123* OR test* OR 123*)"+ r#"("test123"* OR "test"* OR "123"*)"#);}#[test]fn test_expand_multi_word_query() {// Each word gets expanded independently- assert_eq!(expand_search_query("hello world"), "(hello* OR world*)");+ assert_eq!(+ expand_search_query("hello world"),+ r#"("hello"* OR "world"*)"#+ );}#[test]@@ -155,11 +220,20 @@ mod tests {#[test]fn test_expand_filters_short_parts() {// Single char parts should be filtered out- assert_eq!(expand_search_query("iPhone"), "(iPhone* OR Phone*)");+ assert_eq!(+ expand_search_query("iPhone"),+ r#"("iPhone"* OR "Phone"*)"#+ );}#[test]fn test_expand_preserves_lowercase() {- assert_eq!(expand_search_query("simple"), "simple*");+ assert_eq!(expand_search_query("simple"), r#""simple"*"#);+ }++ #[test]+ fn test_expand_dots_in_query() {+ // IP addresses and dotted identifiers should be safely quoted+ assert_eq!(expand_search_query("100.100.0.42"), r#""100.100.0.42"*"#);}}diff --git a/crates/screenpipe-db/tests/db.rs b/crates/screenpipe-db/tests/db.rsindex b45d71a92..a41ba6963 100644--- a/crates/screenpipe-db/tests/db.rs+++ b/crates/screenpipe-db/tests/db.rs@@ -1234,7 +1234,7 @@ mod tests {// Test searching OCR with frame_name filterlet results = db.search(- "text:Hello",+ "Hello",ContentType::OCR,100,0,