Skip to content

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

fix rust formatting

Louis Beaumont482534b22bca
diff --git a/screenpipe-db/benches/search_accuracy.rs b/screenpipe-db/benches/search_accuracy.rs
index e07a0e3d9..cdf72b389 100644
--- a/screenpipe-db/benches/search_accuracy.rs
+++ b/screenpipe-db/benches/search_accuracy.rs
@@ -99,12 +99,11 @@ async fn fts_prefix_search(pool: &sqlx::SqlitePool, query: &str) -> HashSet<i64>
async fn like_search(pool: &sqlx::SqlitePool, query: &str) -> HashSet<i64> {
let pattern = format!("%{}%", query.to_lowercase());
- let rows =
- sqlx::query("SELECT frame_id FROM ocr_text WHERE LOWER(text) LIKE ?")
- .bind(&pattern)
- .fetch_all(pool)
- .await
- .unwrap_or_default();
+ let rows = sqlx::query("SELECT frame_id FROM ocr_text WHERE LOWER(text) LIKE ?")
+ .bind(&pattern)
+ .fetch_all(pool)
+ .await
+ .unwrap_or_default();
rows.iter().map(|r| r.get::<i64, _>("frame_id")).collect()
}
@@ -118,13 +117,11 @@ async fn simulated_split_search(pool: &sqlx::SqlitePool, query: &str) -> HashSet
let pattern = format!("%{}%", query.to_lowercase());
// Get all LIKE matches
- let rows = sqlx::query(
- "SELECT frame_id, text FROM ocr_text WHERE LOWER(text) LIKE ?",
- )
- .bind(&pattern)
- .fetch_all(pool)
- .await
- .unwrap_or_default();
+ let rows = sqlx::query("SELECT frame_id, text FROM ocr_text WHERE LOWER(text) LIKE ?")
+ .bind(&pattern)
+ .fetch_all(pool)
+ .await
+ .unwrap_or_default();
let query_lower = query.to_lowercase();
@@ -165,7 +162,10 @@ fn bench_search_accuracy(c: &mut Criterion) {
});
let test_words = rt.block_on(get_test_words(&pool));
- println!("\n📊 Testing with {} words from your database\n", test_words.len());
+ println!(
+ "\n📊 Testing with {} words from your database\n",
+ test_words.len()
+ );
// Collect accuracy metrics
let mut total_fts = 0usize;
diff --git a/screenpipe-db/src/db.rs b/screenpipe-db/src/db.rs
index 472ca9a34..f7384bfef 100644
--- a/screenpipe-db/src/db.rs
+++ b/screenpipe-db/src/db.rs
@@ -1119,8 +1119,7 @@ impl DatabaseManager {
match text_json {
Some(json_str) => {
- let blocks: Vec<OcrTextBlock> =
- serde_json::from_str(&json_str).unwrap_or_default();
+ let blocks: Vec<OcrTextBlock> = serde_json::from_str(&json_str).unwrap_or_default();
Ok(parse_all_text_positions(&blocks))
}
None => Ok(Vec::new()),
@@ -2721,12 +2720,11 @@ LIMIT ? OFFSET ?
.rows_affected();
// 4. Move the embedding from old speaker to new speaker
- let embedding_id: Option<i64> = sqlx::query_scalar(
- "SELECT id FROM speaker_embeddings WHERE speaker_id = ? LIMIT 1",
- )
- .bind(current_speaker_id)
- .fetch_optional(&mut *tx)
- .await?;
+ let embedding_id: Option<i64> =
+ sqlx::query_scalar("SELECT id FROM speaker_embeddings WHERE speaker_id = ? LIMIT 1")
+ .bind(current_speaker_id)
+ .fetch_optional(&mut *tx)
+ .await?;
let mut embeddings_moved = 0u64;
if let Some(emb_id) = embedding_id {
@@ -2998,9 +2996,9 @@ mod tests {
#[test]
fn test_parse_all_text_positions_handles_invalid_numbers() {
- let blocks = vec![
- create_test_block("Test", "invalid", "0.1", "0.5", "0.08", "0.02"),
- ];
+ let blocks = vec![create_test_block(
+ "Test", "invalid", "0.1", "0.5", "0.08", "0.02",
+ )];
let positions = parse_all_text_positions(&blocks);
diff --git a/screenpipe-db/src/lib.rs b/screenpipe-db/src/lib.rs
index 8fcfba830..f7bfaf4be 100644
--- a/screenpipe-db/src/lib.rs
+++ b/screenpipe-db/src/lib.rs
@@ -6,9 +6,9 @@ mod types;
mod video_db;
pub use db::{parse_all_text_positions, DatabaseManager};
-pub use text_normalizer::expand_search_query;
pub use migration_worker::{
create_migration_worker, MigrationCommand, MigrationConfig, MigrationResponse, MigrationStatus,
MigrationWorker,
};
+pub use text_normalizer::expand_search_query;
pub use types::*;
diff --git a/screenpipe-db/src/text_normalizer.rs b/screenpipe-db/src/text_normalizer.rs
index ce3425ef8..05cbb0638 100644
--- a/screenpipe-db/src/text_normalizer.rs
+++ b/screenpipe-db/src/text_normalizer.rs
@@ -18,7 +18,10 @@ static LETTER_TO_NUM: Lazy<Regex> = Lazy::new(|| Regex::new(r"([a-zA-Z])([0-9])"
#[inline]
fn split_compound(text: &str) -> String {
// Fast path: if no uppercase letters or digits, skip processing
- if !text.bytes().any(|b| b.is_ascii_uppercase() || b.is_ascii_digit()) {
+ if !text
+ .bytes()
+ .any(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
+ {
return text.to_string();
}
@@ -92,7 +95,10 @@ mod tests {
fn test_split_compound_camel_case() {
assert_eq!(split_compound("camelCase"), "camel Case");
assert_eq!(split_compound("CamelCase"), "Camel Case");
- assert_eq!(split_compound("ActivityPerformance"), "Activity Performance");
+ assert_eq!(
+ split_compound("ActivityPerformance"),
+ "Activity Performance"
+ );
}
#[test]
@@ -137,10 +143,7 @@ mod tests {
#[test]
fn test_expand_multi_word_query() {
// Each word gets expanded independently
- assert_eq!(
- expand_search_query("hello world"),
- "(hello* OR world*)"
- );
+ assert_eq!(expand_search_query("hello world"), "(hello* OR world*)");
}
#[test]
diff --git a/screenpipe-db/src/text_similarity.rs b/screenpipe-db/src/text_similarity.rs
index 4f6e063ec..beb9d7e1a 100644
--- a/screenpipe-db/src/text_similarity.rs
+++ b/screenpipe-db/src/text_similarity.rs
@@ -5,7 +5,6 @@
/// independently, resulting in duplicate entries with slightly different text.
///
/// This module provides similarity functions to detect these cross-device duplicates.
-
use std::collections::HashSet;
/// Calculate word-level Jaccard similarity between two strings.
@@ -54,10 +53,7 @@ pub fn containment_similarity(shorter: &str, longer: &str) -> f64 {
}
let set_long: HashSet<_> = words_long.iter().collect();
- let contained = words_short
- .iter()
- .filter(|w| set_long.contains(w))
- .count();
+ let contained = words_short.iter().filter(|w| set_long.contains(w)).count();
contained as f64 / words_short.len() as f64
}
@@ -122,26 +118,17 @@ mod tests {
#[test]
fn test_jaccard_exact_match() {
- assert_eq!(
- word_jaccard_similarity("hello world", "hello world"),
- 1.0
- );
+ assert_eq!(word_jaccard_similarity("hello world", "hello world"), 1.0);
}
#[test]
fn test_jaccard_case_insensitive() {
- assert_eq!(
- word_jaccard_similarity("Hello World", "hello world"),
- 1.0
- );
+ assert_eq!(word_jaccard_similarity("Hello World", "hello world"), 1.0);
}
#[test]
fn test_jaccard_punctuation_ignored() {
- assert_eq!(
- word_jaccard_similarity("Hello, world!", "hello world"),
- 1.0
- );
+ assert_eq!(word_jaccard_similarity("Hello, world!", "hello world"), 1.0);
}
#[test]
diff --git a/screenpipe-db/tests/audio_duplicate_test.rs b/screenpipe-db/tests/audio_duplicate_test.rs
index d8d964e2a..9d6100efb 100644
--- a/screenpipe-db/tests/audio_duplicate_test.rs
+++ b/screenpipe-db/tests/audio_duplicate_test.rs
@@ -69,7 +69,7 @@ mod tests {
let chunk_input = db.insert_audio_chunk("input_audio.mp4").await.unwrap();
let id2 = db
.insert_audio_transcription(
- chunk_input, // Different chunk!
+ chunk_input, // Different chunk!
"It was the first computer with beautiful typography.", // Same text
0,
"whisper",
@@ -399,7 +399,14 @@ mod tests {
let chunk1 = db.insert_audio_chunk("output.mp4").await.unwrap();
let id1 = db
.insert_audio_transcription(
- chunk1, "Yeah", 0, "whisper", &output_device(), None, None, None,
+ chunk1,
+ "Yeah",
+ 0,
+ "whisper",
+ &output_device(),
+ None,
+ None,
+ None,
)
.await
.unwrap();
@@ -411,7 +418,14 @@ mod tests {
let chunk2 = db.insert_audio_chunk("input.mp4").await.unwrap();
let _id2 = db
.insert_audio_transcription(
- chunk2, "Yeah", 0, "whisper", &input_device(), None, None, None,
+ chunk2,
+ "Yeah",
+ 0,
+ "whisper",
+ &input_device(),
+ None,
+ None,
+ None,
)
.await
.unwrap();
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 39ccbb037..b7ddea981 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -407,9 +407,8 @@ pub(crate) async fn search(
})?;
// Helper to check if app name contains "screenpipe" (case insensitive)
- let is_screenpipe_app = |app_name: &str| -> bool {
- app_name.to_lowercase().contains("screenpipe")
- };
+ let is_screenpipe_app =
+ |app_name: &str| -> bool { app_name.to_lowercase().contains("screenpipe") };
let mut content_items: Vec<ContentItem> = results
.iter()
@@ -2293,7 +2292,11 @@ struct WsConnectionGuard {
impl Drop for WsConnectionGuard {
fn drop(&mut self) {
let prev = self.counter.fetch_sub(1, Ordering::SeqCst);
- debug!("WebSocket connection closed, count: {} -> {}", prev, prev - 1);
+ debug!(
+ "WebSocket connection closed, count: {} -> {}",
+ prev,
+ prev - 1
+ );
}
}
@@ -2411,7 +2414,11 @@ async fn ws_health_handler(ws: WebSocketUpgrade, State(state): State<Arc<AppStat
}
}
-async fn handle_health_socket(mut socket: WebSocket, state: Arc<AppState>, _guard: WsConnectionGuard) {
+async fn handle_health_socket(
+ mut socket: WebSocket,
+ state: Arc<AppState>,
+ _guard: WsConnectionGuard,
+) {
let mut interval = tokio::time::interval(Duration::from_secs(5));
loop {
@@ -3208,9 +3215,7 @@ fn create_time_series_frame(chunk: FrameData) -> TimeSeriesFrame {
.ocr_entries
.into_iter()
// Filter out screenpipe frames at display time
- .filter(|device_data| {
- !device_data.app_name.to_lowercase().contains("screenpipe")
- })
+ .filter(|device_data| !device_data.app_name.to_lowercase().contains("screenpipe"))
.map(|device_data| DeviceFrame {
device_id: device_data.device_name,
frame_id: chunk.frame_id,
@@ -3248,7 +3253,11 @@ fn create_time_series_frame(chunk: FrameData) -> TimeSeriesFrame {
}
}
-async fn handle_stream_frames_socket(socket: WebSocket, state: Arc<AppState>, _guard: WsConnectionGuard) {
+async fn handle_stream_frames_socket(
+ socket: WebSocket,
+ state: Arc<AppState>,
+ _guard: WsConnectionGuard,
+) {
let (mut sender, mut receiver) = socket.split();
let (frame_tx, frame_rx) = tokio::sync::mpsc::channel(100);
let db = state.db.clone();
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index 73d852e98..5e81bd912 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -374,10 +374,7 @@ pub async fn start_ffmpeg_process(output_file: &str, fps: f64) -> Result<Child,
// This writes the moov atom at the start instead of the end, enabling:
// - Frame extraction from incomplete/in-progress recordings
// - Streaming playback before recording finishes
- args.extend_from_slice(&[
- "-movflags",
- "frag_keyframe+empty_moov+default_base_moof",
- ]);
+ args.extend_from_slice(&["-movflags", "frag_keyframe+empty_moov+default_base_moof"]);
args.extend_from_slice(&["-pix_fmt", "yuv420p", output_file]);
diff --git a/screenpipe-server/src/video_utils.rs b/screenpipe-server/src/video_utils.rs
index 0b6a9b1ce..61d142d16 100644
--- a/screenpipe-server/src/video_utils.rs
+++ b/screenpipe-server/src/video_utils.rs
@@ -575,13 +575,14 @@ pub async fn extract_frame_from_video(file_path: &str, offset_index: i64) -> Res
let ffmpeg_path = find_ffmpeg_path().expect("failed to find ffmpeg path");
// Get video FPS and duration
- let (source_fps, video_duration) = match get_video_fps_and_duration(&ffmpeg_path, file_path).await {
- Ok((fps, duration)) => (fps, duration),
- Err(e) => {
- error!("failed to get video metadata, using defaults: {}", e);
- (1.0, f64::MAX) // Use MAX duration to disable validation on error
- }
- };
+ let (source_fps, video_duration) =
+ match get_video_fps_and_duration(&ffmpeg_path, file_path).await {
+ Ok((fps, duration)) => (fps, duration),
+ Err(e) => {
+ error!("failed to get video metadata, using defaults: {}", e);
+ (1.0, f64::MAX) // Use MAX duration to disable validation on error
+ }
+ };
// Convert frame index to seconds: frame_time = frame_index / fps
let mut offset_seconds = offset_index as f64 / source_fps;
diff --git a/screenpipe-server/tests/first_frames_test.rs b/screenpipe-server/tests/first_frames_test.rs
index af5b0d10b..ecce8047b 100644
--- a/screenpipe-server/tests/first_frames_test.rs
+++ b/screenpipe-server/tests/first_frames_test.rs
@@ -83,7 +83,11 @@ async fn test_first_frames_loading() -> Result<()> {
truncate_str(timestamp, 18)
);
failure_count += 1;
- failures.push((*frame_id, file_path.clone(), "File does not exist".to_string()));
+ failures.push((
+ *frame_id,
+ file_path.clone(),
+ "File does not exist".to_string(),
+ ));
continue;
}
@@ -119,7 +123,11 @@ async fn test_first_frames_loading() -> Result<()> {
truncate_str(timestamp, 18)
);
failure_count += 1;
- failures.push((*frame_id, file_path.clone(), format!("Empty file: {} bytes", meta.len())));
+ failures.push((
+ *frame_id,
+ file_path.clone(),
+ format!("Empty file: {} bytes", meta.len()),
+ ));
}
Err(e) => {
println!(
@@ -130,7 +138,11 @@ async fn test_first_frames_loading() -> Result<()> {
truncate_str(timestamp, 18)
);
failure_count += 1;
- failures.push((*frame_id, file_path.clone(), format!("Output file error: {}", e)));
+ failures.push((
+ *frame_id,
+ file_path.clone(),
+ format!("Output file error: {}", e),
+ ));
}
}
}
@@ -145,7 +157,11 @@ async fn test_first_frames_loading() -> Result<()> {
elapsed.as_millis()
);
failure_count += 1;
- failures.push((*frame_id, file_path.clone(), format!("Extraction failed: {}", e)));
+ failures.push((
+ *frame_id,
+ file_path.clone(),
+ format!("Extraction failed: {}", e),
+ ));
}
Err(_) => {
println!(
@@ -156,7 +172,11 @@ async fn test_first_frames_loading() -> Result<()> {
truncate_str(timestamp, 18)
);
failure_count += 1;
- failures.push((*frame_id, file_path.clone(), "Timeout after 10s".to_string()));
+ failures.push((
+ *frame_id,
+ file_path.clone(),
+ "Timeout after 10s".to_string(),
+ ));
}
}
}
@@ -292,11 +312,10 @@ async fn test_frame_endpoint_response_times() -> Result<()> {
println!("\n=== Frame Endpoint Response Time Test ===\n");
// Get 5 recent frame IDs
- let frame_ids: Vec<i64> = sqlx::query_scalar(
- "SELECT id FROM frames ORDER BY timestamp DESC LIMIT 5",
- )
- .fetch_all(&db.pool)
- .await?;
+ let frame_ids: Vec<i64> =
+ sqlx::query_scalar("SELECT id FROM frames ORDER BY timestamp DESC LIMIT 5")
+ .fetch_all(&db.pool)
+ .await?;
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
@@ -367,7 +386,10 @@ async fn test_video_file_write_status() -> Result<()> {
.fetch_all(&db.pool)
.await?;
- println!("Checking {} video files from last 5 minutes\n", video_files.len());
+ println!(
+ "Checking {} video files from last 5 minutes\n",
+ video_files.len()
+ );
println!(
"{:<70} {:<15} {:<20}",
"Video Path", "Size (MB)", "Last Modified"
diff --git a/screenpipe-server/tests/frame_extraction_test.rs b/screenpipe-server/tests/frame_extraction_test.rs
index 7b35bd8d8..3af34461f 100644
--- a/screenpipe-server/tests/frame_extraction_test.rs
+++ b/screenpipe-server/tests/frame_extraction_test.rs
@@ -173,7 +173,11 @@ async fn test_complete_mp4_extraction_succeeds() {
let frame_path = temp_dir.path().join("frame.jpg");
let result = extract_frame(video_path_str, frame_path.to_str().unwrap()).await;
- assert!(result.is_ok(), "Should succeed on complete MP4: {:?}", result);
+ assert!(
+ result.is_ok(),
+ "Should succeed on complete MP4: {:?}",
+ result
+ );
assert!(frame_path.exists(), "Frame file should exist");
}
@@ -263,10 +267,14 @@ async fn test_regular_vs_fragmented_mp4() {
let regular_path = temp_dir.path().join("regular.mp4");
let regular_output = Command::new(&ffmpeg)
.args([
- "-f", "lavfi",
- "-i", "testsrc=duration=2:size=320x240:rate=1",
- "-c:v", "libx264",
- "-preset", "ultrafast",
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc=duration=2:size=320x240:rate=1",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "ultrafast",
"-y",
regular_path.to_str().unwrap(),
])
@@ -279,11 +287,16 @@ async fn test_regular_vs_fragmented_mp4() {
let frag_path = temp_dir.path().join("fragmented.mp4");
let frag_output = Command::new(&ffmpeg)
.args([
- "-f", "lavfi",
- "-i", "testsrc=duration=2:size=320x240:rate=1",
- "-c:v", "libx264",
- "-preset", "ultrafast",
- "-movflags", "frag_keyframe+empty_moov+default_base_moof",
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc=duration=2:size=320x240:rate=1",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "ultrafast",
+ "-movflags",
+ "frag_keyframe+empty_moov+default_base_moof",
"-y",
frag_path.to_str().unwrap(),
])
@@ -299,8 +312,16 @@ async fn test_regular_vs_fragmented_mp4() {
let result1 = extract_frame(regular_path.to_str().unwrap(), frame1.to_str().unwrap()).await;
let result2 = extract_frame(frag_path.to_str().unwrap(), frame2.to_str().unwrap()).await;
- assert!(result1.is_ok(), "Regular MP4 extraction should work: {:?}", result1);
- assert!(result2.is_ok(), "Fragmented MP4 extraction should work: {:?}", result2);
+ assert!(
+ result1.is_ok(),
+ "Regular MP4 extraction should work: {:?}",
+ result1
+ );
+ assert!(
+ result2.is_ok(),
+ "Fragmented MP4 extraction should work: {:?}",
+ result2
+ );
// Check file sizes - fragmented may be slightly larger
let regular_size = std::fs::metadata(&regular_path).unwrap().len();
@@ -333,12 +354,18 @@ async fn test_fragmented_mp4_is_valid() {
// Create fragmented MP4 with H.265 (same as production)
let output = Command::new(&ffmpeg)
.args([
- "-f", "lavfi",
- "-i", "testsrc=duration=3:size=320x240:rate=10",
- "-c:v", "libx265",
- "-preset", "ultrafast",
- "-tag:v", "hvc1",
- "-movflags", "frag_keyframe+empty_moov+default_base_moof",
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc=duration=3:size=320x240:rate=10",
+ "-c:v",
+ "libx265",
+ "-preset",
+ "ultrafast",
+ "-tag:v",
+ "hvc1",
+ "-movflags",
+ "frag_keyframe+empty_moov+default_base_moof",
"-y",
video_path_str,
])
@@ -361,10 +388,14 @@ async fn test_fragmented_mp4_is_valid() {
let probe_output = Command::new(&ffprobe)
.args([
- "-v", "error",
- "-select_streams", "v:0",
- "-show_entries", "stream=codec_name,width,height,duration",
- "-of", "json",
+ "-v",
+ "error",
+ "-select_streams",
+ "v:0",
+ "-show_entries",
+ "stream=codec_name,width,height,duration",
+ "-of",
+ "json",
video_path_str,
])
.output()
@@ -392,9 +423,12 @@ async fn test_fragmented_mp4_is_valid() {
let extract_output = Command::new(&ffmpeg)
.args([
- "-ss", &seek_time,
- "-i", video_path_str,
- "-vframes", "1",
+ "-ss",
+ &seek_time,
+ "-i",
+ video_path_str,
+ "-vframes",
+ "1",
"-y",
frame_path.to_str().unwrap(),
])
diff --git a/screenpipe-server/tests/stream_frames_test.rs b/screenpipe-server/tests/stream_frames_test.rs
index 6abce945f..aa524c13e 100644
--- a/screenpipe-server/tests/stream_frames_test.rs
+++ b/screenpipe-server/tests/stream_frames_test.rs
@@ -48,11 +48,11 @@ async fn create_test_db_with_frames(num_frames: i64) -> Arc<DatabaseManager> {
db.insert_frame(
"test_device",
Some(timestamp),
- None, // browser_url
+ None, // browser_url
Some("test_app"),
Some("test_window"),
- false, // focused (not Option)
- Some(i), // offset_index
+ false, // focused (not Option)
+ Some(i), // offset_index
)
.await
.expect("Failed to insert frame");
@@ -118,10 +118,7 @@ mod tests {
})
.await;
- println!(
- "Received {} frames in initial fetch",
- received_frames.len()
- );
+ println!("Received {} frames in initial fetch", received_frames.len());
// Now wait for any new frames (this should timeout with current bug)
let wait_for_new = timeout(std::time::Duration::from_secs(10), async {
@@ -226,7 +223,10 @@ mod tests {
println!("Client 2 received {} frames", client2_frames);
// Both clients should receive the same data
- assert!(client1_frames > 0 || client2_frames > 0, "At least one client should receive frames");
+ assert!(
+ client1_frames > 0 || client2_frames > 0,
+ "At least one client should receive frames"
+ );
}
/// TEST 3: Client should only receive frames within requested time range
@@ -263,7 +263,8 @@ mod tests {
if text == "\"keep-alive-text\"" {
break;
}
- if let Ok(batch) = serde_json::from_str::<Vec<StreamTimeSeriesResponse>>(&text) {
+ if let Ok(batch) = serde_json::from_str::<Vec<StreamTimeSeriesResponse>>(&text)
+ {
for frame in batch {
// Verify each frame is within the requested time range
let timestamp = chrono::DateTime::parse_from_rfc3339(&frame.timestamp)
@@ -409,7 +410,8 @@ mod tests {
if text == "\"keep-alive-text\"" {
break;
}
- if let Ok(batch) = serde_json::from_str::<Vec<StreamTimeSeriesResponse>>(&text) {
+ if let Ok(batch) = serde_json::from_str::<Vec<StreamTimeSeriesResponse>>(&text)
+ {
frames.extend(batch);
}
}
diff --git a/screenpipe-server/tests/timeline_refresh_bug_test.rs b/screenpipe-server/tests/timeline_refresh_bug_test.rs
index 6a3841ec1..3dbec92da 100644
--- a/screenpipe-server/tests/timeline_refresh_bug_test.rs
+++ b/screenpipe-server/tests/timeline_refresh_bug_test.rs
@@ -154,10 +154,7 @@ mod tests {
1,
"Should only find the new frame, not duplicates"
);
- assert!(
- latest_ts.is_some(),
- "Latest timestamp should be updated"
- );
+ assert!(latest_ts.is_some(), "Latest timestamp should be updated");
}
/// TEST 2: Verify that already-sent frames are correctly excluded
@@ -256,14 +253,10 @@ mod tests {
let sent_frame_ids: Arc<Mutex<HashSet<i64>>> = Arc::new(Mutex::new(HashSet::new()));
// Poll only for the last hour
- let (new_frames, _) = simulate_fetch_new_frames(
- db.clone(),
- one_hour_ago,
- now,
- sent_frame_ids.clone(),
- )
- .await
- .expect("Poll should succeed");
+ let (new_frames, _) =
+ simulate_fetch_new_frames(db.clone(), one_hour_ago, now, sent_frame_ids.clone())
+ .await
+ .expect("Poll should succeed");
assert!(
new_frames.contains(&new_frame_id),
@@ -374,7 +367,8 @@ mod tests {
assert!(
poll_start < poll_end,
"Poll range should be valid: poll_start={}, poll_end={}",
- poll_start, poll_end
+ poll_start,
+ poll_end
);
}
@@ -546,10 +540,7 @@ mod tests {
// Scenario 1: end_time is in the future (today's request) - should poll
let future_end = now + Duration::hours(5);
- assert!(
- now <= future_end,
- "Should poll when end_time is in future"
- );
+ assert!(now <= future_end, "Should poll when end_time is in future");
// Scenario 2: end_time is in the past (historical request) - should NOT poll
let past_end = now - Duration::hours(1);
@@ -580,14 +571,32 @@ mod tests {
// Regular apps should be included
assert!(should_include_entry("Chrome"), "Chrome should be included");
assert!(should_include_entry("Cursor"), "Cursor should be included");
- assert!(should_include_entry("WezTerm"), "WezTerm should be included");
- assert!(should_include_entry(""), "Empty app name should be included");
+ assert!(
+ should_include_entry("WezTerm"),
+ "WezTerm should be included"
+ );
+ assert!(
+ should_include_entry(""),
+ "Empty app name should be included"
+ );
// Screenpipe variants should be filtered out
- assert!(!should_include_entry("screenpipe"), "screenpipe should be filtered");
- assert!(!should_include_entry("Screenpipe"), "Screenpipe should be filtered");
- assert!(!should_include_entry("SCREENPIPE"), "SCREENPIPE should be filtered");
- assert!(!should_include_entry("screenpipe-app"), "screenpipe-app should be filtered");
+ assert!(
+ !should_include_entry("screenpipe"),
+ "screenpipe should be filtered"
+ );
+ assert!(
+ !should_include_entry("Screenpipe"),
+ "Screenpipe should be filtered"
+ );
+ assert!(
+ !should_include_entry("SCREENPIPE"),
+ "SCREENPIPE should be filtered"
+ );
+ assert!(
+ !should_include_entry("screenpipe-app"),
+ "screenpipe-app should be filtered"
+ );
}
/// TEST 10: Test that frames with all-screenpipe entries result in empty frame_data
diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rs
index 9491f4477..713a4a946 100644
--- a/screenpipe-vision/src/capture_screenshot_by_window.rs
+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs
@@ -283,7 +283,17 @@ pub async fn capture_all_visible_windows(
// Capture image immediately while we have access to the window
match window.capture_image() {
- Ok(buffer) => Some((app_name, title, is_focused, buffer, process_id, window_x, window_y, window_width, window_height)),
+ Ok(buffer) => Some((
+ app_name,
+ title,
+ is_focused,
+ buffer,
+ process_id,
+ window_x,
+ window_y,
+ window_width,
+ window_height,
+ )),
Err(e) => {
// Expected for overlay windows, protected content, or transparent windows
debug!(
@@ -301,7 +311,18 @@ pub async fn capture_all_visible_windows(
}
// Process the captured data
- for (app_name, window_name, is_focused, buffer, process_id, window_x, window_y, window_width, window_height) in windows_data {
+ for (
+ app_name,
+ window_name,
+ is_focused,
+ buffer,
+ process_id,
+ window_x,
+ window_y,
+ window_width,
+ window_height,
+ ) in windows_data
+ {
// Convert to DynamicImage
let image = DynamicImage::ImageRgba8(
image::ImageBuffer::from_raw(buffer.width(), buffer.height(), buffer.into_raw())
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index 888091bb0..3ef3eb9aa 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -128,7 +128,6 @@ pub struct OcrTaskData {
pub result_tx: Sender<CaptureResult>,
}
-
#[derive(Debug)]
pub enum ContinuousCaptureError {
MonitorNotFound,
diff --git a/screenpipe-vision/tests/capture_error_test.rs b/screenpipe-vision/tests/capture_error_test.rs
index 606bcec83..3b482f960 100644
--- a/screenpipe-vision/tests/capture_error_test.rs
+++ b/screenpipe-vision/tests/capture_error_test.rs
@@ -57,7 +57,7 @@ fn test_problematic_apps_should_be_skipped() {
let problematic_apps = vec![
"TheBoringNotch", // macOS notch overlay app
"Grammarly Desktop", // Overlay/tooltip windows
- "Omi录屏专家", // Chinese screen recorder with overlay
+ "Omi录屏专家", // Chinese screen recorder with overlay
];
#[cfg(target_os = "macos")]
@@ -157,19 +157,31 @@ fn test_window_filter_logic() {
fn test_error_scenarios_are_expected() {
// These error scenarios are EXPECTED and should not be logged at error level:
let expected_failure_scenarios = vec![
- ("Failed to get title for window", "Some windows don't expose titles"),
- ("Failed to get is_minimized", "Some windows don't report state"),
- ("Failed to get focus state", "Focus tracking can fail for overlays"),
- ("Failed to capture image", "Protected/overlay windows can't be captured"),
- ("GetFileVersionInfoSizeW", "System DLLs may lack version info"),
+ (
+ "Failed to get title for window",
+ "Some windows don't expose titles",
+ ),
+ (
+ "Failed to get is_minimized",
+ "Some windows don't report state",
+ ),
+ (
+ "Failed to get focus state",
+ "Focus tracking can fail for overlays",
+ ),
+ (
+ "Failed to capture image",
+ "Protected/overlay windows can't be captured",
+ ),
+ (
+ "GetFileVersionInfoSizeW",
+ "System DLLs may lack version info",
+ ),
("GetModuleBaseNameW", "Protected processes deny access"),
];
for (error_pattern, reason) in &expected_failure_scenarios {
- println!(
- "Expected failure: '{}' - Reason: {}",
- error_pattern, reason
- );
+ println!("Expected failure: '{}' - Reason: {}", error_pattern, reason);
println!(" -> Should be logged at DEBUG level, not ERROR");
}
diff --git a/screenpipe-vision/tests/empty_window_name_test.rs b/screenpipe-vision/tests/empty_window_name_test.rs
index 461efbf7d..7a45a6b71 100644
--- a/screenpipe-vision/tests/empty_window_name_test.rs
+++ b/screenpipe-vision/tests/empty_window_name_test.rs
@@ -35,18 +35,10 @@ fn is_window_valid_fixed(
}
fn create_skip_sets() -> (HashSet<&'static str>, HashSet<&'static str>) {
- let skip_apps: HashSet<&str> = HashSet::from([
- "Window Server",
- "SystemUIServer",
- "Dock",
- ]);
-
- let skip_titles: HashSet<&str> = HashSet::from([
- "Item-0",
- "App Icon Window",
- "Menu Bar",
- "Control Center",
- ]);
+ let skip_apps: HashSet<&str> = HashSet::from(["Window Server", "SystemUIServer", "Dock"]);
+
+ let skip_titles: HashSet<&str> =
+ HashSet::from(["Item-0", "App Icon Window", "Menu Bar", "Control Center"]);
(skip_apps, skip_titles)
}
@@ -76,10 +68,7 @@ fn test_fix_empty_window_name_filtered() {
// With the fix, empty window_name should be filtered out
let result = is_window_valid_fixed("Arc", "", &skip_apps, &skip_titles);
- assert!(
- !result,
- "FIX: Empty window_name should be filtered out"
- );
+ assert!(!result, "FIX: Empty window_name should be filtered out");
println!("FIX WORKS: Empty window_name is now filtered out");
}
@@ -96,7 +85,7 @@ fn test_production_scenario_arc_browser() {
// 2. Internal overlay/helper window with empty title
let windows = vec![
- ("Arc", ""), // Internal window (empty title)
+ ("Arc", ""), // Internal window (empty title)
("Arc", "Reddit - The heart of the internet"), // Actual browser tab
];
@@ -126,11 +115,20 @@ fn test_production_scenario_arc_browser() {
);
}
- println!("\nCurrent behavior: {} windows captured (creates duplicate DB records)", valid_current);
+ println!(
+ "\nCurrent behavior: {} windows captured (creates duplicate DB records)",
+ valid_current
+ );
println!("Fixed behavior: {} window captured (correct)", valid_fixed);
- assert_eq!(valid_current, 2, "Current behavior captures both windows (bug)");
- assert_eq!(valid_fixed, 1, "Fixed behavior captures only the valid window");
+ assert_eq!(
+ valid_current, 2,
+ "Current behavior captures both windows (bug)"
+ );
+ assert_eq!(
+ valid_fixed, 1,
+ "Fixed behavior captures only the valid window"
+ );
}
#[test]
@@ -139,12 +137,12 @@ fn test_production_scenario_multiple_apps() {
// Simulates a typical capture cycle with multiple apps
let windows = vec![
- ("Arc", ""), // Arc internal (empty)
- ("Arc", "GitHub - screenpipe"), // Arc tab
- ("WezTerm", ""), // Terminal internal? (empty)
- ("WezTerm", "~/code/screenpipe"), // Terminal window
- ("Finder", "Documents"), // Finder window
- ("Dock", "Dock"), // Should be skipped (SKIP_APPS)
+ ("Arc", ""), // Arc internal (empty)
+ ("Arc", "GitHub - screenpipe"), // Arc tab
+ ("WezTerm", ""), // Terminal internal? (empty)
+ ("WezTerm", "~/code/screenpipe"), // Terminal window
+ ("Finder", "Documents"), // Finder window
+ ("Dock", "Dock"), // Should be skipped (SKIP_APPS)
];
println!("\n=== Production Scenario: Multiple Apps ===\n");
@@ -164,9 +162,16 @@ fn test_production_scenario_multiple_apps() {
}
}
- println!("Current behavior captures {} windows:", current_results.len());
+ println!(
+ "Current behavior captures {} windows:",
+ current_results.len()
+ );
for (app, title) in &current_results {
- println!(" - {}: '{}'", app, if title.is_empty() { "<empty>" } else { title });
+ println!(
+ " - {}: '{}'",
+ app,
+ if title.is_empty() { "<empty>" } else { title }
+ );
}
println!("\nFixed behavior captures {} windows:", fixed_results.len());
@@ -176,8 +181,16 @@ fn test_production_scenario_multiple_apps() {
// Current behavior: 5 windows (includes 2 empty titles, excludes Dock)
// Fixed behavior: 3 windows (excludes empty titles and Dock)
- assert_eq!(current_results.len(), 5, "Current captures empty window names");
- assert_eq!(fixed_results.len(), 3, "Fixed filters out empty window names");
+ assert_eq!(
+ current_results.len(),
+ 5,
+ "Current captures empty window names"
+ );
+ assert_eq!(
+ fixed_results.len(),
+ 3,
+ "Fixed filters out empty window names"
+ );
}
// ==================== DB RECORD COUNT SIMULATION ====================
@@ -209,22 +222,37 @@ fn test_db_record_vs_video_frame_mismatch() {
if passes_current {
db_records_current += 1;
- println!(" [CURRENT] DB record: offset={}, window='{}'", cycle_idx, title);
+ println!(
+ " [CURRENT] DB record: offset={}, window='{}'",
+ cycle_idx, title
+ );
}
if passes_fixed {
db_records_fixed += 1;
- println!(" [FIXED] DB record: offset={}, window='{}'", cycle_idx, title);
+ println!(
+ " [FIXED] DB record: offset={}, window='{}'",
+ cycle_idx, title
+ );
}
}
}
println!("\n=== Summary ===");
println!("Video frames: {}", video_frames);
- println!("DB records (current): {} <- DOUBLE the video frames!", db_records_current);
- println!("DB records (fixed): {} <- Matches video frames!", db_records_fixed);
+ println!(
+ "DB records (current): {} <- DOUBLE the video frames!",
+ db_records_current
+ );
+ println!(
+ "DB records (fixed): {} <- Matches video frames!",
+ db_records_fixed
+ );
assert_eq!(video_frames, 3);
- assert_eq!(db_records_current, 6, "Current: 2x DB records vs video frames");
+ assert_eq!(
+ db_records_current, 6,
+ "Current: 2x DB records vs video frames"
+ );
assert_eq!(db_records_fixed, 3, "Fixed: 1:1 DB records to video frames");
}
@@ -276,8 +304,16 @@ fn test_normal_windows_not_affected() {
let passes_current = is_window_valid_current(app, title, &skip_apps, &skip_titles);
let passes_fixed = is_window_valid_fixed(app, title, &skip_apps, &skip_titles);
- assert!(passes_current, "Normal window should pass current: {} - {}", app, title);
- assert!(passes_fixed, "Normal window should pass fixed: {} - {}", app, title);
+ assert!(
+ passes_current,
+ "Normal window should pass current: {} - {}",
+ app, title
+ );
+ assert!(
+ passes_fixed,
+ "Normal window should pass fixed: {} - {}",
+ app, title
+ );
println!(" {}: '{}' -> PASS (both)", app, title);
}
diff --git a/screenpipe-vision/tests/frame_window_mismatch_test.rs b/screenpipe-vision/tests/frame_window_mismatch_test.rs
index 09e967215..2987a1261 100644
--- a/screenpipe-vision/tests/frame_window_mismatch_test.rs
+++ b/screenpipe-vision/tests/frame_window_mismatch_test.rs
@@ -105,7 +105,8 @@ fn process_capture_cycle_buggy(
// This is the bug - offset_index will be out of sync!
let mut frame_ids = Vec::new();
for window in &capture.windows {
- let frame_id = db.insert_frame_buggy(&window.app_name, &window.window_name, &window.ocr_text);
+ let frame_id =
+ db.insert_frame_buggy(&window.app_name, &window.window_name, &window.ocr_text);
frame_ids.push(frame_id);
}
@@ -121,7 +122,8 @@ fn test_bug_frame_window_mismatch() {
// Capture cycle 1: User has WezTerm and Arc visible
let capture1 = CaptureResult {
- full_screen_content: "Screen showing: WezTerm terminal with code, Arc browser with GitHub".to_string(),
+ full_screen_content: "Screen showing: WezTerm terminal with code, Arc browser with GitHub"
+ .to_string(),
windows: vec![
WindowResult {
app_name: "WezTerm".to_string(),
@@ -139,41 +141,49 @@ fn test_bug_frame_window_mismatch() {
println!("Capture cycle 1: WezTerm + Arc visible");
let frame_ids_1 = process_capture_cycle_buggy(&capture1, &mut video, &mut db);
println!(" Video frames written: {}", video.frame_count());
- println!(" DB records created: {} (frame_ids: {:?})", frame_ids_1.len(), frame_ids_1);
+ println!(
+ " DB records created: {} (frame_ids: {:?})",
+ frame_ids_1.len(),
+ frame_ids_1
+ );
// Capture cycle 2: User switches to Finder
let capture2 = CaptureResult {
full_screen_content: "Screen showing: Finder window with Documents folder".to_string(),
- windows: vec![
- WindowResult {
- app_name: "Finder".to_string(),
- window_name: "Documents".to_string(),
- ocr_text: "Desktop Documents Downloads".to_string(),
- },
- ],
+ windows: vec![WindowResult {
+ app_name: "Finder".to_string(),
+ window_name: "Documents".to_string(),
+ ocr_text: "Desktop Documents Downloads".to_string(),
+ }],
};
println!("\nCapture cycle 2: Finder visible");
let frame_ids_2 = process_capture_cycle_buggy(&capture2, &mut video, &mut db);
println!(" Video frames written: {}", video.frame_count());
- println!(" DB records created: {} (frame_ids: {:?})", frame_ids_2.len(), frame_ids_2);
+ println!(
+ " DB records created: {} (frame_ids: {:?})",
+ frame_ids_2.len(),
+ frame_ids_2
+ );
// Capture cycle 3: User has Safari open
let capture3 = CaptureResult {
full_screen_content: "Screen showing: Safari with Google Maps".to_string(),
- windows: vec![
- WindowResult {
- app_name: "Safari".to_string(),
- window_name: "Google Maps".to_string(),
- ocr_text: "San Francisco CA directions".to_string(),
- },
- ],
+ windows: vec![WindowResult {
+ app_name: "Safari".to_string(),
+ window_name: "Google Maps".to_string(),
+ ocr_text: "San Francisco CA directions".to_string(),
+ }],
};
println!("\nCapture cycle 3: Safari visible");
let frame_ids_3 = process_capture_cycle_buggy(&capture3, &mut video, &mut db);
println!(" Video frames written: {}", video.frame_count());
- println!(" DB records created: {} (frame_ids: {:?})", frame_ids_3.len(), frame_ids_3);
+ println!(
+ " DB records created: {} (frame_ids: {:?})",
+ frame_ids_3.len(),
+ frame_ids_3
+ );
// Now let's see the mismatch
println!("\n=== Checking for mismatches ===\n");
@@ -199,11 +209,17 @@ fn test_bug_frame_window_mismatch() {
if let Some(content) = video_frame {
if !matches {
- println!(" MISMATCH! DB says '{}' but video shows: '{}'", record.app_name, content);
+ println!(
+ " MISMATCH! DB says '{}' but video shows: '{}'",
+ record.app_name, content
+ );
mismatches += 1;
}
} else {
- println!(" MISMATCH! No video frame at offset {}", record.offset_index);
+ println!(
+ " MISMATCH! No video frame at offset {}",
+ record.offset_index
+ );
mismatches += 1;
}
}
@@ -259,16 +275,26 @@ fn test_fix_one_db_record_per_capture_cycle() {
let capture1 = CaptureResult {
full_screen_content: "Screen: WezTerm + Arc".to_string(),
windows: vec![
- WindowResult { app_name: "WezTerm".to_string(), window_name: "code".to_string(), ocr_text: "code".to_string() },
- WindowResult { app_name: "Arc".to_string(), window_name: "GitHub".to_string(), ocr_text: "github".to_string() },
+ WindowResult {
+ app_name: "WezTerm".to_string(),
+ window_name: "code".to_string(),
+ ocr_text: "code".to_string(),
+ },
+ WindowResult {
+ app_name: "Arc".to_string(),
+ window_name: "GitHub".to_string(),
+ ocr_text: "github".to_string(),
+ },
],
};
let capture2 = CaptureResult {
full_screen_content: "Screen: Finder".to_string(),
- windows: vec![
- WindowResult { app_name: "Finder".to_string(), window_name: "Documents".to_string(), ocr_text: "docs".to_string() },
- ],
+ windows: vec![WindowResult {
+ app_name: "Finder".to_string(),
+ window_name: "Documents".to_string(),
+ ocr_text: "docs".to_string(),
+ }],
};
process_capture_fixed(&capture1);
diff --git a/screenpipe-vision/tests/url_timing_test.rs b/screenpipe-vision/tests/url_timing_test.rs
index 1b921afb6..a6b1693e8 100644
--- a/screenpipe-vision/tests/url_timing_test.rs
+++ b/screenpipe-vision/tests/url_timing_test.rs
@@ -49,7 +49,10 @@ impl MockBrowser {
async fn capture_frame_current_buggy_behavior(browser: Arc<MockBrowser>) -> (String, String) {
// Step 1: Capture screenshot - this is what the user SEES in the frame
let url_visible_in_screenshot = browser.get_current_url();
- let screenshot_content = format!("Screenshot showing content from: {}", url_visible_in_screenshot);
+ let screenshot_content = format!(
+ "Screenshot showing content from: {}",
+ url_visible_in_screenshot
+ );
// Step 2: Simulate the async delay that exists in current code:
// - OCR processing happens
@@ -132,8 +135,7 @@ async fn test_bug_url_mismatch_when_browser_navigates_during_capture() {
Associated URL: {}\n\n\
The screenshot shows content from a different URL than what's stored in metadata.\n\
This is the root cause of the 'wrong URL associated with frame' bug.\n",
- screenshot,
- associated_url
+ screenshot, associated_url
);
}