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

release-app fix #1603

Louis Beaumont848d6b7c69f4
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 379f5a090..2a9476fd7 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.42.2"
+version = "0.42.3"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index d4f05d3ed..e75866569 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -10,7 +10,7 @@ use screenpipe_vision::OcrEngine;
use std::sync::Arc;
use std::time::Duration;
use tokio::runtime::Handle;
-use tracing::{debug, error, warn};
+use tracing::{debug, error, info, warn};
#[allow(clippy::too_many_arguments)]
pub async fn start_continuous_recording(
@@ -29,7 +29,7 @@ pub async fn start_continuous_recording(
capture_unfocused_windows: bool,
realtime_vision: bool,
) -> Result<()> {
- debug!("Starting video recording for monitor {:?}", monitor_ids);
+ info!("Starting video recording for monitors {:?}", monitor_ids);
let video_tasks = if !vision_disabled {
monitor_ids
.iter()
@@ -42,36 +42,56 @@ pub async fn start_continuous_recording(
let languages = languages.clone();
- debug!("Starting video recording for monitor {}", monitor_id);
+ info!("Starting video recording for monitor {}", monitor_id);
vision_handle.spawn(async move {
- record_video(
- db_manager_video,
- output_path_video,
- fps,
- ocr_engine,
- monitor_id,
- use_pii_removal,
- &ignored_windows_video,
- &include_windows_video,
- video_chunk_duration,
- languages.clone(),
- capture_unfocused_windows,
- realtime_vision,
- )
- .await
+ // Wrap in a loop with recovery logic
+ loop {
+ info!("Starting/restarting vision capture for monitor {}", monitor_id);
+ match record_video(
+ db_manager_video.clone(),
+ output_path_video.clone(),
+ fps,
+ ocr_engine.clone(),
+ monitor_id,
+ use_pii_removal,
+ &ignored_windows_video,
+ &include_windows_video,
+ video_chunk_duration,
+ languages.clone(),
+ capture_unfocused_windows,
+ realtime_vision,
+ )
+ .await
+ {
+ Ok(_) => {
+ warn!("record_video for monitor {} completed unexpectedly but without error", monitor_id);
+ // Short delay before restarting to prevent CPU spinning
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ }
+ Err(e) => {
+ error!("record_video for monitor {} failed with error: {}", monitor_id, e);
+ // Short delay before restarting to prevent CPU spinning
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ }
+ }
+ }
})
})
.collect::<Vec<_>>()
} else {
vec![vision_handle.spawn(async move {
tokio::time::sleep(Duration::from_secs(60)).await;
- Ok(())
+ Ok::<(), anyhow::Error>(())
})]
};
if !vision_disabled {
vision_handle.spawn(async move {
- let _ = poll_meetings_events().await;
+ info!("Starting meeting events polling");
+ match poll_meetings_events().await {
+ Ok(_) => warn!("Meeting events polling completed unexpectedly"),
+ Err(e) => error!("Meeting events polling failed: {}", e),
+ }
});
}
@@ -105,34 +125,40 @@ async fn record_video(
capture_unfocused_windows: bool,
realtime_vision: bool,
) -> Result<()> {
- debug!("record_video: Starting for monitor {}", monitor_id);
- let db_chunk_callback = Arc::clone(&db);
- let rt = Handle::current();
+ info!("record_video: Starting for monitor {}", monitor_id);
let device_name = Arc::new(format!("monitor_{}", monitor_id));
// Add heartbeat counter
let mut heartbeat_counter: u64 = 0;
let heartbeat_interval = 100; // Log every 100 iterations
+ let db_health_check_interval = 1000; // Check DB health every 1000 iterations
+ let start_time = std::time::Instant::now();
+
+ // Add health check interval
+ let health_check_interval = 500; // Check task health every 500 iterations
+ // Define a simpler callback that just returns the file path
let new_chunk_callback = {
- let db_chunk_callback = Arc::clone(&db_chunk_callback);
- let device_name = Arc::clone(&device_name);
+ let db_clone = Arc::clone(&db);
+ let device_name_clone = Arc::clone(&device_name);
move |file_path: &str| {
let file_path = file_path.to_string();
- let db_chunk_callback = Arc::clone(&db_chunk_callback);
- let device_name = Arc::clone(&device_name);
- rt.spawn(async move {
- if let Err(e) = db_chunk_callback
- .insert_video_chunk(&file_path, &device_name)
- .await
- {
+ let db = Arc::clone(&db_clone);
+ let device_name = Arc::clone(&device_name_clone);
+
+ // Just spawn the task directly
+ tokio::spawn(async move {
+ debug!("Inserting new video chunk: {}", file_path);
+ if let Err(e) = db.insert_video_chunk(&file_path, &device_name).await {
error!("Failed to insert new video chunk: {}", e);
+ } else {
+ debug!("Successfully inserted video chunk: {}", file_path);
}
- debug!("record_video: Inserted new video chunk: {}", file_path);
});
}
};
+ info!("Creating VideoCapture for monitor {}", monitor_id);
let video_capture = VideoCapture::new(
&output_path,
fps,
@@ -146,23 +172,72 @@ async fn record_video(
capture_unfocused_windows,
);
+ info!(
+ "Starting main video processing loop for monitor {}",
+ monitor_id
+ );
+ let mut last_frame_time = std::time::Instant::now();
+ let mut frames_processed = 0;
+
+ // Keep count of consecutive errors to detect unhealthy state
+ let mut consecutive_db_errors = 0;
+ const MAX_CONSECUTIVE_DB_ERRORS: u32 = 100; // Threshold before reporting unhealthy state
+
loop {
// Increment and check heartbeat
heartbeat_counter += 1;
if heartbeat_counter % heartbeat_interval == 0 {
+ let uptime = start_time.elapsed().as_secs();
+ let frames_per_sec = if uptime > 0 {
+ frames_processed as f64 / uptime as f64
+ } else {
+ 0.0
+ };
+ info!(
+ "record_video: Heartbeat for monitor {} - iteration {}, uptime: {}s, frames processed: {}, frames/sec: {:.2}",
+ monitor_id, heartbeat_counter, uptime, frames_processed, frames_per_sec
+ );
+ }
+
+ // Periodically check database health
+ if heartbeat_counter % db_health_check_interval == 0 {
+ debug!("Checking database health for monitor {}", monitor_id);
+ // Just log that we're checking the DB health
+ debug!("Database health check periodic reminder");
+ // We'll rely on the actual DB operations during normal processing to detect issues
+ }
+
+ // In the try-catch block inside the loop, add health checks
+ if heartbeat_counter % health_check_interval == 0 {
debug!(
- "record_video: Heartbeat for monitor {} - iteration {}",
- monitor_id, heartbeat_counter
+ "Checking VideoCapture task health for monitor {}",
+ monitor_id
);
+ if !video_capture.check_health() {
+ error!(
+ "One or more VideoCapture tasks have terminated for monitor {}",
+ monitor_id
+ );
+ // Instead of immediately failing, log the error and continue
+ // This helps us diagnose which task is failing
+ }
}
if let Some(frame) = video_capture.ocr_frame_queue.pop() {
+ let time_since_last_frame = last_frame_time.elapsed();
+ last_frame_time = std::time::Instant::now();
+ frames_processed += 1;
+
debug!(
- "record_video: Processing frame with {} window results",
- frame.window_ocr_results.len()
+ "record_video: Processing frame {} with {} window results ({}ms since last frame)",
+ frames_processed,
+ frame.window_ocr_results.len(),
+ time_since_last_frame.as_millis()
);
+
for window_result in &frame.window_ocr_results {
- match db
+ let insert_frame_start = std::time::Instant::now();
+ let result = db
.insert_frame(
&device_name,
None,
@@ -171,9 +246,23 @@ async fn record_video(
Some(window_result.window_name.as_str()),
window_result.focused,
)
- .await
- {
+ .await;
+
+ let insert_duration = insert_frame_start.elapsed();
+ if insert_duration.as_millis() > 100 {
+ warn!(
+ "Slow DB insert_frame operation: {}ms",
+ insert_duration.as_millis()
+ );
+ }
+
+ match result {
Ok(frame_id) => {
+ debug!(
+ "Successfully inserted frame {} in {}ms",
+ frame_id,
+ insert_duration.as_millis()
+ );
let text_json =
serde_json::to_string(&window_result.text_json).unwrap_or_default();
@@ -184,7 +273,8 @@ async fn record_video(
};
if realtime_vision {
- let _ = send_event(
+ let send_event_start = std::time::Instant::now();
+ match send_event(
"ocr_result",
WindowOcr {
image: Some(frame.image.clone()),
@@ -197,8 +287,21 @@ async fn record_video(
timestamp: frame.timestamp,
browser_url: window_result.browser_url.clone(),
},
- );
+ ) {
+ Ok(_) => {
+ let event_duration = send_event_start.elapsed();
+ if event_duration.as_millis() > 100 {
+ warn!(
+ "Slow event sending: {}ms",
+ event_duration.as_millis()
+ );
+ }
+ }
+ Err(e) => error!("Failed to send OCR event: {}", e),
+ }
}
+
+ let insert_ocr_start = std::time::Instant::now();
if let Err(e) = db
.insert_ocr_text(
frame_id,
@@ -212,11 +315,27 @@ async fn record_video(
"Failed to insert OCR text: {}, skipping window {} of frame {}",
e, window_result.window_name, frame_id
);
+ consecutive_db_errors += 1;
continue;
+ } else {
+ let ocr_insert_duration = insert_ocr_start.elapsed();
+ if ocr_insert_duration.as_millis() > 100 {
+ warn!(
+ "Slow DB insert_ocr_text operation: {}ms",
+ ocr_insert_duration.as_millis()
+ );
+ }
+ consecutive_db_errors = 0; // Reset on success
+ debug!(
+ "OCR text inserted for frame {} in {}ms",
+ frame_id,
+ ocr_insert_duration.as_millis()
+ );
}
}
Err(e) => {
warn!("Failed to insert frame: {}", e);
+ consecutive_db_errors += 1;
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
}
@@ -231,6 +350,18 @@ async fn record_video(
);
}
}
+
+ // Check if we're seeing too many consecutive DB errors
+ if consecutive_db_errors > MAX_CONSECUTIVE_DB_ERRORS {
+ error!(
+ "Excessive consecutive database errors ({}), vision processing may be impaired",
+ consecutive_db_errors
+ );
+ // Instead of failing, we'll continue but log the issue clearly
+ consecutive_db_errors = 0; // Reset to prevent continuous error logging
+ }
+
+ // Sleep for the frame interval
tokio::time::sleep(Duration::from_secs_f64(1.0 / fps)).await;
}
}
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index 3da2bb434..5a60d2322 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -19,12 +19,16 @@ use tokio::time::sleep;
use tracing::{debug, error, info, warn};
pub(crate) const MAX_FPS: f64 = 30.0; // Adjust based on your needs
-const MAX_QUEUE_SIZE: usize = 10;
+const MAX_QUEUE_SIZE: usize = 30; // Increased from 10 for more buffer room
pub struct VideoCapture {
#[allow(unused)]
video_frame_queue: Arc<ArrayQueue<Arc<CaptureResult>>>,
pub ocr_frame_queue: Arc<ArrayQueue<Arc<CaptureResult>>>,
+ // Add handles to tasks so we can monitor their status
+ capture_thread_handle: tokio::task::JoinHandle<()>,
+ queue_thread_handle: tokio::task::JoinHandle<()>,
+ video_thread_handle: tokio::task::JoinHandle<()>,
}
impl VideoCapture {
@@ -53,13 +57,24 @@ impl VideoCapture {
let new_chunk_callback = Arc::new(new_chunk_callback);
let new_chunk_callback_clone = Arc::clone(&new_chunk_callback);
+ info!(
+ "Starting VideoCapture for monitor {}, max queue size: {}, fps: {}",
+ monitor_id, MAX_QUEUE_SIZE, fps
+ );
+
let capture_video_frame_queue = video_frame_queue.clone();
let capture_ocr_frame_queue = ocr_frame_queue.clone();
let (result_sender, mut result_receiver) = channel(512);
let window_filters = Arc::new(WindowFilters::new(ignore_list, include_list));
let window_filters_clone = Arc::clone(&window_filters);
- let _capture_thread = tokio::spawn(async move {
- continuous_capture(
+
+ // Store task handles for health monitoring
+ let capture_thread = tokio::spawn(async move {
+ info!(
+ "Starting continuous_capture task for monitor {}",
+ monitor_id
+ );
+ match continuous_capture(
result_sender,
interval,
(*ocr_engine).clone(),
@@ -68,11 +83,31 @@ impl VideoCapture {
languages.clone(),
capture_unfocused_windows,
)
- .await;
+ .await
+ {
+ Ok(_) => warn!(
+ "continuous_capture task for monitor {} completed unexpectedly",
+ monitor_id
+ ),
+ Err(e) => error!(
+ "continuous_capture task for monitor {} failed with error: {}",
+ monitor_id, e
+ ),
+ }
+ warn!(
+ "continuous_capture task terminated for monitor {}",
+ monitor_id
+ );
});
// In the _queue_thread
- let _queue_thread = tokio::spawn(async move {
+ let queue_thread = tokio::spawn(async move {
+ info!("Starting queue processing task for monitor {}", monitor_id);
+ let mut processed_count = 0;
+ let start_time = std::time::Instant::now();
+ let mut last_log_time = start_time;
+ let log_interval = Duration::from_secs(30); // Log stats every 30 seconds
+
// Helper function to push to queue and handle errors
fn push_to_queue(
queue: &ArrayQueue<Arc<CaptureResult>>,
@@ -80,6 +115,15 @@ impl VideoCapture {
queue_name: &str,
) -> bool {
if queue.push(Arc::clone(result)).is_err() {
+ if queue.len() >= queue.capacity() {
+ error!(
+ "{} queue is full ({}/{})",
+ queue_name,
+ queue.len(),
+ queue.capacity()
+ );
+ }
+
if queue.pop().is_none() {
error!("{} queue is in an inconsistent state", queue_name);
return false;
@@ -91,12 +135,38 @@ impl VideoCapture {
);
return false;
}
- debug!("{} queue was full, dropped oldest frame", queue_name);
+ debug!(
+ "{} queue was full, dropped oldest frame, new size: {}/{}",
+ queue_name,
+ queue.len(),
+ queue.capacity()
+ );
}
true
}
+
while let Some(result) = result_receiver.recv().await {
let frame_number = result.frame_number;
+ processed_count += 1;
+
+ // Periodically log stats
+ let now = std::time::Instant::now();
+ if now.duration_since(last_log_time) >= log_interval {
+ let elapsed_secs = now.duration_since(start_time).as_secs_f64();
+ let rate = if elapsed_secs > 0.0 {
+ processed_count as f64 / elapsed_secs
+ } else {
+ 0.0
+ };
+ info!(
+ "Queue stats for monitor {}: processed {} frames in {:.1}s ({:.2} fps), queue sizes: video={}/{}, ocr={}/{}",
+ monitor_id, processed_count, elapsed_secs, rate,
+ capture_video_frame_queue.len(), capture_video_frame_queue.capacity(),
+ capture_ocr_frame_queue.len(), capture_ocr_frame_queue.capacity()
+ );
+ last_log_time = now;
+ }
+
debug!("Received frame {} for queueing", frame_number);
let result = Arc::new(result);
@@ -113,19 +183,30 @@ impl VideoCapture {
}
debug!(
- "Frame {} pushed to queues. Queue lengths: {}, {}",
+ "Frame {} pushed to queues. Queue lengths: video={}/{}, ocr={}/{}",
frame_number,
capture_video_frame_queue.len(),
- capture_ocr_frame_queue.len()
+ capture_video_frame_queue.capacity(),
+ capture_ocr_frame_queue.len(),
+ capture_ocr_frame_queue.capacity()
);
}
+
+ warn!(
+ "Queue processing task terminated for monitor {} - channel closed",
+ monitor_id
+ );
});
let video_frame_queue_clone = video_frame_queue.clone();
let output_path = output_path.to_string();
- let _video_thread = tokio::spawn(async move {
- save_frames_as_video(
+ let video_thread = tokio::spawn(async move {
+ info!(
+ "Starting save_frames_as_video task for monitor {}",
+ monitor_id
+ );
+ match save_frames_as_video(
&video_frame_queue_clone,
&output_path,
fps,
@@ -133,13 +214,49 @@ impl VideoCapture {
monitor_id,
video_chunk_duration,
)
- .await;
+ .await
+ {
+ Ok(_) => warn!(
+ "save_frames_as_video task completed unexpectedly for monitor {}",
+ monitor_id
+ ),
+ Err(e) => error!(
+ "save_frames_as_video task failed for monitor {}: {}",
+ monitor_id, e
+ ),
+ }
+ warn!(
+ "save_frames_as_video task terminated for monitor {}",
+ monitor_id
+ );
});
VideoCapture {
video_frame_queue,
ocr_frame_queue,
+ capture_thread_handle: capture_thread,
+ queue_thread_handle: queue_thread,
+ video_thread_handle: video_thread,
+ }
+ }
+
+ // Add method to check health of tasks
+ pub fn check_health(&self) -> bool {
+ let capture_ok = !self.capture_thread_handle.is_finished();
+ let queue_ok = !self.queue_thread_handle.is_finished();
+ let video_ok = !self.video_thread_handle.is_finished();
+
+ if !capture_ok {
+ error!("continuous_capture task has terminated unexpectedly");
+ }
+ if !queue_ok {
+ error!("queue processing task has terminated unexpectedly");
+ }
+ if !video_ok {
+ error!("save_frames_as_video task has terminated unexpectedly");
}
+
+ capture_ok && queue_ok && video_ok
}
}
@@ -218,24 +335,45 @@ async fn save_frames_as_video(
new_chunk_callback: Arc<dyn Fn(&str) + Send + Sync>,
monitor_id: u32,
video_chunk_duration: Duration,
-) {
- debug!("Starting save_frames_as_video function");
+) -> Result<(), anyhow::Error> {
+ info!(
+ "Starting save_frames_as_video function for monitor {}",
+ monitor_id
+ );
let frames_per_video = (fps * video_chunk_duration.as_secs_f64()).ceil() as usize;
let mut frame_count = 0;
let mut current_ffmpeg: Option<Child> = None;
let mut current_stdin: Option<ChildStdin> = None;
+ // Track health metrics
+ let start_time = std::time::Instant::now();
+ let mut frames_total = 0;
+ let mut chunks_total = 0;
+ let mut last_stats_time = start_time;
+ let stats_interval = Duration::from_secs(60);
+
loop {
if frame_count >= frames_per_video || current_ffmpeg.is_none() {
if let Some(child) = current_ffmpeg.take() {
+ info!(
+ "Finishing FFmpeg process for monitor {} after {} frames",
+ monitor_id, frame_count
+ );
finish_ffmpeg_process(child, current_stdin.take()).await;
+ chunks_total += 1;
}
frame_count = 0;
+ debug!("Waiting for first frame for monitor {}", monitor_id);
let first_frame = wait_for_first_frame(frame_queue).await;
let buffer = encode_frame(&first_frame);
+ debug!("Got first frame for new chunk for monitor {}", monitor_id);
let output_file = create_output_file(output_path, monitor_id);
+ info!(
+ "Starting new video chunk: {} for monitor {}",
+ output_file, monitor_id
+ );
new_chunk_callback(&output_file);
match start_ffmpeg_process(&output_file, fps).await {
@@ -243,23 +381,53 @@ async fn save_frames_as_video(
let mut stdin = child.stdin.take().expect("Failed to open stdin");
spawn_ffmpeg_loggers(child.stderr.take(), child.stdout.take());
+ debug!("Writing first frame to FFmpeg for monitor {}", monitor_id);
if let Err(e) = write_frame_to_ffmpeg(&mut stdin, &buffer).await {
- error!("Failed to write first frame to ffmpeg: {}", e);
+ error!(
+ "Failed to write first frame to ffmpeg for monitor {}: {}",
+ monitor_id, e
+ );
continue;
}
frame_count += 1;
+ frames_total += 1;
current_ffmpeg = Some(child);
current_stdin = Some(stdin);
- debug!("New FFmpeg process started for file: {}", output_file);
+ info!(
+ "New FFmpeg process started for file: {} (monitor {})",
+ output_file, monitor_id
+ );
}
Err(e) => {
- error!("Failed to start FFmpeg process: {}", e);
+ error!(
+ "Failed to start FFmpeg process for monitor {}: {}",
+ monitor_id, e
+ );
continue;
}
}
}
+ let now = std::time::Instant::now();
+ if now.duration_since(last_stats_time) >= stats_interval {
+ let runtime = now.duration_since(start_time).as_secs();
+ let fps_avg = if runtime > 0 {
+ frames_total as f64 / runtime as f64
+ } else {
+ 0.0
+ };
+ info!(
+ "Video stats for monitor {}: processed {} frames in {} chunks over {}s ({:.2} avg fps)",
+ monitor_id, frames_total, chunks_total, runtime, fps_avg
+ );
+ last_stats_time = now;
+ }
+
+ debug!(
+ "Processing frames for monitor {}, current count: {}/{}",
+ monitor_id, frame_count, frames_per_video
+ );
process_frames(
frame_queue,
&mut current_stdin,
@@ -269,8 +437,15 @@ async fn save_frames_as_video(
)
.await;
+ // Update total frame count
+ frames_total = frames_total.max(frame_count);
+
tokio::task::yield_now().await;
}
+
+ // This is unreachable, but we need to return a Result to match the function signature
+ #[allow(unreachable_code)]
+ Ok(())
}
async fn wait_for_first_frame(
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.toml
index b472ef27d..4c77b87f9 100644
--- a/screenpipe-vision/Cargo.toml
+++ b/screenpipe-vision/Cargo.toml
@@ -40,7 +40,7 @@ tracing = { workspace = true }
which = "6.0"
serde = "1.0.200"
-xcap = "0.3.3" # non broken version
+xcap = { git = "https://github.com/nashaofu/xcap.git", rev = "09c11cc67a37434f6cdcf73f3305ee8608dac83c" }
once_cell = { workspace = true }
base64 = "0.22.1"
diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rs
index c287c8970..0cc5c8741 100644
--- a/screenpipe-vision/src/capture_screenshot_by_window.rs
+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs
@@ -1,9 +1,9 @@
use image::DynamicImage;
-use tracing::error;
use once_cell::sync::Lazy;
use std::collections::HashSet;
use std::error::Error;
use std::fmt;
+use tracing::error;
use xcap::{Window, XCapError};
@@ -201,14 +201,55 @@ pub async fn capture_all_visible_windows(
.into_iter()
.filter_map(|window| {
// Extract all necessary data from the window while in the main thread
- let app_name = window.app_name().to_string();
- let title = window.title().to_string();
- let is_focused = window.is_focused();
- let process_id = window.pid();
+ let app_name = match window.app_name() {
+ Ok(name) => name.to_string(),
+ Err(e) => {
+ // Log warning and skip this window
+ error!("Failed to get app_name for window: {}", e);
+ return None;
+ }
+ };
+
+ let title = match window.title() {
+ Ok(title) => title.to_string(),
+ Err(e) => {
+ error!("Failed to get title for window {}: {}", app_name, e);
+ return None;
+ }
+ };
+
+ let is_focused = match window.is_focused() {
+ Ok(focused) => focused,
+ Err(e) => {
+ error!(
+ "Failed to get focus state for window {} ({}): {}",
+ app_name, title, e
+ );
+ return None;
+ }
+ };
+
+ let process_id = match window.pid() {
+ Ok(pid) => pid,
+ Err(e) => {
+ error!(
+ "Failed to get process ID for window {} ({}): {}",
+ app_name, title, e
+ );
+ return None;
+ }
+ };
+
// 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)),
- Err(_) => None,
+ Err(e) => {
+ error!(
+ "Failed to capture image for window {} ({}): {}",
+ app_name, title, e
+ );
+ None
+ }
}
})
.collect::<Vec<_>>();
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index b749ac428..56e760dd8 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -13,7 +13,6 @@ use anyhow::Result;
use base64::{engine::general_purpose, Engine as _};
use image::codecs::jpeg::JpegEncoder;
use image::DynamicImage;
-use tracing::{debug, error, warn};
use screenpipe_core::Language;
use screenpipe_integrations::unstructured_ocr::perform_ocr_cloud;
use serde::Deserialize;
@@ -30,6 +29,7 @@ use tokio::fs::File;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc::Sender;
use tokio::time::sleep;
+use tracing::{debug, error, warn};
use crate::browser_utils::create_url_detector;
@@ -131,6 +131,20 @@ const BROWSER_NAMES: [&str; 9] = [
"chrome", "firefox", "safari", "edge", "brave", "arc", "chromium", "vivaldi", "opera",
];
+#[derive(Debug)]
+pub enum ContinuousCaptureError {
+ MonitorNotFound,
+ ErrorCapturingScreenshot(String),
+ ErrorProcessingOcr(String),
+ ErrorSendingOcrResult(String),
+}
+
+impl std::fmt::Display for ContinuousCaptureError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{:?}", self)
+ }
+}
+
pub async fn continuous_capture(
result_tx: Sender<CaptureResult>,
interval: Duration,
@@ -139,7 +153,7 @@ pub async fn continuous_capture(
window_filters: Arc<WindowFilters>,
languages: Vec<Language>,
capture_unfocused_windows: bool,
-) {
+) -> Result<(), ContinuousCaptureError> {
let mut frame_counter: u64 = 0;
let mut previous_image: Option<DynamicImage> = None;
let mut max_average: Option<MaxAverageFrame> = None;
@@ -154,7 +168,7 @@ pub async fn continuous_capture(
Some(m) => m,
None => {
error!("Monitor not found");
- return;
+ return Err(ContinuousCaptureError::MonitorNotFound);
}
};
@@ -195,7 +209,11 @@ pub async fn continuous_capture(
// 5. Process max average frame if available
if let Some(max_avg_frame) = max_average.take() {
- process_max_average_frame(max_avg_frame, &ocr_engine, languages.clone()).await;
+ if let Err(e) =
+ process_max_average_frame(max_avg_frame, &ocr_engine, languages.clone()).await
+ {
+ error!("Error processing max average frame: {}", e);
+ }
frame_counter = 0;
max_avg_value = 0.0;
}
@@ -264,7 +282,7 @@ async fn process_max_average_frame(
max_avg_frame: MaxAverageFrame,
ocr_engine: &OcrEngine,
languages: Vec<Language>,
-) {
+) -> Result<(), ContinuousCaptureError> {
let ocr_task_data = OcrTaskData {
image: max_avg_frame.image,
window_images: max_avg_frame.window_images,
@@ -275,7 +293,10 @@ async fn process_max_average_frame(
if let Err(e) = process_ocr_task(ocr_task_data, ocr_engine, languages).await {
error!("Error processing OCR task: {}", e);
+ return Err(ContinuousCaptureError::ErrorProcessingOcr(e.to_string()));
}
+
+ Ok(())
}
pub struct MaxAverageFrame {
@@ -292,7 +313,7 @@ pub async fn process_ocr_task(
ocr_task_data: OcrTaskData,
ocr_engine: &OcrEngine,
languages: Vec<Language>,
-) -> Result<(), std::io::Error> {
+) -> Result<(), ContinuousCaptureError> {
let OcrTaskData {
image,
window_images,
@@ -319,7 +340,8 @@ pub async fn process_ocr_task(
&mut total_confidence,
&mut window_count,
)
- .await?;
+ .await
+ .map_err(|e| ContinuousCaptureError::ErrorProcessingOcr(e.to_string()))?;
window_ocr_results.push(ocr_result);
}
@@ -332,7 +354,9 @@ pub async fn process_ocr_task(
window_ocr_results,
};
- send_ocr_result(&result_tx, capture_result).await?;
+ send_ocr_result(&result_tx, capture_result)
+ .await
+ .map_err(|e| ContinuousCaptureError::ErrorSendingOcrResult(e.to_string()))?;
// Log performance metrics
log_ocr_performance(start_time, window_count, total_confidence, frame_number);
@@ -346,7 +370,7 @@ async fn process_window_ocr(
languages: &[Language],
total_confidence: &mut f64,
window_count: &mut u32,
-) -> Result<WindowOcrResult, std::io::Error> {
+) -> Result<WindowOcrResult, ContinuousCaptureError> {
let app_name = captured_window.app_name.clone();
// Get browser URL if applicable
@@ -359,7 +383,9 @@ async fn process_window_ocr(
// Perform OCR based on the selected engine
let (window_text, window_json_output, confidence) =
- perform_ocr_with_engine(ocr_engine, &captured_window.image, languages.to_vec()).await?;
+ perform_ocr_with_engine(ocr_engine, &captured_window.image, languages.to_vec())
+ .await
+ .map_err(|e| ContinuousCaptureError::ErrorProcessingOcr(e.to_string()))?;
// Update confidence metrics
if let Some(conf) = confidence {
@@ -412,24 +438,23 @@ async fn perform_ocr_with_engine(
ocr_engine: &OcrEngine,
image: &DynamicImage,
languages: Vec<Language>,
-) -> Result<(String, String, Option<f64>), std::io::Error> {
+) -> Result<(String, String, Option<f64>), ContinuousCaptureError> {
match ocr_engine {
OcrEngine::Unstructured => perform_ocr_cloud(image, languages)
.await
- .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)),
+ .map_err(|e| ContinuousCaptureError::ErrorProcessingOcr(e.to_string())),
OcrEngine::Tesseract => Ok(perform_ocr_tesseract(image, languages)),
#[cfg(target_os = "windows")]
OcrEngine::WindowsNative => perform_ocr_windows(image)
.await
- .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)),
+ .map_err(|e| ContinuousCaptureError::ErrorProcessingOcr(e.to_string())),
#[cfg(target_os = "macos")]
OcrEngine::AppleNative => Ok(perform_ocr_apple(image, &languages)),
OcrEngine::Custom(config) => perform_ocr_custom(image, languages, config)
.await
- .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)),
- _ => Err(std::io::Error::new(
- std::io::ErrorKind::Other,
- "Unsupported OCR engine",
+ .map_err(|e| ContinuousCaptureError::ErrorProcessingOcr(e.to_string())),
+ _ => Err(ContinuousCaptureError::ErrorProcessingOcr(
+ "Unsupported OCR engine".to_string(),
)),
}
}
@@ -437,7 +462,7 @@ async fn perform_ocr_with_engine(
async fn send_ocr_result(
result_tx: &Sender<CaptureResult>,
capture_result: CaptureResult,
-) -> Result<(), std::io::Error> {
+) -> Result<(), ContinuousCaptureError> {
// Add channel health check
if result_tx.capacity() == 0 {
warn!("OCR task channel at capacity - receiver may be blocked or slow");
@@ -446,17 +471,16 @@ async fn send_ocr_result(
if let Err(e) = result_tx.send(capture_result).await {
if e.to_string().contains("channel closed") {
error!("OCR task channel closed, recording may have stopped: {}", e);
- return Err(std::io::Error::new(
- std::io::ErrorKind::BrokenPipe,
- "Channel closed - recording appears to have stopped",
+ return Err(ContinuousCaptureError::ErrorSendingOcrResult(
+ "Channel closed - recording appears to have stopped".to_string(),
));
}
error!("Failed to send OCR result: {}", e);
- return Err(std::io::Error::new(
- std::io::ErrorKind::Other,
- format!("Failed to send OCR result: {}", e),
- ));
+ return Err(ContinuousCaptureError::ErrorSendingOcrResult(format!(
+ "Failed to send OCR result: {}",
+ e
+ )));
}
Ok(())
diff --git a/screenpipe-vision/src/monitor.rs b/screenpipe-vision/src/monitor.rs
index 3d3ee2221..d04454b97 100644
--- a/screenpipe-vision/src/monitor.rs
+++ b/screenpipe-vision/src/monitor.rs
@@ -20,12 +20,12 @@ pub struct MonitorData {
impl SafeMonitor {
pub fn new(monitor: Monitor) -> Self {
- let monitor_id = monitor.id();
+ let monitor_id = monitor.id().unwrap();
let monitor_data = Arc::new(MonitorData {
- width: monitor.width(),
- height: monitor.height(),
- name: monitor.name().to_string(),
- is_primary: monitor.is_primary(),
+ width: monitor.width().unwrap(),
+ height: monitor.height().unwrap(),
+ name: monitor.name().unwrap().to_string(),
+ is_primary: monitor.is_primary().unwrap(),
});
Self {
@@ -41,10 +41,10 @@ impl SafeMonitor {
let monitor = Monitor::all()
.map_err(Error::from)?
.into_iter()
- .find(|m| m.id() == monitor_id)
+ .find(|m| m.id().unwrap() == monitor_id)
.ok_or_else(|| anyhow::anyhow!("Monitor not found"))?;
- if monitor.width() == 0 || monitor.height() == 0 {
+ if monitor.width().unwrap() == 0 || monitor.height().unwrap() == 0 {
return Err(anyhow::anyhow!("Invalid monitor dimensions"));
}
@@ -112,7 +112,7 @@ pub async fn get_monitor_by_id(id: u32) -> Option<SafeMonitor> {
tokio::task::spawn_blocking(move || match Monitor::all() {
Ok(monitors) => {
let monitor_count = monitors.len();
- let monitor_ids: Vec<u32> = monitors.iter().map(|m| m.id()).collect();
+ let monitor_ids: Vec<u32> = monitors.iter().map(|m| m.id().unwrap()).collect();
tracing::debug!(
"Found {} monitors with IDs: {:?}",
@@ -122,7 +122,7 @@ pub async fn get_monitor_by_id(id: u32) -> Option<SafeMonitor> {
monitors
.into_iter()
- .find(|m| m.id() == id)
+ .find(|m| m.id().unwrap() == id)
.map(SafeMonitor::new)
}
Err(e) => {