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: some improvement on memory, still ongoing #1269, feat: make it possible to full screen pipe, focused by default,
Louis Beaumont453e74104e1b
diff --git a/screenpipe-app-tauri/components/pipe-store.tsx b/screenpipe-app-tauri/components/pipe-store.tsxindex 26433e9f0..9ee137bc4 100644--- a/screenpipe-app-tauri/components/pipe-store.tsx+++ b/screenpipe-app-tauri/components/pipe-store.tsx@@ -137,12 +137,7 @@ export const PipeStore: React.FC = () => {setPipes([...storePluginsWithStatus, ...customPipes]);} catch (error) {- console.error("Failed to fetch store plugins:", error);- toast({- title: "error loading store",- description: "failed to fetch available pipes",- variant: "destructive",- });+ console.warn("Failed to fetch store plugins:", error);}};diff --git a/screenpipe-app-tauri/src-tauri/src/commands.rs b/screenpipe-app-tauri/src-tauri/src/commands.rsindex 0f5b73e6f..1db540bc9 100644--- a/screenpipe-app-tauri/src-tauri/src/commands.rs+++ b/screenpipe-app-tauri/src-tauri/src/commands.rs@@ -247,8 +247,6 @@ pub struct AuthStatus {message: Option<String>,}--#[tauri::command]pub async fn open_pipe_window(app_handle: tauri::AppHandle<tauri::Wry>,@@ -270,8 +268,9 @@ pub async fn open_pipe_window().title(title).inner_size(1200.0, 850.0)- // .always_on_top(true)- .visible_on_all_workspaces(true)+ .min_inner_size(600.0, 400.0)+ .focused(true)+ .fullscreen(false).build(){Ok(window) => window,@@ -290,7 +289,7 @@ pub async fn open_pipe_window(}#[cfg(target_os = "macos")]- if let Err(e) = app_handle.set_activation_policy(tauri::ActivationPolicy::Accessory) {+ if let Err(e) = app_handle.set_activation_policy(tauri::ActivationPolicy::Regular) {error!("failed to set activation policy: {}", e);}@@ -301,18 +300,16 @@ pub async fn open_pipe_window(pub async fn get_disk_usage(app_handle: tauri::AppHandle<tauri::Wry>,) -> Result<serde_json::Value, String> {- let screenpipe_dir_path = get_data_dir(&app_handle)- .unwrap_or_else(|_| dirs::home_dir().unwrap().join(".screenpipe"));+ let screenpipe_dir_path =+ get_data_dir(&app_handle).unwrap_or_else(|_| dirs::home_dir().unwrap().join(".screenpipe"));match crate::disk_usage::disk_usage(&screenpipe_dir_path).await {- Ok(Some(disk_usage)) => {- match serde_json::to_value(&disk_usage) {- Ok(json_value) => Ok(json_value),- Err(e) => {- error!("Failed to serialize disk usage: {}", e);- Err(format!("Failed to serialize disk usage: {}", e))- }+ Ok(Some(disk_usage)) => match serde_json::to_value(&disk_usage) {+ Ok(json_value) => Ok(json_value),+ Err(e) => {+ error!("Failed to serialize disk usage: {}", e);+ Err(format!("Failed to serialize disk usage: {}", e))}- }+ },Ok(None) => Err("No disk usage data found".to_string()),Err(e) => {error!("Failed to get disk usage: {}", e);@@ -320,4 +317,3 @@ pub async fn get_disk_usage(}}}-diff --git a/screenpipe-server/src/add.rs b/screenpipe-server/src/add.rsindex af0df606b..704c51516 100644--- a/screenpipe-server/src/add.rs+++ b/screenpipe-server/src/add.rs@@ -140,7 +140,7 @@ pub async fn handle_index_command().await?;- let mut previous_image: Option<DynamicImage> = None;+ let mut previous_image: Option<Arc<DynamicImage>> = None;let mut frame_counter: i64 = 0;for (idx, frame) in frames.iter().enumerate() {@@ -162,7 +162,7 @@ pub async fn handle_index_command(continue;}- previous_image = Some(frame.clone());+ previous_image = Some(Arc::new(frame.clone()));// Use specified OCR engine or fall back to platform defaultlet engine = match ocr_engine {diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex bc5150521..96d84b8af 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -16,6 +16,7 @@ use screenpipe_vision::{CaptureResult, OcrEngine};use std::collections::HashMap;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;+use std::sync::Weak;use std::time::Duration;use tokio::runtime::Handle;use tokio::task::JoinHandle;@@ -58,7 +59,7 @@ pub struct VideoRecordingConfig {pub db: Arc<DatabaseManager>,pub output_path: Arc<String>,pub fps: f64,- pub ocr_engine: Arc<OcrEngine>,+ pub ocr_engine: Weak<OcrEngine>,pub monitor_id: u32,pub use_pii_removal: bool,pub ignored_windows: Arc<Vec<String>>,@@ -211,7 +212,7 @@ async fn record_vision(let db_manager_video = Arc::clone(&db);let output_path_video = Arc::clone(&output_path);- let ocr_engine = Arc::clone(&ocr_engine);+ let ocr_engine_weak = Arc::downgrade(&ocr_engine);let languages = languages.clone();// Use weak reference for the device manager@@ -223,7 +224,7 @@ async fn record_vision(db: db_manager_video,output_path: output_path_video,fps,- ocr_engine,+ ocr_engine: ocr_engine_weak,monitor_id,use_pii_removal,ignored_windows,@@ -294,7 +295,7 @@ async fn record_video(config.fps,config.video_chunk_duration,new_chunk_callback,- Arc::clone(&config.ocr_engine),+ config.ocr_engine.clone(),config.monitor_id,config.ignored_windows,config.include_windows,@@ -344,8 +345,16 @@ async fn process_ocr_frame(db: &DatabaseManager,device_name: &str,use_pii_removal: bool,- ocr_engine: Arc<OcrEngine>,+ ocr_engine: Weak<OcrEngine>,) {+ let ocr_engine = match ocr_engine.upgrade() {+ Some(engine) => engine,+ None => {+ warn!("OCR engine no longer exists");+ return;+ }+ };+for window_result in &frame.window_ocr_results {let frame_id = match db.insert_frame(device_name, None).await {Ok(id) => id,diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex 1c36d0b28..060ece17a 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -1,6 +1,5 @@use chrono::Utc;use crossbeam::queue::ArrayQueue;-use tracing::{debug, error, info, warn};use screenpipe_core::{find_ffmpeg_path, Language};use screenpipe_vision::{capture_screenshot_by_window::WindowFilters, continuous_capture, CaptureResult, OcrEngine,@@ -9,6 +8,7 @@ use std::borrow::Cow;use std::path::PathBuf;use std::process::Stdio;use std::sync::Arc;+use std::sync::Weak;use std::time::Duration;use tokio::io::AsyncBufReadExt;use tokio::io::AsyncWriteExt;@@ -18,6 +18,7 @@ use tokio::sync::mpsc::channel;use tokio::sync::watch;use tokio::task::JoinHandle;use tokio::time::sleep;+use tracing::{debug, error, info, warn};pub(crate) const MAX_FPS: f64 = 30.0; // Adjust based on your needsconst MAX_QUEUE_SIZE: usize = 10;@@ -36,7 +37,7 @@ impl VideoCapture {fps: f64,video_chunk_duration: Duration,new_chunk_callback: impl Fn(&str) + Send + Sync + 'static,- ocr_engine: Arc<OcrEngine>,+ ocr_engine: Weak<OcrEngine>,monitor_id: u32,ignore_list: Arc<Vec<String>>,include_list: Arc<Vec<String>>,@@ -85,11 +86,19 @@ impl VideoCapture {let window_filters_clone = Arc::clone(&window_filters_clone);let languages_clone = languages_clone.clone();+ let ocr_engine = match ocr_engine.upgrade() {+ Some(engine) => engine,+ None => {+ warn!("[monitor_id: {}] OCR engine no longer exists", monitor_id);+ break;+ }+ };+tokio::select! {_ = continuous_capture(result_sender,interval,- ocr_engine.clone(),+ ocr_engine,monitor_id,window_filters_clone,languages_clone.clone(),diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex b45b70b15..078037c29 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -22,13 +22,11 @@ use serde::Serialize;use serde::Serializer;use serde_json;use std::sync::Arc;-use std::{- collections::HashMap,- time::{Duration, Instant, UNIX_EPOCH},-};+use std::time::{Duration, Instant, UNIX_EPOCH};use tokio::fs::File;use tokio::io::{AsyncBufReadExt, BufReader};use tokio::sync::mpsc::Sender;+use tokio::sync::mpsc::WeakSender;use tokio::sync::watch;use tracing::info;use tracing::warn;@@ -39,54 +37,44 @@ use xcap_macos::Monitor;#[cfg(not(target_os = "macos"))]use xcap::Monitor;-fn serialize_image<S>(image: &Option<DynamicImage>, serializer: S) -> Result<S::Ok, S::Error>+fn serialize_image<S>(image: &Option<Arc<DynamicImage>>, serializer: S) -> Result<S::Ok, S::Error>whereS: serde::Serializer,{if let Some(image) = image {let mut webp_buffer = Vec::new();let mut cursor = std::io::Cursor::new(&mut webp_buffer);-let mut encoder = JpegEncoder::new_with_quality(&mut cursor, 80);- // Encode the image as WebPencoder- .encode_image(image)+ .encode_image(image.as_ref()).map_err(serde::ser::Error::custom)?;- // Base64 encode the WebP datalet base64_string = general_purpose::STANDARD.encode(webp_buffer);-- // Serialize the base64 stringserializer.serialize_str(&base64_string)} else {serializer.serialize_none()}}-fn deserialize_image<'de, D>(deserializer: D) -> Result<Option<DynamicImage>, D::Error>+fn deserialize_image<'de, D>(deserializer: D) -> Result<Option<Arc<DynamicImage>>, D::Error>whereD: serde::Deserializer<'de>,{- // Deserialize the base64 stringlet base64_string: String = serde::Deserialize::deserialize(deserializer)?;- // Check if the base64 string is empty or invalidif base64_string.trim().is_empty() {return Ok(None);}- // Decode base64 to byteslet image_bytes = general_purpose::STANDARD.decode(&base64_string).map_err(serde::de::Error::custom)?;- // Create a cursor to read from the byteslet cursor = std::io::Cursor::new(image_bytes);-- // Decode the JPEG data back into an imagelet image = image::load(cursor, image::ImageFormat::Jpeg).map_err(serde::de::Error::custom)?;- Ok(Some(image))++ Ok(Some(Arc::new(image)))}fn serialize_instant<S>(instant: &Instant, serializer: S) -> Result<S::Ok, S::Error>@@ -108,24 +96,24 @@ where}pub struct CaptureResult {- pub image: DynamicImage,+ pub image: Arc<DynamicImage>,pub frame_number: u64,pub timestamp: Instant,pub window_ocr_results: Vec<WindowOcrResult>,}pub struct WindowOcrResult {- pub image: DynamicImage,+ pub image: Arc<DynamicImage>,pub window_name: String,pub app_name: String,pub text: String,- pub text_json: Vec<HashMap<String, String>>, // Change this line+ pub text_json: Vec<serde_json::Value>,pub focused: bool,pub confidence: f64,}pub struct OcrTaskData {- pub image: DynamicImage,+ pub image: Arc<DynamicImage>,pub window_images: Vec<CapturedWindow>,pub frame_number: u64,pub timestamp: Instant,@@ -143,7 +131,7 @@ pub async fn continuous_capture(mut shutdown_rx: watch::Receiver<bool>,) {let mut frame_counter: u64 = 0;- let mut previous_image: Option<DynamicImage> = None;+ let mut previous_image: Option<Arc<DynamicImage>> = None;let mut max_average: Option<MaxAverageFrame> = None;let mut max_avg_value = 0.0;@@ -192,6 +180,7 @@ pub async fn continuous_capture(};if let Some((image, window_images, image_hash)) = capture_result {+ let image = Arc::new(image);let current_average = match compare_with_previous_image(previous_image.as_ref(),&image,@@ -227,40 +216,41 @@ pub async fn continuous_capture(if current_average > max_avg_value {max_average = Some(MaxAverageFrame {- image: image.clone(),- window_images: window_images.clone(),+ image: Arc::clone(&image),+ window_images,image_hash,frame_number: frame_counter,timestamp: Instant::now(),- result_tx: result_tx.clone(),+ result_tx: result_tx.downgrade(),average: current_average,});max_avg_value = current_average;}- previous_image = Some(image);+ previous_image = Some(Arc::clone(&image));if let Some(max_avg_frame) = max_average.take() {- if max_avg_frame.result_tx.clone().is_closed() {- warn!("result_tx is closed, skipping OCR task");+ if let Some(sender) = max_avg_frame.result_tx.upgrade() {+ let ocr_task_data = OcrTaskData {+ image: max_avg_frame.image.clone(),+ window_images: max_avg_frame.window_images.iter().cloned().collect(),+ frame_number: max_avg_frame.frame_number,+ timestamp: max_avg_frame.timestamp,+ result_tx: sender,+ };++ if let Err(e) =+ process_ocr_task(ocr_task_data, ocr_engine.clone(), languages_clone).await+ {+ error!("Error processing OCR task: {}", e);+ }++ frame_counter = 0;+ max_avg_value = 0.0;+ } else {+ warn!("result_tx was dropped, skipping OCR task");return;}- let ocr_task_data = OcrTaskData {- image: max_avg_frame.image.clone(),- window_images: max_avg_frame.window_images.iter().cloned().collect(),- frame_number: max_avg_frame.frame_number,- timestamp: max_avg_frame.timestamp,- result_tx: max_avg_frame.result_tx,- };-- if let Err(e) =- process_ocr_task(ocr_task_data, ocr_engine.clone(), languages_clone).await- {- error!("Error processing OCR task: {}", e);- }-- frame_counter = 0;- max_avg_value = 0.0;}} else {debug!("Skipping frame {} due to capture failure", frame_counter);@@ -276,12 +266,12 @@ pub async fn continuous_capture(}pub struct MaxAverageFrame {- pub image: DynamicImage,+ pub image: Arc<DynamicImage>,pub window_images: Vec<CapturedWindow>,pub image_hash: u64,pub frame_number: u64,pub timestamp: Instant,- pub result_tx: Sender<CaptureResult>,+ pub result_tx: WeakSender<CaptureResult>,pub average: f64,}@@ -341,7 +331,7 @@ pub async fn process_ocr_task(}let ocr_result = WindowOcrResult {- image: captured_window.image,+ image: Arc::new(captured_window.image),window_name: captured_window.window_name,app_name: captured_window.app_name,text: window_text,@@ -388,14 +378,12 @@ pub async fn process_ocr_task(Ok(())}-fn parse_json_output(json_output: &str) -> Vec<HashMap<String, String>> {- let parsed_output: Vec<HashMap<String, String>> = serde_json::from_str(json_output)+fn parse_json_output(json_output: &str) -> Vec<serde_json::Value> {+ serde_json::from_str(json_output) // <-- Temporary allocations.unwrap_or_else(|e| {error!("Failed to parse JSON output: {}", e);Vec::new()- });-- parsed_output+ })}pub fn trigger_screen_capture_permission() -> Result<()> {@@ -423,11 +411,11 @@ pub struct WindowOcr {serialize_with = "serialize_image",deserialize_with = "deserialize_image")]- pub image: Option<DynamicImage>,+ pub image: Option<Arc<DynamicImage>>,pub window_name: String,pub app_name: String,pub text: String,- pub text_json: Vec<HashMap<String, String>>, // Change this line+ pub text_json: Vec<serde_json::Value>,pub focused: bool,pub confidence: f64,#[serde(diff --git a/screenpipe-vision/src/utils.rs b/screenpipe-vision/src/utils.rsindex 28a8f2349..dae184916 100644--- a/screenpipe-vision/src/utils.rs+++ b/screenpipe-vision/src/utils.rs@@ -7,6 +7,7 @@ use image::DynamicImage;use image_compare::{Algorithm, Metric, Similarity};use log::{debug, error, warn};use std::hash::{DefaultHasher, Hash, Hasher};+use std::sync::Arc;use std::time::{Duration, Instant};#[cfg(target_os = "macos")]@@ -82,7 +83,7 @@ pub async fn capture_screenshot(}pub async fn compare_with_previous_image(- previous_image: Option<&DynamicImage>,+ previous_image: Option<&Arc<DynamicImage>>,current_image: &DynamicImage,max_average: &mut Option<MaxAverageFrame>,frame_number: u64,