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: screen capture, remove dead code

Louis Beaumont562c9da8fb2a
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index a4b068a56..09d8adac9 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -31,13 +31,7 @@ use screenpipe_vision::monitor::list_monitors;
use screenpipe_vision::run_ui;
use serde_json::{json, Value};
use std::{
- env, fs,
- io::Write,
- net::SocketAddr,
- ops::Deref,
- path::PathBuf,
- sync::{atomic::AtomicBool, Arc},
- time::Duration,
+ env, fs, io::Write, net::SocketAddr, ops::Deref, path::PathBuf, sync::Arc, time::Duration,
};
use tokio::{runtime::Runtime, signal, sync::broadcast};
use tracing::{debug, error, info, warn};
@@ -664,9 +658,6 @@ async fn main() -> anyhow::Result<()> {
let db_server = db.clone();
- // Channel for controlling the recorder ! TODO RENAME SHIT
- let vision_control = Arc::new(AtomicBool::new(true));
-
let warning_ocr_engine_clone = cli.ocr_engine.clone();
let warning_audio_transcription_engine_clone = cli.audio_transcription_engine.clone();
let monitor_ids = if cli.monitor_id.is_empty() {
@@ -692,7 +683,6 @@ async fn main() -> anyhow::Result<()> {
let db_clone = Arc::clone(&db);
let output_path_clone = Arc::new(local_data_dir.join("data").to_string_lossy().into_owned());
- let vision_control_clone = Arc::clone(&vision_control);
let shutdown_tx_clone = shutdown_tx.clone();
let monitor_ids_clone = monitor_ids.clone();
let ignored_windows_clone = cli.ignored_windows.clone();
@@ -737,7 +727,6 @@ async fn main() -> anyhow::Result<()> {
output_path_clone.clone(),
fps,
Duration::from_secs(cli.video_chunk_duration),
- vision_control_clone.clone(),
Arc::new(cli.ocr_engine.clone().into()),
monitor_ids_clone.clone(),
cli.use_pii_removal,
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index febfec7cd..d4f05d3ed 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -7,7 +7,6 @@ use screenpipe_db::{DatabaseManager, Speaker};
use screenpipe_events::{poll_meetings_events, send_event};
use screenpipe_vision::core::WindowOcr;
use screenpipe_vision::OcrEngine;
-use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::runtime::Handle;
@@ -19,7 +18,6 @@ pub async fn start_continuous_recording(
output_path: Arc<String>,
fps: f64,
video_chunk_duration: Duration,
- vision_control: Arc<AtomicBool>,
ocr_engine: Arc<OcrEngine>,
monitor_ids: Vec<u32>,
use_pii_removal: bool,
@@ -38,7 +36,6 @@ pub async fn start_continuous_recording(
.map(|&monitor_id| {
let db_manager_video = Arc::clone(&db);
let output_path_video = Arc::clone(&output_path);
- let is_running_video = Arc::clone(&vision_control);
let ocr_engine = Arc::clone(&ocr_engine);
let ignored_windows_video = ignored_windows.to_vec();
let include_windows_video = include_windows.to_vec();
@@ -51,7 +48,6 @@ pub async fn start_continuous_recording(
db_manager_video,
output_path_video,
fps,
- is_running_video,
ocr_engine,
monitor_id,
use_pii_removal,
@@ -99,7 +95,6 @@ async fn record_video(
db: Arc<DatabaseManager>,
output_path: Arc<String>,
fps: f64,
- is_running: Arc<AtomicBool>,
ocr_engine: Arc<OcrEngine>,
monitor_id: u32,
use_pii_removal: bool,
@@ -110,11 +105,15 @@ async fn record_video(
capture_unfocused_windows: bool,
realtime_vision: bool,
) -> Result<()> {
- debug!("record_video: Starting");
+ debug!("record_video: Starting for monitor {}", monitor_id);
let db_chunk_callback = Arc::clone(&db);
let rt = Handle::current();
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 new_chunk_callback = {
let db_chunk_callback = Arc::clone(&db_chunk_callback);
let device_name = Arc::clone(&device_name);
@@ -147,8 +146,21 @@ async fn record_video(
capture_unfocused_windows,
);
- while is_running.load(Ordering::SeqCst) {
+ loop {
+ // Increment and check heartbeat
+ heartbeat_counter += 1;
+ if heartbeat_counter % heartbeat_interval == 0 {
+ debug!(
+ "record_video: Heartbeat for monitor {} - iteration {}",
+ monitor_id, heartbeat_counter
+ );
+ }
+
if let Some(frame) = video_capture.ocr_frame_queue.pop() {
+ debug!(
+ "record_video: Processing frame with {} window results",
+ frame.window_ocr_results.len()
+ );
for window_result in &frame.window_ocr_results {
match db
.insert_frame(
@@ -210,11 +222,17 @@ async fn record_video(
}
}
}
+ } else {
+ // Log when frame queue is empty
+ if heartbeat_counter % 10 == 0 {
+ debug!(
+ "record_video: No frames in queue for monitor {}",
+ monitor_id
+ );
+ }
}
tokio::time::sleep(Duration::from_secs_f64(1.0 / fps)).await;
}
-
- Ok(())
}
pub async fn merge_speakers(
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index c50531472..b21e3b737 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -610,7 +610,7 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
};
let now = Utc::now();
- let threshold = Duration::from_secs(3600); // 1 hour
+ let threshold = Duration::from_secs(1800); // 30 minutes
let frame_status = if state.vision_disabled {
"disabled"
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.toml
index 48fa23663..ceb91f1c5 100644
--- a/screenpipe-vision/Cargo.toml
+++ b/screenpipe-vision/Cargo.toml
@@ -44,7 +44,7 @@ tracing = { workspace = true }
which = "6.0"
serde = "1.0.200"
-xcap = { git = "https://github.com/nashaofu/xcap", rev = "09c11cc" }
+xcap = "0.3.3" # non broken version
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 b3ff6f01d..8c72ee87b 100644
--- a/screenpipe-vision/src/capture_screenshot_by_window.rs
+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs
@@ -201,10 +201,10 @@ 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().unwrap_or_default().to_string();
- let title = window.title().unwrap_or_default().to_string();
- let is_focused = window.is_focused().unwrap_or(false);
- let process_id = window.pid().unwrap_or(0);
+ 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();
// 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)),
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index 6df6fd7fe..914dca06d 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -13,7 +13,7 @@ use anyhow::{anyhow, Result};
use base64::{engine::general_purpose, Engine as _};
use image::codecs::jpeg::JpegEncoder;
use image::DynamicImage;
-use log::{debug, error};
+use log::{debug, error, warn};
use screenpipe_core::Language;
use screenpipe_integrations::unstructured_ocr::perform_ocr_cloud;
use serde::Deserialize;
@@ -146,33 +146,67 @@ pub async fn continuous_capture(
let mut max_average: Option<MaxAverageFrame> = None;
let mut max_avg_value = 0.0;
+ // Add failure tracking
+ let mut consecutive_failures = 0;
+ let failure_threshold = 10;
+
+ // Add heartbeat counter
+ let mut last_heartbeat = Instant::now();
+ let heartbeat_interval = Duration::from_secs(60);
+
debug!(
"continuous_capture: Starting using monitor: {:?}",
monitor_id
);
+ let monitor = match get_monitor_by_id(monitor_id).await {
+ Some(m) => m,
+ None => {
+ error!("continuous_capture: Failed to get monitor {}", monitor_id);
+ return;
+ }
+ };
+
loop {
- let monitor = match get_monitor_by_id(monitor_id).await {
- Some(m) => m,
- None => {
- sleep(Duration::from_secs(1)).await;
- continue;
+ // Log heartbeat periodically
+ if last_heartbeat.elapsed() >= heartbeat_interval {
+ debug!(
+ "continuous_capture: Heartbeat for monitor {} - frame {}",
+ monitor_id, frame_counter
+ );
+ last_heartbeat = Instant::now();
+ }
+
+ let capture_result = match capture_screenshot(
+ &monitor,
+ &window_filters,
+ capture_unfocused_windows,
+ )
+ .await
+ {
+ Ok((image, window_images, image_hash, _capture_duration)) => {
+ debug!(
+ "Captured screenshot on monitor {} with hash: {} (frame {})",
+ monitor_id, image_hash, frame_counter
+ );
+ consecutive_failures = 0; // Reset failure counter on success
+ Some((image, window_images, image_hash))
}
- };
- let capture_result =
- match capture_screenshot(&monitor, &window_filters, capture_unfocused_windows).await {
- Ok((image, window_images, image_hash, _capture_duration)) => {
- debug!(
- "Captured screenshot on monitor {} with hash: {}",
- monitor_id, image_hash
- );
- Some((image, window_images, image_hash))
- }
- Err(e) => {
- error!("Failed to capture screenshot: {}", e);
- None
+ Err(e) => {
+ consecutive_failures += 1;
+ error!(
+ "Failed to capture screenshot on monitor {} (attempt {}/{} failures): {}",
+ monitor_id, consecutive_failures, failure_threshold, e
+ );
+
+ if consecutive_failures >= failure_threshold {
+ error!("continuous_capture: Too many consecutive capture failures, will retry in 5s");
+ sleep(Duration::from_secs(5)).await;
+ consecutive_failures = 0; // Reset after longer wait
}
- };
+ None
+ }
+ };
if let Some((image, window_images, image_hash)) = capture_result {
let current_average = match compare_with_previous_image(
@@ -360,18 +394,24 @@ pub async fn process_ocr_task(
window_ocr_results,
};
+ // Add channel health check
+ if result_tx.capacity() == 0 {
+ warn!("OCR task channel at capacity - receiver may be blocked or slow");
+ }
+
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::Other,
- "Channel closed",
+ std::io::ErrorKind::BrokenPipe,
+ "Channel closed - recording appears to have stopped",
));
}
error!("Failed to send OCR result: {}", e);
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
- "Failed to send OCR result",
+ format!("Failed to send OCR result: {}", e),
));
}
diff --git a/screenpipe-vision/src/monitor.rs b/screenpipe-vision/src/monitor.rs
index e6fa7d8fc..3d3ee2221 100644
--- a/screenpipe-vision/src/monitor.rs
+++ b/screenpipe-vision/src/monitor.rs
@@ -1,6 +1,7 @@
use anyhow::{Error, Result};
use image::DynamicImage;
use std::sync::Arc;
+use tracing;
use xcap::Monitor;
#[derive(Clone)]
@@ -19,12 +20,12 @@ pub struct MonitorData {
impl SafeMonitor {
pub fn new(monitor: Monitor) -> Self {
- let monitor_id = monitor.id().unwrap();
+ let monitor_id = monitor.id();
let monitor_data = Arc::new(MonitorData {
- width: monitor.width().unwrap(),
- height: monitor.height().unwrap(),
- name: monitor.name().unwrap(),
- is_primary: monitor.is_primary().unwrap(),
+ width: monitor.width(),
+ height: monitor.height(),
+ name: monitor.name().to_string(),
+ is_primary: monitor.is_primary(),
});
Self {
@@ -40,10 +41,10 @@ impl SafeMonitor {
let monitor = Monitor::all()
.map_err(Error::from)?
.into_iter()
- .find(|m| m.id().unwrap() == monitor_id)
+ .find(|m| m.id() == monitor_id)
.ok_or_else(|| anyhow::anyhow!("Monitor not found"))?;
- if monitor.width().unwrap() == 0 || monitor.height().unwrap() == 0 {
+ if monitor.width() == 0 || monitor.height() == 0 {
return Err(anyhow::anyhow!("Invalid monitor dimensions"));
}
@@ -108,13 +109,30 @@ pub async fn get_default_monitor() -> SafeMonitor {
}
pub async fn get_monitor_by_id(id: u32) -> Option<SafeMonitor> {
- tokio::task::spawn_blocking(move || {
- Monitor::all()
- .unwrap()
- .into_iter()
- .find(|m| m.id().unwrap() == id)
- .map(SafeMonitor::new)
+ 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();
+
+ tracing::debug!(
+ "Found {} monitors with IDs: {:?}",
+ monitor_count,
+ monitor_ids
+ );
+
+ monitors
+ .into_iter()
+ .find(|m| m.id() == id)
+ .map(SafeMonitor::new)
+ }
+ Err(e) => {
+ tracing::error!("Failed to list monitors: {}", e);
+ None
+ }
})
.await
- .unwrap()
+ .unwrap_or_else(|e| {
+ tracing::error!("Task to get monitor by ID {} panicked: {}", id, e);
+ None
+ })
}