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

feat: include or ignore specific windows, apps, tabs

Louis Beaumont794f1997a8b2
diff --git a/Cargo.toml b/Cargo.toml
index 7696164bc..01b4733b9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -16,7 +16,7 @@ resolver = "2"
[workspace.package]
-version = "0.1.79"
+version = "0.1.80"
authors = ["louis030195 <[email protected]>"]
description = ""
repository = "https://github.com/mediar-ai/screenpipe"
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 0842efc6c..cbcefc3cd 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -234,7 +234,7 @@ async fn main() -> anyhow::Result<()> {
cli.self_healing,
Duration::from_secs(60),
3,
- restart_sender, // TODO: remove self healing its dead code atm
+ restart_sender, // TODO: remove self healing its dead code atm
cli.port,
);
resource_monitor.start_monitoring(Duration::from_secs(10));
@@ -293,7 +293,7 @@ async fn main() -> anyhow::Result<()> {
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 friend_wearable_uid_clone = friend_wearable_uid.clone(); // Clone here
+ let friend_wearable_uid_clone = friend_wearable_uid.clone(); // Clone here
let fps = if cli.fps.is_finite() && cli.fps > 0.0 {
cli.fps
@@ -333,6 +333,8 @@ async fn main() -> anyhow::Result<()> {
cli.disable_vision,
&vision_handle,
&audio_handle,
+ &cli.ignored_windows,
+ &cli.included_windows,
);
let result = tokio::select! {
diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rs
index b073c14a2..465b42a28 100644
--- a/screenpipe-server/src/cli.rs
+++ b/screenpipe-server/src/cli.rs
@@ -151,6 +151,18 @@ pub struct Cli {
#[arg(long, default_value_t = false)]
pub disable_vision: bool,
+ /// List of windows to ignore (by title) for screen recording - we use contains to match, example:
+ /// --ignored-windows "Spotify" --ignored-windows "Bit" will ignore both "Bitwarden" and "Bittorrent"
+ /// --ignored-windows "porn" will ignore "pornhub" and "youporn"
+ #[arg(long)]
+ pub ignored_windows: Vec<String>,
+
+ /// List of windows to include (by title) for screen recording - we use contains to match, example:
+ /// --included-windows "Chrome" will include "Google Chrome"
+ /// --included-windows "WhatsApp" will include "WhatsApp"
+ #[arg(long)]
+ pub included_windows: Vec<String>,
+
#[command(subcommand)]
pub command: Option<Command>,
}
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 16e925969..7ada9793b 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -36,6 +36,8 @@ pub async fn start_continuous_recording(
vision_disabled: bool,
vision_handle: &Handle,
audio_handle: &Handle,
+ ignored_windows: &[String],
+ include_windows: &[String],
) -> Result<()> {
let (whisper_sender, whisper_receiver, whisper_shutdown_flag) = if audio_disabled {
// Create a dummy channel if no audio devices are available, e.g. audio disabled
@@ -63,7 +65,8 @@ pub async fn start_continuous_recording(
let output_path_audio = Arc::clone(&output_path);
let friend_wearable_uid_video = friend_wearable_uid.clone();
-
+ let ignored_windows_video = ignored_windows.to_vec();
+ let include_windows_video = include_windows.to_vec();
// Initialize friend wearable loop
if let Some(uid) = &friend_wearable_uid {
tokio::spawn(initialize_friend_wearable_loop(
@@ -84,6 +87,8 @@ pub async fn start_continuous_recording(
friend_wearable_uid_video,
monitor_id,
use_pii_removal,
+ &ignored_windows_video,
+ &include_windows_video,
)
.await
})
@@ -148,6 +153,8 @@ async fn record_video(
_friend_wearable_uid: Option<String>,
monitor_id: u32,
use_pii_removal: bool,
+ ignored_windows: &[String],
+ include_windows: &[String],
) -> Result<()> {
debug!("record_video: Starting");
let db_chunk_callback = Arc::clone(&db);
@@ -170,6 +177,8 @@ async fn record_video(
save_text_files,
Arc::clone(&ocr_engine),
monitor_id,
+ ignored_windows,
+ include_windows,
);
while is_running.load(Ordering::SeqCst) {
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index a0b183c0f..1299f50ff 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -31,8 +31,10 @@ impl VideoCapture {
save_text_files: bool,
ocr_engine: Arc<OcrEngine>,
monitor_id: u32,
+ ignore_list: &[String],
+ include_list: &[String],
) -> Self {
- info!("Starting new video capture");
+ info!("Starting new video capture");
let fps = if fps.is_finite() && fps > 0.0 {
fps
} else {
@@ -48,6 +50,8 @@ impl VideoCapture {
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 ignore_list_clone = ignore_list.to_vec();
+ let include_list_clone = include_list.to_vec();
let _capture_thread = tokio::spawn(async move {
continuous_capture(
result_sender,
@@ -55,6 +59,8 @@ impl VideoCapture {
save_text_files,
*ocr_engine,
monitor_id,
+ &ignore_list_clone,
+ &include_list_clone,
)
.await;
});
diff --git a/screenpipe-vision/benches/vision_benchmark.rs b/screenpipe-vision/benches/vision_benchmark.rs
index 65864dfb3..f7d3e99e1 100644
--- a/screenpipe-vision/benches/vision_benchmark.rs
+++ b/screenpipe-vision/benches/vision_benchmark.rs
@@ -21,6 +21,8 @@ async fn benchmark_continuous_capture(duration_secs: u64) -> f64 {
false,
Arc::new(OcrEngine::Tesseract),
get_default_monitor().await.id(),
+ &[],
+ &[],
)
.await;
});
diff --git a/screenpipe-vision/examples/websocket.rs b/screenpipe-vision/examples/websocket.rs
index 7a1ff734b..b83b54c97 100644
--- a/screenpipe-vision/examples/websocket.rs
+++ b/screenpipe-vision/examples/websocket.rs
@@ -81,6 +81,8 @@ async fn main() -> Result<()> {
OcrEngine::Tesseract
},
id,
+ &[],
+ &[],
)
.await
});
diff --git a/screenpipe-vision/examples/window-filtering.rs b/screenpipe-vision/examples/window-filtering.rs
new file mode 100644
index 000000000..2b7b8f723
--- /dev/null
+++ b/screenpipe-vision/examples/window-filtering.rs
@@ -0,0 +1,81 @@
+use anyhow::Result;
+use clap::Parser;
+use screenpipe_vision::{
+ continuous_capture, monitor::get_default_monitor, CaptureResult, OcrEngine,
+};
+use std::time::Duration;
+use tokio::sync::mpsc::channel;
+use tracing_subscriber::{fmt::format::FmtSpan, EnvFilter};
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ /// Windows to ignore (can be specified multiple times)
+ #[arg(long)]
+ ignore: Vec<String>,
+ /// Windows to include (can be specified multiple times)
+ #[arg(long)]
+ include: Vec<String>,
+}
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ tracing_subscriber::fmt()
+ .with_env_filter(
+ EnvFilter::from_default_env()
+ .add_directive(tracing::Level::DEBUG.into())
+ .add_directive("tokenizers=error".parse().unwrap()),
+ )
+ .with_span_events(FmtSpan::CLOSE)
+ .init();
+
+ let cli = Cli::parse();
+
+ let (result_tx, mut result_rx) = channel(512);
+
+ let monitor = get_default_monitor().await;
+ let id = monitor.id();
+
+ tokio::spawn(async move {
+ continuous_capture(
+ result_tx,
+ Duration::from_secs_f32(1.0 / 1.0),
+ false,
+ // if apple use apple otherwise if windows use windows native otherwise use tesseract
+ if cfg!(target_os = "macos") {
+ OcrEngine::AppleNative
+ } else if cfg!(target_os = "windows") {
+ OcrEngine::WindowsNative
+ } else {
+ OcrEngine::Tesseract
+ },
+ id,
+ &cli.ignore,
+ &cli.include,
+ )
+ .await
+ });
+
+ // Stream OCR results to logs
+ while let Some(result) = result_rx.recv().await {
+ log_capture_result(&result);
+ }
+
+ Ok(())
+}
+
+fn log_capture_result(result: &CaptureResult) {
+ for window in &result.window_ocr_results {
+ tracing::info!(
+ "Window: '{}' (App: '{}', Focused: {})",
+ window.window_name,
+ window.app_name,
+ window.focused
+ );
+ tracing::info!("Text: {}", window.text);
+ tracing::info!("Confidence: {:.2}", window.confidence);
+ tracing::info!("---");
+ }
+ tracing::info!("Timestamp: {:?}", result.timestamp);
+ tracing::info!("=====================================");
+}
diff --git a/screenpipe-vision/src/bin/screenpipe-vision.rs b/screenpipe-vision/src/bin/screenpipe-vision.rs
index d2a2bc648..2e1721de0 100644
--- a/screenpipe-vision/src/bin/screenpipe-vision.rs
+++ b/screenpipe-vision/src/bin/screenpipe-vision.rs
@@ -42,6 +42,8 @@ async fn main() {
save_text_files,
OcrEngine::AppleNative,
id,
+ &[],
+ &[],
)
.await
});
diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rs
index e80b4e2ca..0e71027be 100644
--- a/screenpipe-vision/src/capture_screenshot_by_window.rs
+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs
@@ -1,15 +1,10 @@
-use std::sync::Arc;
use image::DynamicImage;
-// use image::{DynamicImage, ImageFormat};
-use xcap::{Monitor, Window, XCapError};
use log::error;
-// use log::{debug, error, info, warn};
-use std::time::Duration;
-use tokio::time;
use std::error::Error;
use std::fmt;
-// use std::fs;
-// use std::path::Path;
+use std::time::Duration;
+use tokio::time;
+use xcap::{Monitor, Window, XCapError};
#[derive(Debug)]
enum CaptureError {
@@ -35,99 +30,119 @@ impl From<XCapError> for CaptureError {
}
}
-pub async fn capture_all_visible_windows() -> Result<Vec<(DynamicImage, String, String, bool)>, Box<dyn Error>> {
+pub async fn capture_all_visible_windows(
+ ignore_list: &[String],
+ include_list: &[String],
+) -> Result<Vec<(DynamicImage, String, String, bool)>, Box<dyn Error>> {
let monitors = Monitor::all()?;
- // info!("Found {} monitors", monitors.len());
let mut all_captured_images = Vec::new();
for monitor in monitors {
- // debug!("Capturing windows for monitor: {:?}", monitor);
-
- // info!("Attempting to get all windows for monitor {} with retry mechanism", monitor.name());
- let windows = retry_with_backoff(|| {
- let windows = Window::all()?;
- if windows.is_empty() {
- Err(CaptureError::NoWindows)
- } else {
- Ok(windows)
- }
- }, 3, Duration::from_millis(500)).await?;
-
- // let windows_count = windows.len();
- // info!("Successfully retrieved {} windows for monitor {}", windows_count, monitor.name());
-
- // if windows_count == 0 {
- // warn!("No windows were retrieved for monitor {}. This might indicate an issue.", monitor.name());
- // }
-
- let focused_window = get_focused_window(Arc::new(monitor.clone())).await;
+ let windows = retry_with_backoff(
+ || {
+ let windows = Window::all()?;
+ if windows.is_empty() {
+ Err(CaptureError::NoWindows)
+ } else {
+ Ok(windows)
+ }
+ },
+ 3,
+ Duration::from_millis(500),
+ )
+ .await?;
- // Create 'last_screenshots' directory if it doesn't exist
- // let screenshots_dir = Path::new("last_screenshots");
- // fs::create_dir_all(screenshots_dir)?;
+ // ! THIS is extremely inefficient
+ let focused_window = get_focused_window(&monitor, ignore_list, include_list).await;
for (_index, window) in windows.into_iter().enumerate() {
- if is_valid_window(&window, &monitor) {
+ if is_valid_window(&window, &monitor, ignore_list, include_list) {
let app_name = window.app_name();
let window_name = window.title();
- let is_focused = focused_window.as_ref().map_or(false, |fw| fw.id() == window.id());
-
+ let is_focused = focused_window
+ .as_ref()
+ .map_or(false, |fw| fw.id() == window.id());
+
match window.capture_image() {
Ok(buffer) => {
- let image = DynamicImage::ImageRgba8(image::ImageBuffer::from_raw(
- buffer.width() as u32,
- buffer.height() as u32,
- buffer.into_raw(),
- ).unwrap());
-
- // Save the image to the 'last_screenshots' directory
- // let file_name = format!("monitor_{}_window_{:03}_{}.png",
- // sanitize_filename(&monitor.name()), index, sanitize_filename(&window_name));
- // let file_path = screenshots_dir.join(file_name);
- // image.save_with_format(&file_path, ImageFormat::Png)?;
- // info!("Saved screenshot: {:?}", file_path);
-
- all_captured_images.push((image, app_name.to_string(), window_name.to_string(), is_focused));
- },
- Err(e) => error!("Failed to capture image for window {} on monitor {}: {}", window_name, monitor.name(), e),
+ let image = DynamicImage::ImageRgba8(
+ image::ImageBuffer::from_raw(
+ buffer.width() as u32,
+ buffer.height() as u32,
+ buffer.into_raw(),
+ )
+ .unwrap(),
+ );
+
+ all_captured_images.push((
+ image,
+ app_name.to_string(),
+ window_name.to_string(),
+ is_focused,
+ ));
+ }
+ Err(e) => error!(
+ "Failed to capture image for window {} on monitor {}: {}",
+ window_name,
+ monitor.name(),
+ e
+ ),
}
- } else {
- // debug!("Skipped invalid window: {} on monitor {}", window.title(), monitor.name());
}
}
-
- // info!("Captured {} valid windows out of {} total windows for monitor {}",
- // all_captured_images.len(), windows_count, monitor.name());
}
Ok(all_captured_images)
}
-// fn sanitize_filename(name: &str) -> String {
-// name.chars()
-// .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
-// .collect()
-// }
-
-fn is_valid_window(window: &Window, monitor: &Monitor) -> bool {
+fn is_valid_window(
+ window: &Window,
+ monitor: &Monitor,
+ ignore_list: &[String],
+ include_list: &[String],
+) -> bool {
let monitor_match = window.current_monitor().id() == monitor.id();
let not_minimized = !window.is_minimized();
let not_window_server = window.app_name() != "Window Server";
let not_contexts = window.app_name() != "Contexts";
let has_title = !window.title().is_empty();
-
- let valid = monitor_match && not_minimized && not_window_server && not_contexts && has_title;
-
- // if !valid {
- // debug!("Invalid window on monitor {}: {} (app: {}). Reasons: monitor_match={}, not_minimized={}, not_window_server={}, not_contexts={}, has_title={}",
- // monitor.name(), window.title(), window.app_name(), monitor_match, not_minimized, not_window_server, not_contexts, has_title);
- // }
-
- valid
+ let included = include_list.is_empty()
+ || include_list.iter().any(|include| {
+ window
+ .app_name()
+ .to_lowercase()
+ .contains(&include.to_lowercase())
+ || window
+ .title()
+ .to_lowercase()
+ .contains(&include.to_lowercase())
+ });
+ let not_ignored = !ignore_list.iter().any(|ignore| {
+ window
+ .app_name()
+ .to_lowercase()
+ .contains(&ignore.to_lowercase())
+ || window
+ .title()
+ .to_lowercase()
+ .contains(&ignore.to_lowercase())
+ });
+
+ monitor_match
+ && not_minimized
+ && not_window_server
+ && not_contexts
+ && has_title
+ && not_ignored
+ && included
}
-async fn retry_with_backoff<F, T, E>(mut f: F, max_retries: u32, initial_delay: Duration) -> Result<T, E>
+async fn retry_with_backoff<F, T, E>(
+ mut f: F,
+ max_retries: u32,
+ initial_delay: Duration,
+) -> Result<T, E>
where
F: FnMut() -> Result<T, E>,
E: Error + 'static,
@@ -139,7 +154,7 @@ where
Ok(result) => {
// info!("Function executed successfully on attempt {}", attempt);
return Ok(result);
- },
+ }
Err(e) => {
if attempt == max_retries {
error!("All {} attempts failed. Last error: {}", max_retries, e);
@@ -154,9 +169,22 @@ where
unreachable!()
}
-async fn get_focused_window(monitor: Arc<Monitor>) -> Option<Window> {
- retry_with_backoff(|| -> Result<Option<Window>, CaptureError> {
- let windows = Window::all()?;
- Ok(windows.into_iter().find(|w| is_valid_window(w, &monitor)))
- }, 3, Duration::from_millis(500)).await.ok().flatten()
-}
\ No newline at end of file
+async fn get_focused_window(
+ monitor: &Monitor,
+ ignore_list: &[String],
+ include_list: &[String],
+) -> Option<Window> {
+ retry_with_backoff(
+ || -> Result<Option<Window>, CaptureError> {
+ let windows = Window::all()?;
+ Ok(windows
+ .into_iter()
+ .find(|w| is_valid_window(w, &monitor, ignore_list, include_list)))
+ },
+ 3,
+ Duration::from_millis(500),
+ )
+ .await
+ .ok()
+ .flatten()
+}
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index e0bee4611..3af3d3c5a 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -50,6 +50,8 @@ pub async fn continuous_capture(
save_text_files_flag: bool,
ocr_engine: OcrEngine,
monitor_id: u32,
+ ignore_list: &[String],
+ include_list: &[String],
) {
debug!(
"continuous_capture: Starting using monitor: {:?}",
@@ -63,15 +65,21 @@ pub async fn continuous_capture(
let monitor = match get_monitor_by_id(monitor_id).await {
Some(m) => m,
None => {
- error!("Failed to get monitor with id: {}. Exiting continuous_capture.", monitor_id);
+ error!(
+ "Failed to get monitor with id: {}. Exiting continuous_capture.",
+ monitor_id
+ );
return;
}
};
loop {
- let capture_result = match capture_screenshot(&monitor).await {
+ let capture_result = match capture_screenshot(&monitor, &ignore_list, &include_list).await {
Ok((image, window_images, image_hash, _capture_duration)) => {
- debug!("Captured screenshot on monitor {} with hash: {}", monitor_id, image_hash);
+ debug!(
+ "Captured screenshot on monitor {} with hash: {}",
+ monitor_id, image_hash
+ );
Some((image, window_images, image_hash))
}
Err(e) => {
diff --git a/screenpipe-vision/src/utils.rs b/screenpipe-vision/src/utils.rs
index 13897c499..f4c0485c2 100644
--- a/screenpipe-vision/src/utils.rs
+++ b/screenpipe-vision/src/utils.rs
@@ -51,6 +51,8 @@ pub fn compare_images_ssim(image1: &DynamicImage, image2: &DynamicImage) -> f64
pub async fn capture_screenshot(
monitor: &Monitor,
+ ignore_list: &[String],
+ include_list: &[String],
) -> Result<
(
DynamicImage,
@@ -71,7 +73,7 @@ pub async fn capture_screenshot(
let capture_duration = capture_start.elapsed();
// info!("Attempting to capture all visible windows");
- let window_images = match capture_all_visible_windows().await {
+ let window_images = match capture_all_visible_windows(ignore_list, include_list).await {
Ok(images) => {
// info!("Successfully captured {} window images", images.len());
images
diff --git a/screenpipe-vision/tests/windows_vision_test.rs b/screenpipe-vision/tests/windows_vision_test.rs
index cacb262d1..843d6d7cf 100644
--- a/screenpipe-vision/tests/windows_vision_test.rs
+++ b/screenpipe-vision/tests/windows_vision_test.rs
@@ -73,6 +73,8 @@ mod tests {
save_text_files_flag,
ocr_engine,
monitor,
+ &[],
+ &[],
));
// Wait for a short duration to allow some captures to occur