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
release-app make vision code more reliable and readable, make screencapturekit retry in case of failure to read the host devices
Louis Beaumont6904972cb2df
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex f2d4d42e6..fbe82ab4a 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.41.2"+version = "0.41.3"description = ""authors = ["you"]license = ""diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.tomlindex 6f4e2bb34..7ea99c62f 100644--- a/screenpipe-audio/Cargo.toml+++ b/screenpipe-audio/Cargo.toml@@ -78,6 +78,7 @@ ort-sys = "=2.0.0-rc.8"futures = "0.3.31"deepgram = "0.6.4"bytes = { version = "1.9.0", features = ["serde"] }+rand = "0.9.0"[target.'cfg(target_os = "windows")'.dependencies]ort = { version = "=2.0.0-rc.6", features = [diff --git a/screenpipe-audio/src/core/device.rs b/screenpipe-audio/src/core/device.rsindex 8fae2bb15..ae4558536 100644--- a/screenpipe-audio/src/core/device.rs+++ b/screenpipe-audio/src/core/device.rs@@ -107,6 +107,57 @@ pub fn parse_audio_device(name: &str) -> Result<AudioDevice> {AudioDevice::from_name(name)}+/// Attempts an operation with exponential backoff retry+#[cfg(target_os = "macos")]+async fn with_retry<T, F, Fut>(operation: F, max_retries: usize) -> Result<T>+where+ F: Fn() -> Fut,+ Fut: std::future::Future<Output = Result<T>>,+{+ let mut retries = 0;+ let mut delay_ms = 10; // Start with 10ms delay++ loop {+ match operation().await {+ Ok(value) => return Ok(value),+ Err(e) => {+ if retries >= max_retries {+ return Err(anyhow!("Max retries reached: {}", e));+ }++ // Add some jitter to prevent synchronized retries+ use rand::{rng, Rng};+ let jitter = rng().random_range(0..=10) as u64;+ let delay = std::time::Duration::from_millis(delay_ms + jitter);++ tracing::warn!(+ "ScreenCaptureKit host error, retrying in {}ms: {}",+ delay_ms + jitter,+ e+ );+ tokio::time::sleep(delay).await;++ retries += 1;+ delay_ms = std::cmp::min(delay_ms * 2, 1000); // Exponential backoff, max 1s+ }+ }+ }+}++/// Gets the ScreenCaptureKit host with retry mechanism+#[cfg(target_os = "macos")]+async fn get_screen_capture_host() -> Result<cpal::Host> {+ // necessary hack because this is unreliable+ with_retry(+ || async {+ cpal::host_from_id(cpal::HostId::ScreenCaptureKit)+ .map_err(|e| anyhow!("Failed to get ScreenCaptureKit host: {}", e))+ },+ 3,+ )+ .await+}+pub async fn get_cpal_device_and_config(audio_device: &AudioDevice,) -> Result<(cpal::Device, cpal::SupportedStreamConfig)> {@@ -133,7 +184,7 @@ pub async fn get_cpal_device_and_config(#[cfg(target_os = "macos")]if is_output_device {- if let Ok(screen_capture_host) = cpal::host_from_id(cpal::HostId::ScreenCaptureKit) {+ if let Ok(screen_capture_host) = get_screen_capture_host().await {devices = screen_capture_host.input_devices()?;}}@@ -152,102 +203,66 @@ pub async fn get_cpal_device_and_config(}pub async fn list_audio_devices() -> Result<Vec<AudioDevice>> {- // Helper function containing the original implementation- async fn try_list_audio_devices() -> Result<Vec<AudioDevice>> {- let host = cpal::default_host();- let mut devices = Vec::new();-- for device in host.input_devices()? {- if let Ok(name) = device.name() {- devices.push(AudioDevice::new(name, DeviceType::Input));- }- }+ let host = cpal::default_host();+ let mut devices = Vec::new();- // Filter function to exclude macOS speakers and AirPods for output devices- fn should_include_output_device(name: &str) -> bool {- #[cfg(target_os = "macos")]- {- !name.to_lowercase().contains("speakers")- && !name.to_lowercase().contains("airpods")- }- #[cfg(not(target_os = "macos"))]- {- // Avoid "unused variable" warning in non-macOS systems- let _ = name;- true- }+ for device in host.input_devices()? {+ if let Ok(name) = device.name() {+ devices.push(AudioDevice::new(name, DeviceType::Input));}+ }- // macos hack using screen capture kit for output devices - does not work well+ // Filter function to exclude macOS speakers and AirPods for output devices+ fn should_include_output_device(name: &str) -> bool {#[cfg(target_os = "macos")]{- // !HACK macos is supposed to use special macos feature "display capture"- // ! see https://github.com/RustAudio/cpal/pull/894- if let Ok(host) = cpal::host_from_id(cpal::HostId::ScreenCaptureKit) {- for device in host.input_devices()? {- if let Ok(name) = device.name() {- if should_include_output_device(&name) {- devices.push(AudioDevice::new(name, DeviceType::Output));- }- }- }- }+ !name.to_lowercase().contains("speakers") && !name.to_lowercase().contains("airpods")}+ #[cfg(not(target_os = "macos"))]+ {+ // Avoid "unused variable" warning in non-macOS systems+ let _ = name;+ true+ }+ }- // add default output device - on macos think of custom virtual devices- for device in host.output_devices()? {- if let Ok(name) = device.name() {- if should_include_output_device(&name) {- devices.push(AudioDevice::new(name, DeviceType::Output));+ // macos hack using screen capture kit for output devices - does not work well+ #[cfg(target_os = "macos")]+ {+ // !HACK macos is supposed to use special macos feature "display capture"+ // ! see https://github.com/RustAudio/cpal/pull/894+ if let Ok(screen_capture_host) = get_screen_capture_host().await {+ for device in screen_capture_host.input_devices()? {+ if let Ok(name) = device.name() {+ if should_include_output_device(&name) {+ devices.push(AudioDevice::new(name, DeviceType::Output));+ }}}}+ }- // last, add devices that are listed in .devices() which are not already in the devices vector- let other_devices = host.devices().unwrap();- for device in other_devices {- if !devices.iter().any(|d| d.name == device.name().unwrap())- && should_include_output_device(&device.name().unwrap())- {- // TODO: not sure if it can be input, usually aggregate or multi output- devices.push(AudioDevice::new(device.name().unwrap(), DeviceType::Output));+ // add default output device - on macos think of custom virtual devices+ for device in host.output_devices()? {+ if let Ok(name) = device.name() {+ if should_include_output_device(&name) {+ devices.push(AudioDevice::new(name, DeviceType::Output));}}-- Ok(devices)}- // Implement retry logic with exponential backoff- const MAX_RETRIES: u32 = 3;- let mut delay = std::time::Duration::from_millis(100);- let mut last_error = None;-- for attempt in 0..MAX_RETRIES {- match try_list_audio_devices().await {- Ok(devices) => return Ok(devices),- Err(err) => {- last_error = Some(err);- if attempt < MAX_RETRIES - 1 {- tracing::warn!(- "Failed to list audio devices (attempt {}/{}): {}. Retrying after {:?}...",- attempt + 1,- MAX_RETRIES,- last_error.as_ref().unwrap(),- delay- );- tokio::time::sleep(delay).await;- delay *= 2; // Exponential backoff- }- }+ // last, add devices that are listed in .devices() which are not already in the devices vector+ let other_devices = host.devices().unwrap();+ for device in other_devices {+ if !devices.iter().any(|d| d.name == device.name().unwrap())+ && should_include_output_device(&device.name().unwrap())+ {+ // TODO: not sure if it can be input, usually aggregate or multi output+ devices.push(AudioDevice::new(device.name().unwrap(), DeviceType::Output));}}- Err(last_error.unwrap_or_else(|| {- anyhow!(- "Failed to list audio devices after {} attempts",- MAX_RETRIES- )- }))+ Ok(devices)}pub fn default_input_device() -> Result<AudioDevice> {@@ -262,18 +277,28 @@ pub fn default_output_device() -> Result<AudioDevice> {#[cfg(target_os = "macos")]{// ! see https://github.com/RustAudio/cpal/pull/894- if let Ok(host) = cpal::host_from_id(cpal::HostId::ScreenCaptureKit) {- if let Some(device) = host.default_input_device() {- if let Ok(name) = device.name() {- return Ok(AudioDevice::new(name, DeviceType::Output));+ let screen_capture_result = tokio::runtime::Handle::current().block_on(async {+ if let Ok(host) = get_screen_capture_host().await {+ if let Some(device) = host.default_input_device() {+ if let Ok(name) = device.name() {+ return Some(AudioDevice::new(name, DeviceType::Output));+ }}+ None+ } else {+ None}+ });++ if let Some(device) = screen_capture_result {+ return Ok(device);}+let host = cpal::default_host();let device = host.default_output_device().ok_or_else(|| anyhow!("No default output device found"))?;- Ok(AudioDevice::new(device.name()?, DeviceType::Output))+ return Ok(AudioDevice::new(device.name()?, DeviceType::Output));}#[cfg(not(target_os = "macos"))]@@ -285,27 +310,3 @@ pub fn default_output_device() -> Result<AudioDevice> {return Ok(AudioDevice::new(device.name()?, DeviceType::Output));}}--pub fn trigger_audio_permission() -> Result<()> {- let host = cpal::default_host();- let device = host- .default_input_device()- .ok_or_else(|| anyhow!("No default input device found"))?;-- let config = device.default_input_config()?;-- // Attempt to build an input stream, which should trigger the permission request- let _stream = device.build_input_stream(- &config.into(),- |_data: &[f32], _: &cpal::InputCallbackInfo| {- // Do nothing, we just want to trigger the permission request- },- |err| eprintln!("Error in audio stream: {}", err),- None,- )?;-- // We don't actually need to start the stream- // The mere attempt to build it should trigger the permission request-- Ok(())-}diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex f3a961e26..25f27b95d 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -8,10 +8,7 @@ use screenpipe_audio::{audio_manager::AudioManagerBuilder,core::device::{default_input_device, default_output_device, list_audio_devices, parse_audio_device,- trigger_audio_permission,},- transcription::whisper::model::download_whisper_model,- vad::silero::SileroVad,};use screenpipe_core::find_ffmpeg_path;use screenpipe_db::{@@ -293,56 +290,6 @@ async fn main() -> anyhow::Result<()> {handle_pipe_command(subcommand, &pipe_manager).await?;return Ok(());}- Command::Setup {} => {- use screenpipe_vision::core::trigger_screen_capture_permission;-- // Trigger audio permission request- if let Err(e) = trigger_audio_permission() {- warn!("failed to trigger audio permission: {:?}", e);- warn!("please grant microphone permission manually in System Preferences.");- } else {- info!("audio permission requested. please grant permission if prompted.");- }-- // Trigger screen capture permission request- if let Err(e) = trigger_screen_capture_permission() {- warn!("failed to trigger screen capture permission: {:?}", e);- warn!(- "please grant screen recording permission manually in System Preferences."- );- } else {- info!(- "screen capture permission requested. please grant permission if prompted."- );- }-- // this command just download models and stuff (useful to have specific step to display in UI)-- // ! should prob skip if deepgram?- download_whisper_model(Arc::new(cli.audio_transcription_engine.into())).unwrap();- // ! assuming silero is used- SileroVad::new().await.unwrap();-- // Check if FFmpeg is working properly- if let Some(ffmpeg_path) = find_ffmpeg_path() {- println!("ffmpeg found at: {:?}", ffmpeg_path);- } else {- eprintln!("failed to find or install ffmpeg.");- return Err(anyhow::anyhow!("ffmpeg installation failed"));- }-- match check_ffmpeg().await {- Ok(_) => info!("FFmpeg is working properly"),- Err(e) => {- warn!("ffmpeg check failed: {}", e);- warn!("please ensure ffmpeg is installed correctly and is in your PATH");- return Err(e);- }- }-- info!("screenpipe setup complete");- return Ok(());- }Command::Migrate {migration_name,data_dir,@@ -1443,18 +1390,3 @@ async fn handle_pipe_command(}Ok(())}--// Add this function near the end of the file-async fn check_ffmpeg() -> anyhow::Result<()> {- // TODO: this should also check if it can properly encode mp4 etc- use tokio::process::Command;-- let output = Command::new("ffmpeg").arg("-version").output().await?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- return Err(anyhow::anyhow!("FFmpeg check failed: {}", stderr));- }-- Ok(())-}diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rsindex a91ea5f64..787a8bd06 100644--- a/screenpipe-server/src/cli.rs+++ b/screenpipe-server/src/cli.rs@@ -351,8 +351,6 @@ pub enum Command {#[arg(long, default_value_t = false)]use_embedding: bool,},- /// Setup screenpipe environment- Setup,/// Run data migrations in the backgroundMigrate {/// The name of the migration to rundiff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex 7af443489..a9b8326f2 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -9,7 +9,7 @@ use crate::monitor::get_monitor_by_id;use crate::tesseract::perform_ocr_tesseract;use crate::utils::OcrEngine;use crate::utils::{capture_screenshot, compare_with_previous_image};-use anyhow::{anyhow, Result};+use anyhow::Result;use base64::{engine::general_purpose, Engine as _};use image::codecs::jpeg::JpegEncoder;use image::DynamicImage;@@ -32,7 +32,7 @@ use tokio::sync::mpsc::Sender;use tokio::time::sleep;use crate::browser_utils::create_url_detector;-use xcap::Monitor;+use crate::monitor::SafeMonitor;fn serialize_image<S>(image: &Option<DynamicImage>, serializer: S) -> Result<S::Ok, S::Error>where@@ -154,132 +154,246 @@ pub async fn continuous_capture(let mut last_heartbeat = Instant::now();let heartbeat_interval = Duration::from_secs(60);+ // Add monitor retrieval failure tracking+ let mut monitor_retrieval_failures = 0;+ let max_monitor_retrieval_attempts = 3;+debug!("continuous_capture: Starting using monitor: {:?}",monitor_id);loop {- let monitor = match get_monitor_by_id(monitor_id).await {+ // 1. Get monitor+ let monitor = match get_monitor(+ &monitor_id,+ &mut monitor_retrieval_failures,+ max_monitor_retrieval_attempts,+ )+ .await+ {Some(m) => m,None => {- error!("continuous_capture: Failed to get monitor {}", monitor_id);- return;+ 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(+ // 2. Log heartbeat if needed+ log_heartbeat_if_needed(+ &mut last_heartbeat,+ heartbeat_interval,+ monitor_id,+ frame_counter,+ );++ // 3. Capture screenshot+ let capture_result = match capture_screenshot_with_retry(&monitor,&window_filters,capture_unfocused_windows,+ &mut consecutive_failures,+ failure_threshold,+ monitor_id,+ frame_counter,).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))+ Some(result) => result,+ None => {+ frame_counter += 1;+ tokio::time::sleep(interval).await;+ continue;}- Err(e) => {- consecutive_failures += 1;- error!(- "Failed to capture screenshot on monitor {} (attempt {}/{} failures): {}",- monitor_id, consecutive_failures, failure_threshold, e- );+ };++ // 4. Process captured image+ let (image, window_images, image_hash) = capture_result;++ let should_skip = should_skip_frame(+ &previous_image,+ &image,+ &mut max_average,+ frame_counter,+ &mut max_avg_value,+ &window_images,+ image_hash,+ result_tx.clone(),+ )+ .await;++ if should_skip {+ frame_counter += 1;+ tokio::time::sleep(interval).await;+ continue;+ }- 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- }+ previous_image = Some(image);++ // 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;+ frame_counter = 0;+ max_avg_value = 0.0;+ }++ frame_counter += 1;+ tokio::time::sleep(interval).await;+ }+}++// Helper functions to break down the complex continuous_capture function+async fn get_monitor(+ monitor_id: &u32,+ retrieval_failures: &mut u32,+ max_attempts: u32,+) -> Option<SafeMonitor> {+ match get_monitor_by_id(*monitor_id).await {+ Some(m) => {+ // Reset the counter when successful+ *retrieval_failures = 0;+ Some(m)+ }+ None => {+ *retrieval_failures += 1;+ error!(+ "continuous_capture: Failed to get monitor {} (attempt {}/{})",+ monitor_id, retrieval_failures, max_attempts+ );++ if *retrieval_failures >= max_attempts {+ error!("continuous_capture: Failed to get monitor after {} attempts, stopping capture process",+ max_attempts);+ None+ } else {None}- };+ }+ }+}- if let Some((image, window_images, image_hash)) = capture_result {- let current_average = match compare_with_previous_image(- previous_image.as_ref(),- &image,- &mut max_average,- frame_counter,- &mut max_avg_value,- )- .await- {- Ok(avg) => avg,- Err(e) => {- error!("Error comparing images: {}", e);- previous_image = None;- 0.0- }- };-- let current_average = if previous_image.is_none() {- 1.0- } else {- current_average- };+fn log_heartbeat_if_needed(+ last_heartbeat: &mut Instant,+ heartbeat_interval: Duration,+ monitor_id: u32,+ frame_counter: u64,+) {+ if last_heartbeat.elapsed() >= heartbeat_interval {+ debug!(+ "continuous_capture: Heartbeat for monitor {} - frame {}",+ monitor_id, frame_counter+ );+ *last_heartbeat = Instant::now();+ }+}++async fn capture_screenshot_with_retry(+ monitor: &SafeMonitor,+ window_filters: &Arc<WindowFilters>,+ capture_unfocused_windows: bool,+ consecutive_failures: &mut u32,+ failure_threshold: u32,+ monitor_id: u32,+ frame_counter: u64,+) -> Option<(DynamicImage, Vec<CapturedWindow>, u64)> {+ 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))+ }+ Err(e) => {+ *consecutive_failures += 1;+ error!(+ "Failed to capture screenshot on monitor {} (attempt {}/{} failures): {}",+ monitor_id, consecutive_failures, failure_threshold, e+ );- if current_average < 0.006 {- debug!(- "Skipping frame {} due to low average difference: {:.3}",- frame_counter, current_average+ if *consecutive_failures >= failure_threshold {+ error!(+ "continuous_capture: Too many consecutive capture failures, will retry in 5s");- frame_counter += 1;- tokio::time::sleep(interval).await;- continue;+ sleep(Duration::from_secs(5)).await;+ *consecutive_failures = 0; // Reset after longer wait}+ None+ }+ }+}- if current_average > max_avg_value {- max_average = Some(MaxAverageFrame {- image: image.clone(),- window_images: window_images.clone(),- image_hash,- frame_number: frame_counter,- timestamp: Instant::now(),- result_tx: result_tx.clone(),- average: current_average,- });- max_avg_value = current_average;- }+async fn should_skip_frame(+ previous_image: &Option<DynamicImage>,+ current_image: &DynamicImage,+ max_average: &mut Option<MaxAverageFrame>,+ frame_counter: u64,+ max_avg_value: &mut f64,+ window_images: &Vec<CapturedWindow>,+ image_hash: u64,+ result_tx: Sender<CaptureResult>,+) -> bool {+ let current_average = match compare_with_previous_image(+ previous_image.as_ref(),+ current_image,+ max_average,+ frame_counter,+ max_avg_value,+ )+ .await+ {+ Ok(avg) => avg,+ Err(e) => {+ error!("Error comparing images: {}", e);+ 0.0+ }+ };- previous_image = Some(image);-- if let Some(max_avg_frame) = max_average.take() {- let ocr_task_data = OcrTaskData {- image: max_avg_frame.image,- window_images: max_avg_frame.window_images,- 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, 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);+ let current_average = if previous_image.is_none() {+ 1.0+ } else {+ current_average+ };++ if current_average < 0.006 {+ debug!(+ "Skipping frame {} due to low average difference: {:.3}",+ frame_counter, current_average+ );+ true+ } else {+ if current_average > *max_avg_value {+ *max_average = Some(MaxAverageFrame {+ image: current_image.clone(),+ window_images: window_images.clone(),+ image_hash,+ frame_number: frame_counter,+ timestamp: Instant::now(),+ result_tx: result_tx.clone(),+ average: current_average,+ });+ *max_avg_value = current_average;}+ false+ }+}- frame_counter += 1;- tokio::time::sleep(interval).await;+async fn process_max_average_frame(+ max_avg_frame: MaxAverageFrame,+ ocr_engine: &OcrEngine,+ languages: Vec<Language>,+) {+ let ocr_task_data = OcrTaskData {+ image: max_avg_frame.image,+ window_images: max_avg_frame.window_images,+ 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, languages).await {+ error!("Error processing OCR task: {}", e);}}@@ -317,75 +431,19 @@ pub async fn process_ocr_task(let mut window_count = 0;for captured_window in window_images {- let app_name = captured_window.app_name.clone();- let browser_url = if cfg!(not(target_os = "linux"))- && captured_window.is_focused- && BROWSER_NAMES- .iter()- .any(|&browser| app_name.to_lowercase().contains(browser))- {- match tokio::task::spawn_blocking(move || {- get_active_browser_url_sync(&app_name, captured_window.process_id)- })- .await- {- Ok(Ok(url)) => Some(url),- Ok(Err(_)) => {- // error!("Failed to get browser URL: {}", e);- None- }- Err(e) => {- error!("Failed to spawn blocking task: {}", e);- None- }- }- } else {- None- };-- let (window_text, window_json_output, confidence) = match ocr_engine {- OcrEngine::Unstructured => perform_ocr_cloud(&captured_window.image, languages.clone())- .await- .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,- OcrEngine::Tesseract => {- perform_ocr_tesseract(&captured_window.image, languages.clone())- }- #[cfg(target_os = "windows")]- OcrEngine::WindowsNative => perform_ocr_windows(&captured_window.image)- .await- .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,- #[cfg(target_os = "macos")]- OcrEngine::AppleNative => perform_ocr_apple(&captured_window.image, &languages),- OcrEngine::Custom(config) => {- perform_ocr_custom(&captured_window.image, languages.clone(), config)- .await- .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?- }- _ => {- return Err(std::io::Error::new(- std::io::ErrorKind::Other,- "Unsupported OCR engine",- ))- }- };-- if let Some(conf) = confidence {- total_confidence += conf;- window_count += 1;- }+ let ocr_result = process_window_ocr(+ captured_window,+ ocr_engine,+ &languages,+ &mut total_confidence,+ &mut window_count,+ )+ .await?;- window_ocr_results.push(WindowOcrResult {- image: captured_window.image,- window_name: captured_window.window_name,- app_name: captured_window.app_name,- text: window_text,- text_json: parse_json_output(&window_json_output),- focused: captured_window.is_focused,- confidence: confidence.unwrap_or(0.0),- browser_url: browser_url.clone(),- });+ window_ocr_results.push(ocr_result);}+ // Create and send the resultlet capture_result = CaptureResult {image,frame_number,@@ -393,6 +451,112 @@ pub async fn process_ocr_task(window_ocr_results,};+ send_ocr_result(&result_tx, capture_result).await?;++ // Log performance metrics+ log_ocr_performance(start_time, window_count, total_confidence, frame_number);++ Ok(())+}++async fn process_window_ocr(+ captured_window: CapturedWindow,+ ocr_engine: &OcrEngine,+ languages: &[Language],+ total_confidence: &mut f64,+ window_count: &mut u32,+) -> Result<WindowOcrResult, std::io::Error> {+ let app_name = captured_window.app_name.clone();++ // Get browser URL if applicable+ let browser_url = get_browser_url_if_needed(+ &app_name,+ captured_window.is_focused,+ captured_window.process_id,+ )+ .await;++ // 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?;++ // Update confidence metrics+ if let Some(conf) = confidence {+ *total_confidence += conf;+ *window_count += 1;+ }++ Ok(WindowOcrResult {+ image: captured_window.image,+ window_name: captured_window.window_name,+ app_name: captured_window.app_name,+ text: window_text,+ text_json: parse_json_output(&window_json_output),+ focused: captured_window.is_focused,+ confidence: confidence.unwrap_or(0.0),+ browser_url,+ })+}++async fn get_browser_url_if_needed(+ app_name: &str,+ is_focused: bool,+ process_id: i32,+) -> Option<String> {+ if cfg!(not(target_os = "linux"))+ && is_focused+ && BROWSER_NAMES+ .iter()+ .any(|&browser| app_name.to_lowercase().contains(browser))+ {+ let app_name = app_name.to_string(); // Clone to move into the closure+ match tokio::task::spawn_blocking(move || {+ get_active_browser_url_sync(&app_name, process_id)+ })+ .await+ {+ Ok(Ok(url)) => Some(url),+ Ok(Err(_)) => None,+ Err(e) => {+ error!("Failed to spawn blocking task: {}", e);+ None+ }+ }+ } else {+ None+ }+}++async fn perform_ocr_with_engine(+ ocr_engine: &OcrEngine,+ image: &DynamicImage,+ languages: Vec<Language>,+) -> Result<(String, String, Option<f64>), std::io::Error> {+ match ocr_engine {+ OcrEngine::Unstructured => perform_ocr_cloud(image, languages)+ .await+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)),+ 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)),+ #[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",+ )),+ }+}++async fn send_ocr_result(+ result_tx: &Sender<CaptureResult>,+ capture_result: CaptureResult,+) -> Result<(), std::io::Error> {// Add channel health checkif result_tx.capacity() == 0 {warn!("OCR task channel at capacity - receiver may be blocked or slow");@@ -414,6 +578,15 @@ pub async fn process_ocr_task());}+ Ok(())+}++fn log_ocr_performance(+ start_time: Instant,+ window_count: u32,+ total_confidence: f64,+ frame_number: u64,+) {let duration = start_time.elapsed();let avg_confidence = if window_count > 0 {total_confidence / window_count as f64@@ -424,7 +597,6 @@ pub async fn process_ocr_task("OCR task processed frame {} with {} windows in {:?}, average confidence: {:.2}",frame_number, window_count, duration, avg_confidence);- Ok(())}fn parse_json_output(json_output: &str) -> Vec<HashMap<String, String>> {@@ -437,19 +609,6 @@ fn parse_json_output(json_output: &str) -> Vec<HashMap<String, String>> {parsed_output}-pub fn trigger_screen_capture_permission() -> Result<()> {- // Get the primary monitor- let monitor = Monitor::all().map_err(|e| anyhow!("Failed to get monitor: {}", e))?;-- // Attempt to capture a screenshot, which should trigger the permission request- let _screenshot = monitor.first().unwrap().capture_image()?;-- // We don't need to do anything with the screenshot- // The mere attempt to capture it should trigger the permission request-- Ok(())-}-#[derive(Debug, Clone, Serialize, Deserialize)]pub enum RealtimeVisionEvent {Ocr(WindowOcr),