YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix: handle channel lag and improve error handling
Louis Beaumont383ff96fc9c5
diff --git a/.claude/agents/sentry.md b/.claude/agents/sentry.mdindex 30cbac2f6..e2421e989 100644--- a/.claude/agents/sentry.md+++ b/.claude/agents/sentry.md@@ -17,7 +17,15 @@ Query Sentry issues for Screenpipe applications.- `screenpipe-ai-proxy` - AI proxy service- Other projects may exist - list them with the projects query-**Credentials:** Read `SENTRY_AUTH_TOKEN` from environment variable+**Credentials:** Read `SENTRY_AUTH_TOKEN` from `.env.local`++### Loading the Token++**IMPORTANT:** Before running any Sentry query, first load the token from `.env.local`:++```bash+export SENTRY_AUTH_TOKEN=$(grep SENTRY_AUTH_TOKEN /Users/louisbeaumont/Documents/screenpipe/.env.local | cut -d'=' -f2)+```### Getting a Sentry Auth Tokendiff --git a/screenpipe-audio/src/core/run_record_and_transcribe.rs b/screenpipe-audio/src/core/run_record_and_transcribe.rsindex 46989e996..1f1f4bcbd 100644--- a/screenpipe-audio/src/core/run_record_and_transcribe.rs+++ b/screenpipe-audio/src/core/run_record_and_transcribe.rs@@ -7,6 +7,7 @@ use std::{};use anyhow::{anyhow, Result};+use tokio::sync::broadcast;use tracing::{debug, error, info, warn};use crate::{core::update_device_capture_time, AudioInput};@@ -44,6 +45,15 @@ pub async fn run_record_and_transcribe(collected_audio.extend(chunk);update_device_capture_time(&device_name);}+ Err(broadcast::error::RecvError::Lagged(n)) => {+ // Channel buffer overflow - receiver fell behind producer+ // This is expected under heavy load, continue instead of failing+ warn!(+ "audio channel lagged by {} messages for {}, continuing",+ n, device_name+ );+ continue;+ }Err(e) => {error!("error receiving audio data: {}", e);return Err(anyhow!("Audio stream error: {}", e));diff --git a/screenpipe-audio/tests/channel_lag_test.rs b/screenpipe-audio/tests/channel_lag_test.rsnew file mode 100644index 000000000..1c0a4968c--- /dev/null+++ b/screenpipe-audio/tests/channel_lag_test.rs@@ -0,0 +1,151 @@+use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};+use std::sync::Arc;+use std::time::Duration;+use tokio::sync::broadcast;++/// Test that reproduces the "channel lagged" error from Sentry+/// Issue: SCREENPIPE-CLI-22 - "error receiving audio data: channel lagged by 214"+///+/// The broadcast channel with capacity 1000 returns RecvError::Lagged when+/// the receiver falls behind. Currently this causes the entire recording to fail.+#[tokio::test]+async fn test_broadcast_channel_lag_causes_error() {+ // Create a broadcast channel with small capacity to trigger lag quickly+ let (tx, mut rx) = broadcast::channel::<Vec<f32>>(10);++ // Simulate fast producer (audio input) - send more messages than buffer can hold+ for i in 0..20 {+ let chunk = vec![i as f32; 100];+ let _ = tx.send(chunk);+ }++ // Now try to receive - this should return Lagged error+ let result = rx.recv().await;++ match result {+ Err(broadcast::error::RecvError::Lagged(n)) => {+ println!("Received expected Lagged error: {} messages skipped", n);+ // This is the current behavior that causes the recording to restart+ assert!(n > 0, "Should have lagged by at least 1 message");+ }+ Ok(_) => {+ panic!("Expected Lagged error but got Ok");+ }+ Err(broadcast::error::RecvError::Closed) => {+ panic!("Expected Lagged error but channel was closed");+ }+ }+}++/// Test that demonstrates the fix: handle Lagged error gracefully+/// Instead of terminating, we should continue receiving after lag+#[tokio::test]+async fn test_broadcast_channel_lag_recovery() {+ let (tx, mut rx) = broadcast::channel::<Vec<f32>>(10);+ let received_count = Arc::new(AtomicU32::new(0));+ let lag_count = Arc::new(AtomicU32::new(0));++ // Send 25 messages (more than buffer size of 10)+ for i in 0..25 {+ let chunk = vec![i as f32; 100];+ let _ = tx.send(chunk);+ }++ // Try to receive with graceful lag handling+ loop {+ match rx.recv().await {+ Ok(chunk) => {+ received_count.fetch_add(1, Ordering::Relaxed);+ // Successfully received a chunk after potential lag+ }+ Err(broadcast::error::RecvError::Lagged(n)) => {+ lag_count.fetch_add(1, Ordering::Relaxed);+ println!("Lagged by {} messages, continuing...", n);+ // Key fix: continue instead of returning error+ continue;+ }+ Err(broadcast::error::RecvError::Closed) => {+ break;+ }+ }++ // Stop after receiving some messages+ if received_count.load(Ordering::Relaxed) >= 5 {+ break;+ }+ }++ let received = received_count.load(Ordering::Relaxed);+ let lagged = lag_count.load(Ordering::Relaxed);++ println!(+ "Received {} messages, experienced {} lag events",+ received, lagged+ );++ // With graceful handling, we should have received some messages despite lag+ assert!(received > 0, "Should have received at least some messages");+ assert!(lagged > 0, "Should have experienced at least one lag event");+}++/// Test simulating real audio recording scenario with slow consumer+#[tokio::test]+async fn test_slow_consumer_causes_lag() {+ let (tx, mut rx) = broadcast::channel::<Vec<f32>>(100);+ let is_running = Arc::new(AtomicBool::new(true));+ let is_running_producer = is_running.clone();+ let lag_detected = Arc::new(AtomicBool::new(false));+ let lag_detected_clone = lag_detected.clone();++ // Producer: simulates fast audio input (~44100 samples/sec in chunks)+ let producer = tokio::spawn(async move {+ for i in 0..200 {+ if !is_running_producer.load(Ordering::Relaxed) {+ break;+ }+ let chunk = vec![0.0f32; 1024]; // ~23ms of audio at 44.1kHz+ let _ = tx.send(chunk);+ // Audio comes in faster than we process+ tokio::time::sleep(Duration::from_micros(100)).await;+ }+ });++ // Consumer: simulates slow transcription processing+ let consumer = tokio::spawn(async move {+ let mut received = 0;+ loop {+ match rx.recv().await {+ Ok(_chunk) => {+ received += 1;+ // Simulate slow processing (transcription takes time)+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ Err(broadcast::error::RecvError::Lagged(n)) => {+ println!("Consumer lagged by {} chunks at message {}", n, received);+ lag_detected_clone.store(true, Ordering::Relaxed);+ // With fix: continue instead of failing+ continue;+ }+ Err(broadcast::error::RecvError::Closed) => {+ break;+ }+ }++ if received >= 10 {+ break;+ }+ }+ received+ });++ let _ = producer.await;+ is_running.store(false, Ordering::Relaxed);+ let received = consumer.await.unwrap();++ println!("Consumer received {} chunks", received);+ assert!(+ lag_detected.load(Ordering::Relaxed),+ "Slow consumer should have experienced lag"+ );+ assert!(received > 0, "Should have received some chunks despite lag");+}diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex 18ad773bb..73d852e98 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -370,6 +370,15 @@ pub async fn start_ffmpeg_process(output_file: &str, fps: f64) -> Result<Child,"23",]);+ // Use fragmented MP4 to allow reading frames while file is still being written+ // 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(&["-pix_fmt", "yuv420p", output_file]);commanddiff --git a/screenpipe-server/tests/frame_extraction_test.rs b/screenpipe-server/tests/frame_extraction_test.rsnew file mode 100644index 000000000..7b35bd8d8--- /dev/null+++ b/screenpipe-server/tests/frame_extraction_test.rs@@ -0,0 +1,473 @@+use std::process::Stdio;+use std::time::Duration;+use tempfile::TempDir;+use tokio::io::AsyncWriteExt;+use tokio::process::Command;++/// Test that reproduces the "moov atom not found" error from Sentry+/// Issue: SCREENPIPE-CLI-D, SCREENPIPE-CLI-X, SCREENPIPE-CLI-T+///+/// Root cause: User requests frame from video file that's still being written.+/// MP4 files have the moov atom (index/metadata) at the END, so incomplete+/// files cannot be read by ffmpeg.++/// Helper to find ffmpeg path+fn find_ffmpeg() -> String {+ // Try common locations+ for path in &[+ "/opt/homebrew/bin/ffmpeg",+ "/usr/local/bin/ffmpeg",+ "/usr/bin/ffmpeg",+ "ffmpeg",+ ] {+ if std::process::Command::new(path)+ .arg("-version")+ .output()+ .is_ok()+ {+ return path.to_string();+ }+ }+ "ffmpeg".to_string()+}++/// Simulate creating an incomplete MP4 file (still being written)+async fn create_incomplete_mp4(path: &str) -> Result<tokio::process::Child, std::io::Error> {+ let ffmpeg = find_ffmpeg();++ // Start ffmpeg process that reads from stdin (simulating live encoding)+ // This creates an MP4 file without a moov atom until the process finishes+ let child = Command::new(&ffmpeg)+ .args([+ "-f",+ "lavfi",+ "-i",+ "testsrc=duration=10:size=320x240:rate=1", // 10 second test pattern+ "-c:v",+ "libx264",+ "-preset",+ "ultrafast",+ "-t",+ "10",+ "-y",+ path,+ ])+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()?;++ Ok(child)+}++/// Try to extract a frame from a video file+async fn extract_frame(video_path: &str, output_path: &str) -> Result<(), String> {+ let ffmpeg = find_ffmpeg();++ let output = Command::new(&ffmpeg)+ .args([+ "-ss",+ "0",+ "-i",+ video_path,+ "-vframes",+ "1",+ "-y",+ output_path,+ ])+ .output()+ .await+ .map_err(|e| e.to_string())?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ return Err(stderr.to_string());+ }++ if !std::path::Path::new(output_path).exists() {+ return Err("file not created".to_string());+ }++ Ok(())+}++/// Test: Extracting frame from incomplete MP4 fails with "moov atom not found"+#[tokio::test]+async fn test_incomplete_mp4_causes_moov_error() {+ let temp_dir = TempDir::new().unwrap();+ let video_path = temp_dir.path().join("test_incomplete.mp4");+ let video_path_str = video_path.to_str().unwrap();++ // Create an incomplete MP4 by writing partial data+ // Simulate what happens when ffmpeg is still encoding+ {+ let mut file = tokio::fs::File::create(&video_path).await.unwrap();+ // Write some bytes that look like an MP4 header but are incomplete+ // ftyp box (file type) - valid MP4 files start with this+ file.write_all(&[+ 0x00, 0x00, 0x00, 0x18, // box size+ 0x66, 0x74, 0x79, 0x70, // 'ftyp'+ 0x69, 0x73, 0x6F, 0x6D, // 'isom'+ 0x00, 0x00, 0x00, 0x01, // minor version+ 0x69, 0x73, 0x6F, 0x6D, // compatible brand 'isom'+ 0x61, 0x76, 0x63, 0x31, // compatible brand 'avc1'+ ])+ .await+ .unwrap();+ // Don't write moov atom - this is what happens during active recording+ file.flush().await.unwrap();+ }++ // Try to extract a frame - this should fail+ 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_err(), "Should fail on incomplete MP4");+ let error = result.unwrap_err();+ println!("Error message: {}", error);++ // The error should mention moov atom or invalid data+ assert!(+ error.contains("moov atom not found")+ || error.contains("Invalid data")+ || error.contains("could not find codec"),+ "Expected moov-related error, got: {}",+ error+ );+}++/// Test: Extracting frame from complete MP4 succeeds+#[tokio::test]+#[ignore] // Requires ffmpeg and takes time+async fn test_complete_mp4_extraction_succeeds() {+ let temp_dir = TempDir::new().unwrap();+ let video_path = temp_dir.path().join("test_complete.mp4");+ let video_path_str = video_path.to_str().unwrap();++ // Create a complete, valid MP4 file+ let ffmpeg = find_ffmpeg();+ let output = Command::new(&ffmpeg)+ .args([+ "-f",+ "lavfi",+ "-i",+ "testsrc=duration=2:size=320x240:rate=1",+ "-c:v",+ "libx264",+ "-preset",+ "ultrafast",+ "-y",+ video_path_str,+ ])+ .output()+ .await+ .expect("ffmpeg should run");++ assert!(output.status.success(), "ffmpeg should succeed");+ assert!(video_path.exists(), "Video file should exist");++ // Wait for file to be fully written+ tokio::time::sleep(Duration::from_millis(100)).await;++ // Extract frame - should succeed+ 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!(frame_path.exists(), "Frame file should exist");+}++/// Test: Fragmented MP4 allows frame extraction during recording+/// This is the FIX for the moov atom issue - using -movflags frag_keyframe+empty_moov+#[tokio::test]+#[ignore] // Requires ffmpeg+async fn test_fragmented_mp4_allows_extraction_during_write() {+ let temp_dir = TempDir::new().unwrap();+ let video_path = temp_dir.path().join("test_fragmented.mp4");+ let video_path_str = video_path.to_str().unwrap().to_string();++ // Start ffmpeg with fragmented MP4 flags (same as our fix)+ let ffmpeg = find_ffmpeg();+ let mut child = Command::new(&ffmpeg)+ .args([+ "-f",+ "lavfi",+ "-i",+ "testsrc=duration=5:size=320x240:rate=1",+ "-c:v",+ "libx264", // Use x264 for faster test+ "-preset",+ "ultrafast",+ // THE FIX: fragmented MP4 flags+ "-movflags",+ "frag_keyframe+empty_moov+default_base_moof",+ "-y",+ &video_path_str,+ ])+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .expect("ffmpeg should start");++ // Wait a bit for file to be created and some data written+ tokio::time::sleep(Duration::from_millis(1500)).await;++ // Try to extract frame WHILE recording is in progress+ let frame_path = temp_dir.path().join("frame_during.jpg");+ let frame_path_str = frame_path.to_str().unwrap();++ if video_path.exists() {+ let result = extract_frame(&video_path_str, frame_path_str).await;+ println!("Extraction during fragmented recording: {:?}", result);++ // With fragmented MP4, this SHOULD succeed!+ if result.is_ok() {+ println!("SUCCESS: Frame extracted during recording with fragmented MP4!");+ assert!(+ std::path::Path::new(frame_path_str).exists(),+ "Frame file should exist"+ );+ } else {+ // May still fail if not enough data written yet, but shouldn't be moov error+ let err = result.unwrap_err();+ println!("Extraction failed (may be timing): {}", err);+ assert!(+ !err.contains("moov atom not found"),+ "Should NOT get moov atom error with fragmented MP4"+ );+ }+ }++ // Wait for recording to finish+ let _ = child.wait_with_output().await;++ // After recording, extraction should definitely work+ let frame_path_after = temp_dir.path().join("frame_after.jpg");+ let result = extract_frame(&video_path_str, frame_path_after.to_str().unwrap()).await;+ assert!(+ result.is_ok(),+ "Should succeed after recording: {:?}",+ result+ );+}++/// Test: Compare regular MP4 vs fragmented MP4 behavior+#[tokio::test]+#[ignore] // Requires ffmpeg+async fn test_regular_vs_fragmented_mp4() {+ let temp_dir = TempDir::new().unwrap();+ let ffmpeg = find_ffmpeg();++ // Create regular MP4 (will have moov at end)+ 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",+ "-y",+ regular_path.to_str().unwrap(),+ ])+ .output()+ .await+ .unwrap();+ assert!(regular_output.status.success());++ // Create fragmented MP4 (moov at start)+ 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",+ "-y",+ frag_path.to_str().unwrap(),+ ])+ .output()+ .await+ .unwrap();+ assert!(frag_output.status.success());++ // Both should allow frame extraction when complete+ let frame1 = temp_dir.path().join("frame1.jpg");+ let frame2 = temp_dir.path().join("frame2.jpg");++ 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);++ // Check file sizes - fragmented may be slightly larger+ let regular_size = std::fs::metadata(®ular_path).unwrap().len();+ let frag_size = std::fs::metadata(&frag_path).unwrap().len();++ println!("Regular MP4 size: {} bytes", regular_size);+ println!("Fragmented MP4 size: {} bytes", frag_size);+ println!(+ "Size difference: {:.1}%",+ ((frag_size as f64 - regular_size as f64) / regular_size as f64) * 100.0+ );++ // Fragmented should not be more than 20% larger+ assert!(+ frag_size < regular_size * 2,+ "Fragmented MP4 should not be excessively larger"+ );+}++/// Test: Verify fragmented MP4 is playable and valid+#[tokio::test]+#[ignore] // Requires ffmpeg+async fn test_fragmented_mp4_is_valid() {+ let temp_dir = TempDir::new().unwrap();+ let video_path = temp_dir.path().join("valid_frag.mp4");+ let video_path_str = video_path.to_str().unwrap();++ let ffmpeg = find_ffmpeg();++ // 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",+ "-y",+ video_path_str,+ ])+ .output()+ .await+ .unwrap();++ assert!(output.status.success(), "ffmpeg encoding should succeed");++ // Verify file is valid using ffprobe+ let ffprobe_path = std::path::Path::new(&ffmpeg)+ .parent()+ .unwrap()+ .join("ffprobe");+ let ffprobe = if ffprobe_path.exists() {+ ffprobe_path.to_str().unwrap().to_string()+ } else {+ "ffprobe".to_string()+ };++ let probe_output = Command::new(&ffprobe)+ .args([+ "-v", "error",+ "-select_streams", "v:0",+ "-show_entries", "stream=codec_name,width,height,duration",+ "-of", "json",+ video_path_str,+ ])+ .output()+ .await+ .unwrap();++ assert!(+ probe_output.status.success(),+ "ffprobe should succeed on fragmented MP4"+ );++ let probe_stdout = String::from_utf8_lossy(&probe_output.stdout);+ println!("ffprobe output: {}", probe_stdout);++ // Verify it's H.265+ assert!(+ probe_stdout.contains("hevc") || probe_stdout.contains("h265"),+ "Should be H.265 encoded"+ );++ // Extract multiple frames to verify seekability+ for i in 0..3 {+ let frame_path = temp_dir.path().join(format!("frame_{}.jpg", i));+ let seek_time = format!("{}", i as f64 * 0.1);++ let extract_output = Command::new(&ffmpeg)+ .args([+ "-ss", &seek_time,+ "-i", video_path_str,+ "-vframes", "1",+ "-y",+ frame_path.to_str().unwrap(),+ ])+ .output()+ .await+ .unwrap();++ assert!(+ extract_output.status.success(),+ "Frame {} extraction should succeed",+ i+ );+ assert!(frame_path.exists(), "Frame {} file should exist", i);+ }++ println!("All frame extractions succeeded - fragmented MP4 is valid and seekable");+}++/// Test: Simulating the race condition - file registered before complete+#[tokio::test]+#[ignore] // Requires ffmpeg and demonstrates timing issue+async fn test_race_condition_during_recording() {+ let temp_dir = TempDir::new().unwrap();+ let video_path = temp_dir.path().join("test_race.mp4");+ let video_path_str = video_path.to_str().unwrap().to_string();+ let frame_path = temp_dir.path().join("frame.jpg");+ let frame_path_str = frame_path.to_str().unwrap().to_string();++ // Start ffmpeg encoding (simulates video recording)+ let ffmpeg = find_ffmpeg();+ let mut child = Command::new(&ffmpeg)+ .args([+ "-f",+ "lavfi",+ "-i",+ "testsrc=duration=5:size=320x240:rate=1", // 5 second video+ "-c:v",+ "libx264",+ "-preset",+ "ultrafast",+ "-y",+ &video_path_str,+ ])+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .expect("ffmpeg should start");++ // Immediately try to extract frame (simulates user clicking on timeline)+ // This is the race condition - file exists but moov atom not written yet+ tokio::time::sleep(Duration::from_millis(500)).await; // Wait for file to be created++ if video_path.exists() {+ let result = extract_frame(&video_path_str, &frame_path_str).await;+ println!("Extraction during recording: {:?}", result);++ // This SHOULD fail because recording is in progress+ // (may or may not fail depending on timing and ffmpeg buffering)+ if result.is_err() {+ println!("Expected failure during recording: {}", result.unwrap_err());+ }+ }++ // Wait for recording to finish+ let output = child.wait_with_output().await.unwrap();+ assert!(output.status.success(), "Recording should complete");++ // Now extraction should succeed+ let result = extract_frame(&video_path_str, &frame_path_str).await;+ assert!(+ result.is_ok(),+ "Should succeed after recording completes: {:?}",+ result+ );+}diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rsindex fd3fe08f8..b8834a8cf 100644--- a/screenpipe-vision/src/capture_screenshot_by_window.rs+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs@@ -28,7 +28,8 @@ impl Error for CaptureError {}impl From<XCapError> for CaptureError {fn from(error: XCapError) -> Self {- error!("XCap error occurred: {}", error);+ // XCap errors are often expected (system windows, protected content)+ debug!("XCap error occurred: {}", error);CaptureError::XCapError(error)}}@@ -46,6 +47,9 @@ static SKIP_APPS: Lazy<HashSet<&'static str>> = Lazy::new(|| {"WindowManager","Contexts","Screenshot",+ // Apps with overlay windows that frequently fail capture+ "TheBoringNotch",+ "Grammarly Desktop",])});@@ -214,7 +218,8 @@ pub async fn capture_all_visible_windows(let title = match window.title() {Ok(title) => title.to_string(),Err(e) => {- error!("Failed to get title for window {}: {}", app_name, e);+ // Expected for some system/overlay windows+ debug!("Failed to get title for window {}: {}", app_name, e);return None;}};@@ -227,16 +232,16 @@ pub async fn capture_all_visible_windows(}}Err(e) => {- // Log warning and skip this window- // mostly noise- error!("Failed to get is_minimized for window {}: {}", app_name, e);+ // Expected for some system/overlay windows - not a real error+ debug!("Failed to get is_minimized for window {}: {}", app_name, e);}};let is_focused = match window.is_focused() {Ok(focused) => focused,Err(e) => {- error!(+ // Expected for overlay/system windows+ debug!("Failed to get focus state for window {} ({}): {}",app_name, title, e);@@ -247,7 +252,8 @@ pub async fn capture_all_visible_windows(let process_id = match window.pid() {Ok(pid) => pid as i32,Err(e) => {- error!(+ // Expected for some protected/system processes+ debug!("Failed to get process ID for window {} ({}): {}",app_name, title, e);@@ -259,7 +265,8 @@ pub async fn capture_all_visible_windows(match window.capture_image() {Ok(buffer) => Some((app_name, title, is_focused, buffer, process_id)),Err(e) => {- error!(+ // Expected for overlay windows, protected content, or transparent windows+ debug!("Failed to capture image for window {} ({}): {}",app_name, title, e);diff --git a/screenpipe-vision/tests/capture_error_test.rs b/screenpipe-vision/tests/capture_error_test.rsnew file mode 100644index 000000000..606bcec83--- /dev/null+++ b/screenpipe-vision/tests/capture_error_test.rs@@ -0,0 +1,178 @@+use std::collections::HashSet;++/// Test demonstrating window capture error scenarios+/// Related Sentry issues:+/// - SCREENPIPE-CLI-1Z: "Failed to capture image for window TheBoringNotch"+/// - SCREENPIPE-CLI-1Y: "Failed to capture image for window Grammarly Desktop"+/// - SCREENPIPE-CLI-2: "GetFileVersionInfoSizeW failed: WIN32_ERROR(1813)"+///+/// These errors are expected for certain system/overlay windows and should+/// be logged at debug level, not error level.++/// Test that SKIP_APPS contains expected system apps that can't be captured+#[test]+fn test_skip_apps_contains_system_windows() {+ #[cfg(target_os = "macos")]+ {+ let skip_apps: HashSet<&str> = HashSet::from([+ "Window Server",+ "SystemUIServer",+ "ControlCenter",+ "Dock",+ "NotificationCenter",+ "loginwindow",+ "WindowManager",+ "Contexts",+ "Screenshot",+ ]);++ // These are known to fail capture - should be in skip list+ assert!(skip_apps.contains("Window Server"));+ assert!(skip_apps.contains("Dock"));+ assert!(skip_apps.contains("NotificationCenter"));+ }++ #[cfg(target_os = "windows")]+ {+ let skip_apps: HashSet<&str> = HashSet::from([+ "Windows Shell Experience Host",+ "Microsoft Text Input Application",+ "Windows Explorer",+ "Program Manager",+ "Microsoft Store",+ "Search",+ "TaskBar",+ ]);++ assert!(skip_apps.contains("Program Manager"));+ assert!(skip_apps.contains("TaskBar"));+ }+}++/// Test that problematic apps from Sentry are identified+/// These apps were causing errors in production and should be added to skip list+#[test]+fn test_problematic_apps_should_be_skipped() {+ // Apps that frequently fail capture (from Sentry errors)+ let problematic_apps = vec![+ "TheBoringNotch", // macOS notch overlay app+ "Grammarly Desktop", // Overlay/tooltip windows+ "Omi录屏专家", // Chinese screen recorder with overlay+ ];++ #[cfg(target_os = "macos")]+ {+ let current_skip_apps: HashSet<&str> = HashSet::from([+ "Window Server",+ "SystemUIServer",+ "ControlCenter",+ "Dock",+ "NotificationCenter",+ "loginwindow",+ "WindowManager",+ "Contexts",+ "Screenshot",+ ]);++ // Check which problematic apps are NOT in the skip list+ // These should be added+ for app in &problematic_apps {+ if !current_skip_apps.contains(*app) {+ println!("MISSING from SKIP_APPS: {} - should be added", app);+ }+ }++ let _ = current_skip_apps; // silence unused warning on other platforms+ }++ // This test documents apps that should be added to SKIP_APPS+ // The actual assertion is that we've identified them+ assert!(!problematic_apps.is_empty());+}++/// Test that window filtering logic works correctly+#[test]+fn test_window_filter_logic() {+ struct WindowFilters {+ ignore_set: HashSet<String>,+ include_set: HashSet<String>,+ }++ impl WindowFilters {+ fn new(ignore_list: &[String], include_list: &[String]) -> Self {+ Self {+ ignore_set: ignore_list.iter().map(|s| s.to_lowercase()).collect(),+ include_set: include_list.iter().map(|s| s.to_lowercase()).collect(),+ }+ }++ fn is_valid(&self, app_name: &str, title: &str) -> bool {+ let app_name_lower = app_name.to_lowercase();+ let title_lower = title.to_lowercase();++ if self.include_set.is_empty() {+ return true;+ }++ if self+ .include_set+ .iter()+ .any(|include| app_name_lower.contains(include) || title_lower.contains(include))+ {+ return true;+ }++ if !self.ignore_set.is_empty()+ && self+ .ignore_set+ .iter()+ .any(|ignore| app_name_lower.contains(ignore) || title_lower.contains(ignore))+ {+ return false;+ }++ false+ }+ }++ // Test with empty lists (should allow all)+ let filters = WindowFilters::new(&[], &[]);+ assert!(filters.is_valid("Chrome", "Google"));++ // Test with ignore list+ let filters = WindowFilters::new(&["grammarly".to_string()], &[]);+ // Empty include list means is_valid returns true (line 165-167 in source)+ assert!(filters.is_valid("Grammarly Desktop", "Writing Assistant"));++ // Test with include list only+ let filters = WindowFilters::new(&[], &["chrome".to_string()]);+ assert!(filters.is_valid("Chrome", "Google"));+ assert!(!filters.is_valid("Firefox", "Mozilla"));+}++/// Verify error log level expectations+/// Current: error!() - causes noise in Sentry+/// Expected: debug!() - reduces noise, these are expected failures+#[test]+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"),+ ("GetModuleBaseNameW", "Protected processes deny access"),+ ];++ for (error_pattern, reason) in &expected_failure_scenarios {+ println!(+ "Expected failure: '{}' - Reason: {}",+ error_pattern, reason+ );+ println!(" -> Should be logged at DEBUG level, not ERROR");+ }++ // This test documents that these are expected failures+ assert_eq!(expected_failure_scenarios.len(), 6);+}