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
feat: add cancel button for obsidian sync
Louis Beaumontecf773c935ac
diff --git a/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx b/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsxindex 98329615a..f4b85bc5b 100644--- a/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx+++ b/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx@@ -21,6 +21,7 @@ import {AlertCircle,Clock,ExternalLink,+ X,} from "lucide-react";// Official Obsidian logo SVG@@ -344,6 +345,14 @@ export function ObsidianSyncCard() {}};+ const handleCancel = async () => {+ try {+ await invoke("obsidian_cancel_sync");+ } catch (e) {+ console.error("Failed to cancel sync:", e);+ }+ };+const handleEnableScheduler = async () => {if (!isValidVault || settings.syncIntervalMinutes === 0) {return;@@ -459,23 +468,25 @@ export function ObsidianSyncCard() {{isExpanded ? "Hide Settings" : "Configure"}</Button>- <Button- onClick={handleSync}- disabled={!isValidVault || status.isSyncing || !isLoggedIn}- className="gap-2"- >- {status.isSyncing ? (- <>- <Loader2 className="h-4 w-4 animate-spin" />- Syncing...- </>- ) : (- <>- <RefreshCw className="h-4 w-4" />- Sync Now- </>- )}- </Button>+ {status.isSyncing ? (+ <Button+ onClick={handleCancel}+ variant="outline"+ className="gap-2"+ >+ <X className="h-4 w-4" />+ Cancel+ </Button>+ ) : (+ <Button+ onClick={handleSync}+ disabled={!isValidVault || !isLoggedIn}+ className="gap-2"+ >+ <RefreshCw className="h-4 w-4" />+ Sync Now+ </Button>+ )}{settings.vaultPath && (<Buttondiff --git a/screenpipe-app-tauri/lib/utils/tauri.ts b/screenpipe-app-tauri/lib/utils/tauri.tsindex bc44aedae..2150b50a4 100644--- a/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/screenpipe-app-tauri/lib/utils/tauri.ts@@ -455,6 +455,17 @@ async obsidianStopScheduler() : Promise<Result<null, string>> {if(e instanceof Error) throw e;else return { status: "error", error: e as any };}+},+/**+ * Cancel the currently running sync+ */+async obsidianCancelSync() : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("obsidian_cancel_sync") };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}}}diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex c8ce9dd0c..3ca6f01a3 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -829,6 +829,7 @@ async fn main() {obsidian_sync::obsidian_run_sync,obsidian_sync::obsidian_start_scheduler,obsidian_sync::obsidian_stop_scheduler,+ obsidian_sync::obsidian_cancel_sync,]).typ::<SettingsStore>().typ::<OnboardingStore>()@@ -970,7 +971,8 @@ async fn main() {obsidian_sync::obsidian_get_sync_status,obsidian_sync::obsidian_run_sync,obsidian_sync::obsidian_start_scheduler,- obsidian_sync::obsidian_stop_scheduler+ obsidian_sync::obsidian_stop_scheduler,+ obsidian_sync::obsidian_cancel_sync]).setup(move |app| {//deep link register_alldiff --git a/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rs b/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rsindex e1047c2d7..91dc4d493 100644--- a/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rs+++ b/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rs@@ -62,12 +62,14 @@ impl Default for ObsidianSyncStatus {pub struct ObsidianSyncState {pub status: Arc<Mutex<ObsidianSyncStatus>>,pub scheduler_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,+ pub current_pid: Arc<Mutex<Option<u32>>>,}impl ObsidianSyncState {pub fn new() -> Self {Self {status: Arc::new(Mutex::new(ObsidianSyncStatus::default())),+ current_pid: Arc::new(Mutex::new(None)),scheduler_handle: Arc::new(Mutex::new(None)),}}@@ -313,12 +315,22 @@ pub async fn obsidian_run_sync(// Debug: check if token is passedinfo!("obsidian_run_sync: user_token present = {}, vault_path = {}", user_token.is_some(), settings.vault_path);- // Emit progress- let _ = app.emit("obsidian_sync_progress", "Querying screenpipe data...");+ // Create channel to receive PID+ let (pid_tx, pid_rx) = tokio::sync::oneshot::channel();+ let current_pid = state.current_pid.clone();++ // Spawn task to store PID when received+ tokio::spawn(async move {+ if let Ok(pid) = pid_rx.await {+ *current_pid.lock().await = Some(pid);+ }+ });// Run pi in the vault directory- let _ = app.emit("obsidian_sync_progress", "AI is analyzing and writing notes...");- let result = pi::run(&prompt, user_token.as_deref(), &settings.vault_path).await.map(|_| ());+ let result = pi::run(&prompt, user_token.as_deref(), &settings.vault_path, Some(pid_tx)).await.map(|_| ());++ // Clear PID when done+ *state.current_pid.lock().await = None;// Update status based on result{@@ -363,6 +375,7 @@ pub async fn obsidian_start_scheduler(let interval_mins = settings.sync_interval_minutes;let settings_clone = settings.clone();let status_arc = state.status.clone();+ let current_pid_arc = state.current_pid.clone();let app_handle = app.clone();let token_clone = user_token.clone();@@ -393,7 +406,7 @@ pub async fn obsidian_start_scheduler(info!("Running scheduled obsidian sync");// Run sync- let result = run_scheduled_sync(&app_handle, &settings_clone, &status_arc, token_clone.as_deref()).await;+ let result = run_scheduled_sync(&app_handle, &settings_clone, &status_arc, ¤t_pid_arc, token_clone.as_deref()).await;if let Err(e) = result {warn!("Scheduled obsidian sync failed: {}", e);@@ -422,11 +435,34 @@ pub async fn obsidian_stop_scheduler(Ok(())}+/// Cancel the currently running sync+#[tauri::command]+#[specta::specta]+pub async fn obsidian_cancel_sync(+ app: AppHandle,+ state: tauri::State<'_, ObsidianSyncState>,+) -> Result<(), String> {+ let mut pid = state.current_pid.lock().await;+ if let Some(p) = pid.take() {+ crate::pi::kill(p)?;++ // Update status+ let mut status = state.status.lock().await;+ status.is_syncing = false;+ status.last_error = Some("Cancelled by user".to_string());++ let _ = app.emit("obsidian_sync_error", "Cancelled by user");+ info!("Obsidian sync cancelled");+ }+ Ok(())+}+/// Internal function to run a scheduled syncasync fn run_scheduled_sync(app: &AppHandle,settings: &ObsidianSyncSettings,status: &Arc<Mutex<ObsidianSyncStatus>>,+ current_pid: &Arc<Mutex<Option<u32>>>,user_token: Option<&str>,) -> Result<(), String> {// Update status@@ -443,7 +479,20 @@ async fn run_scheduled_sync(let start_time = end_time - chrono::Duration::hours(settings.sync_hours as i64);let prompt = build_prompt(settings, &start_time.to_rfc3339(), &end_time.to_rfc3339());- let result = pi::run(&prompt, user_token, &settings.vault_path).await.map(|_| ());++ // Create channel to receive PID+ let (pid_tx, pid_rx) = tokio::sync::oneshot::channel();+ let pid_clone = current_pid.clone();+ tokio::spawn(async move {+ if let Ok(pid) = pid_rx.await {+ *pid_clone.lock().await = Some(pid);+ }+ });++ let result = pi::run(&prompt, user_token, &settings.vault_path, Some(pid_tx)).await.map(|_| ());++ // Clear PID when done+ *current_pid.lock().await = None;// Update status{diff --git a/screenpipe-app-tauri/src-tauri/src/pi.rs b/screenpipe-app-tauri/src-tauri/src/pi.rsindex e22db3492..a9bb33848 100644--- a/screenpipe-app-tauri/src-tauri/src/pi.rs+++ b/screenpipe-app-tauri/src-tauri/src/pi.rs@@ -126,7 +126,8 @@ fn find_executable() -> Result<String, String> {/// Run pi with a prompt (non-interactive print mode)/// vault_path: Working directory where pi should run (e.g., Obsidian vault)-pub async fn run(prompt: &str, user_token: Option<&str>, working_dir: &str) -> Result<String, String> {+/// Returns (stdout, pid) on success+pub async fn run(prompt: &str, user_token: Option<&str>, working_dir: &str, pid_tx: Option<tokio::sync::oneshot::Sender<u32>>) -> Result<String, String> {// Ensure pi is installed and configuredensure_installed().await?;ensure_config()?;@@ -151,9 +152,20 @@ pub async fn run(prompt: &str, user_token: Option<&str>, working_dir: &str) -> Rcmd.stderr(std::process::Stdio::piped());info!("Running pi command...");- let output = cmd.output().await+ let mut child = cmd.spawn().map_err(|e| format!("Failed to spawn pi: {}", e))?;+ // Send PID if requested+ if let Some(tx) = pid_tx {+ if let Some(pid) = child.id() {+ let _ = tx.send(pid);+ info!("Pi process started with PID: {}", pid);+ }+ }++ let output = child.wait_with_output().await+ .map_err(|e| format!("Failed to wait for pi: {}", e))?;+let stdout = String::from_utf8_lossy(&output.stdout).to_string();let stderr = String::from_utf8_lossy(&output.stderr).to_string();@@ -177,3 +189,44 @@ pub async fn run(prompt: &str, user_token: Option<&str>, working_dir: &str) -> RErr(error_msg)}}++/// Kill a pi process by PID+pub fn kill(pid: u32) -> Result<(), String> {+ info!("Killing pi process with PID: {}", pid);++ #[cfg(unix)]+ {+ use std::process::Command;+ // Kill process group to also kill child processes+ let _ = Command::new("kill")+ .args(["-TERM", &format!("-{}", pid)])+ .output();+ // Also try direct kill+ let output = Command::new("kill")+ .args(["-TERM", &pid.to_string()])+ .output()+ .map_err(|e| format!("Failed to kill process: {}", e))?;++ if output.status.success() {+ info!("Pi process {} killed", pid);+ Ok(())+ } else {+ Err(format!("Failed to kill process {}", pid))+ }+ }++ #[cfg(windows)]+ {+ use std::process::Command;+ let output = Command::new("taskkill")+ .args(["/F", "/PID", &pid.to_string()])+ .output()+ .map_err(|e| format!("Failed to kill process: {}", e))?;++ if output.status.success() {+ Ok(())+ } else {+ Err(format!("Failed to kill process {}", pid))+ }+ }+}diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.tomlindex 845f1c641..61787c115 100644--- a/screenpipe-vision/Cargo.toml+++ b/screenpipe-vision/Cargo.toml@@ -52,13 +52,6 @@ base64 = "0.22.1"reqwest = { workspace = true }url = "2.5.0"-# Screen capture - platform specific-[target.'cfg(target_os = "macos")'.dependencies.sck-rs]-git = "https://github.com/louis030195/sck-rs"--[target.'cfg(not(target_os = "macos"))'.dependencies]-xcap = "0.8.1"-[dev-dependencies]tempfile = "3.3.0"criterion = { workspace = true }@@ -93,7 +86,19 @@ harness = falsename = "screenpipe-vision-websocket"path = "examples/websocket.rs"+# Platform-specific dependencies++# macOS: sck-rs for 12.3+ (ScreenCaptureKit), xcap as fallback for older versions+[target.'cfg(target_os = "macos")'.dependencies]+sck-rs = { git = "https://github.com/louis030195/sck-rs" }+xcap = "0.8.1"+libc = "0.2.168"+cidre = { git = "https://github.com/yury/cidre.git", features = ["vn", "cv", "cg"] }+accessibility-sys = { git = "https://github.com/eiz/accessibility.git", branch = "master" }+core-foundation = "=0.10.0"+[target.'cfg(target_os = "windows")'.dependencies]+xcap = "0.8.1"uiautomation = { version = "0.16.1" }windows = { version = "0.58", features = ["Graphics_Imaging",@@ -103,13 +108,8 @@ windows = { version = "0.58", features = ["Foundation_Collections",] }-[target.'cfg(target_os = "macos")'.dependencies]-libc = "0.2.168"-cidre = { git = "https://github.com/yury/cidre.git", features = ["vn", "cv", "cg"] }-accessibility-sys = { git = "https://github.com/eiz/accessibility.git", branch = "master" }-core-foundation = "=0.10.0"-[target.'cfg(target_os = "linux")'.dependencies]+xcap = "0.8.1"libc = "0.2.168"atspi = { version = "0.25.0", features = ["tokio","proxies-tokio","zbus"] }zbus = { version = "5.5", default-features = false }diff --git a/screenpipe-vision/examples/screenpipe-vision.rs b/screenpipe-vision/examples/screenpipe-vision.rsindex c2fb57b71..d074c4789 100644--- a/screenpipe-vision/examples/screenpipe-vision.rs+++ b/screenpipe-vision/examples/screenpipe-vision.rs@@ -1,17 +1,12 @@use clap::Parser;-#[cfg(target_os = "macos")]-use sck_rs::Monitor;use screenpipe_core::Language;use screenpipe_vision::{- capture_screenshot_by_window::WindowFilters, continuous_capture, OcrEngine,+ capture_screenshot_by_window::WindowFilters, continuous_capture, monitor::list_monitors, OcrEngine,};use std::{sync::Arc, time::Duration};use tokio::sync::mpsc::channel;use tracing_subscriber::{fmt::format::FmtSpan, EnvFilter};-#[cfg(not(target_os = "macos"))]-use xcap::Monitor;-#[derive(Parser)]#[command(author, version, about, long_about = None)]struct Cli {@@ -39,16 +34,8 @@ async fn main() {let languages = cli.language;// Get monitor ID before spawning the task- #[cfg(target_os = "macos")]- let monitor_id = tokio::task::spawn_blocking(|| Monitor::all().unwrap().first().unwrap().id())- .await- .unwrap();-- #[cfg(not(target_os = "macos"))]- let monitor_id =- tokio::task::spawn_blocking(|| Monitor::all().unwrap().first().unwrap().id().unwrap())- .await- .unwrap();+ let monitors = list_monitors().await;+ let monitor_id = monitors.first().expect("No monitors found").id();let window_filters = Arc::new(WindowFilters::new(&[], &[], &[]));diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rsindex ac645f804..044220818 100644--- a/screenpipe-vision/src/capture_screenshot_by_window.rs+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs@@ -5,14 +5,22 @@ use std::error::Error;use std::fmt;use tracing::debug;+// On macOS, we have both sck-rs (for 12.3+) and xcap (fallback for older versions)#[cfg(target_os = "macos")]-use sck_rs::{Window, XCapError};+use sck_rs::{Window as SckWindow, XCapError as SckXCapError};+#[cfg(target_os = "macos")]+use xcap::{Window as XcapWindow, XCapError as XcapXCapError};++// Non-macOS only uses xcap#[cfg(not(target_os = "macos"))]use xcap::{Window, XCapError};use crate::browser_utils::create_url_detector;use crate::monitor::SafeMonitor;++#[cfg(target_os = "macos")]+use crate::monitor::macos_version::use_sck_rs;use url::Url;const BROWSER_NAMES: [&str; 9] = [@@ -22,28 +30,50 @@ const BROWSER_NAMES: [&str; 9] = [#[derive(Debug)]enum CaptureError {NoWindows,+ #[cfg(not(target_os = "macos"))]XCapError(XCapError),+ #[cfg(target_os = "macos")]+ CaptureBackendError(String),}impl fmt::Display for CaptureError {fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {match self {CaptureError::NoWindows => write!(f, "No windows found"),+ #[cfg(not(target_os = "macos"))]CaptureError::XCapError(e) => write!(f, "XCap error: {}", e),+ #[cfg(target_os = "macos")]+ CaptureError::CaptureBackendError(e) => write!(f, "Capture error: {}", e),}}}impl Error for CaptureError {}+#[cfg(not(target_os = "macos"))]impl From<XCapError> for CaptureError {fn from(error: XCapError) -> Self {- // XCap errors are often expected (system windows, protected content)debug!("XCap error occurred: {}", error);CaptureError::XCapError(error)}}+#[cfg(target_os = "macos")]+impl From<SckXCapError> for CaptureError {+ fn from(error: SckXCapError) -> Self {+ debug!("sck-rs error occurred: {}", error);+ CaptureError::CaptureBackendError(error.to_string())+ }+}++#[cfg(target_os = "macos")]+impl From<XcapXCapError> for CaptureError {+ fn from(error: XcapXCapError) -> Self {+ debug!("xcap error occurred: {}", error);+ CaptureError::CaptureBackendError(error.to_string())+ }+}+// Platform specific skip lists#[cfg(target_os = "macos")]static SKIP_APPS: Lazy<HashSet<&'static str>> = Lazy::new(|| {@@ -335,23 +365,162 @@ impl WindowFilters {}}-pub async fn capture_all_visible_windows(- monitor: &SafeMonitor,- window_filters: &WindowFilters,- capture_unfocused_windows: bool,-) -> Result<Vec<CapturedWindow>, Box<dyn Error>> {- let mut all_captured_images = Vec::new();+/// Intermediate structure for window data extracted from platform-specific Window types+struct WindowData {+ app_name: String,+ title: String,+ is_focused: bool,+ process_id: i32,+ window_x: i32,+ window_y: i32,+ window_width: u32,+ window_height: u32,+ image_buffer: image::RgbaImage,+}++/// Get all visible windows using the appropriate backend+#[cfg(target_os = "macos")]+fn get_all_windows() -> Result<Vec<WindowData>, Box<dyn Error>> {+ if use_sck_rs() {+ get_all_windows_sck()+ } else {+ get_all_windows_xcap()+ }+}++#[cfg(target_os = "macos")]+fn get_all_windows_sck() -> Result<Vec<WindowData>, Box<dyn Error>> {+ let windows = SckWindow::all()?;+ Ok(windows+ .into_iter()+ .filter_map(|window| extract_window_data_sck(window))+ .collect())+}++#[cfg(target_os = "macos")]+fn extract_window_data_sck(window: SckWindow) -> Option<WindowData> {+ let app_name = match window.app_name() {+ Ok(name) => name.to_string(),+ Err(e) => {+ debug!("Failed to get app_name for window: {}", e);+ return None;+ }+ };++ let title = match window.title() {+ Ok(title) => title.to_string(),+ Err(e) => {+ debug!("Failed to get title for window {}: {}", app_name, e);+ return None;+ }+ };++ if let Ok(is_minimized) = window.is_minimized() {+ if is_minimized {+ debug!("Window {} ({}) is_minimized", app_name, title);+ return None;+ }+ }++ let is_focused = window.is_focused().unwrap_or(false);+ let process_id = window.pid().map(|p| p as i32).unwrap_or(-1);+ let (window_x, window_y, window_width, window_height) = (+ window.x().unwrap_or(0),+ window.y().unwrap_or(0),+ window.width().unwrap_or(0),+ window.height().unwrap_or(0),+ );++ match window.capture_image() {+ Ok(buffer) => Some(WindowData {+ app_name,+ title,+ is_focused,+ process_id,+ window_x,+ window_y,+ window_width,+ window_height,+ image_buffer: buffer,+ }),+ Err(e) => {+ debug!("Failed to capture image for window {} ({}): {}", app_name, title, e);+ None+ }+ }+}++#[cfg(target_os = "macos")]+fn get_all_windows_xcap() -> Result<Vec<WindowData>, Box<dyn Error>> {+ let windows = XcapWindow::all()?;+ Ok(windows+ .into_iter()+ .filter_map(|window| extract_window_data_xcap(window))+ .collect())+}++#[cfg(target_os = "macos")]+fn extract_window_data_xcap(window: XcapWindow) -> Option<WindowData> {+ let app_name = match window.app_name() {+ Ok(name) => name.to_string(),+ Err(e) => {+ debug!("Failed to get app_name for window: {}", e);+ return None;+ }+ };- // Get windows and immediately extract the data we need- let windows_data = Window::all()?+ let title = match window.title() {+ Ok(title) => title.to_string(),+ Err(e) => {+ debug!("Failed to get title for window {}: {}", app_name, e);+ return None;+ }+ };++ if let Ok(is_minimized) = window.is_minimized() {+ if is_minimized {+ debug!("Window {} ({}) is_minimized", app_name, title);+ return None;+ }+ }++ let is_focused = window.is_focused().unwrap_or(false);+ let process_id = window.pid().map(|p| p as i32).unwrap_or(-1);+ let (window_x, window_y, window_width, window_height) = (+ window.x().unwrap_or(0),+ window.y().unwrap_or(0),+ window.width().unwrap_or(0),+ window.height().unwrap_or(0),+ );++ match window.capture_image() {+ Ok(buffer) => Some(WindowData {+ app_name,+ title,+ is_focused,+ process_id,+ window_x,+ window_y,+ window_width,+ window_height,+ image_buffer: buffer,+ }),+ Err(e) => {+ debug!("Failed to capture image for window {} ({}): {}", app_name, title, e);+ None+ }+ }+}++#[cfg(not(target_os = "macos"))]+fn get_all_windows() -> Result<Vec<WindowData>, Box<dyn Error>> {+ let windows = Window::all()?;+ Ok(windows.into_iter().filter_map(|window| {- // Extract all necessary data from the window while in the main threadlet app_name = match window.app_name() {Ok(name) => name.to_string(),Err(e) => {- // Log warning and skip this window- // mostly noisedebug!("Failed to get app_name for window: {}", e);return None;}@@ -360,50 +529,20 @@ pub async fn capture_all_visible_windows(let title = match window.title() {Ok(title) => title.to_string(),Err(e) => {- // Expected for some system/overlay windowsdebug!("Failed to get title for window {}: {}", app_name, e);return None;}};- match window.is_minimized() {- Ok(is_minimized) => {- if is_minimized {- debug!("Window {} ({}) is_minimized", app_name, title);- return None;- }- }- Err(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) => {- // Expected for overlay/system windows- debug!(- "Failed to get focus state for window {} ({}): {}",- app_name, title, e- );+ if let Ok(is_minimized) = window.is_minimized() {+ if is_minimized {+ debug!("Window {} ({}) is_minimized", app_name, title);return None;}- };-- let process_id = match window.pid() {- Ok(pid) => pid as i32,- Err(e) => {- // Expected for some protected/system processes- debug!(- "Failed to get process ID for window {} ({}): {}",- app_name, title, e- );- -1- }- };+ }- // Get window position and size for coordinate transformation+ let is_focused = window.is_focused().unwrap_or(false);+ let process_id = window.pid().map(|p| p as i32).unwrap_or(-1);let (window_x, window_y, window_width, window_height) = (window.x().unwrap_or(0),window.y().unwrap_or(0),@@ -411,53 +550,57 @@ pub async fn capture_all_visible_windows(window.height().unwrap_or(0),);- // Capture image immediately while we have access to the windowmatch window.capture_image() {- Ok(buffer) => Some((+ Ok(buffer) => Some(WindowData {app_name,title,is_focused,- buffer,process_id,window_x,window_y,window_width,window_height,- )),+ image_buffer: buffer,+ }),Err(e) => {- // Expected for overlay windows, protected content, or transparent windows- debug!(- "Failed to capture image for window {} ({}): {}",- app_name, title, e- );+ debug!("Failed to capture image for window {} ({}): {}", app_name, title, e);None}}})- .collect::<Vec<_>>();+ .collect())+}++pub async fn capture_all_visible_windows(+ monitor: &SafeMonitor,+ window_filters: &WindowFilters,+ capture_unfocused_windows: bool,+) -> Result<Vec<CapturedWindow>, Box<dyn Error>> {+ let mut all_captured_images = Vec::new();++ // Get windows using the appropriate backend+ let windows_data = get_all_windows()?;if windows_data.is_empty() {return Err(Box::new(CaptureError::NoWindows));}// Process the captured data- for (- app_name,- window_name,- is_focused,- buffer,- process_id,- window_x,- window_y,- window_width,- window_height,- ) in windows_data- {+ for window_data in windows_data {+ let WindowData {+ app_name,+ title: window_name,+ is_focused,+ process_id,+ window_x,+ window_y,+ window_width,+ window_height,+ image_buffer,+ } = window_data;+// Convert to DynamicImage- let image = DynamicImage::ImageRgba8(- image::ImageBuffer::from_raw(buffer.width(), buffer.height(), buffer.into_raw())- .unwrap(),- );+ let image = DynamicImage::ImageRgba8(image_buffer);// Apply filters// Note: Empty window_name/app_name check fixes frame-window mismatch bug where apps like Arcdiff --git a/screenpipe-vision/src/monitor.rs b/screenpipe-vision/src/monitor.rsindex c8a8a67e9..75850e338 100644--- a/screenpipe-vision/src/monitor.rs+++ b/screenpipe-vision/src/monitor.rs@@ -3,16 +3,19 @@ use image::DynamicImage;use std::sync::Arc;use tracing;+// On macOS, we have both sck-rs (for 12.3+) and xcap (fallback for older versions)#[cfg(target_os = "macos")]-use sck_rs::Monitor;+use sck_rs::Monitor as SckMonitor;-#[cfg(not(target_os = "macos"))]-use xcap::Monitor;+// xcap is used on non-macOS platforms, and as fallback on older macOS+use xcap::Monitor as XcapMonitor;#[derive(Clone)]pub struct SafeMonitor {monitor_id: u32,monitor_data: Arc<MonitorData>,+ #[cfg(target_os = "macos")]+ use_sck: bool,}#[derive(Clone)]@@ -23,10 +26,48 @@ pub struct MonitorData {pub is_primary: bool,}+// macOS version detection for runtime fallback+#[cfg(target_os = "macos")]+pub mod macos_version {+ use once_cell::sync::Lazy;+ use std::process::Command;++ /// Cached macOS version (major, minor)+ pub static MACOS_VERSION: Lazy<(u32, u32)> = Lazy::new(|| {+ get_macos_version().unwrap_or((0, 0))+ });++ /// Check if we should use sck-rs (requires macOS 12.3+)+ pub fn use_sck_rs() -> bool {+ let (major, minor) = *MACOS_VERSION;+ major > 12 || (major == 12 && minor >= 3)+ }++ fn get_macos_version() -> Option<(u32, u32)> {+ // Use sw_vers to get macOS version+ let output = Command::new("sw_vers")+ .arg("-productVersion")+ .output()+ .ok()?;++ let version_str = String::from_utf8_lossy(&output.stdout);+ let parts: Vec<&str> = version_str.trim().split('.').collect();++ let major: u32 = parts.get(0)?.parse().ok()?;+ let minor: u32 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);++ tracing::info!("Detected macOS version: {}.{}", major, minor);+ Some((major, minor))+ }+}++#[cfg(target_os = "macos")]+use macos_version::use_sck_rs;+impl SafeMonitor {+ // macOS: Create from sck-rs monitor#[cfg(target_os = "macos")]- pub fn new(monitor: Monitor) -> Self {- // sck-rs API: id(), name(), is_primary() return values directly+ pub fn from_sck(monitor: SckMonitor) -> Self {let monitor_id = monitor.id();let monitor_data = Arc::new(MonitorData {width: monitor.width().unwrap_or(0),@@ -38,12 +79,31 @@ impl SafeMonitor {Self {monitor_id,monitor_data,+ use_sck: true,+ }+ }++ // macOS: Create from xcap monitor (fallback)+ #[cfg(target_os = "macos")]+ pub fn from_xcap(monitor: XcapMonitor) -> Self {+ let monitor_id = monitor.id().unwrap_or(0);+ let monitor_data = Arc::new(MonitorData {+ width: monitor.width().unwrap_or(0),+ height: monitor.height().unwrap_or(0),+ name: monitor.name().unwrap_or_default().to_string(),+ is_primary: monitor.is_primary().unwrap_or(false),+ });++ Self {+ monitor_id,+ monitor_data,+ use_sck: false,}}+ // Non-macOS: Create from xcap monitor#[cfg(not(target_os = "macos"))]- pub fn new(monitor: Monitor) -> Self {- // xcap API: id(), name(), is_primary() return Result+ pub fn new(monitor: XcapMonitor) -> Self {let monitor_id = monitor.id().unwrap();let monitor_data = Arc::new(MonitorData {width: monitor.width().unwrap(),@@ -61,22 +121,42 @@ impl SafeMonitor {#[cfg(target_os = "macos")]pub async fn capture_image(&self) -> Result<DynamicImage> {let monitor_id = self.monitor_id;+ let use_sck = self.use_sck;let image = std::thread::spawn(move || -> Result<DynamicImage> {- let monitor = Monitor::all()- .map_err(Error::from)?- .into_iter()- .find(|m| m.id() == monitor_id)- .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?;-- if monitor.width().unwrap_or(0) == 0 || monitor.height().unwrap_or(0) == 0 {- return Err(anyhow::anyhow!("Invalid monitor dimensions"));+ if use_sck {+ // Use sck-rs (ScreenCaptureKit)+ let monitor = SckMonitor::all()+ .map_err(Error::from)?+ .into_iter()+ .find(|m| m.id() == monitor_id)+ .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?;++ if monitor.width().unwrap_or(0) == 0 || monitor.height().unwrap_or(0) == 0 {+ return Err(anyhow::anyhow!("Invalid monitor dimensions"));+ }++ monitor+ .capture_image()+ .map_err(|e| anyhow::anyhow!("{}", e))+ .map(DynamicImage::ImageRgba8)+ } else {+ // Use xcap (fallback for older macOS)+ let monitor = XcapMonitor::all()+ .map_err(Error::from)?+ .into_iter()+ .find(|m| m.id().unwrap_or(0) == monitor_id)+ .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?;++ if monitor.width().unwrap_or(0) == 0 || monitor.height().unwrap_or(0) == 0 {+ return Err(anyhow::anyhow!("Invalid monitor dimensions"));+ }++ monitor+ .capture_image()+ .map_err(Error::from)+ .map(DynamicImage::ImageRgba8)}-- monitor- .capture_image()- .map_err(|e| anyhow::anyhow!("{}", e))- .map(DynamicImage::ImageRgba8)}).join().unwrap()?;@@ -89,7 +169,7 @@ impl SafeMonitor {let monitor_id = self.monitor_id;let image = std::thread::spawn(move || -> Result<DynamicImage> {- let monitor = Monitor::all()+ let monitor = XcapMonitor::all().map_err(Error::from)?.into_iter().find(|m| m.id().unwrap() == monitor_id)@@ -139,9 +219,33 @@ impl SafeMonitor {}}+#[cfg(target_os = "macos")]+pub async fn list_monitors() -> Vec<SafeMonitor> {+ tokio::task::spawn_blocking(|| {+ if use_sck_rs() {+ tracing::debug!("Using sck-rs for screen capture (macOS 12.3+)");+ SckMonitor::all()+ .unwrap_or_default()+ .into_iter()+ .map(SafeMonitor::from_sck)+ .collect()+ } else {+ tracing::info!("Using xcap fallback for screen capture (macOS < 12.3)");+ XcapMonitor::all()+ .unwrap_or_default()+ .into_iter()+ .map(SafeMonitor::from_xcap)+ .collect()+ }+ })+ .await+ .unwrap()+}++#[cfg(not(target_os = "macos"))]pub async fn list_monitors() -> Vec<SafeMonitor> {tokio::task::spawn_blocking(|| {- Monitor::all()+ XcapMonitor::all().unwrap().into_iter().map(SafeMonitor::new)@@ -151,9 +255,23 @@ pub async fn list_monitors() -> Vec<SafeMonitor> {.unwrap()}+#[cfg(target_os = "macos")]+pub async fn get_default_monitor() -> SafeMonitor {+ tokio::task::spawn_blocking(|| {+ if use_sck_rs() {+ SafeMonitor::from_sck(SckMonitor::all().unwrap().first().unwrap().clone())+ } else {+ SafeMonitor::from_xcap(XcapMonitor::all().unwrap().first().unwrap().clone())+ }+ })+ .await+ .unwrap()+}++#[cfg(not(target_os = "macos"))]pub async fn get_default_monitor() -> SafeMonitor {tokio::task::spawn_blocking(|| {- SafeMonitor::new(Monitor::all().unwrap().first().unwrap().clone())+ SafeMonitor::new(XcapMonitor::all().unwrap().first().unwrap().clone())}).await.unwrap()@@ -161,25 +279,51 @@ pub async fn get_default_monitor() -> SafeMonitor {#[cfg(target_os = "macos")]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();-- 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+ tokio::task::spawn_blocking(move || {+ if use_sck_rs() {+ match SckMonitor::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: {:?} (using sck-rs)",+ monitor_count,+ monitor_ids+ );++ monitors+ .into_iter()+ .find(|m| m.id() == id)+ .map(SafeMonitor::from_sck)+ }+ Err(e) => {+ tracing::error!("Failed to list monitors with sck-rs: {}", e);+ None+ }+ }+ } else {+ match XcapMonitor::all() {+ Ok(monitors) => {+ let monitor_count = monitors.len();+ let monitor_ids: Vec<u32> = monitors.iter().filter_map(|m| m.id().ok()).collect();++ tracing::debug!(+ "Found {} monitors with IDs: {:?} (using xcap fallback)",+ monitor_count,+ monitor_ids+ );++ monitors+ .into_iter()+ .find(|m| m.id().unwrap_or(0) == id)+ .map(SafeMonitor::from_xcap)+ }+ Err(e) => {+ tracing::error!("Failed to list monitors with xcap: {}", e);+ None+ }+ }}}).await@@ -191,7 +335,7 @@ pub async fn get_monitor_by_id(id: u32) -> Option<SafeMonitor> {#[cfg(not(target_os = "macos"))]pub async fn get_monitor_by_id(id: u32) -> Option<SafeMonitor> {- tokio::task::spawn_blocking(move || match Monitor::all() {+ tokio::task::spawn_blocking(move || match XcapMonitor::all() {Ok(monitors) => {let monitor_count = monitors.len();let monitor_ids: Vec<u32> = monitors.iter().map(|m| m.id().unwrap()).collect();@@ -218,3 +362,30 @@ pub async fn get_monitor_by_id(id: u32) -> Option<SafeMonitor> {None})}++/// Check if the current system supports screen capture+#[cfg(target_os = "macos")]+pub fn is_screen_capture_supported() -> bool {+ // xcap works on all macOS versions, so we always have support now+ true+}++#[cfg(not(target_os = "macos"))]+pub fn is_screen_capture_supported() -> bool {+ true+}++/// Get the screen capture backend being used+#[cfg(target_os = "macos")]+pub fn get_capture_backend() -> &'static str {+ if use_sck_rs() {+ "sck-rs (ScreenCaptureKit)"+ } else {+ "xcap (legacy)"+ }+}++#[cfg(not(target_os = "macos"))]+pub fn get_capture_backend() -> &'static str {+ "xcap"+}