Skip to content

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

stuff

Louis Beaumont165b830980dd
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index e7e144e98..a578af11f 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -105,6 +105,7 @@ tempfile = "3.3.0"
criterion = { workspace = true }
rand = "0.8"
+axum-test = "15.3.0"
[[bench]]
name = "db_benchmarks"
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index 886ccae57..6eb39251d 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -1,24 +1,23 @@
+use crate::chunking::{text_chunking_by_similarity, text_chunking_simple};
+use crate::filtering::filter_texts;
+use async_trait::async_trait;
use chrono::{DateTime, Utc};
use log::{debug, error, info, warn};
+use screenpipe_integrations::friend_wearable::FriendWearableDatabase;
+use screenpipe_integrations::unstructured_ocr::unstructured_chunking;
+use screenpipe_vision::OcrEngine;
use serde::{Deserialize, Serialize};
use sqlx::migrate::MigrateDatabase;
+use sqlx::Error as SqlxError;
use sqlx::{
sqlite::{SqlitePool, SqlitePoolOptions},
FromRow,
};
-use std::time::Duration;
-use tokio::time::{timeout, Duration as TokioDuration};
-use crate::chunking::{text_chunking_by_similarity, text_chunking_simple};
-use screenpipe_vision::OcrEngine;
-use std::sync::Arc;
-use screenpipe_integrations::friend_wearable::FriendWearableDatabase;
-use async_trait::async_trait;
use std::error::Error as StdError;
use std::fmt;
-use screenpipe_integrations::unstructured_ocr::unstructured_chunking;
-use crate::filtering::filter_texts;
-use sqlx::sqlite::SqliteRow;
-use sqlx::Row;
+use std::sync::Arc;
+use std::time::Duration;
+use tokio::time::{timeout, Duration as TokioDuration};
#[derive(Debug)]
pub struct DatabaseError(String);
@@ -31,8 +30,21 @@ impl fmt::Display for DatabaseError {
impl StdError for DatabaseError {}
+// Intermediate struct for fetching FTS data
+#[derive(FromRow)]
+struct FTSSearchResultRaw {
+ text_id: i64,
+ matched_text: String,
+ frame_id: i64,
+ frame_timestamp: DateTime<Utc>,
+ app_name: String,
+ window_name: String,
+ video_file_path: String,
+ original_frame_text: Option<String>,
+ tags: Option<String>,
+}
// Define the FTSSearchResult struct
-#[derive(Debug, Serialize)]
+#[derive(Debug, Serialize, Deserialize)]
pub struct FTSSearchResult {
pub text_id: i64,
pub matched_text: String,
@@ -42,16 +54,32 @@ pub struct FTSSearchResult {
pub window_name: String,
pub video_file_path: String,
pub original_frame_text: Option<String>,
+ pub tags: Vec<String>,
}
-#[derive(Debug, Serialize)]
+#[derive(Debug, Serialize, Deserialize)]
pub enum SearchResult {
OCR(OCRResult),
Audio(AudioResult),
FTS(FTSSearchResult),
}
-#[derive(Debug, Serialize, FromRow)]
+// Intermediate struct for fetching data
+#[derive(FromRow)]
+struct OCRResultRaw {
+ frame_id: i64,
+ ocr_text: String,
+ text_json: String,
+ timestamp: DateTime<Utc>,
+ file_path: String,
+ offset_index: i64,
+ app_name: String,
+ ocr_engine: String,
+ window_name: String,
+ tags: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
pub struct OCRResult {
pub frame_id: i64,
pub ocr_text: String,
@@ -62,6 +90,7 @@ pub struct OCRResult {
pub app_name: String,
pub ocr_engine: String,
pub window_name: String,
+ pub tags: Vec<String>,
}
#[derive(Debug, Deserialize, PartialEq, Default, Clone, Copy)]
@@ -69,11 +98,22 @@ pub struct OCRResult {
pub enum ContentType {
#[default]
All,
- OCR,
+ OCR, // TODO replace by vision and make this deprecated
Audio,
}
-#[derive(Debug, Serialize, FromRow)]
+#[derive(FromRow)]
+struct AudioResultRaw {
+ audio_chunk_id: i64,
+ transcription: String,
+ timestamp: DateTime<Utc>,
+ file_path: String,
+ offset_index: i64,
+ transcription_engine: String,
+ tags: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
pub struct AudioResult {
pub audio_chunk_id: i64,
pub transcription: String,
@@ -81,6 +121,14 @@ pub struct AudioResult {
pub file_path: String,
pub offset_index: i64,
pub transcription_engine: String,
+ pub tags: Vec<String>,
+}
+
+#[derive(Debug, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum TagContentType {
+ Vision,
+ Audio,
}
pub struct DatabaseManager {
@@ -171,22 +219,30 @@ impl DatabaseManager {
let chunks = match CHUNKING_ENGINE {
"local_simple" => text_chunking_simple(transcription),
"candle_jina_bert" => text_chunking_by_similarity(transcription).await,
- "unstructured" => unstructured_chunking(transcription).map_err(|e| anyhow::anyhow!(e)).and_then(|chunks| Ok(chunks)),
+ "unstructured" => unstructured_chunking(transcription)
+ .map_err(|e| anyhow::anyhow!(e))
+ .and_then(|chunks| Ok(chunks)),
_ => text_chunking_simple(transcription), // Default to simple chunking for unknown engines
};
match chunks {
Ok(chunks) => {
- info!("Successfully chunked audio transcription into {} chunks", chunks.len());
+ info!(
+ "Successfully chunked audio transcription into {} chunks",
+ chunks.len()
+ );
for chunk in chunks.iter() {
- if let Err(e) = self.insert_chunked_text(
- audio_chunk_id,
- chunk,
- Utc::now(),
- transcription_engine,
- CHUNKING_ENGINE,
- ContentSource::Audio,
- ).await {
+ if let Err(e) = self
+ .insert_chunked_text(
+ audio_chunk_id,
+ chunk,
+ Utc::now(),
+ transcription_engine,
+ CHUNKING_ENGINE,
+ ContentSource::Audio,
+ )
+ .await
+ {
error!("Failed to insert chunk into chunked text index: {}", e);
}
}
@@ -194,15 +250,21 @@ impl DatabaseManager {
Err(e) => {
error!("Failed to chunk audio transcription: {}", e);
// Fallback to inserting the whole transcription as a single chunk
- if let Err(e) = self.insert_chunked_text(
- audio_chunk_id,
- transcription,
- Utc::now(),
- transcription_engine,
- "No_Chunking",
- ContentSource::Audio,
- ).await {
- error!("Failed to insert whole audio transcription into chunked text index: {}", e);
+ if let Err(e) = self
+ .insert_chunked_text(
+ audio_chunk_id,
+ transcription,
+ Utc::now(),
+ transcription_engine,
+ "No_Chunking",
+ ContentSource::Audio,
+ )
+ .await
+ {
+ error!(
+ "Failed to insert whole audio transcription into chunked text index: {}",
+ e
+ );
}
}
}
@@ -305,7 +367,9 @@ impl DatabaseManager {
let chunks = match CHUNKING_ENGINE {
"local_simple" => text_chunking_simple(text),
"candle_jina_bert" => text_chunking_by_similarity(text).await,
- "unstructured" => unstructured_chunking(text).map_err(|e| anyhow::anyhow!(e)).and_then(|chunks| Ok(chunks)),
+ "unstructured" => unstructured_chunking(text)
+ .map_err(|e| anyhow::anyhow!(e))
+ .and_then(|chunks| Ok(chunks)),
_ => text_chunking_simple(text), // Default to simple chunking for unknown engines
};
@@ -313,14 +377,17 @@ impl DatabaseManager {
Ok(chunks) => {
debug!("Successfully chunked text into {} chunks", chunks.len());
for chunk in chunks.iter() {
- if let Err(e) = self.insert_chunked_text(
- frame_id,
- chunk,
- Utc::now(),
- &format!("{:?}", *ocr_engine),
- CHUNKING_ENGINE,
- ContentSource::Screen,
- ).await {
+ if let Err(e) = self
+ .insert_chunked_text(
+ frame_id,
+ chunk,
+ Utc::now(),
+ &format!("{:?}", *ocr_engine),
+ CHUNKING_ENGINE,
+ ContentSource::Screen,
+ )
+ .await
+ {
error!("Failed to insert chunk into chunked text index: {}", e);
}
}
@@ -329,15 +396,21 @@ impl DatabaseManager {
error!("Failed to chunk text: {}", e);
// Fallback to inserting the whole text if chunking fails
debug!("Inserting whole text as a single chunk");
- if let Err(e) = self.insert_chunked_text(
- frame_id,
- text,
- Utc::now(),
- &format!("{:?}", *ocr_engine),
- "No_Chunking",
- ContentSource::Screen,
- ).await {
- error!("Failed to insert whole text into chunked text index: {}", e);
+ if let Err(e) = self
+ .insert_chunked_text(
+ frame_id,
+ text,
+ Utc::now(),
+ &format!("{:?}", *ocr_engine),
+ "No_Chunking",
+ ContentSource::Screen,
+ )
+ .await
+ {
+ error!(
+ "Failed to insert whole text into chunked text index: {}",
+ e
+ );
}
}
}
@@ -374,7 +447,10 @@ impl DatabaseManager {
}
}
- error!("Exiting insert_ocr_text for frame_id: {} with PoolTimedOut error", frame_id);
+ error!(
+ "Exiting insert_ocr_text for frame_id: {} with PoolTimedOut error",
+ frame_id
+ );
Err(sqlx::Error::PoolTimedOut)
}
@@ -430,25 +506,32 @@ impl DatabaseManager {
start_time: Option<DateTime<Utc>>,
end_time: Option<DateTime<Utc>>,
app_name: Option<&str>,
- window_name: Option<&str>, // Add window_name parameter
+ window_name: Option<&str>,
) -> Result<Vec<SearchResult>, sqlx::Error> {
let mut results = Vec::new();
-
+
// If app_name is specified, only search OCR content
if app_name.is_some() || window_name.is_some() {
let ocr_results = self
- .search_ocr(query, limit, offset, start_time, end_time, app_name, window_name) // Add window_name parameter
+ .search_ocr(
+ query,
+ limit,
+ offset,
+ start_time,
+ end_time,
+ app_name,
+ window_name,
+ ) // Add window_name parameter
.await?;
results.extend(ocr_results.into_iter().map(SearchResult::OCR));
} else {
- // If no app_name or window_name is specified, proceed with normal search
if content_type == ContentType::All || content_type == ContentType::OCR {
let ocr_results = self
- .search_ocr(query, limit, offset, start_time, end_time, None, None) // Add window_name parameter
+ .search_ocr(query, limit, offset, start_time, end_time, None, None)
.await?;
results.extend(ocr_results.into_iter().map(SearchResult::OCR));
}
-
+
if content_type == ContentType::All || content_type == ContentType::Audio {
let audio_results = self
.search_audio(query, limit, offset, start_time, end_time)
@@ -456,7 +539,7 @@ impl DatabaseManager {
results.extend(audio_results.into_iter().map(SearchResult::Audio));
}
}
-
+
// Sort results by timestamp in descending order
results.sort_by(|a, b| {
let timestamp_a = match a {
@@ -471,18 +554,20 @@ impl DatabaseManager {
};
timestamp_b.cmp(&timestamp_a)
});
-
+
+ // !HACK THIS SHOULDNT BE NEEDED AND BE DONE AT QUERY LEVEL
+
// Apply limit after combining and sorting
results.truncate(limit as usize);
-
+
Ok(results)
}
- pub async fn search_fts(
+ async fn search_fts(
&self,
query: &str,
limit: u32,
- ) -> Result<Vec<SearchResult>, sqlx::Error> {
+ ) -> Result<Vec<FTSSearchResult>, sqlx::Error> {
let sql = r#"
SELECT
fts.text_id,
@@ -490,39 +575,48 @@ impl DatabaseManager {
f.id AS frame_id,
f.timestamp AS frame_timestamp,
cte.app_name,
- cte.window_name, // Ensure this field is selected
+ cte.window_name,
vc.file_path AS video_file_path,
- o.text AS original_frame_text
- FROM chunked_text_index_fts fts
+ o.text AS original_frame_text,
+ GROUP_CONCAT(tags.name, ',') as tags
+ FROM
+ chunked_text_index_fts fts
JOIN chunked_text_entries cte ON fts.text_id = cte.text_id
JOIN frames f ON cte.frame_id = f.id
JOIN video_chunks vc ON f.video_chunk_id = vc.id
LEFT JOIN ocr_text o ON f.id = o.frame_id
+ LEFT JOIN vision_tags vt ON f.id = vt.vision_id
+ LEFT JOIN tags ON vt.tag_id = tags.id
WHERE fts.text MATCH ?1 COLLATE NOCASE
ORDER BY fts.rank
LIMIT ?2
"#;
- let results = sqlx::query(sql)
+ let fts_results_raw = sqlx::query_as::<_, FTSSearchResultRaw>(sql)
.bind(query)
.bind(limit)
- .map(|row: SqliteRow| {
- let result = SearchResult::FTS(FTSSearchResult {
- text_id: row.get("text_id"),
- matched_text: row.get("matched_text"),
- frame_id: row.get("frame_id"),
- frame_timestamp: row.get("frame_timestamp"),
- app_name: row.get("app_name"),
- window_name: row.get("window_name"), // Add this line
- video_file_path: row.get("video_file_path"),
- original_frame_text: row.get("original_frame_text"),
- });
- result
- })
.fetch_all(&self.pool)
.await?;
- Ok(results)
+ let fts_results = fts_results_raw
+ .into_iter()
+ .map(|raw| FTSSearchResult {
+ text_id: raw.text_id,
+ matched_text: raw.matched_text,
+ frame_id: raw.frame_id,
+ frame_timestamp: raw.frame_timestamp,
+ app_name: raw.app_name,
+ window_name: raw.window_name,
+ video_file_path: raw.video_file_path,
+ original_frame_text: raw.original_frame_text,
+ tags: raw
+ .tags
+ .map(|s| s.split(',').map(String::from).collect())
+ .unwrap_or_default(),
+ })
+ .collect();
+
+ Ok(fts_results)
}
async fn search_ocr(
@@ -545,28 +639,34 @@ impl DatabaseManager {
frames.offset_index,
ocr_text.app_name,
ocr_text.ocr_engine,
- ocr_text.window_name
+ ocr_text.window_name,
+ GROUP_CONCAT(tags.name, ',') as tags
FROM
ocr_text
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
WHERE
ocr_text.text LIKE '%' || ?1 || '%' COLLATE NOCASE
AND ocr_text.text != 'No text found'
AND (?2 IS NULL OR frames.timestamp >= ?2)
AND (?3 IS NULL OR frames.timestamp <= ?3)
- "#.to_string();
-
+ "#
+ .to_string();
+
if app_name.is_some() {
sql.push_str(" AND ocr_text.app_name = ?6 COLLATE NOCASE");
}
-
+
if window_name.is_some() {
sql.push_str(" AND ocr_text.window_name = ?7 COLLATE NOCASE");
}
-
+
sql.push_str(
r#"
ORDER BY
@@ -574,24 +674,45 @@ impl DatabaseManager {
LIMIT ?4 OFFSET ?5
"#,
);
-
- let mut query = sqlx::query_as::<_, OCRResult>(&sql)
+
+ println!("{}", sql);
+ let mut query = sqlx::query_as::<_, OCRResultRaw>(&sql)
.bind(query)
.bind(start_time)
.bind(end_time)
.bind(limit)
.bind(offset);
-
+ println!("{:?}", start_time);
if let Some(app_name) = app_name {
query = query.bind(app_name);
}
-
+
if let Some(window_name) = window_name {
query = query.bind(window_name);
}
-
- let ocr_results = query.fetch_all(&self.pool).await?;
- debug!("Fetched OCR results: {:?}", ocr_results);
+
+ let ocr_results_raw = query.fetch_all(&self.pool).await?;
+
+ // Convert OCRResultRaw to OCRResult
+ let ocr_results = ocr_results_raw
+ .into_iter()
+ .map(|raw| OCRResult {
+ frame_id: raw.frame_id,
+ ocr_text: raw.ocr_text,
+ text_json: raw.text_json,
+ timestamp: raw.timestamp,
+ file_path: raw.file_path,
+ offset_index: raw.offset_index,
+ app_name: raw.app_name,
+ ocr_engine: raw.ocr_engine,
+ window_name: raw.window_name,
+ tags: raw
+ .tags
+ .map(|s| s.split(',').map(String::from).collect())
+ .unwrap_or_default(),
+ })
+ .collect();
+
Ok(ocr_results)
}
@@ -603,35 +724,61 @@ impl DatabaseManager {
start_time: Option<DateTime<Utc>>,
end_time: Option<DateTime<Utc>>,
) -> Result<Vec<AudioResult>, sqlx::Error> {
- sqlx::query_as::<_, AudioResult>(
- r#"
+ let sql = r#"
SELECT
audio_transcriptions.audio_chunk_id,
audio_transcriptions.transcription,
audio_transcriptions.timestamp,
audio_chunks.file_path,
audio_transcriptions.offset_index,
- audio_transcriptions.transcription_engine
+ audio_transcriptions.transcription_engine,
+ GROUP_CONCAT(tags.name, ',') as tags
FROM
audio_transcriptions
JOIN
audio_chunks ON audio_transcriptions.audio_chunk_id = audio_chunks.id
+ LEFT JOIN
+ audio_tags ON audio_chunks.id = audio_tags.audio_chunk_id
+ LEFT JOIN
+ tags ON audio_tags.tag_id = tags.id
WHERE
audio_transcriptions.transcription LIKE '%' || ?1 || '%' COLLATE NOCASE
AND (?2 IS NULL OR audio_transcriptions.timestamp >= ?2)
AND (?3 IS NULL OR audio_transcriptions.timestamp <= ?3)
+ GROUP BY
+ audio_transcriptions.audio_chunk_id
ORDER BY
audio_transcriptions.timestamp DESC
LIMIT ?4 OFFSET ?5
- "#,
- )
- .bind(query)
- .bind(start_time)
- .bind(end_time)
- .bind(limit)
- .bind(offset)
- .fetch_all(&self.pool)
- .await
+ "#;
+
+ let audio_results_raw = sqlx::query_as::<_, AudioResultRaw>(sql)
+ .bind(query)
+ .bind(start_time)
+ .bind(end_time)
+ .bind(limit)
+ .bind(offset)
+ .fetch_all(&self.pool)
+ .await?;
+
+ // Parse the tags string into a Vec<String>
+ let audio_results = audio_results_raw
+ .into_iter()
+ .map(|raw| 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(String::from).collect())
+ .unwrap_or_default(),
+ })
+ .collect();
+
+ Ok(audio_results)
}
pub async fn get_frame(&self, frame_id: i64) -> Result<Option<(String, i64)>, sqlx::Error> {
@@ -663,7 +810,7 @@ impl DatabaseManager {
window_name: Option<&str>, // Add window_name parameter
) -> Result<usize, sqlx::Error> {
let mut total_count = 0;
-
+
// If app_name is specified, only count OCR results
if app_name.is_some() || window_name.is_some() {
let ocr_count = self
@@ -678,7 +825,7 @@ impl DatabaseManager {
.await?;
total_count += ocr_count;
}
-
+
if content_type == ContentType::All || content_type == ContentType::Audio {
let audio_count = self
.count_audio_results(query, start_time, end_time)
@@ -686,7 +833,7 @@ impl DatabaseManager {
total_count += audio_count;
}
}
-
+
Ok(total_count)
}
pub async fn count_recent_results(
@@ -746,7 +893,8 @@ impl DatabaseManager {
WHERE text LIKE '%' || ?1 || '%' COLLATE NOCASE
AND (?2 IS NULL OR frames.timestamp >= ?2)
AND (?3 IS NULL OR frames.timestamp <= ?3)
- "#.to_string();
+ "#
+ .to_string();
if app_name.is_some() {
sql.push_str(" AND ocr_text.app_name = ?6 COLLATE NOCASE");
@@ -883,17 +1031,38 @@ impl DatabaseManager {
Ok(results)
}
- pub async fn get_chunked_data_since_last_request(&self, memory_source: &str, friend_user_id: &str) -> Result<(Vec<String>, i64, i64, DateTime<Utc>, DateTime<Utc>), DatabaseError> {
- let last_request_info = self.get_last_successful_request_info(memory_source, friend_user_id).await?;
+ pub async fn get_chunked_data_since_last_request(
+ &self,
+ memory_source: &str,
+ friend_user_id: &str,
+ ) -> Result<(Vec<String>, i64, i64, DateTime<Utc>, DateTime<Utc>), DatabaseError> {
+ let last_request_info = self
+ .get_last_successful_request_info(memory_source, friend_user_id)
+ .await?;
let (last_chunk_id, last_timestamp) = last_request_info
.map(|(chunk_range, time_range, _)| {
- let last_chunk_id = chunk_range.split('-').last().unwrap_or("0").parse::<i64>().unwrap_or(0);
- let last_timestamp = DateTime::parse_from_rfc3339(time_range.split('-').last().unwrap_or("1970-01-01T00:00:00Z"))
- .unwrap_or_else(|_| DateTime::parse_from_rfc3339("1970-01-01T00:00:00Z").unwrap())
- .with_timezone(&Utc);
+ let last_chunk_id = chunk_range
+ .split('-')
+ .last()
+ .unwrap_or("0")
+ .parse::<i64>()
+ .unwrap_or(0);
+ let last_timestamp = DateTime::parse_from_rfc3339(
+ time_range
+ .split('-')
+ .last()
+ .unwrap_or("1970-01-01T00:00:00Z"),
+ )
+ .unwrap_or_else(|_| DateTime::parse_from_rfc3339("1970-01-01T00:00:00Z").unwrap())
+ .with_timezone(&Utc);
(last_chunk_id, last_timestamp)
})
- .unwrap_or((0, DateTime::parse_from_rfc3339("1970-01-01T00:00:00Z").unwrap().with_timezone(&Utc)));
+ .unwrap_or((
+ 0,
+ DateTime::parse_from_rfc3339("1970-01-01T00:00:00Z")
+ .unwrap()
+ .with_timezone(&Utc),
+ ));
let query = r#"
SELECT
@@ -906,7 +1075,7 @@ impl DatabaseManager {
JOIN chunked_text_entries cte ON cti.text_id = cte.text_id
WHERE cte.source = ?1 AND (cte.timestamp > ?2 OR (cte.timestamp = ?2 AND COALESCE(cte.frame_id, cte.audio_chunk_id) > ?3))
"#;
-
+
sqlx::query_as(query)
.bind(memory_source)
.bind(&last_timestamp.to_rfc3339())
@@ -918,14 +1087,22 @@ impl DatabaseManager {
row.0.split(' ').map(String::from).collect(),
row.1,
row.2,
- DateTime::parse_from_rfc3339(&row.3).unwrap().with_timezone(&Utc),
- DateTime::parse_from_rfc3339(&row.4).unwrap().with_timezone(&Utc),
+ DateTime::parse_from_rfc3339(&row.3)
+ .unwrap()
+ .with_timezone(&Utc),
+ DateTime::parse_from_rfc3339(&row.4)
+ .unwrap()
+ .with_timezone(&Utc),
)
})
.map_err(|e| DatabaseError(e.to_string()))
}
- pub async fn get_last_successful_request_info(&self, memory_source: &str, friend_user_id: &str) -> Result<Option<(String, String, String)>, DatabaseError> {
+ pub async fn get_last_successful_request_info(
+ &self,
+ memory_source: &str,
+ friend_user_id: &str,
+ ) -> Result<Option<(String, String, String)>, DatabaseError> {
let query = r#"
SELECT chunk_id_range, timestamp_range, request_id
FROM friend_wearable_requests
@@ -960,9 +1137,9 @@ impl DatabaseManager {
)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
"#;
-
+
let is_successful = !structured_response.contains("\"error\"");
-
+
sqlx::query(query)
.bind(request_id)
.bind(memory_source)
@@ -979,6 +1156,171 @@ impl DatabaseManager {
.map(|_| ())
.map_err(|e| DatabaseError(e.to_string()))
}
+
+ pub async fn add_tags(
+ &self,
+ id: i64,
+ content_type: TagContentType,
+ tags: Vec<String>,
+ ) -> Result<(), SqlxError> {
+ match content_type {
+ TagContentType::Vision => self.add_tags_to_vision(id, tags).await,
+ TagContentType::Audio => self.add_tags_to_audio(id, tags).await,
+ }
+ }
+
+ async fn add_tags_to_vision(&self, frame_id: i64, tags: Vec<String>) -> Result<(), SqlxError> {
+ let mut tx = self.pool.begin().await?;
+
+ for tag in tags {
+ // Insert tag if it doesn't exist
+ let tag_id: i64 = sqlx::query_scalar(
+ "INSERT INTO tags (name) VALUES (?) ON CONFLICT(name) DO UPDATE SET name=name RETURNING id",
+ )
+ .bind(&tag)
+ .fetch_one(&mut *tx)
+ .await?;
+
+ // Insert into vision_tags
+ sqlx::query(
+ "INSERT INTO vision_tags (vision_id, tag_id) VALUES (?, ?) ON CONFLICT DO NOTHING",
+ )
+ .bind(frame_id)
+ .bind(tag_id)
+ .execute(&mut *tx)
+ .await?;
+ }
+
+ tx.commit().await?;
+ Ok(())
+ }
+
+ async fn add_tags_to_audio(
+ &self,
+ audio_chunk_id: i64,
+ tags: Vec<String>,
+ ) -> Result<(), SqlxError> {
+ let mut tx = self.pool.begin().await?;
+
+ for tag in tags {
+ // Insert tag if it doesn't exist
+ let tag_id: i64 = sqlx::query_scalar(
+ "INSERT INTO tags (name) VALUES (?) ON CONFLICT(name) DO UPDATE SET name=name RETURNING id",
+ )
+ .bind(&tag)
+ .fetch_one(&mut *tx)
+ .await?;
+
+ // Insert into audio_tags
+ sqlx::query(
+ "INSERT INTO audio_tags (audio_chunk_id, tag_id) VALUES (?, ?) ON CONFLICT DO NOTHING",
+ )
+ .bind(audio_chunk_id)
+ .bind(tag_id)
+ .execute(&mut *tx)
+ .await?;
+ }
+
+ tx.commit().await?;
+ Ok(())
+ }
+
+ pub async fn get_tags(
+ &self,
+ id: i64,
+ content_type: TagContentType,
+ ) -> Result<Vec<String>, SqlxError> {
+ match content_type {
+ TagContentType::Vision => self.get_vision_tags(id).await,
+ TagContentType::Audio => self.get_audio_tags(id).await,
+ }
+ }
+
+ async fn get_vision_tags(&self, vision_id: i64) -> Result<Vec<String>, SqlxError> {
+ sqlx::query_scalar(
+ r#"
+ SELECT t.name
+ FROM tags t
+ JOIN vision_tags vt ON t.id = vt.tag_id
+ WHERE vt.vision_id = ?
+ ORDER BY t.name
+ "#,
+ )
+ .bind(vision_id)
+ .fetch_all(&self.pool)
+ .await
+ }
+
+ async fn get_audio_tags(&self, audio_chunk_id: i64) -> Result<Vec<String>, SqlxError> {
+ sqlx::query_scalar(
+ r#"
+ SELECT t.name
+ FROM tags t
+ JOIN audio_tags at ON t.id = at.tag_id
+ WHERE at.audio_chunk_id = ?
+ ORDER BY t.name
+ "#,
+ )
+ .bind(audio_chunk_id)
+ .fetch_all(&self.pool)
+ .await
+ }
+
+ pub async fn remove_tags(
+ &self,
+ id: i64,
+ content_type: TagContentType,
+ tags: Vec<String>,
+ ) -> Result<(), SqlxError> {
+ match content_type {
+ TagContentType::Vision => self.remove_vision_tags(id, tags).await,
+ TagContentType::Audio => self.remove_audio_tags(id, tags).await,
+ }
+ }
+
+ async fn remove_vision_tags(&self, vision_id: i64, tags: Vec<String>) -> Result<(), SqlxError> {
+ let mut tx = self.pool.begin().await?;
+
+ for tag in tags {
+ sqlx::query(
+ r#"
+ DELETE FROM vision_tags
+ WHERE vision_id = ? AND tag_id = (SELECT id FROM tags WHERE name = ?)
+ "#,
+ )
+ .bind(vision_id)
+ .bind(&tag)
+ .execute(&mut *tx)
+ .await?;
+ }
+
+ tx.commit().await?;
+ Ok(())
+ }
+
+ async fn remove_audio_tags(
+ &self,
+ audio_chunk_id: i64,
+ tags: Vec<String>,
+ ) -> Result<(), SqlxError> {
+ let mut tx = self.pool.begin().await?;
+
+ for tag in tags {
+ sqlx::query(
+ r#"
+ DELETE FROM audio_tags
+ WHERE audio_chunk_id = ? AND tag_id = (SELECT id FROM tags WHERE name = ?)
+ "#,
+ )
+ .bind(audio_chunk_id)
+ .bind(&tag)
+ .execute(&mut *tx)
+ .await?;
+ }
+
+ tx.commit().await?;
+ Ok(())
+ }
}
impl Clone for DatabaseManager {
@@ -1006,13 +1348,28 @@ impl ToString for ContentSource {
#[async_trait]
impl FriendWearableDatabase for DatabaseManager {
- async fn get_chunked_data_since_last_request(&self, memory_source: &str, friend_user_id: &str) -> Result<(Vec<String>, i64, i64, DateTime<Utc>, DateTime<Utc>), Box<dyn StdError + Send + Sync>> {
+ async fn get_chunked_data_since_last_request(
+ &self,
+ memory_source: &str,
+ friend_user_id: &str,
+ ) -> Result<
+ (Vec<String>, i64, i64, DateTime<Utc>, DateTime<Utc>),
+ Box<dyn StdError + Send + Sync>,
+ > {
self.get_chunked_data_since_last_request(memory_source, friend_user_id)
.await
.map_err(|e| Box::new(e) as Box<dyn StdError + Send + Sync>)
}
- async fn get_chunked_data_since_timestamp(&self, memory_source: &str, _friend_user_id: &str, since: DateTime<Utc>) -> Result<(Vec<String>, i64, i64, DateTime<Utc>, DateTime<Utc>), Box<dyn StdError + Send + Sync>> {
+ async fn get_chunked_data_since_timestamp(
+ &self,
+ memory_source: &str,
+ _friend_user_id: &str,
+ since: DateTime<Utc>,
+ ) -> Result<
+ (Vec<String>, i64, i64, DateTime<Utc>, DateTime<Utc>),
+ Box<dyn StdError + Send + Sync>,
+ > {
let since_str = since.to_rfc3339();
let filtered_text = filter_texts(&since_str, memory_source, &self.pool).await?;
@@ -1023,7 +1380,13 @@ impl FriendWearableDatabase for DatabaseManager {
let min_timestamp = since;
let max_timestamp = Utc::now();
- Ok((texts, min_chunk_id, max_chunk_id, min_timestamp, max_timestamp))
+ Ok((
+ texts,
+ min_chunk_id,
+ max_chunk_id,
+ min_timestamp,
+ max_timestamp,
+ ))
}
async fn insert_friend_wearable_request(
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index f78f582fc..d48abfc31 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -10,11 +10,14 @@ mod server;
mod video;
pub use cli::Cli;
pub use core::{start_continuous_recording, RecorderControl};
-pub use db::{ContentType, DatabaseManager, SearchResult};
+pub use db::{ContentSource, ContentType, DatabaseManager, SearchResult};
pub use logs::MultiWriter;
pub use resource_monitor::{ResourceMonitor, RestartSignal};
+pub use server::create_router;
pub use server::health_check;
pub use server::AppState;
pub use server::HealthCheckResponse;
+pub use server::PaginatedResponse;
+pub use server::ContentItem;
pub use server::Server;
pub use video::VideoCapture;
diff --git a/screenpipe-server/src/migrations/20240821074222_create_tags.sql b/screenpipe-server/src/migrations/20240821074222_create_tags.sql
new file mode 100644
index 000000000..d1fea6eae
--- /dev/null
+++ b/screenpipe-server/src/migrations/20240821074222_create_tags.sql
@@ -0,0 +1,29 @@
+-- Create tags table
+CREATE TABLE tags (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL UNIQUE
+);
+
+-- Create junction table for vision (frames) and tags
+CREATE TABLE vision_tags (
+ vision_id INTEGER NOT NULL,
+ tag_id INTEGER NOT NULL,
+ PRIMARY KEY (vision_id, tag_id),
+ FOREIGN KEY (vision_id) REFERENCES frames(id) ON DELETE CASCADE,
+ FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
+);
+
+-- Create junction table for audio and tags
+CREATE TABLE audio_tags (
+ audio_chunk_id INTEGER NOT NULL,
+ tag_id INTEGER NOT NULL,
+ PRIMARY KEY (audio_chunk_id, tag_id),
+ FOREIGN KEY (audio_chunk_id) REFERENCES audio_chunks(id) ON DELETE CASCADE,
+ FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
+);
+
+-- Create indexes for faster querying
+CREATE INDEX idx_vision_tags_vision_id ON vision_tags(vision_id);
+CREATE INDEX idx_vision_tags_tag_id ON vision_tags(tag_id);
+CREATE INDEX idx_audio_tags_audio_chunk_id ON audio_tags(audio_chunk_id);
+CREATE INDEX idx_audio_tags_tag_id ON audio_tags(tag_id);
\ No newline at end of file
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 2e291775b..dd061c4d3 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1,5 +1,5 @@
use axum::{
- extract::{Query, State},
+ extract::{Path, Query, State},
http::StatusCode,
response::Json as JsonResponse,
routing::{get, post},
@@ -8,7 +8,7 @@ use axum::{
use crossbeam::queue::SegQueue;
use screenpipe_vision::monitor::list_monitors;
-use crate::{ContentType, DatabaseManager, SearchResult};
+use crate::{db::TagContentType, ContentType, DatabaseManager, SearchResult};
use chrono::{DateTime, Utc};
use log::{debug, error, info};
use screenpipe_audio::{
@@ -73,57 +73,60 @@ where
}
// Response structs
-#[derive(Serialize)]
-pub(crate) struct PaginatedResponse<T> {
- data: Vec<T>,
- pagination: PaginationInfo,
+#[derive(Serialize, Deserialize)]
+pub struct PaginatedResponse<T> {
+ pub data: Vec<T>,
+ pub pagination: PaginationInfo,
}
-#[derive(Serialize)]
-struct PaginationInfo {
- limit: u32,
- offset: u32,
- total: i64,
+#[derive(Serialize, Deserialize)]
+pub struct PaginationInfo {
+ pub limit: u32,
+ pub offset: u32,
+ pub total: i64,
}
-#[derive(Serialize)]
+#[derive(Serialize, Deserialize)]
#[serde(tag = "type", content = "content")]
-pub(crate) enum ContentItem {
+pub enum ContentItem {
OCR(OCRContent),
Audio(AudioContent),
FTS(FTSContent),
}
-#[derive(Serialize)]
-pub(crate) struct OCRContent {
- frame_id: i64,
- text: String,
- timestamp: DateTime<Utc>,
- file_path: String,
- offset_index: i64,
- app_name: String,
- window_name: String,
+#[derive(Serialize, Deserialize)]
+pub struct OCRContent {
+ pub frame_id: i64,
+ pub text: String,
+ pub timestamp: DateTime<Utc>,
+ pub file_path: String,
+ pub offset_index: i64,
+ pub app_name: String,
+ pub window_name: String,
+ pub tags: Vec<String>,
}
-#[derive(Serialize)]
-pub(crate) struct AudioContent {
- chunk_id: i64,
- transcription: String,
- timestamp: DateTime<Utc>,
- file_path: String,
- offset_index: i64,
+#[derive(Serialize, Deserialize)]
+pub struct AudioContent {
+ pub chunk_id: i64,
+ pub transcription: String,
+ pub timestamp: DateTime<Utc>,
+ pub file_path: String,
+ pub offset_index: i64,
+ pub tags: Vec<String>,
}
-#[derive(Serialize)]
-pub(crate) struct FTSContent {
- text_id: i64,
- matched_text: String,
- frame_id: i64,
- timestamp: DateTime<Utc>,
- app_name: String,
- window_name: String, // Add this field
- file_path: String,
- original_frame_text: Option<String>,
+#[derive(Serialize, Deserialize)]
+pub struct FTSContent {
+ pub text_id: i64,
+ pub matched_text: String,
+ pub frame_id: i64,
+ pub timestamp: DateTime<Utc>,
+ pub app_name: String,
+ pub window_name: String, // Add this field
+ pub file_path: String,
+ pub original_frame_text: Option<String>,
+ pub tags: Vec<String>,
}
#[derive(Serialize)]
@@ -141,6 +144,26 @@ pub struct MonitorInfo {
is_default: bool,
}
+#[derive(Deserialize)]
+pub struct AddTagsRequest {
+ tags: Vec<String>,
+}
+
+#[derive(Serialize)]
+pub struct AddTagsResponse {
+ success: bool,
+}
+
+#[derive(Deserialize)]
+pub struct RemoveTagsRequest {
+ tags: Vec<String>,
+}
+
+#[derive(Serialize)]
+pub struct RemoveTagsResponse {
+ success: bool,
+}
+
// Helper functions
fn default_limit() -> u32 {
20
@@ -179,13 +202,13 @@ pub(crate) async fn search(
let query_str = query.q.as_deref().unwrap_or("");
// If app_name is specified, force content_type to OCR
- let content_type = if query.app_name.is_some() {
+ let content_type = if query.app_name.is_some() || query.window_name.is_some() {
ContentType::OCR
} else {
query.content_type
};
- let results = state
+ let results = match state
.db
.search(
query_str,
@@ -195,16 +218,19 @@ pub(crate) async fn search(
query.start_time,
query.end_time,
query.app_name.as_deref(),
- query.window_name.as_deref(), // Add window_name parameter
+ query.window_name.as_deref(),
)
.await
- .map_err(|e| {
+ {
+ Ok(results) => results,
+ Err(e) => {
error!("Failed to search for content: {}", e);
- (
+ return Err((
StatusCode::INTERNAL_SERVER_ERROR,
JsonResponse(json!({"error": format!("Failed to search for content: {}", e)})),
- )
- })?;
+ ));
+ }
+ };
let total = state
.db
@@ -305,6 +331,46 @@ pub async fn api_list_monitors(
}
}
+pub(crate) async fn add_tags(
+ State(state): State<Arc<AppState>>,
+ Path((content_type, id)): Path<(String, i64)>,
+ JsonResponse(payload): JsonResponse<AddTagsRequest>,
+) -> Result<JsonResponse<AddTagsResponse>, (StatusCode, String)> {
+ let content_type = match content_type.as_str() {
+ "vision" => TagContentType::Vision,
+ "audio" => TagContentType::Audio,
+ _ => return Err((StatusCode::BAD_REQUEST, "Invalid content type".to_string())),
+ };
+
+ match state.db.add_tags(id, content_type, payload.tags).await {
+ Ok(_) => Ok(JsonResponse(AddTagsResponse { success: true })),
+ Err(e) => {
+ error!("Failed to add tags: {}", e);
+ Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
+ }
+ }
+}
+
+pub(crate) async fn remove_tags(
+ State(state): State<Arc<AppState>>,
+ Path((content_type, id)): Path<(String, i64)>,
+ JsonResponse(payload): JsonResponse<RemoveTagsRequest>,
+) -> Result<JsonResponse<RemoveTagsResponse>, (StatusCode, String)> {
+ let content_type = match content_type.as_str() {
+ "vision" => TagContentType::Vision,
+ "audio" => TagContentType::Audio,
+ _ => return Err((StatusCode::BAD_REQUEST, "Invalid content type".to_string())),
+ };
+
+ match state.db.remove_tags(id, content_type, payload.tags).await {
+ Ok(_) => Ok(JsonResponse(RemoveTagsResponse { success: true })),
+ Err(e) => {
+ error!("Failed to remove tag: {}", e);
+ Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
+ }
+ }
+}
+
pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<HealthCheckResponse> {
let (last_frame, last_audio) = match state.db.get_latest_timestamps().await {
Ok((frame, audio)) => (frame, audio),
@@ -398,7 +464,8 @@ fn into_content_item(result: SearchResult) -> ContentItem {
file_path: ocr.file_path,
offset_index: ocr.offset_index,
app_name: ocr.app_name,
- window_name: ocr.window_name, // Ensure this field is included
+ window_name: ocr.window_name,
+ tags: ocr.tags,
}),
SearchResult::Audio(audio) => ContentItem::Audio(AudioContent {
chunk_id: audio.audio_chunk_id,
@@ -406,6 +473,7 @@ fn into_content_item(result: SearchResult) -> ContentItem {
timestamp: audio.timestamp,
file_path: audio.file_path,
offset_index: audio.offset_index,
+ tags: audio.tags,
}),
SearchResult::FTS(fts) => ContentItem::FTS(FTSContent {
text_id: fts.text_id,
@@ -416,6 +484,7 @@ fn into_content_item(result: SearchResult) -> ContentItem {
window_name: fts.window_name, // Ensure this field is included
file_path: fts.video_file_path,
original_frame_text: fts.original_frame_text,
+ tags: fts.tags,
}),
}
}
@@ -460,11 +529,7 @@ impl Server {
});
// https://github.com/tokio-rs/console
- let app = Router::new()
- .route("/search", get(search))
- .route("/audio/list", get(api_list_audio_devices))
- .route("/vision/list", post(api_list_monitors))
- .route("/health", get(health_check))
+ let app = create_router()
.layer(ApiPluginLayer::new(api_plugin))
.layer(CorsLayer::permissive())
.layer(
@@ -489,6 +554,18 @@ impl Server {
}
}
+pub fn create_router() -> Router<Arc<AppState>> {
+ Router::new()
+ .route("/search", get(search))
+ .route("/audio/list", get(api_list_audio_devices))
+ .route("/vision/list", post(api_list_monitors))
+ .route(
+ "/tags/:content_type/:id",
+ post(add_tags).delete(remove_tags),
+ )
+ .route("/health", get(health_check))
+}
+
// Curl commands for reference:
// # 1. Basic search query
// # curl "http://localhost:3030/search?q=test&limit=5&offset=0"
diff --git a/screenpipe-server/tests/search_test.rs b/screenpipe-server/tests/search_test.rs
new file mode 100644
index 000000000..9f52625e7
--- /dev/null
+++ b/screenpipe-server/tests/search_test.rs
@@ -0,0 +1,389 @@
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrono::{Duration, Utc};
+use screenpipe_server::{create_router, AppState, ContentItem, DatabaseManager, PaginatedResponse};
+use serde_json::json;
+use std::collections::HashMap;
+use std::sync::atomic::AtomicBool;
+use std::sync::Arc;
+use tower::ServiceExt;
+fn init() {
+ let _ = env_logger::builder()
+ .is_test(true)
+ .filter_level(log::LevelFilter::Debug)
+ .try_init()
+ .map_err(|e| eprintln!("Logger initialization failed: {}", e));
+}
+// Helper function to set up the test app
+async fn setup_test_app() -> (Router, Arc<AppState>) {
+ let db = Arc::new(DatabaseManager::new("sqlite::memory:").await.unwrap());
+ let app_state = Arc::new(AppState {
+ db: db.clone(),
+ vision_control: Arc::new(AtomicBool::new(false)),
+ audio_devices_control: Arc::new(crossbeam::queue::SegQueue::new()),
+ devices_status: HashMap::new(),
+ app_start_time: Utc::now(),
+ });
+
+ init();
+ let app = create_router().with_state(app_state.clone());
+ (app, app_state)
+}
+
+// Helper function to insert test data
+async fn insert_test_data(db: &Arc<DatabaseManager>) {
+ // Insert OCR data
+ db.insert_video_chunk("test_video.mp4").await.unwrap();
+ let frame_id = db.insert_frame().await.unwrap();
+ db.insert_ocr_text(
+ frame_id,
+ "Test OCR text",
+ &serde_json::to_string(&json!({
+ "x": 10,
+ "y": 20,
+ "width": 100,
+ "height": 200
+ }))
+ .unwrap(),
+ "TestApp",
+ "TestWindow",
+ Arc::new(screenpipe_vision::OcrEngine::Tesseract),
+ true,
+ )
+ .await
+ .unwrap();
+
+ // Insert Audio data
+ let audio_chunk_id = db.insert_audio_chunk("test_audio.wav").await.unwrap();
+ db.insert_audio_transcription(audio_chunk_id, "Test audio transcription", 0, "TestEngine")
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn test_basic_search() {
+ let (app, app_state) = setup_test_app().await;
+ insert_test_data(&app_state.db).await;
+
+ let response = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?q=test&limit=10&offset=0")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 2); // One OCR result and one Audio result
+ assert_eq!(search_results.pagination.total, 2);
+}
+
+#[tokio::test]
+async fn test_content_type_filter() {
+ let (app, app_state) = setup_test_app().await;
+ insert_test_data(&app_state.db).await;
+
+ // Test OCR filter
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?q=test&limit=10&offset=0&content_type=ocr")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 1);
+ assert!(matches!(search_results.data[0], ContentItem::OCR(_)));
+
+ // Test Audio filter
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?q=test&limit=10&offset=0&content_type=audio")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 1);
+ assert!(matches!(search_results.data[0], ContentItem::Audio(_)));
+}
+
+#[tokio::test]
+async fn test_pagination() {
+ let (app, app_state) = setup_test_app().await;
+ insert_test_data(&app_state.db).await;
+
+ // Test with limit 1 and offset 0
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?q=test&limit=1&offset=0")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 1);
+ assert_eq!(search_results.pagination.total, 2);
+
+ // Test with limit 1 and offset 1
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?q=test&limit=1&offset=1")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 0);
+ assert_eq!(search_results.pagination.total, 2);
+ // assert_ne!(search_results.data[0], search_results.data[0]);
+}
+
+#[tokio::test]
+async fn test_time_range_filter() {
+ let (app, app_state) = setup_test_app().await;
+ insert_test_data(&app_state.db).await;
+
+ let now = Utc::now();
+ let one_hour_ago = now - Duration::hours(1);
+ let two_hours_ago = now - Duration::hours(2);
+
+ // Test search within the last hour
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri(&format!(
+ "/search?q=test&limit=10&offset=0&start_time={}&end_time={}",
+ one_hour_ago.to_rfc3339(),
+ now.to_rfc3339()
+ ))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 2);
+
+ // Test search between two hours ago and one hour ago (should return no results)
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri(&format!(
+ "/search?q=test&limit=10&offset=0&start_time={}&end_time={}",
+ two_hours_ago.to_rfc3339(),
+ one_hour_ago.to_rfc3339()
+ ))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 0);
+}
+
+#[tokio::test]
+async fn test_app_name_filter() {
+ let (app, app_state) = setup_test_app().await;
+ insert_test_data(&app_state.db).await;
+
+ // Test search with correct app name
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?q=test&limit=10&offset=0&app_name=TestApp")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 1);
+ assert!(matches!(search_results.data[0], ContentItem::OCR(_)));
+
+ // Test search with incorrect app name
+ let response = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?q=test&limit=10&offset=0&app_name=WrongApp&start_time=2024-01-01T00:00:00Z&end_time=2024-01-02T00:00:00Z")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 0);
+}
+
+#[tokio::test]
+async fn test_window_name_filter() {
+ let (app, app_state) = setup_test_app().await;
+ insert_test_data(&app_state.db).await;
+
+ // Test search with correct window name
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?q=test&limit=10&offset=0&window_name=TestWindow")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 1);
+ assert!(matches!(search_results.data[0], ContentItem::OCR(_)));
+
+ // Test search with incorrect window name
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?q=test&limit=10&offset=0&window_name=WrongWindow")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 0);
+}
+
+#[tokio::test]
+async fn test_empty_query() {
+ let (app, app_state) = setup_test_app().await;
+ insert_test_data(&app_state.db).await;
+
+ // Test search with empty query (should return all results)
+ let response = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?limit=10&offset=0")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 2);
+ assert_eq!(search_results.pagination.total, 2);
+}
+
+#[tokio::test]
+async fn test_no_results() {
+ let (app, app_state) = setup_test_app().await;
+ insert_test_data(&app_state.db).await;
+
+ // Test search with a query that doesn't match any results
+ let response = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?q=nonexistent&limit=10&offset=0&start_time=2024-01-01T00:00:00Z&end_time=2024-01-01T00:00:00Z")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 0);
+ assert_eq!(search_results.pagination.total, 0);
+}
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
new file mode 100644
index 000000000..9b0adc27a
--- /dev/null
+++ b/screenpipe-server/tests/tags_test.rs
@@ -0,0 +1,391 @@
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrono::Utc;
+use crossbeam::queue::SegQueue;
+use screenpipe_vision::OcrEngine;
+use serde_json::json;
+use std::collections::HashMap;
+use std::sync::atomic::AtomicBool;
+use std::sync::Arc;
+use tower::ServiceExt;
+
+use screenpipe_server::{
+ create_router, AppState, ContentItem, ContentSource, DatabaseManager, PaginatedResponse,
+};
+
+// Add this function to initialize the logger
+fn init() {
+ let _ = env_logger::builder().is_test(true).try_init();
+}
+
+async fn setup_test_app() -> (Router, Arc<AppState>) {
+ let db = Arc::new(DatabaseManager::new("sqlite::memory:").await.unwrap());
+ let app_state = Arc::new(AppState {
+ db: db.clone(),
+ vision_control: Arc::new(AtomicBool::new(false)),
+ audio_devices_control: Arc::new(SegQueue::new()),
+ devices_status: HashMap::new(),
+ app_start_time: Utc::now(),
+ });
+
+ let app = create_router().with_state(app_state.clone());
+ init();
+ (app, app_state)
+}
+
+#[tokio::test]
+async fn test_add_tags_and_search() {
+ let (app, app_state) = setup_test_app().await;
+
+ // Insert test data
+ insert_test_data(&app_state.db).await;
+
+ // Test adding tags to vision content
+ let vision_response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/tags/vision/1")
+ .header("Content-Type", "application/json")
+ .body(Body::from(
+ serde_json::to_string(&json!({
+ "tags": ["test", "vision"]
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(vision_response.status(), StatusCode::OK);
+
+ // Test adding tags to audio content
+ let audio_response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/tags/audio/1")
+ .header("Content-Type", "application/json")
+ .body(Body::from(
+ serde_json::to_string(&json!({
+ "tags": ["test", "audio"]
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(audio_response.status(), StatusCode::OK);
+
+ // Test adding tags with invalid content type
+ let invalid_response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/tags/invalid/1")
+ .header("Content-Type", "application/json")
+ .body(Body::from(
+ serde_json::to_string(&json!({
+ "tags": ["test"]
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(invalid_response.status(), StatusCode::BAD_REQUEST);
+
+ // Test search results include tags
+ let search_response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?q=test&content_type=all")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(search_response.status(), StatusCode::OK);
+
+ let body = to_bytes(search_response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+
+ println!("Raw response body: {}", String::from_utf8_lossy(&body));
+
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ // Check if search results contain the added tags
+ for result in search_results.data {
+ match result {
+ ContentItem::OCR(ocr) => {
+ assert!(ocr.tags.contains(&"test".to_string()));
+ assert!(ocr.tags.contains(&"vision".to_string()));
+ }
+ ContentItem::Audio(audio) => {
+ assert!(audio.tags.contains(&"test".to_string()));
+ assert!(audio.tags.contains(&"audio".to_string()));
+ }
+ ContentItem::FTS(fts) => {
+ assert!(fts.tags.contains(&"test".to_string()));
+ assert!(fts.tags.contains(&"vision".to_string()));
+ }
+ }
+ }
+}
+
+#[tokio::test]
+async fn test_add_multiple_tags_to_single_item() {
+ let (app, app_state) = setup_test_app().await;
+ insert_test_data(&app_state.db).await;
+
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/tags/vision/1")
+ .header("Content-Type", "application/json")
+ .body(Body::from(
+ serde_json::to_string(&json!({
+ "tags": ["work", "meeting", "important", "follow-up"]
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ // Verify tags were added
+ let search_response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?content_type=ocr")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(search_response.status(), StatusCode::OK);
+
+ let body = to_bytes(search_response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert!(!search_results.data.is_empty());
+ if let ContentItem::OCR(ocr) = &search_results.data[0] {
+ assert!(ocr.tags.contains(&"important".to_string()));
+ assert!(ocr.tags.contains(&"follow-up".to_string()));
+ }
+}
+
+#[tokio::test]
+async fn test_remove_tags() {
+ let (app, app_state) = setup_test_app().await;
+ insert_test_data(&app_state.db).await;
+
+ // Add tags
+ app.clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/tags/audio/1")
+ .header("Content-Type", "application/json")
+ .body(Body::from(
+ serde_json::to_string(&json!({
+ "tags": ["meeting", "client", "project-x"]
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ // Remove a tag
+ let remove_response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("DELETE")
+ .uri("/tags/audio/1")
+ .header("Content-Type", "application/json")
+ .body(Body::from(
+ serde_json::to_string(&json!({
+ "tags": ["client"]
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(remove_response.status(), StatusCode::OK);
+
+ // Verify tag was removed
+ let search_response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?content_type=audio")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ let body = to_bytes(search_response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ println!("Search results: {}", search_results.data.len());
+ assert!(!search_results.data.is_empty());
+ if let ContentItem::Audio(audio) = &search_results.data[0] {
+ assert!(audio.tags.contains(&"project-x".to_string()));
+ assert!(!audio.tags.contains(&"client".to_string()));
+ }
+}
+
+#[tokio::test]
+async fn test_search_by_multiple_tags() {
+ let (app, app_state) = setup_test_app().await;
+ insert_test_data(&app_state.db).await;
+
+ // Add tags to multiple items
+ app.clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/tags/vision/1")
+ .header("Content-Type", "application/json")
+ .body(Body::from(
+ serde_json::to_string(&json!({
+ "tags": ["work", "meeting", "project-a"]
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ app.clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/tags/audio/1")
+ .header("Content-Type", "application/json")
+ .body(Body::from(
+ serde_json::to_string(&json!({
+ "tags": ["work", "call", "project-b"]
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ // Search for items with multiple tags
+ let search_response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/search?content_type=all")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(search_response.status(), StatusCode::OK);
+
+ let body = to_bytes(search_response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let search_results: PaginatedResponse<ContentItem> = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(search_results.data.len(), 2);
+ for item in search_results.data {
+ match item {
+ ContentItem::OCR(ocr) => {
+ assert!(ocr.tags.contains(&"work".to_string()));
+ assert!(ocr.tags.contains(&"meeting".to_string()));
+ }
+ ContentItem::Audio(audio) => {
+ assert!(audio.tags.contains(&"work".to_string()));
+ assert!(audio.tags.contains(&"call".to_string()));
+ }
+ ContentItem::FTS(fts) => {
+ assert!(fts.tags.contains(&"work".to_string()));
+ assert!(fts.tags.contains(&"meeting".to_string()));
+ }
+ }
+ }
+}
+
+async fn insert_test_data(db: &Arc<DatabaseManager>) {
+ // Insert test video chunk
+ let _video_chunk_id = db.insert_video_chunk("test_video_file.mp4").await.unwrap();
+
+ // Insert test frame
+ let frame_id = db.insert_frame().await.unwrap();
+
+ // Insert test OCR data
+ db.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();
+
+ // Insert test audio chunk
+ let audio_chunk_id = db.insert_audio_chunk("test_audio_file.wav").await.unwrap();
+
+ // Insert test audio data
+ db.insert_audio_transcription(audio_chunk_id, "Test audio transcription", 0, "test_engine")
+ .await
+ .unwrap();
+
+ // Insert test FTS data
+ db.insert_chunked_text(
+ frame_id,
+ "Test FTS text",
+ Utc::now(),
+ "tesseract",
+ "local_simple",
+ ContentSource::Screen,
+ )
+ .await
+ .unwrap();
+}