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
chore: move fts and stuff to frames fts (#1472)
Louis Beaumont859338661493
diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex eaf46062b..1a8ad7892 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -31,6 +31,7 @@ use updates::start_update_check;mod analytics;mod icons;use crate::analytics::start_analytics;+use tauri_plugin_shell::ShellExt;mod commands;mod disk_usage;@@ -902,6 +903,116 @@ async fn main() {warn!("Failed to initialize global shortcuts: {}", e);}});+ let app_handle = app.handle().clone();+ tauri::async_runtime::spawn(async move {+ // spawn async migration worker+ match app_handle.shell().sidecar("screenpipe") {+ Ok(command) => {+ match command+ .args(&["migrate", "--batch-size", "100000", "start"])+ .spawn()+ {+ Ok((mut rx, _)) => {+ info!("Migration worker started successfully");+ // stream logs+ while let Some(event) = rx.recv().await {+ match event {+ CommandEvent::Stdout(line) => {+ match String::from_utf8(line) {+ Ok(log_line) => {+ print!("{}", log_line);+ if let Err(e) =+ app_handle.emit("sidecar_log", log_line)+ {+ error!("Failed to emit sidecar log: {}", e);+ }+ }+ Err(e) => {+ error!(+ "Invalid UTF-8 in sidecar stdout: {}",+ e+ );+ }+ }+ }+ CommandEvent::Stderr(line) => {+ match String::from_utf8(line) {+ Ok(log_line) => {+ error!("Sidecar stderr: {}", log_line);+ if let Err(e) = app_handle.emit(+ "sidecar_log",+ format!("ERROR: {}", log_line),+ ) {+ error!(+ "Failed to emit sidecar error log: {}",+ e+ );+ }+ }+ Err(e) => {+ error!(+ "Invalid UTF-8 in sidecar stderr: {}",+ e+ );+ }+ }+ }+ CommandEvent::Error(err) => {+ error!("Sidecar command error: {}", err);+ if let Err(e) = app_handle.emit(+ "sidecar_log",+ format!("COMMAND ERROR: {}", err),+ ) {+ error!(+ "Failed to emit sidecar command error: {}",+ e+ );+ }+ }+ CommandEvent::Terminated(exit_data) => {+ info!(+ "Migration worker terminated with code: {:?}",+ exit_data.code+ );+ if let Err(e) = app_handle.emit(+ "sidecar_log",+ format!(+ "Migration process terminated with code: {:?}",+ exit_data.code+ ),+ ) {+ error!(+ "Failed to emit sidecar termination event: {}",+ e+ );+ }+ }+ _ => {}+ }+ }+ }+ Err(e) => {+ error!("Failed to spawn migration worker: {}", e);+ if let Err(emit_err) = app_handle.emit(+ "sidecar_log",+ format!("ERROR: Failed to spawn migration worker: {}", e),+ ) {+ error!("Failed to emit error message: {}", emit_err);+ }+ }+ }+ }+ Err(e) => {+ error!("Failed to create sidecar command: {}", e);+ if let Err(emit_err) = app_handle.emit(+ "sidecar_log",+ format!("ERROR: Failed to create sidecar command: {}", e),+ ) {+ error!("Failed to emit error message: {}", emit_err);+ }+ }+ }+ });Ok(())}).build(tauri::generate_context!())diff --git a/screenpipe-core/tests/pipes_test.rs b/screenpipe-core/tests/pipes_test.rsindex 821fddd96..50f88d3d7 100644--- a/screenpipe-core/tests/pipes_test.rs+++ b/screenpipe-core/tests/pipes_test.rs@@ -4,10 +4,9 @@ mod tests {use screenpipe_core::{download_pipe, get_last_cron_execution, run_pipe, save_cron_execution};use serde_json::json;use std::sync::Arc;+ use std::sync::Once;use std::time::{Duration, SystemTime, UNIX_EPOCH};- use std::{path::PathBuf, sync::Once};use tempfile::TempDir;- use tokio::fs::create_dir_all;use tokio::sync::Mutex;use tokio::time::sleep;use tracing::subscriber::set_global_default;@@ -25,7 +24,6 @@ mod tests {});}-#[tokio::test]async fn test_download_pipe_invalid_url() {init();@@ -38,8 +36,6 @@ mod tests {assert!(result.is_err(), "Expected an error for invalid URL");}--#[tokio::test]#[ignore]async fn test_nextjs_pipe_app_dir() {diff --git a/screenpipe-server/src/add.rs b/screenpipe-server/src/add.rsindex 3a15ca795..d0881baf9 100644--- a/screenpipe-server/src/add.rs+++ b/screenpipe-server/src/add.rs@@ -225,10 +225,7 @@ pub async fn handle_index_command(frame_ids[idx],&text,"{}", // empty json- "", // no app name- "", // no window nameengine_arc.clone(),- true, // focused).await{diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex eff369e43..8df7dd63e 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -12,12 +12,13 @@ use screenpipe_audio::{use screenpipe_core::find_ffmpeg_path;use screenpipe_server::{cli::{- AudioCommand, Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, OutputFormat,- PipeCommand, VisionCommand,+ AudioCommand, Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, MigrationSubCommand,+ OutputFormat, PipeCommand, VisionCommand,},- handle_index_command,+ create_migration_worker, handle_index_command,pipe_manager::PipeInfo,- start_continuous_recording, watch_pid, DatabaseManager, PipeManager, ResourceMonitor, Server,+ start_continuous_recording, watch_pid, DatabaseManager, MigrationCommand, MigrationConfig,+ MigrationStatus, PipeManager, ResourceMonitor, Server,};use screenpipe_vision::monitor::list_monitors;#[cfg(target_os = "macos")]@@ -190,6 +191,10 @@ async fn main() -> anyhow::Result<()> {output: OutputFormat::Text,..}) => true,+ Some(Command::Migrate {+ output: OutputFormat::Text,+ ..+ }) => true,_ => true,};@@ -260,7 +265,6 @@ async fn main() -> anyhow::Result<()> {handle_pipe_command(subcommand, &pipe_manager).await?;return Ok(());}- #[allow(unused_variables)]Command::Setup {} => {use screenpipe_audio::{trigger_audio_permission, vad_engine::SileroVad, whisper::WhisperModel,@@ -314,15 +318,188 @@ async fn main() -> anyhow::Result<()> {info!("screenpipe setup complete");return Ok(());}- Command::Migrate => {- info!("running database migrations...");- DatabaseManager::new(&format!("{}/db.sqlite", local_data_dir.to_string_lossy()))+ Command::Migrate {+ migration_name,+ data_dir,+ subcommand,+ output,+ batch_size,+ batch_delay_ms,+ continue_on_error,+ } => {+ // Initialize the database+ let local_data_dir = get_base_dir(&data_dir)?;+ let db = Arc::new(+ DatabaseManager::new(&format!(+ "{}/db.sqlite",+ local_data_dir.to_string_lossy()+ )).await.map_err(|e| {error!("failed to initialize database: {:?}", e);e- })?;- info!("database migrations completed successfully");+ })?,+ );++ // Create a migration worker config+ let config = MigrationConfig::new(*batch_size, *batch_delay_ms, *continue_on_error);++ // Start the migration worker+ let (cmd_tx, mut status_rx, worker_handle) =+ create_migration_worker(db, Some(config));++ // Process the specified subcommand or default to status+ let cmd = match subcommand {+ Some(MigrationSubCommand::Start) => MigrationCommand::Start,+ Some(MigrationSubCommand::Pause) => MigrationCommand::Pause,+ Some(MigrationSubCommand::Stop) => MigrationCommand::Stop,+ Some(MigrationSubCommand::Status) | None => MigrationCommand::Status,+ };++ // Send the command to the worker+ if let Err(e) = cmd_tx.send(cmd.clone()).await {+ error!("failed to send command to migration worker: {}", e);+ return Err(anyhow::anyhow!(+ "Failed to send command to migration worker"+ ));+ }++ // If the command is start, we need to track the progress+ if matches!(cmd, MigrationCommand::Start) {+ // Send the start command and wait for the worker to acknowledge+ if let Some(response) = status_rx.recv().await {+ match output {+ OutputFormat::Json => {+ println!("{}", serde_json::to_string_pretty(&response.status)?);+ }+ OutputFormat::Text => {+ info!("Started migration: {}", migration_name);+ match response.status {+ MigrationStatus::Running {+ total_records,+ processed_records,+ } => {+ info!(+ "Processing records: {}/{} ({:.2}%)",+ processed_records,+ total_records,+ if total_records > 0 {+ (processed_records as f64 / total_records as f64)+ * 100.0+ } else {+ 0.0+ }+ );+ }+ _ => {+ info!("Migration status: {:?}", response.status);+ }+ }+ }+ }+ }++ // Keep checking status periodically until migration completes, fails, or is stopped+ let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(5));+ loop {+ interval.tick().await;++ // Send status command+ if let Err(e) = cmd_tx.send(MigrationCommand::Status).await {+ error!("failed to send status command: {}", e);+ break;+ }++ // Wait for response+ if let Some(response) = status_rx.recv().await {+ match output {+ OutputFormat::Json => {+ println!("{}", serde_json::to_string_pretty(&response.status)?);+ }+ OutputFormat::Text => match &response.status {+ MigrationStatus::Running {+ total_records,+ processed_records,+ } => {+ info!(+ "Processing records: {}/{} ({:.2}%)",+ processed_records,+ total_records,+ if *total_records > 0 {+ (*processed_records as f64 / *total_records as f64)+ * 100.0+ } else {+ 0.0+ }+ );+ }+ MigrationStatus::Completed {+ total_records,+ duration_secs,+ } => {+ info!(+ "Migration completed: {} records processed in {} seconds",+ total_records, duration_secs+ );+ break;+ }+ MigrationStatus::Paused {+ total_records,+ processed_records,+ } => {+ info!(+ "Migration paused: {}/{} ({:.2}%)",+ processed_records,+ total_records,+ if *total_records > 0 {+ (*processed_records as f64 / *total_records as f64)+ * 100.0+ } else {+ 0.0+ }+ );+ }+ MigrationStatus::Failed {+ total_records,+ processed_records,+ error,+ } => {+ error!(+ "Migration failed: {}/{} records processed. Error: {}",+ processed_records, total_records, error+ );+ break;+ }+ _ => {+ info!("Migration status: {:?}", response.status);+ }+ },+ }+ } else {+ break;+ }+ }+ } else {+ // For non-start commands, just get the status once+ if let Some(response) = status_rx.recv().await {+ match output {+ OutputFormat::Json => {+ println!("{}", serde_json::to_string_pretty(&response.status)?);+ }+ OutputFormat::Text => {+ info!("Migration status: {:?}", response.status);+ }+ }+ }+ }++ // If we explicitly stopped, wait for the worker to finish+ if matches!(cmd, MigrationCommand::Stop) {+ if let Err(e) = worker_handle.await {+ error!("error waiting for worker to finish: {}", e);+ }+ }+return Ok(());}Command::Add {diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rsindex 498877e7c..1d119e2d4 100644--- a/screenpipe-server/src/cli.rs+++ b/screenpipe-server/src/cli.rs@@ -325,9 +325,31 @@ pub enum Command {},/// Setup screenpipe environmentSetup,- /// Run database migrations- Migrate,- /// Generate shell completions+ /// Run data migrations in the background+ Migrate {+ /// The name of the migration to run+ #[arg(long, default_value = "ocr_text_to_frames")]+ migration_name: String,+ /// Data directory. Default to $HOME/.screenpipe+ #[arg(long, value_hint = ValueHint::DirPath)]+ data_dir: Option<String>,+ /// The subcommand for data migration+ #[command(subcommand)]+ subcommand: Option<MigrationSubCommand>,+ /// Output format+ #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Text)]+ output: OutputFormat,+ /// Batch size for processing records+ #[arg(long, default_value_t = 100_000)]+ batch_size: i64,+ /// Delay between batches in milliseconds+ #[arg(long, default_value_t = 100)]+ batch_delay_ms: u64,+ /// Continue processing if errors occur+ #[arg(long, default_value_t = true)]+ continue_on_error: bool,+ },+ /// Generate shell completionsCompletions {/// The shell to generate completions for#[arg(value_enum)]@@ -335,6 +357,18 @@ pub enum Command {},}+#[derive(Subcommand)]+pub enum MigrationSubCommand {+ /// Start or resume a migration+ Start,+ /// Pause a running migration+ Pause,+ /// Stop a running migration+ Stop,+ /// Get migration status+ Status,+}+#[derive(Subcommand)]pub enum AudioCommand {/// List available audio devicesdiff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex 3812d5fc6..5160ec296 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -230,7 +230,14 @@ async fn record_video(if let Some(frame) = video_capture.ocr_frame_queue.pop() {for window_result in &frame.window_ocr_results {match db- .insert_frame(&device_name, None, window_result.browser_url.as_deref())+ .insert_frame(+ &device_name,+ None,+ window_result.browser_url.as_deref(),+ Some(window_result.app_name.as_str()),+ Some(window_result.window_name.as_str()),+ window_result.focused,+ ).await{Ok(frame_id) => {@@ -258,15 +265,7 @@ async fn record_video(},);if let Err(e) = db- .insert_ocr_text(- frame_id,- text,- &text_json,- &window_result.app_name,- &window_result.window_name,- Arc::clone(&ocr_engine),- window_result.focused, // Add this line- )+ .insert_ocr_text(frame_id, text, &text_json, Arc::clone(&ocr_engine)).await{error!(diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rsindex 097991849..9cb3d02e2 100644--- a/screenpipe-server/src/db.rs+++ b/screenpipe-server/src/db.rs@@ -16,7 +16,6 @@ use std::time::Duration;use tracing::{debug, error, warn};use std::collections::BTreeMap;-use tokio::time::{timeout, Duration as TokioDuration};use zerocopy::AsBytes;@@ -304,6 +303,9 @@ impl DatabaseManager {device_name: &str,timestamp: Option<DateTime<Utc>>,browser_url: Option<&str>,+ app_name: Option<&str>,+ window_name: Option<&str>,+ focused: bool,) -> Result<i64, sqlx::Error> {let mut tx = self.pool.begin().await?;debug!("insert_frame Transaction started");@@ -338,15 +340,18 @@ impl DatabaseManager {let timestamp = timestamp.unwrap_or_else(Utc::now);- // Insert the new frame with file_path as name+ // Insert the new frame with file_path as name and app/window metadatalet id = sqlx::query(- "INSERT INTO frames (video_chunk_id, offset_index, timestamp, name, browser_url) VALUES (?1, ?2, ?3, ?4, ?5)",+ "INSERT INTO frames (video_chunk_id, offset_index, timestamp, name, browser_url, app_name, window_name, focused) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",).bind(video_chunk_id).bind(offset_index).bind(timestamp).bind(file_path)- .bind(browser_url.map(|s| s.to_string()))+ .bind(browser_url)+ .bind(app_name)+ .bind(window_name)+ .bind(focused).execute(&mut *tx).await?.last_insert_rowid();@@ -358,109 +363,20 @@ impl DatabaseManager {Ok(id)}- #[allow(clippy::too_many_arguments)]pub async fn insert_ocr_text(&self,frame_id: i64,text: &str,text_json: &str,- app_name: &str,- window_name: &str,- ocr_engine: Arc<OcrEngine>,- focused: bool,- ) -> Result<(), sqlx::Error> {- const MAX_RETRIES: u32 = 3;- const TIMEOUT_DURATION: TokioDuration = TokioDuration::from_secs(10);-- for attempt in 1..=MAX_RETRIES {- match timeout(- TIMEOUT_DURATION,- self.insert_ocr_text_old(- frame_id,- text,- text_json,- app_name,- window_name,- Arc::clone(&ocr_engine),- focused,- ),- )- .await- {- Ok(Ok(())) => {- return Ok(());- }- Ok(Err(e)) => {- error!("Failed to insert OCR text on attempt {}: {}", attempt, e);- }- Err(_) => {- warn!(- "Timeout occurred on attempt {} while inserting OCR text for frame_id: {}",- attempt, frame_id- );- }- }-- if attempt < MAX_RETRIES {- warn!(- "Retrying to insert OCR text for frame_id: {} (attempt {}/{})",- frame_id,- attempt + 1,- MAX_RETRIES- );- } else {- error!(- "Failed to insert OCR text for frame_id: {} after {} attempts",- frame_id, MAX_RETRIES- );- return Err(sqlx::Error::PoolTimedOut);- }- }-- error!(- "Exiting insert_ocr_text for frame_id: {} with PoolTimedOut error",- frame_id- );- Err(sqlx::Error::PoolTimedOut)- }-- #[allow(clippy::too_many_arguments)]- async fn insert_ocr_text_old(- &self,- frame_id: i64,- text: &str,- text_json: &str,- app_name: &str,- window_name: &str,ocr_engine: Arc<OcrEngine>,- focused: bool,) -> Result<(), sqlx::Error> {let text_length = text.len() as i64;- let display_window_name = if window_name.chars().count() > 20 {- format!("{}...", window_name.chars().take(20).collect::<String>())- } else {- window_name.to_string()- };-- debug!(- "Inserting OCR: frame_id {}, app {}, window {}, focused {}, text {}{}",- frame_id,- app_name,- display_window_name,- focused,- text.replace('\n', " ").chars().take(60).collect::<String>(),- if text.len() > 60 { "..." } else { "" },- );-let mut tx = self.pool.begin().await?;- sqlx::query("INSERT INTO ocr_text (frame_id, text, text_json, app_name, ocr_engine, window_name, focused, text_length) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)")+ sqlx::query("INSERT INTO ocr_text (frame_id, text, text_json, ocr_engine, text_length) VALUES (?1, ?2, ?3, ?4, ?5)").bind(frame_id).bind(text).bind(text_json)- .bind(app_name).bind(format!("{:?}", *ocr_engine))- .bind(window_name)- .bind(focused).bind(text_length).execute(&mut *tx).await?;@@ -485,6 +401,8 @@ impl DatabaseManager {max_length: Option<usize>,speaker_ids: Option<Vec<i64>>,frame_name: Option<&str>,+ browser_url: Option<&str>,+ focused: Option<bool>,) -> Result<Vec<SearchResult>, sqlx::Error> {let mut results = Vec::new();@@ -505,6 +423,8 @@ impl DatabaseManager {min_length,max_length,frame_name,+ browser_url,+ focused,),self.search_audio(query,@@ -541,6 +461,8 @@ impl DatabaseManager {min_length,max_length,frame_name,+ browser_url,+ focused,),self.search_ui_monitoring(query,@@ -574,6 +496,8 @@ impl DatabaseManager {min_length,max_length,frame_name,+ browser_url,+ focused,).await?;results.extend(ocr_results.into_iter().map(SearchResult::OCR));@@ -650,6 +574,8 @@ impl DatabaseManager {min_length,max_length,frame_name,+ browser_url,+ focused,).await?;let ui_results = self@@ -692,6 +618,8 @@ impl DatabaseManager {min_length,max_length,frame_name,+ browser_url,+ focused,).await?;@@ -738,63 +666,110 @@ impl DatabaseManager {min_length: Option<usize>,max_length: Option<usize>,frame_name: Option<&str>,+ browser_url: Option<&str>,+ focused: Option<bool>,) -> Result<Vec<OCRResult>, sqlx::Error> {- let base_sql = if query.is_empty() {- "ocr_text"- } else {- "ocr_text_fts JOIN ocr_text ON ocr_text_fts.frame_id = ocr_text.frame_id"- };+ let mut frame_fts_parts = Vec::new();- let where_clause = if query.is_empty() {- "WHERE 1=1"- } else {- "WHERE ocr_text_fts MATCH ?1"- };+ if let Some(app) = app_name {+ if !app.is_empty() {+ frame_fts_parts.push(format!("app_name:{}", app));+ }+ }+ if let Some(window) = window_name {+ if !window.is_empty() {+ frame_fts_parts.push(format!("window_name:{}", window));+ }+ }+ if let Some(browser) = browser_url {+ if !browser.is_empty() {+ frame_fts_parts.push(format!("browser_url:{}", browser));+ }+ }+ if let Some(is_focused) = focused {+ frame_fts_parts.push(format!("focused:{}", if is_focused { "1" } else { "0" }));+ }+ if let Some(frame_name) = frame_name {+ if !frame_name.is_empty() {+ frame_fts_parts.push(format!("name:{}", frame_name));+ }+ }++ let frame_query = frame_fts_parts.join(" ");let sql = format!(r#"- SELECT- ocr_text.frame_id,- ocr_text.text as ocr_text,- ocr_text.text_json,- frames.timestamp,- frames.name as frame_name,- video_chunks.file_path,- frames.offset_index,- ocr_text.app_name,- ocr_text.ocr_engine,- ocr_text.window_name,- GROUP_CONCAT(tags.name, ',') as tags,- frames.browser_url- FROM {}- JOIN frames ON ocr_text.frame_id = frames.id- JOIN video_chunks ON frames.video_chunk_id = video_chunks.id- LEFT JOIN vision_tags ON frames.id = vision_tags.vision_id- LEFT JOIN tags ON vision_tags.tag_id = tags.id- {}- AND (?2 IS NULL OR frames.timestamp >= ?2)- AND (?3 IS NULL OR frames.timestamp <= ?3)- AND (?4 IS NULL OR ocr_text.app_name LIKE '%' || ?4 || '%')- AND (?5 IS NULL OR ocr_text.window_name LIKE '%' || ?5 || '%')- AND (?6 IS NULL OR COALESCE(ocr_text.text_length,LENGTH(ocr_text.text)) >= ?6)- AND (?7 IS NULL OR COALESCE(ocr_text.text_length,LENGTH(ocr_text.text)) <= ?7)- AND (?8 IS NULL OR frames.name LIKE '%' || ?8 || '%' COLLATE NOCASE)- GROUP BY ocr_text.frame_id- ORDER BY frames.timestamp DESC- LIMIT ?9 OFFSET ?10- "#,- base_sql, where_clause+ SELECT+ ocr_text.frame_id,+ ocr_text.text as ocr_text,+ ocr_text.text_json,+ frames.timestamp,+ frames.name as frame_name,+ video_chunks.file_path,+ frames.offset_index,+ frames.app_name,+ ocr_text.ocr_engine,+ frames.window_name,+ GROUP_CONCAT(tags.name, ',') as tags,+ frames.browser_url,+ frames.focused+ FROM frames+ JOIN video_chunks ON frames.video_chunk_id = video_chunks.id+ JOIN ocr_text ON frames.id = ocr_text.frame_id+ LEFT JOIN vision_tags ON frames.id = vision_tags.vision_id+ LEFT JOIN tags ON vision_tags.tag_id = tags.id+ {frame_fts_join}+ {ocr_fts_join}+ WHERE 1=1+ {frame_fts_condition}+ {ocr_fts_condition}+ AND (?2 IS NULL OR frames.timestamp >= ?2)+ AND (?3 IS NULL OR frames.timestamp <= ?3)+ AND (?4 IS NULL OR COALESCE(ocr_text.text_length, LENGTH(ocr_text.text)) >= ?4)+ AND (?5 IS NULL OR COALESCE(ocr_text.text_length, LENGTH(ocr_text.text)) <= ?5)+ GROUP BY frames.id+ ORDER BY frames.timestamp DESC+ LIMIT ?7 OFFSET ?8+ "#,+ frame_fts_join = if frame_query.trim().is_empty() {+ ""+ } else {+ "JOIN frames_fts ON frames.id = frames_fts.id"+ },+ ocr_fts_join = if query.trim().is_empty() {+ ""+ } else {+ "JOIN ocr_text_fts ON ocr_text.frame_id = ocr_text_fts.frame_id"+ },+ frame_fts_condition = if frame_query.trim().is_empty() {+ ""+ } else {+ "AND frames_fts MATCH ?1"+ },+ ocr_fts_condition = if query.trim().is_empty() {+ ""+ } else {+ "AND ocr_text_fts MATCH ?6"+ });- let raw_results: Vec<OCRResultRaw> = sqlx::query_as(&sql)- .bind(query)+ let query_builder = sqlx::query_as(&sql);++ let raw_results: Vec<OCRResultRaw> = query_builder+ .bind(if frame_query.trim().is_empty() {+ None+ } else {+ Some(&frame_query)+ }).bind(start_time).bind(end_time)- .bind(app_name)- .bind(window_name).bind(min_length.map(|l| l as i64)).bind(max_length.map(|l| l as i64))- .bind(frame_name)+ .bind(if query.trim().is_empty() {+ None+ } else {+ Some(query)+ }).bind(limit).bind(offset).fetch_all(&self.pool)@@ -818,6 +793,7 @@ impl DatabaseManager {.map(|t| t.split(',').map(String::from).collect()).unwrap_or_default(),browser_url: raw.browser_url,+ focused: raw.focused,}).collect())}@@ -834,28 +810,9 @@ impl DatabaseManager {max_length: Option<usize>,speaker_ids: Option<Vec<i64>>,) -> Result<Vec<AudioResult>, sqlx::Error> {- let mut json_array: String = "[]".to_string();- if let Some(ids) = speaker_ids {- if !ids.is_empty() {- json_array = serde_json::to_string(&ids).unwrap_or_default();- }- }-- let base_sql = if query.is_empty() {- "audio_transcriptions"- } else {- "audio_transcriptions_fts JOIN audio_transcriptions ON audio_transcriptions_fts.audio_chunk_id = audio_transcriptions.audio_chunk_id"- };-- let where_clause = if query.is_empty() {- "WHERE 1=1"- } else {- "WHERE audio_transcriptions_fts MATCH ?1"- };-- let sql = format!(- r#"- SELECT+ // base query for audio search+ let mut base_sql = String::from(+ "SELECTaudio_transcriptions.audio_chunk_id,audio_transcriptions.transcription,audio_transcriptions.timestamp,@@ -868,68 +825,119 @@ impl DatabaseManager {audio_transcriptions.speaker_id,audio_transcriptions.start_time,audio_transcriptions.end_time- FROM {}- JOIN audio_chunks ON audio_transcriptions.audio_chunk_id = audio_chunks.id- LEFT JOIN speakers on audio_transcriptions.speaker_id = speakers.id- LEFT JOIN audio_tags ON audio_chunks.id = audio_tags.audio_chunk_id- LEFT JOIN tags ON audio_tags.tag_id = tags.id- {}- AND (?2 IS NULL OR audio_transcriptions.timestamp >= ?2)- AND (?3 IS NULL OR audio_transcriptions.timestamp <= ?3)- AND (?4 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) >= ?4)- AND (?5 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) <= ?5)- AND (speakers.id IS NULL OR speakers.hallucination = 0)- AND (json_array_length(?6) = 0 OR audio_transcriptions.speaker_id IN (SELECT value FROM json_each(?6)))- GROUP BY audio_transcriptions.audio_chunk_id, audio_transcriptions.offset_index- ORDER BY audio_transcriptions.timestamp DESC- LIMIT ?7 OFFSET ?8- "#,+ FROM audio_transcriptions+ JOIN audio_chunks ON audio_transcriptions.audio_chunk_id = audio_chunks.id+ LEFT JOIN speakers ON audio_transcriptions.speaker_id = speakers.id+ LEFT JOIN audio_tags ON audio_chunks.id = audio_tags.audio_chunk_id+ LEFT JOIN tags ON audio_tags.tag_id = tags.id",+ );+ // if query is provided, join the corresponding fts table+ if !query.is_empty() {+ base_sql.push_str(" JOIN audio_transcriptions_fts ON audio_transcriptions_fts.audio_chunk_id = audio_transcriptions.audio_chunk_id");+ }++ // build where clause conditions in order+ let mut conditions = Vec::new();+ if !query.is_empty() {+ conditions.push("audio_transcriptions_fts MATCH ?");+ }+ if start_time.is_some() {+ conditions.push("audio_transcriptions.timestamp >= ?");+ }+ if end_time.is_some() {+ conditions.push("audio_transcriptions.timestamp <= ?");+ }+ if min_length.is_some() {+ conditions.push("COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) >= ?");+ }+ if max_length.is_some() {+ conditions.push("COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) <= ?");+ }+ conditions.push("(speakers.id IS NULL OR speakers.hallucination = 0)");+ if speaker_ids.is_some() {+ conditions.push("(json_array_length(?) = 0 OR audio_transcriptions.speaker_id IN (SELECT value FROM json_each(?)))");+ }++ let where_clause = if conditions.is_empty() {+ "WHERE 1=1".to_owned()+ } else {+ format!("WHERE {}", conditions.join(" AND "))+ };++ // complete sql with group, order, limit and offset+ let sql = format!(+ "{} {} GROUP BY audio_transcriptions.audio_chunk_id, audio_transcriptions.offset_index ORDER BY audio_transcriptions.timestamp DESC LIMIT ? OFFSET ?",base_sql, where_clause);- let raw_results: Vec<AudioResultRaw> = sqlx::query_as(&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)- .bind(limit)- .bind(offset)- .fetch_all(&self.pool)- .await?;+ // prepare binding for speaker_ids (if any)+ let speaker_ids_json = speaker_ids.as_ref().map_or_else(+ || "[]".to_string(),+ |ids| serde_json::to_string(&ids).unwrap_or_else(|_| "[]".to_string()),+ );- let futures = raw_results.into_iter().map(|raw| async move {- let speaker = match raw.speaker_id {- Some(id) => match self.get_speaker_by_id(id).await {- Ok(speaker) => Some(speaker),- Err(_) => None,- },- None => None,- };+ let mut query_builder = sqlx::query_as::<_, AudioResultRaw>(&sql);- Ok::<AudioResult, sqlx::Error>(AudioResult {- audio_chunk_id: raw.audio_chunk_id,- transcription: raw.transcription,- timestamp: raw.timestamp,- file_path: raw.file_path,- offset_index: raw.offset_index,- transcription_engine: raw.transcription_engine,- tags: raw- .tags- .map(|t| t.split(',').map(String::from).collect())- .unwrap_or_default(),- device_name: raw.device_name,- device_type: if raw.is_input_device {- DeviceType::Input- } else {- DeviceType::Output- },- speaker,- start_time: raw.start_time,- end_time: raw.end_time,+ // bind parameters in the same order as added to the where clause+ if !query.is_empty() {+ query_builder = query_builder.bind(query);+ }+ if let Some(start) = start_time {+ query_builder = query_builder.bind(start);+ }+ if let Some(end) = end_time {+ query_builder = query_builder.bind(end);+ }+ if let Some(min) = min_length {+ query_builder = query_builder.bind(min as i64);+ }+ if let Some(max) = max_length {+ query_builder = query_builder.bind(max as i64);+ }+ if speaker_ids.is_some() {+ query_builder = query_builder+ .bind(&speaker_ids_json)+ .bind(&speaker_ids_json);+ }+ query_builder = query_builder.bind(limit as i64).bind(offset as i64);++ let results_raw: Vec<AudioResultRaw> = query_builder.fetch_all(&self.pool).await?;++ // map raw results into audio result type+ let futures: Vec<_> = results_raw+ .into_iter()+ .map(|raw| async move {+ let speaker = match raw.speaker_id {+ Some(id) => match self.get_speaker_by_id(id).await {+ Ok(speaker) => Some(speaker),+ Err(_) => None,+ },+ None => None,+ };++ Ok::<AudioResult, sqlx::Error>(AudioResult {+ audio_chunk_id: raw.audio_chunk_id,+ transcription: raw.transcription,+ timestamp: raw.timestamp,+ file_path: raw.file_path,+ offset_index: raw.offset_index,+ transcription_engine: raw.transcription_engine,+ tags: raw+ .tags+ .map(|s| s.split(',').map(|s| s.to_owned()).collect())+ .unwrap_or_default(),+ device_name: raw.device_name,+ device_type: if raw.is_input_device {+ DeviceType::Input+ } else {+ DeviceType::Output+ },+ speaker,+ start_time: raw.start_time,+ end_time: raw.end_time,+ })})- });+ .collect();Ok(try_join_all(futures).await?.into_iter().collect())}@@ -966,7 +974,66 @@ impl DatabaseManager {max_length: Option<usize>,speaker_ids: Option<Vec<i64>>,frame_name: Option<&str>,+ browser_url: Option<&str>,+ focused: Option<bool>,) -> Result<usize, sqlx::Error> {+ if content_type == ContentType::All {+ // Create boxed futures to avoid infinite size issues with recursion+ let ocr_future = Box::pin(self.count_search_results(+ query,+ ContentType::OCR,+ start_time,+ end_time,+ app_name,+ window_name,+ min_length,+ max_length,+ None,+ frame_name,+ browser_url,+ focused,+ ));++ let ui_future = Box::pin(self.count_search_results(+ query,+ ContentType::UI,+ start_time,+ end_time,+ app_name,+ window_name,+ min_length,+ max_length,+ None,+ None,+ None,+ None,+ ));++ if app_name.is_none() && window_name.is_none() {+ let audio_future = Box::pin(self.count_search_results(+ query,+ ContentType::Audio,+ start_time,+ end_time,+ None,+ None,+ min_length,+ max_length,+ speaker_ids,+ None,+ None,+ None,+ ));++ let (ocr_count, audio_count, ui_count) =+ tokio::try_join!(ocr_future, audio_future, ui_future)?;+ return Ok(ocr_count + audio_count + ui_count);+ } else {+ let (ocr_count, ui_count) = tokio::try_join!(ocr_future, ui_future)?;+ return Ok(ocr_count + ui_count);+ }+ }+let json_array = if let Some(ids) = speaker_ids {if !ids.is_empty() {serde_json::to_string(&ids).unwrap_or_default()@@ -976,163 +1043,139 @@ impl DatabaseManager {} else {"[]".to_string()};+ // Build frame and OCR FTS queries+ let mut frame_fts_parts = Vec::new();+ let mut ocr_fts_parts = Vec::new();+ let mut ui_fts_parts = Vec::new();- let sql = match content_type {- ContentType::OCR => {- format!(- r#"- SELECT COUNT(DISTINCT frames.id)- FROM {table}- JOIN frames ON ocr_text.frame_id = frames.id- WHERE {match_condition}- AND (?2 IS NULL OR frames.timestamp >= ?2)- AND (?3 IS NULL OR frames.timestamp <= ?3)- AND (?4 IS NULL OR ocr_text.app_name LIKE '%' || ?4 || '%')- AND (?5 IS NULL OR ocr_text.window_name LIKE '%' || ?5 || '%')- AND (?6 IS NULL OR COALESCE(ocr_text.text_length, LENGTH(ocr_text.text)) >= ?6)- AND (?7 IS NULL OR COALESCE(ocr_text.text_length, LENGTH(ocr_text.text)) <= ?7)- AND (?8 IS NULL OR frames.name LIKE '%' || ?8 || '%' COLLATE NOCASE)- "#,- table = if query.is_empty() {- "ocr_text"- } else {- "ocr_text_fts JOIN ocr_text ON ocr_text_fts.frame_id = ocr_text.frame_id"- },- match_condition = if query.is_empty() {- "1=1"- } else {- "ocr_text_fts MATCH ?1"- }- )- }- ContentType::Audio => {- format!(- r#"- SELECT COUNT(DISTINCT audio_transcriptions.audio_chunk_id || '_' || COALESCE(audio_transcriptions.start_time, '') || '_' || COALESCE(audio_transcriptions.end_time, ''))- FROM {table}- WHERE {match_condition}- AND (?2 IS NULL OR audio_transcriptions.timestamp >= ?2)- AND (?3 IS NULL OR audio_transcriptions.timestamp <= ?3)- AND (?4 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) >= ?4)- AND (?5 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) <= ?5)- AND (json_array_length(?6) = 0 OR audio_transcriptions.speaker_id IN (SELECT value FROM json_each(?6)))- "#,- table = if query.is_empty() {- "audio_transcriptions"- } else {- "audio_transcriptions_fts JOIN audio_transcriptions ON audio_transcriptions_fts.audio_chunk_id = audio_transcriptions.audio_chunk_id"- },- match_condition = if query.is_empty() {- "1=1"- } else {- "audio_transcriptions_fts MATCH ?1"- }- )+ // Split query parts between frame metadata and OCR content+ if !query.is_empty() {+ ocr_fts_parts.push(query.to_owned()); // Just use the query directly+ ui_fts_parts.push(query.to_owned());+ }+ if let Some(app) = app_name {+ if !app.is_empty() {+ frame_fts_parts.push(format!("app_name:{}", app));+ ui_fts_parts.push(format!("app:\"{}\"", app));}- ContentType::UI => {- format!(- r#"- SELECT COUNT(DISTINCT ui_monitoring.id)- FROM {table}- WHERE {match_condition}- AND (?2 IS NULL OR ui_monitoring.timestamp >= ?2)- AND (?3 IS NULL OR ui_monitoring.timestamp <= ?3)- AND (?4 IS NULL OR ui_monitoring.app LIKE '%' || ?4 || '%')- AND (?5 IS NULL OR ui_monitoring.window LIKE '%' || ?5 || '%')- AND (?6 IS NULL OR COALESCE(ui_monitoring.text_length, LENGTH(ui_monitoring.text_output)) >= ?6)- AND (?7 IS NULL OR COALESCE(ui_monitoring.text_length, LENGTH(ui_monitoring.text_output)) <= ?7)- "#,- table = if query.is_empty() {- "ui_monitoring"- } else {- "ui_monitoring_fts JOIN ui_monitoring ON ui_monitoring_fts.ui_id = ui_monitoring.id"- },- match_condition = if query.is_empty() {- "1=1"- } else {- "ui_monitoring_fts MATCH ?1"- }- )+ }+ if let Some(window) = window_name {+ if !window.is_empty() {+ frame_fts_parts.push(format!("window_name:{}", window));+ ui_fts_parts.push(format!("window:\"{}\"", window));}- ContentType::All => {- format!(- r#"- SELECT COUNT(*) FROM (- -- OCR part- SELECT DISTINCT frames.id- FROM {ocr_table}- JOIN frames ON ocr_text.frame_id = frames.id- WHERE {ocr_match}- AND (?2 IS NULL OR frames.timestamp >= ?2)- AND (?3 IS NULL OR frames.timestamp <= ?3)- AND (?4 IS NULL OR ocr_text.app_name LIKE '%' || ?4 || '%')- AND (?5 IS NULL OR ocr_text.window_name LIKE '%' || ?5 || '%')- AND (?6 IS NULL OR COALESCE(ocr_text.text_length, LENGTH(ocr_text.text)) >= ?6)- AND (?7 IS NULL OR COALESCE(ocr_text.text_length, LENGTH(ocr_text.text)) <= ?7)- AND (?8 IS NULL OR frames.name LIKE '%' || ?8 || '%' COLLATE NOCASE)- UNION ALL- -- Audio part- SELECT DISTINCT audio_transcriptions.id- FROM {audio_table}- WHERE {audio_match}- AND (?2 IS NULL OR audio_transcriptions.timestamp >= ?2)- AND (?3 IS NULL OR audio_transcriptions.timestamp <= ?3)- AND (?6 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) >= ?6)- AND (?7 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) <= ?7)- AND audio_transcriptions.transcription != ''- AND (json_array_length(?9) = 0 OR audio_transcriptions.speaker_id IN (SELECT value FROM json_each(?9)))- UNION ALL- -- UI part- SELECT DISTINCT ui_monitoring.id- FROM {ui_table}- WHERE {ui_match}- AND (?2 IS NULL OR ui_monitoring.timestamp >= ?2)- AND (?3 IS NULL OR ui_monitoring.timestamp <= ?3)- AND (?4 IS NULL OR ui_monitoring.app LIKE '%' || ?4 || '%')- AND (?5 IS NULL OR ui_monitoring.window LIKE '%' || ?5 || '%')- AND (?6 IS NULL OR COALESCE(ui_monitoring.text_length, LENGTH(ui_monitoring.text_output)) >= ?6)- AND (?7 IS NULL OR COALESCE(ui_monitoring.text_length, LENGTH(ui_monitoring.text_output)) <= ?7)- AND ui_monitoring.text_output != ''- )"#,- ocr_table = if query.is_empty() {- "ocr_text"- } else {- "ocr_text_fts JOIN ocr_text ON ocr_text_fts.frame_id = ocr_text.frame_id"- },- ocr_match = if query.is_empty() {- "1=1"- } else {- "ocr_text_fts MATCH ?1"- },- audio_table = if query.is_empty() {- "audio_transcriptions"- } else {- "audio_transcriptions_fts JOIN audio_transcriptions ON audio_transcriptions_fts.audio_chunk_id = audio_transcriptions.audio_chunk_id"- },- audio_match = if query.is_empty() {- "1=1"- } else {- "audio_transcriptions_fts MATCH ?1"- },- ui_table = if query.is_empty() {- "ui_monitoring"- } else {- "ui_monitoring_fts JOIN ui_monitoring ON ui_monitoring_fts.ui_id = ui_monitoring.id"- },- ui_match = if query.is_empty() {- "1=1"- } else {- "ui_monitoring_fts MATCH ?1"- }- )+ }+ if let Some(browser) = browser_url {+ if !browser.is_empty() {+ frame_fts_parts.push(format!("browser_url:{}", browser));}+ }+ if let Some(is_focused) = focused {+ frame_fts_parts.push(format!("focused:{}", if is_focused { "1" } else { "0" }));+ }++ let frame_query = frame_fts_parts.join(" ");+ let ocr_query = ocr_fts_parts.join(" ");+ let ui_query = ui_fts_parts.join(" ");++ let sql = match content_type {+ ContentType::OCR => format!(+ r#"SELECT COUNT(DISTINCT frames.id)+ FROM {base_table}+ WHERE {where_clause}+ AND (?2 IS NULL OR frames.timestamp >= ?2)+ AND (?3 IS NULL OR frames.timestamp <= ?3)+ AND (?4 IS NULL OR COALESCE(ocr_text.text_length, LENGTH(ocr_text.text)) >= ?4)+ AND (?5 IS NULL OR COALESCE(ocr_text.text_length, LENGTH(ocr_text.text)) <= ?5)+ AND (?6 IS NULL OR frames.name LIKE '%' || ?6 || '%')"#,+ base_table = if ocr_query.is_empty() {+ "frames+ JOIN ocr_text ON frames.id = ocr_text.frame_id"+ } else {+ "ocr_text_fts+ JOIN ocr_text ON ocr_text_fts.frame_id = ocr_text.frame_id+ JOIN frames ON ocr_text.frame_id = frames.id"+ },+ where_clause = if ocr_query.is_empty() {+ "1=1"+ } else {+ "ocr_text_fts MATCH ?1"+ }+ ),+ ContentType::UI => format!(+ r#"SELECT COUNT(DISTINCT ui_monitoring.id)+ FROM {table}+ WHERE {match_condition}+ AND (?2 IS NULL OR timestamp >= ?2)+ AND (?3 IS NULL OR timestamp <= ?3)+ AND (?4 IS NULL OR COALESCE(text_length, LENGTH(ui_monitoring.text_output)) >= ?4)+ AND (?5 IS NULL OR COALESCE(text_length, LENGTH(ui_monitoring.text_output)) <= ?5)"#,+ table = if ui_query.is_empty() {+ "ui_monitoring"+ } else {+ "ui_monitoring_fts JOIN ui_monitoring ON ui_monitoring_fts.ui_id = ui_monitoring.id"+ },+ match_condition = if ui_query.is_empty() {+ "1=1"+ } else {+ "ui_monitoring_fts MATCH ?1"+ }+ ),+ ContentType::Audio => format!(+ r#"SELECT COUNT(DISTINCT audio_transcriptions.id)+ FROM {table}+ WHERE {match_condition}+ AND (?2 IS NULL OR audio_transcriptions.timestamp >= ?2)+ AND (?3 IS NULL OR audio_transcriptions.timestamp <= ?3)+ AND (?4 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) >= ?4)+ AND (?5 IS NULL OR COALESCE(audio_transcriptions.text_length, LENGTH(audio_transcriptions.transcription)) <= ?5)+ AND (json_array_length(?6) = 0 OR audio_transcriptions.speaker_id IN (SELECT value FROM json_each(?6)))+ "#,+ table = if query.is_empty() {+ "audio_transcriptions"+ } else {+ "audio_transcriptions_fts JOIN audio_transcriptions ON audio_transcriptions_fts.audio_chunk_id = audio_transcriptions.audio_chunk_id"+ },+ match_condition = if query.is_empty() {+ "1=1"+ } else {+ "audio_transcriptions_fts MATCH ?1"+ }+ ),_ => return Ok(0),};let count: i64 = match content_type {+ ContentType::OCR => {+ sqlx::query_scalar(&sql)+ .bind(if frame_query.is_empty() && ocr_query.is_empty() {+ "*".to_owned()+ } else if frame_query.is_empty() {+ ocr_query+ } else {+ frame_query+ })+ .bind(start_time)+ .bind(end_time)+ .bind(min_length.map(|l| l as i64))+ .bind(max_length.map(|l| l as i64))+ .bind(frame_name)+ .fetch_one(&self.pool)+ .await?+ }+ ContentType::UI => {+ sqlx::query_scalar(&sql)+ .bind(if ui_query.is_empty() { "*" } else { &ui_query })+ .bind(start_time)+ .bind(end_time)+ .bind(min_length.map(|l| l as i64))+ .bind(max_length.map(|l| l as i64))+ .fetch_one(&self.pool)+ .await?+ }ContentType::Audio => {sqlx::query_scalar(&sql)- .bind(query)+ .bind(if query.is_empty() { "*" } else { query }).bind(start_time).bind(end_time).bind(min_length.map(|l| l as i64))@@ -1146,9 +1189,6 @@ impl DatabaseManager {.bind(query).bind(start_time).bind(end_time)- .bind(app_name)- .bind(window_name)- .bind(frame_name).bind(min_length.map(|l| l as i64)).bind(max_length.map(|l| l as i64)).bind(json_array)@@ -1422,13 +1462,13 @@ impl DatabaseManager {f.timestamp,f.offset_index,ot.text,- ot.app_name,- ot.window_name,+ f.app_name,+ f.window_name,vc.device_name as screen_device,vc.file_path as video_path,strftime('%Y-%m-%d %H:%M', f.timestamp) as minute_group,ROW_NUMBER() OVER (- PARTITION BY strftime('%Y-%m-%d %H:%M', f.timestamp), ot.app_name, vc.device_name+ PARTITION BY strftime('%Y-%m-%d %H:%M', f.timestamp), f.app_name, vc.device_nameORDER BY f.timestamp DESC) as rnFROM frames f@@ -1541,13 +1581,26 @@ impl DatabaseManager {limit: u32,offset: u32,) -> Result<Vec<UiContent>, sqlx::Error> {- let base_sql = if query.is_empty() {+ // combine search aspects into single fts query+ let mut fts_parts = Vec::new();+ if !query.is_empty() {+ fts_parts.push(query.to_owned());+ }+ if let Some(app) = app_name {+ fts_parts.push(format!("app:{}", app));+ }+ if let Some(window) = window_name {+ fts_parts.push(format!("window:{}", window));+ }+ let combined_query = fts_parts.join(" ");++ let base_sql = if combined_query.is_empty() {"ui_monitoring"} else {"ui_monitoring_fts JOIN ui_monitoring ON ui_monitoring_fts.ui_id = ui_monitoring.id"};- let where_clause = if query.is_empty() {+ let where_clause = if combined_query.is_empty() {"WHERE 1=1"} else {"WHERE ui_monitoring_fts MATCH ?1"@@ -1559,13 +1612,13 @@ impl DatabaseManager {ui_monitoring.id,ui_monitoring.text_output,ui_monitoring.timestamp,- ui_monitoring.app,- ui_monitoring.window,+ ui_monitoring.app as app_name,+ ui_monitoring.window as window_name,ui_monitoring.initial_traversal_at,video_chunks.file_path,frames.offset_index,- frames.browser_url,- frames.name as frame_name+ frames.name as frame_name,+ frames.browser_urlFROM {}LEFT JOIN frames ONframes.timestamp BETWEEN@@ -1575,20 +1628,21 @@ impl DatabaseManager {{}AND (?2 IS NULL OR ui_monitoring.timestamp >= ?2)AND (?3 IS NULL OR ui_monitoring.timestamp <= ?3)- AND (?4 IS NULL OR ui_monitoring.app LIKE '%' || ?4 || '%')- AND (?5 IS NULL OR ui_monitoring.window LIKE '%' || ?5 || '%')+ GROUP BY ui_monitoring.idORDER BY ui_monitoring.timestamp DESC- LIMIT ?6 OFFSET ?7+ LIMIT ?4 OFFSET ?5"#,base_sql, where_clause);sqlx::query_as(&sql)- .bind(query)+ .bind(if combined_query.is_empty() {+ "*".to_owned()+ } else {+ combined_query+ }).bind(start_time).bind(end_time)- .bind(app_name)- .bind(window_name).bind(limit).bind(offset).fetch_all(&self.pool)@@ -2002,9 +2056,9 @@ impl DatabaseManager {video_chunks.file_path,frames.offset_index,frames.name as frame_name,- ocr_text.app_name,+ frames.app_name,ocr_text.ocr_engine,- ocr_text.window_name,+ frames.window_name,GROUP_CONCAT(tags.name, ',') as tags,frames.browser_urlFROM embedding_matches@@ -2044,6 +2098,7 @@ impl DatabaseManager {.map(|t| t.split(',').map(String::from).collect()).unwrap_or_default(),browser_url: raw.browser_url,+ focused: raw.focused,}).collect())}@@ -2181,11 +2236,11 @@ impl DatabaseManager {conditions.push("f.timestamp <= ?");}- // Add app names condition if provided+ // Add app names condition if provided - updated to use f.app_nameif let Some(apps) = &app_names {if !apps.is_empty() {let placeholders = vec!["?"; apps.len()].join(",");- let app_condition = format!("o.app_name IN ({})", placeholders);+ let app_condition = format!("f.app_name IN ({})", placeholders);owned_conditions.push(app_condition);conditions.push(owned_conditions.last().unwrap().as_str());}@@ -2216,8 +2271,8 @@ SELECTf.id,f.timestamp,f.browser_url as url,- o.app_name,- o.window_name,+ f.app_name,+ f.window_name,o.text as ocr_text,o.text_jsonFROM frames fdiff --git a/screenpipe-server/src/db_types.rs b/screenpipe-server/src/db_types.rsindex a065468e7..ef0060c9f 100644--- a/screenpipe-server/src/db_types.rs+++ b/screenpipe-server/src/db_types.rs@@ -23,6 +23,14 @@ pub enum SearchResult {UI(UiContent),}+#[derive(FromRow, Debug)]+pub struct Frame {+ pub id: i64,+ pub timestamp: DateTime<Utc>,+ pub browser_url: String,+ pub app_name: String,+ pub window_name: String,+}#[derive(FromRow, Debug)]pub struct OCRResultRaw {pub frame_id: i64,@@ -37,6 +45,7 @@ pub struct OCRResultRaw {pub window_name: String,pub tags: Option<String>,pub browser_url: Option<String>,+ pub focused: Option<bool>,}#[derive(Debug, Serialize, Deserialize)]@@ -53,6 +62,7 @@ pub struct OCRResult {pub window_name: String,pub tags: Vec<String>,pub browser_url: Option<String>,+ pub focused: Option<bool>,}#[derive(Debug, Deserialize, PartialEq, Default, Clone)]@@ -126,9 +136,9 @@ pub struct UiContent {#[sqlx(rename = "text_output")]pub text: String,pub timestamp: DateTime<Utc>,- #[sqlx(rename = "app")]+ #[sqlx(rename = "app_name")]pub app_name: String,- #[sqlx(rename = "window")]+ #[sqlx(rename = "window_name")]pub window_name: String,pub initial_traversal_at: Option<DateTime<Utc>>,pub file_path: String,diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex 9a1754b59..d195b5439 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -1,26 +1,32 @@+mod add;mod auto_destruct;pub mod chunking;pub mod cli;pub mod core;pub mod db;pub mod db_types;+pub mod embedding;pub mod filtering;-mod add;+pub mod migration_worker;pub mod pipe_manager;mod plugin;mod resource_monitor;mod server;+pub mod text_embeds;mod video;pub mod video_cache;mod video_db;pub mod video_utils;-pub mod text_embeds;-pub mod embedding;+pub use add::handle_index_command;pub use auto_destruct::watch_pid;+pub use axum::Json as JsonResponse;pub use cli::Cli;pub use core::start_continuous_recording;pub use db::DatabaseManager;-pub use add::handle_index_command;+pub use migration_worker::{+ create_migration_worker, MigrationCommand, MigrationConfig, MigrationResponse, MigrationStatus,+ MigrationWorker,+};pub use pipe_manager::PipeManager;pub use resource_monitor::{ResourceMonitor, RestartSignal};pub use screenpipe_core::Language;@@ -31,9 +37,5 @@ pub use server::ContentItem;pub use server::HealthCheckResponse;pub use server::PaginatedResponse;pub use server::Server;+pub use server::{api_list_monitors, MonitorInfo};pub use video::VideoCapture;-pub use axum::Json as JsonResponse;-pub use server::{- api_list_monitors,- MonitorInfo,-};diff --git a/screenpipe-server/src/migration_worker.rs b/screenpipe-server/src/migration_worker.rsnew file mode 100644index 000000000..35b8daf82--- /dev/null+++ b/screenpipe-server/src/migration_worker.rs@@ -0,0 +1,601 @@+use anyhow::{anyhow, Result};+use chrono::Utc;+use serde::Serialize;+use sqlx::{Row, SqlitePool};+use std::sync::{+ atomic::{AtomicBool, Ordering},+ Arc,+};+use std::time::Duration;+use tokio::{sync::mpsc, task::JoinHandle, time};+use tracing::{debug, error, info, warn};++use crate::DatabaseManager;++/// Status of a migration job+#[derive(Debug, Clone, PartialEq, Serialize)]+pub enum MigrationStatus {+ /// Migration is currently running+ Running {+ total_records: i64,+ processed_records: i64,+ },+ /// Migration completed successfully+ Completed {+ total_records: i64,+ duration_secs: u64,+ },+ /// Migration is paused and can be resumed+ Paused {+ total_records: i64,+ processed_records: i64,+ },+ /// Migration failed with an error+ Failed {+ total_records: i64,+ processed_records: i64,+ error: String,+ },+ /// Migration has not been started yet+ NotStarted,+}++/// Commands that can be sent to control the migration worker+#[derive(Debug, Clone)]+pub enum MigrationCommand {+ /// Start or resume the migration+ Start,+ /// Pause the migration (can be resumed later)+ Pause,+ /// Stop the migration (cannot be resumed)+ Stop,+ /// Request current migration status+ Status,+}++/// Response from the migration worker, including current status+#[derive(Serialize)]+pub struct MigrationResponse {+ pub status: MigrationStatus,+}++/// Configuration for the migration worker+#[derive(Debug, Clone)]+pub struct MigrationConfig {+ /// Number of records to process in a single batch+ pub batch_size: i64,+ /// Delay between batches to reduce database load+ pub batch_delay_ms: u64,+ /// Whether to continue processing if an error occurs+ pub continue_on_error: bool,+}++impl Default for MigrationConfig {+ fn default() -> Self {+ Self {+ batch_size: 1000,+ batch_delay_ms: 100,+ continue_on_error: true,+ }+ }+}++/// Worker that handles background migration of data+pub struct MigrationWorker {+ db: Arc<DatabaseManager>,+ status: MigrationStatus,+ is_running: Arc<AtomicBool>,+ is_paused: Arc<AtomicBool>,+ config: MigrationConfig,+ cmd_rx: mpsc::Receiver<MigrationCommand>,+ status_tx: mpsc::Sender<MigrationResponse>,+ worker_handle: Option<JoinHandle<()>>,+}++impl MigrationWorker {+ /// Create a new migration worker+ pub fn new(+ db: Arc<DatabaseManager>,+ cmd_rx: mpsc::Receiver<MigrationCommand>,+ status_tx: mpsc::Sender<MigrationResponse>,+ config: MigrationConfig,+ ) -> Self {+ Self {+ db,+ status: MigrationStatus::NotStarted,+ is_running: Arc::new(AtomicBool::new(false)),+ is_paused: Arc::new(AtomicBool::new(false)),+ config,+ cmd_rx,+ status_tx,+ worker_handle: None,+ }+ }++ /// Start the migration worker to process commands+ pub fn start(mut self) -> JoinHandle<()> {+ tokio::spawn(async move {+ info!("Migration worker started");+ while let Some(cmd) = self.cmd_rx.recv().await {+ match cmd {+ MigrationCommand::Start => {+ self.start_migration().await;+ }+ MigrationCommand::Pause => {+ self.pause_migration();+ }+ MigrationCommand::Stop => {+ self.stop_migration();+ break;+ }+ MigrationCommand::Status => {+ let _ = self+ .status_tx+ .send(MigrationResponse {+ status: self.status.clone(),+ })+ .await;+ }+ }+ }+ info!("Migration worker stopped");+ })+ }++ async fn start_migration(&mut self) {+ if self.is_running.load(Ordering::SeqCst) {+ if self.is_paused.load(Ordering::SeqCst) {+ // Resume migration+ info!("Resuming migration");+ self.is_paused.store(false, Ordering::SeqCst);+ let _ = self+ .status_tx+ .send(MigrationResponse {+ status: self.status.clone(),+ })+ .await;+ return;+ }+ warn!("Migration is already running");+ return;+ }++ // Start the migration worker+ self.is_running.store(true, Ordering::SeqCst);++ // Create clones of shared resources for the worker task+ let db = self.db.clone();+ let config = self.config.clone();+ let is_running = self.is_running.clone();+ let is_paused = self.is_paused.clone();+ let status_tx = self.status_tx.clone();++ // Spawn a task to handle the actual migration work+ let handle = tokio::spawn(async move {+ // Start the migration process+ let result = migrate_ocr_data_to_frames(+ &db.pool,+ config,+ is_running.clone(),+ is_paused.clone(),+ status_tx.clone(),+ )+ .await;++ // Handle completion or failure+ match result {+ Ok((total, duration)) => {+ info!("Migration completed successfully: {total} records processed in {duration} seconds");+ let _ = status_tx+ .send(MigrationResponse {+ status: MigrationStatus::Completed {+ total_records: total,+ duration_secs: duration,+ },+ })+ .await;+ }+ Err(e) => {+ let error_msg = e.to_string();+ error!("Migration failed: {error_msg}");++ // Try to get the current progress+ let processed = get_migration_progress(&db.pool).await.unwrap_or(0);+ let total = get_total_records(&db.pool).await.unwrap_or(0);++ let _ = status_tx+ .send(MigrationResponse {+ status: MigrationStatus::Failed {+ total_records: total,+ processed_records: processed,+ error: error_msg,+ },+ })+ .await;+ }+ }++ is_running.store(false, Ordering::SeqCst);+ });++ self.worker_handle = Some(handle);+ }++ fn pause_migration(&self) {+ if self.is_running.load(Ordering::SeqCst) {+ info!("Pausing migration");+ self.is_paused.store(true, Ordering::SeqCst);+ } else {+ warn!("Cannot pause migration: not running");+ }+ }++ fn stop_migration(&self) {+ if self.is_running.load(Ordering::SeqCst) {+ info!("Stopping migration");+ self.is_running.store(false, Ordering::SeqCst);++ // Cancel the worker task if it's running+ if let Some(handle) = &self.worker_handle {+ handle.abort();+ }+ } else {+ warn!("Cannot stop migration: not running");+ }+ }+}++/// Create a migration progress table if it doesn't exist+async fn ensure_migration_table(pool: &SqlitePool) -> Result<()> {+ sqlx::query(+ r#"+ CREATE TABLE IF NOT EXISTS migration_progress (+ id INTEGER PRIMARY KEY,+ migration_name TEXT NOT NULL,+ last_processed_id INTEGER NOT NULL,+ total_records INTEGER NOT NULL,+ processed_records INTEGER NOT NULL,+ started_at TIMESTAMP NOT NULL,+ updated_at TIMESTAMP NOT NULL,+ completed_at TIMESTAMP+ )+ "#,+ )+ .execute(pool)+ .await?;++ Ok(())+}++/// Get the current migration progress+async fn get_migration_progress(pool: &SqlitePool) -> Result<i64> {+ ensure_migration_table(pool).await?;++ let progress = sqlx::query_scalar::<_, i64>(+ r#"+ SELECT processed_records FROM migration_progress+ WHERE migration_name = 'ocr_text_to_frames'+ ORDER BY id DESC LIMIT 1+ "#,+ )+ .fetch_optional(pool)+ .await?+ .unwrap_or(0);++ Ok(progress)+}++/// Get the total number of records to migrate+async fn get_total_records(pool: &SqlitePool) -> Result<i64> {+ let total = sqlx::query_scalar::<_, i64>(+ r#"+ SELECT COUNT(DISTINCT frame_id) FROM ocr_text+ WHERE (app_name IS NOT NULL AND app_name != '')+ OR (window_name IS NOT NULL AND window_name != '')+ OR (focused IS NOT NULL)+ "#,+ )+ .fetch_one(pool)+ .await?;++ Ok(total)+}++/// Update the migration progress+async fn update_migration_progress(+ pool: &SqlitePool,+ last_id: i64,+ total: i64,+ processed: i64,+ completed: bool,+) -> Result<()> {+ ensure_migration_table(pool).await?;++ let now = Utc::now();+ let completed_at = if completed { Some(now) } else { None };++ // Check if we have an existing record+ let existing = sqlx::query_scalar::<_, i64>(+ r#"+ SELECT id FROM migration_progress+ WHERE migration_name = 'ocr_text_to_frames'+ "#,+ )+ .fetch_optional(pool)+ .await?;++ if let Some(id) = existing {+ // Update existing record+ sqlx::query(+ r#"+ UPDATE migration_progress+ SET last_processed_id = ?,+ total_records = ?,+ processed_records = ?,+ updated_at = ?,+ completed_at = ?+ WHERE id = ?+ "#,+ )+ .bind(last_id)+ .bind(total)+ .bind(processed)+ .bind(now)+ .bind(completed_at)+ .bind(id)+ .execute(pool)+ .await?;+ } else {+ // Insert new record+ sqlx::query(+ r#"+ INSERT INTO migration_progress+ (migration_name, last_processed_id, total_records, processed_records, started_at, updated_at, completed_at)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ "#,+ )+ .bind("ocr_text_to_frames")+ .bind(last_id)+ .bind(total)+ .bind(processed)+ .bind(now)+ .bind(now)+ .bind(completed_at)+ .execute(pool)+ .await?;+ }++ Ok(())+}++/// Perform the actual migration of data from ocr_text to frames+async fn migrate_ocr_data_to_frames(+ pool: &SqlitePool,+ config: MigrationConfig,+ is_running: Arc<AtomicBool>,+ is_paused: Arc<AtomicBool>,+ status_tx: mpsc::Sender<MigrationResponse>,+) -> Result<(i64, u64)> {+ let start_time = std::time::Instant::now();++ // Ensure migration table exists+ ensure_migration_table(pool).await?;++ // Get the total number of records to migrate+ let total_records = get_total_records(pool).await?;++ if total_records == 0 {+ info!("No records to migrate");+ return Ok((0, 0));+ }++ // Get the last processed ID+ let last_processed_id = sqlx::query_scalar::<_, i64>(+ r#"+ SELECT last_processed_id FROM migration_progress+ WHERE migration_name = 'ocr_text_to_frames'+ ORDER BY id DESC LIMIT 1+ "#,+ )+ .fetch_optional(pool)+ .await?+ .unwrap_or(0);++ let mut processed_records = get_migration_progress(pool).await?;++ info!(+ "Starting migration: total_records={}, already_processed={}, last_processed_id={}",+ total_records, processed_records, last_processed_id+ );++ // Update the initial status+ let _ = status_tx+ .send(MigrationResponse {+ status: MigrationStatus::Running {+ total_records,+ processed_records,+ },+ })+ .await;++ // Process in batches+ let batch_size = config.batch_size;+ let mut last_id = last_processed_id;++ while is_running.load(Ordering::SeqCst) && processed_records < total_records {+ // Check if we should pause+ while is_paused.load(Ordering::SeqCst) && is_running.load(Ordering::SeqCst) {+ let _ = status_tx+ .send(MigrationResponse {+ status: MigrationStatus::Paused {+ total_records,+ processed_records,+ },+ })+ .await;+ time::sleep(Duration::from_millis(500)).await;+ }++ if !is_running.load(Ordering::SeqCst) {+ break;+ }++ // Process a batch+ match process_batch(pool, last_id, batch_size).await {+ Ok((batch_processed, new_last_id)) => {+ if batch_processed == 0 {+ // No more records to process+ break;+ }++ processed_records += batch_processed;+ last_id = new_last_id;++ // Update progress+ if let Err(e) = update_migration_progress(+ pool,+ last_id,+ total_records,+ processed_records,+ processed_records >= total_records,+ )+ .await+ {+ warn!("Failed to update migration progress: {}", e);+ }++ // Update status+ let _ = status_tx+ .send(MigrationResponse {+ status: MigrationStatus::Running {+ total_records,+ processed_records,+ },+ })+ .await;++ // Delay between batches to reduce database load+ time::sleep(Duration::from_millis(config.batch_delay_ms)).await;+ }+ Err(e) => {+ error!("Error processing batch: {}", e);++ if !config.continue_on_error {+ return Err(anyhow!("Migration failed: {}", e));+ }++ // Try to continue with the next batch+ last_id += batch_size;++ // Delay a bit longer after an error+ time::sleep(Duration::from_millis(config.batch_delay_ms * 5)).await;+ }+ }+ }++ let duration = start_time.elapsed().as_secs();++ // Final update to mark as completed+ if processed_records >= total_records {+ update_migration_progress(pool, last_id, total_records, processed_records, true).await?;+ }++ Ok((processed_records, duration))+}++/// Process a batch of records+async fn process_batch(pool: &SqlitePool, last_id: i64, batch_size: i64) -> Result<(i64, i64)> {+ let mut tx = pool.begin().await?;++ // Query to get a batch of records with unique frame_ids that need migration+ let records = sqlx::query(+ r#"+ SELECT DISTINCT ocr_text.frame_id,+ ocr_text.app_name,+ ocr_text.window_name,+ ocr_text.focused+ FROM ocr_text+ JOIN frames ON ocr_text.frame_id = frames.id+ WHERE ocr_text.frame_id > ?+ AND (+ -- We need to migrate this data+ (ocr_text.app_name IS NOT NULL AND ocr_text.app_name != '' AND frames.app_name IS NULL) OR+ (ocr_text.window_name IS NOT NULL AND ocr_text.window_name != '' AND frames.window_name IS NULL) OR+ (ocr_text.focused IS NOT NULL AND frames.focused IS NULL)+ )+ ORDER BY ocr_text.frame_id+ LIMIT ?+ "#,+ )+ .bind(last_id)+ .bind(batch_size)+ .fetch_all(&mut *tx)+ .await?;++ let mut count = 0;+ let mut max_id = last_id;++ // Process each record+ for record in records.iter() {+ let frame_id: i64 = record.try_get("frame_id")?;+ let app_name: Option<String> = record.try_get("app_name").unwrap_or(None);+ let window_name: Option<String> = record.try_get("window_name").unwrap_or(None);+ let focused: Option<bool> = record.try_get("focused").unwrap_or(None);++ // Update the frames table+ sqlx::query(+ r#"+ UPDATE frames+ SET app_name = COALESCE(?, app_name),+ window_name = COALESCE(?, window_name),+ focused = COALESCE(?, focused)+ WHERE id = ?+ "#,+ )+ .bind(app_name)+ .bind(window_name)+ .bind(focused)+ .bind(frame_id)+ .execute(&mut *tx)+ .await?;++ count += 1;+ max_id = std::cmp::max(max_id, frame_id);+ }++ // Commit the transaction+ tx.commit().await?;++ debug!("Processed batch: {} records, max_id={}", count, max_id);++ Ok((count, max_id))+}++impl MigrationConfig {+ pub fn new(batch_size: i64, batch_delay_ms: u64, continue_on_error: bool) -> Self {+ Self {+ batch_size,+ batch_delay_ms,+ continue_on_error,+ }+ }+}++/// Create a database migration worker and return channels to control it+pub fn create_migration_worker(+ db: Arc<DatabaseManager>,+ config: Option<MigrationConfig>,+) -> (+ mpsc::Sender<MigrationCommand>,+ mpsc::Receiver<MigrationResponse>,+ JoinHandle<()>,+) {+ let (cmd_tx, cmd_rx) = mpsc::channel(100);+ let (status_tx, status_rx) = mpsc::channel(100);++ let worker = MigrationWorker::new(db, cmd_rx, status_tx, config.unwrap_or_default());++ let handle = worker.start();++ (cmd_tx, status_rx, handle)+}diff --git a/screenpipe-server/src/migrations/20250223204844_browser_url_fts_and_move_window_app_to_frames.sql b/screenpipe-server/src/migrations/20250223204844_browser_url_fts_and_move_window_app_to_frames.sqlnew file mode 100644index 000000000..f9afa664a--- /dev/null+++ b/screenpipe-server/src/migrations/20250223204844_browser_url_fts_and_move_window_app_to_frames.sql@@ -0,0 +1,84 @@+-- Add migration script here+-- Start transaction and temporarily disable foreign keys for the migration+PRAGMA foreign_keys = OFF;++-- Add columns to frames+ALTER TABLE frames ADD COLUMN app_name TEXT DEFAULT NULL;+ALTER TABLE frames ADD COLUMN window_name TEXT DEFAULT NULL;+ALTER TABLE frames ADD COLUMN focused BOOLEAN DEFAULT NULL;++-- Update the existing frames_fts table to include new columns+-- First, drop the existing triggers+DROP TRIGGER IF EXISTS frames_ai;+DROP TRIGGER IF EXISTS frames_ad;+DROP TRIGGER IF EXISTS frames_au;++-- Recreate the FTS table with all columns+DROP TABLE IF EXISTS frames_fts;+CREATE VIRTUAL TABLE IF NOT EXISTS frames_fts USING fts5(+ name,+ browser_url,+ app_name,+ window_name,+ focused,+ id UNINDEXED,+ tokenize='unicode61'+);++-- DATA_MIGRATION: This migration only handles schema changes.+-- The actual data migration from ocr_text to frames table should be done+-- in a background process to avoid blocking database operations.+--+-- See the migration worker implementation that:+-- 1. Runs in a separate thread or process+-- 2. Uses small batches with transaction boundaries+-- 3. Has retry logic and progress tracking+-- 4. Can be paused/resumed if needed+-- 5. Properly handles new incoming data during migration++-- Create updated triggers for frames+CREATE TRIGGER IF NOT EXISTS frames_ai AFTER INSERT ON frames BEGIN+ INSERT INTO frames_fts(id, name, browser_url, app_name, window_name, focused)+ VALUES (+ NEW.id,+ COALESCE(NEW.name, ''),+ COALESCE(NEW.browser_url, ''),+ COALESCE(NEW.app_name, ''),+ COALESCE(NEW.window_name, ''),+ COALESCE(NEW.focused, 0)+ );+END;++CREATE TRIGGER IF NOT EXISTS frames_au AFTER UPDATE ON frames+WHEN (NEW.name IS NOT NULL AND NEW.name != '')+ OR (NEW.browser_url IS NOT NULL AND NEW.browser_url != '')+ OR (NEW.app_name IS NOT NULL AND NEW.app_name != '')+ OR (NEW.window_name IS NOT NULL AND NEW.window_name != '')+ OR (NEW.focused IS NOT NULL)+BEGIN+ INSERT OR REPLACE INTO frames_fts(id, name, browser_url, app_name, window_name, focused)+ VALUES (+ NEW.id,+ COALESCE(NEW.name, ''),+ COALESCE(NEW.browser_url, ''),+ COALESCE(NEW.app_name, ''),+ COALESCE(NEW.window_name, ''),+ COALESCE(NEW.focused, 0)+ );+END;++CREATE TRIGGER IF NOT EXISTS frames_ad AFTER DELETE ON frames+BEGIN+ DELETE FROM frames_fts+ WHERE id = OLD.id;+END;++-- Add indexes for common queries+CREATE INDEX IF NOT EXISTS idx_frames_app_name ON frames(app_name);+CREATE INDEX IF NOT EXISTS idx_frames_window_name ON frames(window_name);+CREATE INDEX IF NOT EXISTS idx_frames_app_window ON frames(app_name, window_name);+CREATE INDEX IF NOT EXISTS idx_frames_browser_url ON frames(browser_url);+CREATE INDEX IF NOT EXISTS idx_frames_focused ON frames(focused);++-- Re-enable foreign keys+PRAGMA foreign_keys = ON;diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex cfac0cc0e..d4eea220a 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -114,6 +114,10 @@ pub(crate) struct SearchQuery {default = "default_speaker_ids")]speaker_ids: Option<Vec<i64>>,+ #[serde(default)]+ focused: Option<bool>,+ #[serde(default)]+ browser_url: Option<String>,}#[derive(Deserialize)]@@ -191,6 +195,7 @@ pub struct OCRContent {pub frame: Option<String>,pub frame_name: Option<String>,pub browser_url: Option<String>,+ pub focused: Option<bool>,}#[derive(Serialize, Deserialize, Debug)]@@ -285,7 +290,7 @@ pub(crate) async fn search((StatusCode, JsonResponse<serde_json::Value>),> {info!(- "received search request: query='{}', content_type={:?}, limit={}, offset={}, start_time={:?}, end_time={:?}, app_name={:?}, window_name={:?}, min_length={:?}, max_length={:?}, speaker_ids={:?}, frame_name={:?}",+ "received search request: query='{}', content_type={:?}, limit={}, offset={}, start_time={:?}, end_time={:?}, app_name={:?}, window_name={:?}, min_length={:?}, max_length={:?}, speaker_ids={:?}, frame_name={:?}, browser_url={:?}",query.q.as_deref().unwrap_or(""),query.content_type,query.pagination.limit,@@ -298,6 +303,7 @@ pub(crate) async fn search(query.max_length,query.speaker_ids,query.frame_name,+ query.browser_url,);let query_str = query.q.as_deref().unwrap_or("");@@ -318,6 +324,8 @@ pub(crate) async fn search(query.max_length,query.speaker_ids.clone(),query.frame_name.as_deref(),+ query.browser_url.as_deref(),+ query.focused,),state.db.count_search_results(query_str,@@ -330,6 +338,8 @@ pub(crate) async fn search(query.max_length,query.speaker_ids.clone(),query.frame_name.as_deref(),+ query.browser_url.as_deref(),+ query.focused,),).await@@ -356,6 +366,7 @@ pub(crate) async fn search(frame: None,frame_name: Some(ocr.frame_name.clone()),browser_url: ocr.browser_url.clone(),+ focused: ocr.focused,}),SearchResult::Audio(audio) => ContentItem::Audio(AudioContent {chunk_id: audio.audio_chunk_id,@@ -1113,6 +1124,9 @@ async fn add_frame_to_db(device_name,Some(frame.timestamp.unwrap_or_else(Utc::now)),None,+ frame.app_name.as_deref(),+ frame.window_name.as_deref(),+ false,).await?;@@ -1122,10 +1136,7 @@ async fn add_frame_to_db(frame_id,&ocr.text,ocr.text_json.as_deref().unwrap_or(""),- frame.app_name.as_deref().unwrap_or(""),- frame.window_name.as_deref().unwrap_or(""),Arc::new(OcrEngine::default()), // Ideally could pass any str as ocr_engine since can be run outside of screenpipe- false,).await?;}diff --git a/screenpipe-server/tests/db.rs b/screenpipe-server/tests/db.rsindex b4f29cd18..ae934508e 100644--- a/screenpipe-server/tests/db.rs+++ b/screenpipe-server/tests/db.rs@@ -5,19 +5,29 @@ mod tests {use chrono::Utc;use screenpipe_audio::{AudioDevice, DeviceType};use screenpipe_server::{- db_types::{ContentType, SearchResult},+ db_types::{ContentType, Frame, SearchResult},DatabaseManager,};use screenpipe_vision::OcrEngine;async fn setup_test_db() -> DatabaseManager {+ // Initialize tracing for debug output+ let _ = tracing_subscriber::fmt()+ .with_max_level(tracing::Level::INFO)+ .try_init();+let db = DatabaseManager::new("sqlite::memory:").await.unwrap();- // Run all migrations- sqlx::migrate!("./src/migrations")- .run(&db.pool)- .await- .unwrap();+ // Run all migrations with better error handling+ match sqlx::migrate!("./src/migrations").run(&db.pool).await {+ Ok(_) => {+ tracing::debug!("Database migrations completed successfully");+ }+ Err(e) => {+ eprintln!("Migration error: {:?}", e);+ panic!("Database migration failed: {}", e);+ }+ }db}@@ -29,15 +39,15 @@ mod tests {.insert_video_chunk("test_video.mp4", "test_device").await.unwrap();- let frame_id = db.insert_frame("test_device", None, None).await.unwrap();+ let frame_id = db+ .insert_frame("test_device", None, None, Some("test"), Some(""), false)+ .await+ .unwrap();db.insert_ocr_text(frame_id,"Hello, world!","",- "test",- "",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();@@ -56,6 +66,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -99,6 +111,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -118,6 +132,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -168,6 +184,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -187,6 +205,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -208,19 +228,38 @@ mod tests {.insert_video_chunk("test_video.mp4", "test_device").await.unwrap();- let frame_id = db.insert_frame("test_device", None, None).await.unwrap();+ let frame_id = db+ .insert_frame("test_device", None, None, Some("test"), Some(""), false)+ .await+ .unwrap();++ // Debug: Check if app_name was inserted correctly+ let frame_data: Frame = sqlx::query_as("SELECT * FROM frames WHERE id = ?")+ .bind(frame_id)+ .fetch_one(&db.pool)+ .await+ .unwrap();+ println!("Inserted frame data: {:?}", frame_data);+db.insert_ocr_text(frame_id,"Hello from OCR","",- "app",- "",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();+ // Verify that frames_fts was populated+ let fts_data: Option<(i64, String, String, String, bool)> = sqlx::query_as(+ "SELECT rowid, browser_url, app_name, window_name, focused FROM frames_fts WHERE rowid = ?",+ )+ .bind(frame_id)+ .fetch_optional(&db.pool)+ .await+ .unwrap();+ println!("Frames FTS data: {:?}", fts_data);+// Insert Audio datalet audio_chunk_id = db.insert_audio_chunk("test_audio.mp4").await.unwrap();db.insert_audio_transcription(@@ -244,7 +283,9 @@ mod tests {0,None,None,- Some("app"),+ Some("test"),+ None,+ None,None,None,None,@@ -269,6 +310,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -298,15 +341,15 @@ mod tests {.insert_video_chunk("test_video.mp4", "test_device").await.unwrap();- let frame_id1 = db.insert_frame("test_device", None, None).await.unwrap();+ let frame_id1 = db+ .insert_frame("test_device", None, None, Some("test"), Some(""), false)+ .await+ .unwrap();db.insert_ocr_text(frame_id1,"Hello from OCR 1","",- "",- "",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();@@ -335,19 +378,49 @@ mod tests {tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;// Insert remaining data- let frame_id2 = db.insert_frame("test_device", None, None).await.unwrap();+ let frame_id2 = db+ .insert_frame("test_device", None, None, Some("test"), Some(""), false)+ .await+ .unwrap();db.insert_ocr_text(frame_id2,"Hello from OCR 2","",- "",- "",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();+ let raw_ocr_text: Vec<(String, Option<i64>)> =+ sqlx::query_as("SELECT text, frame_id FROM ocr_text")+ .fetch_all(&db.pool)+ .await+ .unwrap();+ println!("Raw OCR text in DB: {:?}", raw_ocr_text);+ // print raw frames with timestamp+ let raw_frames: Vec<(Option<i64>, Option<String>)> =+ sqlx::query_as("SELECT id, timestamp FROM frames")+ .fetch_all(&db.pool)+ .await+ .unwrap();+ println!("Raw frames in DB: {:?}", raw_frames);+ // Check if OCR text is properly indexed in FTS+ let ocr_fts_data: Vec<(i64, String)> =+ sqlx::query_as("SELECT rowid, text FROM ocr_text_fts")+ .fetch_all(&db.pool)+ .await+ .unwrap();+ println!("OCR FTS data: {:?}", ocr_fts_data);++ // check if frames_fts is properly indexed+ let frame_fts_data: Vec<(i64, String, String, String, bool)> = sqlx::query_as(+ "SELECT id, browser_url, app_name, window_name, focused FROM frames_fts",+ )+ .fetch_all(&db.pool)+ .await+ .unwrap();+ println!("Frames FTS data: {:?}", frame_fts_data);+let insert_result = db.insert_audio_transcription(audio_chunk_id,@@ -387,6 +460,30 @@ mod tests {let end_time = Utc::now();+ // Debug OCR search with time range+ let ocr_results = db+ .search(+ "Hello",+ ContentType::OCR,+ 100,+ 0,+ Some(start_time),+ Some(end_time),+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ )+ .await+ .unwrap();+ println!("OCR time range results: {:?}", ocr_results);++ assert_eq!(ocr_results.len(), 2);+// Test search with full time rangelet results = db.search(@@ -402,6 +499,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -423,6 +522,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -448,6 +549,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -468,6 +571,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -485,15 +590,15 @@ mod tests {.insert_video_chunk("test_video.mp4", "test_device").await.unwrap();- let frame_id1 = db.insert_frame("test_device", None, None).await.unwrap();+ let frame_id1 = db+ .insert_frame("test_device", None, None, Some("test"), Some(""), false)+ .await+ .unwrap();db.insert_ocr_text(frame_id1,"Hello from OCR 1","",- "",- "",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();@@ -520,15 +625,15 @@ mod tests {tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;// Insert remaining data- let frame_id2 = db.insert_frame("test_device", None, None).await.unwrap();+ let frame_id2 = db+ .insert_frame("test_device", None, None, Some("test"), Some(""), false)+ .await+ .unwrap();db.insert_ocr_text(frame_id2,"Hello from OCR 2","",- "",- "",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();@@ -565,6 +670,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -589,6 +696,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -928,29 +1037,29 @@ mod tests {.unwrap();// Insert first frame with OCR- let frame_id1 = db.insert_frame("test_device", None, None).await.unwrap();+ let frame_id1 = db+ .insert_frame("test_device", None, None, Some("test"), Some(""), false)+ .await+ .unwrap();db.insert_ocr_text(frame_id1,"Hello from frame 1","",- "test_app",- "test_window",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();// Insert second frame with OCR- let frame_id2 = db.insert_frame("test_device", None, None).await.unwrap();+ let frame_id2 = db+ .insert_frame("test_device", None, None, Some("test"), Some(""), false)+ .await+ .unwrap();db.insert_ocr_text(frame_id2,"Hello from frame 2","",- "test_app",- "test_window",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();@@ -970,6 +1079,8 @@ mod tests {None,None,Some("test_video"),+ None,+ None,).await.unwrap();@@ -995,6 +1106,8 @@ mod tests {None,None,Some("non_existent"),+ None,+ None,).await.unwrap();@@ -1020,6 +1133,8 @@ mod tests {None,None,Some("test_video"),+ None,+ None,).await.unwrap();@@ -1043,6 +1158,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -1090,6 +1207,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -1117,6 +1236,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -1137,6 +1258,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -1157,9 +1280,130 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();assert_eq!(results.len(), 1);}++ #[tokio::test]+ async fn test_count_search_results_all_content_types() {+ let db = setup_test_db().await;++ // Insert OCR data+ let _ = db+ .insert_video_chunk("test_video.mp4", "test_device")+ .await+ .unwrap();+ let frame_id = db+ .insert_frame("test_device", None, None, Some("test"), Some(""), false)+ .await+ .unwrap();+ db.insert_ocr_text(+ frame_id,+ "Hello from OCR",+ "",+ Arc::new(OcrEngine::Tesseract),+ )+ .await+ .unwrap();++ // Insert Audio data+ let audio_chunk_id = db.insert_audio_chunk("test_audio.mp4").await.unwrap();+ db.insert_audio_transcription(+ audio_chunk_id,+ "Hello from audio",+ 0,+ "",+ &AudioDevice::new("test".to_string(), DeviceType::Output),+ None,+ None,+ None,+ )+ .await+ .unwrap();++ // Insert UI monitoring data+ sqlx::query(+ r#"+ INSERT INTO ui_monitoring (+ text_output,+ timestamp,+ app,+ window,+ initial_traversal_at+ ) VALUES (?, ?, ?, ?, ?)+ "#,+ )+ .bind("Hello from UI")+ .bind(Utc::now())+ .bind("test_app")+ .bind("test_window")+ .bind(Utc::now())+ .execute(&db.pool)+ .await+ .unwrap();++ // Test count with All content types+ let count = db+ .count_search_results(+ "Hello",+ ContentType::All,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ )+ .await+ .unwrap();+ assert_eq!(count, 3, "Should count OCR, Audio, and UI results");++ // Test count with specific app filter+ let count = db+ .count_search_results(+ "Hello",+ ContentType::All,+ None,+ None,+ Some("test_app"),+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ )+ .await+ .unwrap();+ assert_eq!(count, 1, "Should only count UI result with app filter");++ // Test count with non-matching query+ let count = db+ .count_search_results(+ "nonexistent",+ ContentType::All,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ None,+ )+ .await+ .unwrap();+ assert_eq!(count, 0, "Should count zero results for non-matching query");+ }}diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rsindex d1a17feb3..328300d1d 100644--- a/screenpipe-server/tests/endpoint_test.rs+++ b/screenpipe-server/tests/endpoint_test.rs@@ -172,16 +172,19 @@ mod tests {.insert_video_chunk("test_video1.mp4", "test_device").await.unwrap();- let frame_id1 = db.insert_frame("test_device", None, None).await.unwrap();- let frame_id2 = db.insert_frame("test_device", None, None).await.unwrap();+ let frame_id1 = db+ .insert_frame("test_device", None, None, None, None, true)+ .await+ .unwrap();+ let frame_id2 = db+ .insert_frame("test_device", None, None, None, None, true)+ .await+ .unwrap();db.insert_ocr_text(frame_id1,"This is a test OCR text", // 21 chars"",- "TestApp",- "TestWindow",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();@@ -189,10 +192,7 @@ mod tests {frame_id2,"Another OCR text for testing that should be longer than thirty characters", // >30 chars"",- "TestApp2",- "TestWindow2",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();@@ -239,6 +239,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -257,6 +259,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -275,6 +279,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -293,6 +299,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -311,6 +319,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -329,6 +339,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -347,6 +359,8 @@ mod tests {Some(25),None,None,+ None,+ None,).await.unwrap();@@ -363,7 +377,10 @@ mod tests {.insert_video_chunk("test_video1.mp4", "test_device").await.unwrap();- let frame_id1 = db.insert_frame("test_device", None, None).await.unwrap();+ let frame_id1 = db+ .insert_frame("test_device", None, None, None, None, true)+ .await+ .unwrap();let audio_chunk_id1 = db.insert_audio_chunk("test_audio1.wav").await.unwrap();let now = DateTime::parse_from_rfc3339("2024-09-21T10:49:23.240367Z")@@ -384,10 +401,7 @@ mod tests {frame_id1,"old ocr text","",- "testapp",- "testwindow",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();@@ -427,6 +441,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -446,6 +462,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -466,6 +484,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -490,6 +510,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -513,6 +535,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -530,6 +554,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -551,14 +577,20 @@ mod tests {.insert_video_chunk("old_video.mp4", "test_device").await.unwrap();- let old_frame_id = db.insert_frame("test_device", None, None).await.unwrap();+ let old_frame_id = db+ .insert_frame("test_device", None, None, None, None, true)+ .await+ .unwrap();// Insert recent datalet _ = db.insert_video_chunk("recent_video.mp4", "test_device").await.unwrap();- let recent_frame_id = db.insert_frame("test_device", None, None).await.unwrap();+ let recent_frame_id = db+ .insert_frame("test_device", None, None, None, None, true)+ .await+ .unwrap();// Insert OCR data with different timestampssqlx::query("UPDATE frames SET timestamp = ? WHERE id = ?")@@ -579,10 +611,7 @@ mod tests {old_frame_id,"old task: write documentation","",- "vscode",- "tasks.md",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();@@ -591,10 +620,7 @@ mod tests {recent_frame_id,"current task: fix bug #123","",- "vscode",- "tasks.md",Arc::new(OcrEngine::Tesseract),- false,).await.unwrap();@@ -614,6 +640,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -642,6 +670,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -686,6 +716,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();@@ -707,6 +739,8 @@ mod tests {None,None,None,+ None,+ None,).await.unwrap();diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rsindex 2542d1596..8010ecdac 100644--- a/screenpipe-server/tests/tags_test.rs+++ b/screenpipe-server/tests/tags_test.rs@@ -365,17 +365,24 @@ async fn insert_test_data(db: &Arc<DatabaseManager>) {.unwrap();// Insert test frame- let frame_id = db.insert_frame("test_device", None, None).await.unwrap();+ let frame_id = db+ .insert_frame(+ "test_device",+ None,+ None,+ Some("test_app"),+ Some("test_window"),+ true,+ )+ .await+ .unwrap();// Insert test OCR datadb.insert_ocr_text(frame_id,"Test OCR text","{'text': 'Test OCR text', 'confidence': 0.9}",- "test_app",- "test_window",Arc::new(OcrEngine::Tesseract),- true,).await.unwrap();diff --git a/screenpipe-vision/tests/custom_ocr_test.rs b/screenpipe-vision/tests/custom_ocr_test.rsindex 701e5c9eb..1346c7cca 100644--- a/screenpipe-vision/tests/custom_ocr_test.rs+++ b/screenpipe-vision/tests/custom_ocr_test.rs@@ -69,6 +69,7 @@ mod tests {use std::path::PathBuf;#[tokio::test]+ #[ignore]async fn test_custom_ocr() {println!("Starting custom OCR test...");@@ -117,6 +118,7 @@ mod tests {}#[tokio::test]+ #[ignore]async fn test_custom_ocr_chinese() {println!("Starting custom OCR Chinese test...");