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
style: apply cargo fmt to all Rust source files
Louis Beaumontca6985fedc52
diff --git a/screenpipe-audio/src/core/device.rs b/screenpipe-audio/src/core/device.rsindex 5867429d0..c7799c15f 100644--- a/screenpipe-audio/src/core/device.rs+++ b/screenpipe-audio/src/core/device.rs@@ -198,21 +198,25 @@ pub async fn get_cpal_device_and_config(let configs = cpal_audio_device.supported_output_configs()?;let best_config = configs.max_by(|a, b| {- a.max_sample_rate().0.cmp(&b.max_sample_rate().0)+ a.max_sample_rate()+ .0+ .cmp(&b.max_sample_rate().0).then(a.channels().cmp(&b.channels()))}).ok_or_else(|| anyhow!("No supported output configurations found"))?;-+best_config.with_sample_rate(best_config.max_sample_rate())} else {let configs = cpal_audio_device.supported_input_configs()?;let best_config = configs.max_by(|a, b| {- a.max_sample_rate().0.cmp(&b.max_sample_rate().0)+ a.max_sample_rate()+ .0+ .cmp(&b.max_sample_rate().0).then(a.channels().cmp(&b.channels()))}).ok_or_else(|| anyhow!("No supported input configurations found"))?;-+best_config.with_sample_rate(best_config.max_sample_rate())};diff --git a/screenpipe-audio/src/speaker/models.rs b/screenpipe-audio/src/speaker/models.rsindex 7a56dd8e4..5ab00cf70 100644--- a/screenpipe-audio/src/speaker/models.rs+++ b/screenpipe-audio/src/speaker/models.rs@@ -1,9 +1,9 @@use anyhow::Result;use lazy_static::lazy_static;-use tracing::{debug, info};use std::path::PathBuf;use std::sync::Once;use tokio::sync::Mutex;+use tracing::{debug, info};lazy_static! {static ref SEGMENTATION_MODEL_PATH: Mutex<Option<PathBuf>> = Mutex::new(None);diff --git a/screenpipe-audio/src/transcription/deepgram/streaming.rs b/screenpipe-audio/src/transcription/deepgram/streaming.rsindex 138fd1fd1..97bf577d5 100644--- a/screenpipe-audio/src/transcription/deepgram/streaming.rs+++ b/screenpipe-audio/src/transcription/deepgram/streaming.rs@@ -12,6 +12,8 @@ use futures::{SinkExt, TryStreamExt};use screenpipe_core::Language;use screenpipe_events::send_event;use serde::{Deserialize, Serialize};+use serde_json;+use serde_json::Value;use std::sync::atomic::{AtomicI64, Ordering};use std::sync::{atomic::AtomicBool, Arc};use std::time::{Duration, SystemTime, UNIX_EPOCH};@@ -19,8 +21,6 @@ use tokio::sync::broadcast::Receiver;use tokio::sync::oneshot;use tracing::debug;use tracing::info;-use serde_json;-use serde_json::Value;// Add this near other static/global variablesstatic LAST_DISPLAY_AUDIO_ACTIVITY: AtomicI64 = AtomicI64::new(0);@@ -92,9 +92,12 @@ pub async fn start_deepgram_stream(DEEPGRAM_WEBSOCKET_URL.as_str().to_string()};debug!("connecting to deepgram at: {}", ws_url);-+// Log the audio configuration- debug!("audio configuration: sample_rate={}, channels=1, device={}", sample_rate, device);+ debug!(+ "audio configuration: sample_rate={}, channels=1, device={}",+ sample_rate, device+ );let (shutdown_tx, mut shutdown_rx) = oneshot::channel();@@ -111,7 +114,10 @@ pub async fn start_deepgram_stream(let deepgram = match DEEPGRAM_WEBSOCKET_URL.as_str().is_empty() {true => deepgram::Deepgram::new(api_key)?,false => {- debug!("using custom deepgram websocket url: {}", DEEPGRAM_WEBSOCKET_URL.as_str());+ debug!(+ "using custom deepgram websocket url: {}",+ DEEPGRAM_WEBSOCKET_URL.as_str()+ );deepgram::Deepgram::with_base_url_and_api_key(DEEPGRAM_WEBSOCKET_URL.as_str(), api_key)?}};@@ -123,8 +129,8 @@ pub async fn start_deepgram_stream(.smart_format(true).diarize(true).build();-- debug!("deepgram options: {:?}", options);++ debug!("deepgram options: {:?}", options);let req = deepgram_transcription.stream_request_with_options(options)@@ -133,16 +139,19 @@ pub async fn start_deepgram_stream(.sample_rate(sample_rate).encoding(Encoding::Linear16);- debug!("sending deepgram request with encoding=Linear16, channels=1, sample_rate={}", sample_rate);-+ debug!(+ "sending deepgram request with encoding=Linear16, channels=1, sample_rate={}",+ sample_rate+ );+let mut handle = req.clone().handle().await?;debug!("deepgram handle created successfully");-+let mut results = req.stream(get_stream(stream, device.device_type.clone())).await?;debug!("deepgram stream started successfully");-+let device_clone = device.clone();// Add a sample of the expected response format for debugging@@ -164,7 +173,7 @@ pub async fn start_deepgram_stream(Ok(_) => debug!("sample response format is valid"),Err(e) => {debug!("expected format example error: {}", e);-+// Try to parse as generic JSON to see what we can extractif let Ok(value) = serde_json::from_str::<Value>(sample_response) {debug!("sample can be parsed as generic json: {}", value["type"]);@@ -187,18 +196,18 @@ pub async fn start_deepgram_stream(Err(e) => {// Log the errordebug!("Error in deepgram stream: {}", e);-+// Try to extract and process the raw JSON from the errorif let Some(raw_data) = e.to_string().find("data:") {let raw_str = &e.to_string()[raw_data..];debug!("Raw data excerpt: {}", raw_str);-+// Try to extract and process the raw JSONif let Some(json_start) = raw_str.find('{') {let json_str = &raw_str[json_start..];if let Ok(value) = serde_json::from_str::<Value>(json_str) {debug!("Processing raw JSON from error: {}", value);-+// Try to handle as a Results typeif value.get("type").and_then(|t| t.as_str()) == Some("Results") {debug!("Found Results type in error data, processing...");@@ -208,7 +217,7 @@ pub async fn start_deepgram_stream(}}}-+// Don't break the loop for deserialization errorsif e.to_string().contains("deserialization") {debug!("Continuing despite deserialization error");@@ -236,7 +245,7 @@ fn get_stream(tokio::spawn(async move {let mut packet_count = 0;let mut total_bytes = 0;-+while let Ok(data) = stream.recv().await {if device_type == DeviceType::Output {let sum_squares: f32 = data.iter().map(|&x| x * x).sum();@@ -250,7 +259,7 @@ fn get_stream(.as_millis() as i64,Ordering::SeqCst,);-+// Log display audio activitydebug!("display audio activity detected: rms={:.6}", rms);}@@ -269,15 +278,17 @@ fn get_stream(for sample in data {bytes.put_i16_le((sample * i16::MAX as f32) as i16);}-+packet_count += 1;total_bytes += bytes.len();-+if packet_count % 100 == 0 {- debug!("sent {} audio packets ({} bytes) to deepgram for device_type={:?}",- packet_count, total_bytes, device_type);+ debug!(+ "sent {} audio packets ({} bytes) to deepgram for device_type={:?}",+ packet_count, total_bytes, device_type+ );}-+if tx.send(Ok(bytes.freeze())).await.is_err() {debug!("stream receiver dropped, stopping audio transmission");break; // Stop if receiver is dropped@@ -291,7 +302,9 @@ fn get_stream(async fn handle_transcription(result: StreamResponse, device: Arc<AudioDevice>) {// Try to handle the result as a StreamResponse enum variant firstmatch result {- StreamResponse::TranscriptResponse { channel, is_final, .. } => {+ StreamResponse::TranscriptResponse {+ channel, is_final, ..+ } => {debug!("received transcription for device: {}, is_final: {}",device.name, is_final@@ -311,7 +324,7 @@ async fn handle_transcription(result: StreamResponse, device: Arc<AudioDevice>)if let Some(speaker_id) = &speaker {debug!("speaker identified: {}", speaker_id);}-+let _ = send_event("transcription",RealtimeTranscriptionEvent {@@ -324,38 +337,46 @@ async fn handle_transcription(result: StreamResponse, device: Arc<AudioDevice>)},);}- },+ }// Add a custom handler for the "Results" type that Deepgram actually sends_ => {// Convert the StreamResponse to a JSON Value to handle it genericallyif let Ok(value) = serde_json::to_value(&result) {debug!("handling raw response: {}", value);-+// Check if this is a "Results" type responseif value.get("type").and_then(|t| t.as_str()) == Some("Results") {- let is_final = value.get("is_final").and_then(|v| v.as_bool()).unwrap_or(false);-+ let is_final = value+ .get("is_final")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+// Extract the transcript from the channel alternativesif let Some(channel) = value.get("channel") {if let Some(alternatives) = channel.get("alternatives") {if let Some(first_alt) = alternatives.get(0) {- if let Some(transcript) = first_alt.get("transcript").and_then(|t| t.as_str()) {+ if let Some(transcript) =+ first_alt.get("transcript").and_then(|t| t.as_str())+ {if !transcript.is_empty() {debug!("extracted transcript from results: {}", transcript);-+// Extract speaker if availablelet speaker = if let Some(words) = first_alt.get("words") {if let Some(first_word) = words.get(0) {- first_word.get("speaker").and_then(|s| s.as_u64()).map(|s| s.to_string())+ first_word+ .get("speaker")+ .and_then(|s| s.as_u64())+ .map(|s| s.to_string())} else {None}} else {None};-+let is_input = device.device_type == DeviceType::Input;-+let _ = send_event("transcription",RealtimeTranscriptionEvent {diff --git a/screenpipe-audio/src/transcription/text_utils.rs b/screenpipe-audio/src/transcription/text_utils.rsindex e7cebf826..0bc015212 100644--- a/screenpipe-audio/src/transcription/text_utils.rs+++ b/screenpipe-audio/src/transcription/text_utils.rs@@ -1,38 +1,38 @@pub fn longest_common_word_substring(s1: &str, s2: &str) -> Option<(usize, usize)> {- let s1 = s1.to_lowercase();- let s2 = s2.to_lowercase();+ let s1 = s1.to_lowercase();+ let s2 = s2.to_lowercase();- let s1 = s1.replace(|c| char::is_ascii_punctuation(&c), "");- let s2 = s2.replace(|c| char::is_ascii_punctuation(&c), "");+ let s1 = s1.replace(|c| char::is_ascii_punctuation(&c), "");+ let s2 = s2.replace(|c| char::is_ascii_punctuation(&c), "");- let s1_words: Vec<&str> = s1.split_whitespace().collect();- let s2_words: Vec<&str> = s2.split_whitespace().collect();+ let s1_words: Vec<&str> = s1.split_whitespace().collect();+ let s2_words: Vec<&str> = s2.split_whitespace().collect();- let s1_len = s1_words.len();- let s2_len = s2_words.len();+ let s1_len = s1_words.len();+ let s2_len = s2_words.len();- // Table to store lengths of longest common suffixes of word substrings- let mut dp = vec![vec![0; s2_len + 1]; s1_len + 1];+ // Table to store lengths of longest common suffixes of word substrings+ let mut dp = vec![vec![0; s2_len + 1]; s1_len + 1];- let mut max_len = 0;- let mut max_index_s1 = None; // Store the starting word index of the longest substring in s1- let mut max_index_s2 = None; // Store the starting word index of the longest substring in s2+ let mut max_len = 0;+ let mut max_index_s1 = None; // Store the starting word index of the longest substring in s1+ let mut max_index_s2 = None; // Store the starting word index of the longest substring in s2- for i in 1..=s1_len {- for j in 1..=s2_len {- if s1_words[i - 1] == s2_words[j - 1] {- dp[i][j] = dp[i - 1][j - 1] + 1;- if dp[i][j] > max_len {- max_len = dp[i][j];- max_index_s1 = Some(i - max_len); // The start index of the match in s1- max_index_s2 = Some(j - max_len); // The start index of the match in s2- }- }- }- }+ for i in 1..=s1_len {+ for j in 1..=s2_len {+ if s1_words[i - 1] == s2_words[j - 1] {+ dp[i][j] = dp[i - 1][j - 1] + 1;+ if dp[i][j] > max_len {+ max_len = dp[i][j];+ max_index_s1 = Some(i - max_len); // The start index of the match in s1+ max_index_s2 = Some(j - max_len); // The start index of the match in s2+ }+ }+ }+ }- match (max_index_s1, max_index_s2) {- (Some(idx1), Some(idx2)) => Some((idx1, idx2)),- _ => None,- }+ match (max_index_s1, max_index_s2) {+ (Some(idx1), Some(idx2)) => Some((idx1, idx2)),+ _ => None,+ }}diff --git a/screenpipe-audio/src/utils/audio/resample.rs b/screenpipe-audio/src/utils/audio/resample.rsindex 5bbcb6542..871677b8f 100644--- a/screenpipe-audio/src/utils/audio/resample.rs+++ b/screenpipe-audio/src/utils/audio/resample.rs@@ -1,8 +1,8 @@use anyhow::Result;-use tracing::debug;use rubato::{Resampler, SincFixedIn, SincInterpolationParameters, SincInterpolationType, WindowFunction,};+use tracing::debug;pub fn resample(input: &[f32], from_sample_rate: u32, to_sample_rate: u32) -> Result<Vec<f32>> {debug!("Resampling audio");diff --git a/screenpipe-audio/src/utils/ffmpeg.rs b/screenpipe-audio/src/utils/ffmpeg.rsindex bf4ab8187..1b581e040 100644--- a/screenpipe-audio/src/utils/ffmpeg.rs+++ b/screenpipe-audio/src/utils/ffmpeg.rs@@ -1,6 +1,5 @@use anyhow::Result;use chrono::Utc;-use tracing::debug;use screenpipe_core::find_ffmpeg_path;use std::io::Write;use std::path::PathBuf;@@ -8,6 +7,7 @@ use std::{path::Path,process::{Command, Stdio},};+use tracing::debug;use tracing::error;fn encode_single_audio(diff --git a/screenpipe-core/examples/cron.rs b/screenpipe-core/examples/cron.rsindex 1a28af8fd..c60548c45 100644--- a/screenpipe-core/examples/cron.rs+++ b/screenpipe-core/examples/cron.rs@@ -1,4 +1,3 @@-use cron::Schedule;use std::str::FromStr;diff --git a/screenpipe-core/examples/win_automation.rs b/screenpipe-core/examples/win_automation.rsindex 5ffd19940..d96d3fcf3 100644--- a/screenpipe-core/examples/win_automation.rs+++ b/screenpipe-core/examples/win_automation.rs@@ -2,8 +2,8 @@ use std::thread;use std::time::Duration;use screenpipe_core::operator::platforms;-use screenpipe_core::operator::Selector;use screenpipe_core::operator::AutomationError;+use screenpipe_core::operator::Selector;// like a playground, just uncommentfn main() -> Result<(), AutomationError> {@@ -88,44 +88,43 @@ fn main() -> Result<(), AutomationError> {// // input.press_key("{enter}")?;// }-// Initialize the automation engine// Use true, true if you need debug logs and accessibility mode- let engine = platforms::create_engine(false, false)?;+ let engine = platforms::create_engine(false, false)?;// --- Part 1: Open Notepad and Simulate Legacy App ---// Ensure the file exists before trying to open it- // Open Notepad with the specific file- // Note: Opening notepad directly with a file might be OS dependent or tricky.- // A more robust way might be to open notepad first, then use 'ctrl+o', then type the path.- // Or, just open notepad blank and paste the data (less realistic simulation).- // Let's try opening notepad blank first, then finding the edit area and setting its value.- // let notepad_app = engine.open_application("notepad")?;- let notepad_app = engine.get_application_by_name("notepad")?;- println!("Notepad opened: {:?}", notepad_app.attributes());- thread::sleep(Duration::from_secs(2)); // Wait for app to load- notepad_app.focus()?;-- // Find the main text editing area in Notepad- // The role might be "document" or "edit" - requires inspection- // let notepad_edit_selector = Selector::Name("Text Editor".to_string());- // let notepad_edit_area = notepad_app.locator(notepad_edit_selector).unwrap().first().unwrap().unwrap();- // println!("Found Notepad edit area: {:?}", notepad_edit_area.attributes().properties);- // println!("Found Notepad edit area: {:?}", notepad_edit_area.text(10).unwrap_or_default());-- // Read the data from the file- // let legacy_data = fs::read_to_string(data_file_path)- // .map_err(|e| AutomationError::action(format!("failed to read data file: {}", e)))?;-- // Set the value (paste) the legacy data into Notepad's edit area- // Alternatively use type_text if set_value isn't reliable for this element- // notepad_edit_area.focus()?;- // let edit = notepad_app.children().unwrap();- // println!("edit: {:?}", edit);- thread::sleep(Duration::from_millis(200));- // notepad_edit_area.set_value(&legacy_data)?; // Might work- let formatted_text = r"CUSTOMER RECORD+ // Open Notepad with the specific file+ // Note: Opening notepad directly with a file might be OS dependent or tricky.+ // A more robust way might be to open notepad first, then use 'ctrl+o', then type the path.+ // Or, just open notepad blank and paste the data (less realistic simulation).+ // Let's try opening notepad blank first, then finding the edit area and setting its value.+ // let notepad_app = engine.open_application("notepad")?;+ let notepad_app = engine.get_application_by_name("notepad")?;+ println!("Notepad opened: {:?}", notepad_app.attributes());+ thread::sleep(Duration::from_secs(2)); // Wait for app to load+ notepad_app.focus()?;++ // Find the main text editing area in Notepad+ // The role might be "document" or "edit" - requires inspection+ // let notepad_edit_selector = Selector::Name("Text Editor".to_string());+ // let notepad_edit_area = notepad_app.locator(notepad_edit_selector).unwrap().first().unwrap().unwrap();+ // println!("Found Notepad edit area: {:?}", notepad_edit_area.attributes().properties);+ // println!("Found Notepad edit area: {:?}", notepad_edit_area.text(10).unwrap_or_default());++ // Read the data from the file+ // let legacy_data = fs::read_to_string(data_file_path)+ // .map_err(|e| AutomationError::action(format!("failed to read data file: {}", e)))?;++ // Set the value (paste) the legacy data into Notepad's edit area+ // Alternatively use type_text if set_value isn't reliable for this element+ // notepad_edit_area.focus()?;+ // let edit = notepad_app.children().unwrap();+ // println!("edit: {:?}", edit);+ thread::sleep(Duration::from_millis(200));+ // notepad_edit_area.set_value(&legacy_data)?; // Might work+ let formatted_text = r"CUSTOMER RECORDID 10039485 Created 2023 04 17Acme Industries LtdStatus ACTIVE Contact John Smith Phone 555 123 4567@@ -152,56 +151,55 @@ Balance 2825.50TODO follow up on missing documentation for order 7782remind about maintenance renewal coming up in December";-- // notepad_edit_area.type_text(formatted_text)?;- // sleep for 100ms- println!("Pasted data into Notepad.");- thread::sleep(Duration::from_millis(300));-- // --- Part 2: Extract Data from Notepad ---- // Re-fetch the element or use the existing one- // Get the text *value* from the edit area- let extracted_text = notepad_app.text(10)?; // Use .value() or maybe .text() depending on API- println!("Extracted text from Notepad:\n{}", extracted_text);-- // Basic parsing (replace with robust regex or parsing logic)- // let mut customer_id = "not found";- // let mut name = "not found";- // let mut total = "not found";-- // for line in extracted_text.lines() {- // if line.starts_with("Customer ID:") {- // customer_id = line.split(':').nth(1).map_or("parse error", |s| s.trim());- // } else if line.starts_with("Name:") {- // name = line.split(':').nth(1).map_or("parse error", |s| s.trim());- // } else if line.starts_with("Order Total:") {- // total = line.split(':').nth(1).map_or("parse error", |s| s.trim());- // }- // }- // println!("Parsed - ID: {}, Name: {}, Total: {}", customer_id, name, total);--- // --- Part 3: Open Google Sheets and Input Data ---- println!("Opening Google Sheets...");- let sheets_app = engine.open_url("https://docs.google.com/spreadsheets/d/1u2vPS43pkFdIrtWbl4Ug7D1ROmrtSD-YTo24FwGqDdo/edit?gid=0#gid=0", None)?;- // let sheets_app = engine.open_url("https://docs.google.com/spreadsheets/u/1/", None)?;- println!("Sheets opened: {:?}", sheets_app.attributes());- // Wait for Sheets to load- // thread::sleep(Duration::from_secs(5));-- // sheets_app.focus()?;- // println!("Focused Sheets window.");- // thread::sleep(Duration::from_millis(500));-- // open new sheet using- // let new_sheet = sheets_app.locator(Selector::Text("Blank spreadsheet".to_string())).unwrap().first().unwrap().unwrap();- // println!("new sheet: {:?}", new_sheet);- // new_sheet.focus()?;- // new_sheet.press_key("{enter}")?;- thread::sleep(Duration::from_millis(500));-- // Instead of a single string with {enter} characters, break into separate lines- let sheet_data = [++ // notepad_edit_area.type_text(formatted_text)?;+ // sleep for 100ms+ println!("Pasted data into Notepad.");+ thread::sleep(Duration::from_millis(300));++ // --- Part 2: Extract Data from Notepad ---+ // Re-fetch the element or use the existing one+ // Get the text *value* from the edit area+ let extracted_text = notepad_app.text(10)?; // Use .value() or maybe .text() depending on API+ println!("Extracted text from Notepad:\n{}", extracted_text);++ // Basic parsing (replace with robust regex or parsing logic)+ // let mut customer_id = "not found";+ // let mut name = "not found";+ // let mut total = "not found";++ // for line in extracted_text.lines() {+ // if line.starts_with("Customer ID:") {+ // customer_id = line.split(':').nth(1).map_or("parse error", |s| s.trim());+ // } else if line.starts_with("Name:") {+ // name = line.split(':').nth(1).map_or("parse error", |s| s.trim());+ // } else if line.starts_with("Order Total:") {+ // total = line.split(':').nth(1).map_or("parse error", |s| s.trim());+ // }+ // }+ // println!("Parsed - ID: {}, Name: {}, Total: {}", customer_id, name, total);++ // --- Part 3: Open Google Sheets and Input Data ---+ println!("Opening Google Sheets...");+ let sheets_app = engine.open_url("https://docs.google.com/spreadsheets/d/1u2vPS43pkFdIrtWbl4Ug7D1ROmrtSD-YTo24FwGqDdo/edit?gid=0#gid=0", None)?;+ // let sheets_app = engine.open_url("https://docs.google.com/spreadsheets/u/1/", None)?;+ println!("Sheets opened: {:?}", sheets_app.attributes());+ // Wait for Sheets to load+ // thread::sleep(Duration::from_secs(5));++ // sheets_app.focus()?;+ // println!("Focused Sheets window.");+ // thread::sleep(Duration::from_millis(500));++ // open new sheet using+ // let new_sheet = sheets_app.locator(Selector::Text("Blank spreadsheet".to_string())).unwrap().first().unwrap().unwrap();+ // println!("new sheet: {:?}", new_sheet);+ // new_sheet.focus()?;+ // new_sheet.press_key("{enter}")?;+ thread::sleep(Duration::from_millis(500));++ // Instead of a single string with {enter} characters, break into separate lines+ let sheet_data = ["Customer ID\tCompany\tContact\tPhone\tEmail\tStatus\tBalance","10039485\tAcme Industries Ltd\tJohn Smith\t555 123 4567\[email protected]\tACTIVE\t2825.50","Order ID\tDate\tAmount\tItems\tStatus",@@ -213,50 +211,47 @@ remind about maintenance renewal coming up in December";"Maintenance renewal\t2023-12-15\tReminder sent"];- // Visual indication of AI processing before pasting- println!("ai analyzing legacy system data...");- thread::sleep(Duration::from_millis(800));- println!("extracting structured information...");- thread::sleep(Duration::from_millis(800));- println!("transforming to tabular format...");- thread::sleep(Duration::from_millis(800));- println!("data ready for input. filling spreadsheet...");-- // Get the currently focused element (should be in the sheet)- let focused_element = engine.get_focused_element()?;- focused_element.focus()?;-- // Type each line and press Enter between them- for line in sheet_data.iter() {- focused_element.type_text(line)?;- focused_element.press_key("{enter}")?;- thread::sleep(Duration::from_millis(100)); // Small delay between lines- }-- println!("data successfully transferred from legacy system to google sheets!");- thread::sleep(Duration::from_secs(2));--- // --- Part 4: Close Applications (Optional Cleanup) ---- // This might require specific 'close window' buttons or alt+f4- // println!("Closing Notepad...");- // Find close button? Or send Alt+F4?- // notepad_app.press_key("{alt down}{f4}{alt up}")?;- // thread::sleep(Duration::from_millis(500));- // // Handle potential "Save?" dialog - find "Don't Save" button-- // println!("Closing Excel...");- // excel_app.press_key("{alt down}{f4}{alt up}")?;- // thread::sleep(Duration::from_millis(500));- // // Handle potential "Save?" dialog--+ // Visual indication of AI processing before pasting+ println!("ai analyzing legacy system data...");+ thread::sleep(Duration::from_millis(800));+ println!("extracting structured information...");+ thread::sleep(Duration::from_millis(800));+ println!("transforming to tabular format...");+ thread::sleep(Duration::from_millis(800));+ println!("data ready for input. filling spreadsheet...");++ // Get the currently focused element (should be in the sheet)+ let focused_element = engine.get_focused_element()?;+ focused_element.focus()?;++ // Type each line and press Enter between them+ for line in sheet_data.iter() {+ focused_element.type_text(line)?;+ focused_element.press_key("{enter}")?;+ thread::sleep(Duration::from_millis(100)); // Small delay between lines+ }++ println!("data successfully transferred from legacy system to google sheets!");+ thread::sleep(Duration::from_secs(2));++ // --- Part 4: Close Applications (Optional Cleanup) ---+ // This might require specific 'close window' buttons or alt+f4+ // println!("Closing Notepad...");+ // Find close button? Or send Alt+F4?+ // notepad_app.press_key("{alt down}{f4}{alt up}")?;+ // thread::sleep(Duration::from_millis(500));+ // // Handle potential "Save?" dialog - find "Don't Save" button++ // println!("Closing Excel...");+ // excel_app.press_key("{alt down}{f4}{alt up}")?;+ // thread::sleep(Duration::from_millis(500));+ // // Handle potential "Save?" dialogprintln!("Demo script finished.");// input.focus()?;// input.type_text("hi")?;// input.press_key("{enter}")?;- // get some texts from application root+ // get some texts from application root// (heavy computational task keep depth low)// let text = element.text(10)?;// println!("element text: {:?}", text);@@ -270,7 +265,6 @@ remind about maintenance renewal coming up in December";// println!("locator: {:?}", l.bounds());// }-// check if enabled// let is_enabled = element.is_enabled()?;// println!("Is enabled: {:?}", is_enabled);diff --git a/screenpipe-core/examples/windows_pdf_to_legacy.rs b/screenpipe-core/examples/windows_pdf_to_legacy.rsindex 7c9c5f002..190bee7f8 100644--- a/screenpipe-core/examples/windows_pdf_to_legacy.rs+++ b/screenpipe-core/examples/windows_pdf_to_legacy.rs@@ -1,13 +1,14 @@use std::thread;use std::time::Duration;-use anyhow::{Result}; // Use anyhow for better error handling+use anyhow::Result; // Use anyhow for better error handlinguse screenpipe_core::operator::platforms;use screenpipe_core::operator::{AutomationError, Selector}; // Import Element// like a playground, just uncomment-fn main() -> Result<()> { // Use anyhow::Result+fn main() -> Result<()> {+ // Use anyhow::Result// Initialize the automation engine// Use true, true if you need debug logs and accessibility modelet engine = platforms::create_engine(false, false)?;@@ -23,7 +24,9 @@ fn main() -> Result<()> { // Use anyhow::Result// return Ok(());- let pharma_app = engine.get_application_by_name("pharma.com - v0 App").unwrap();+ let pharma_app = engine+ .get_application_by_name("pharma.com - v0 App")+ .unwrap();pharma_app.focus()?;println!("pdf viewer focused.");thread::sleep(Duration::from_secs(1));@@ -32,78 +35,92 @@ fn main() -> Result<()> { // Use anyhow::Resultthread::sleep(Duration::from_secs(2)); // Wait for app to be ready// find all input fields- let input_fields = pharma_app.locator(Selector::Role { role: "edit".to_string(), name: None }).unwrap().all().unwrap();+ let input_fields = pharma_app+ .locator(Selector::Role {+ role: "edit".to_string(),+ name: None,+ })+ .unwrap()+ .all()+ .unwrap();// println!("input fields: {:?}", input_fields);- // Define the data to be filled using AutomationId- let text_fields = vec![- ("patientName", "Johnathan Michael Sterling"),- ("dob", "03/15/1968"),- ("address", "123 Meadow Lane"),- ("phone", "(555) 123-4567"),- ("cityState", "Anytown, CA 90210"),- ("email", "[email protected]"),- ("physicianName", "Dr. Evelyn Reed"),- ("npiNumber", "1234567890"),- ("facilityName", "Anytown General Hospital"),- ("officePhone", "(555) 987-6543"),- ("facilityAddress", "456 Health Plaza, Anytown, CA 90211"),- ("officeFax", "(555) 987-6544"),- ("medication", "CardiaCare XR"),- ("dosage", "100mg"),- ("frequency", "Once Daily"),- ("diagnosis", "I10 (Essential Hypertension)"),- ("insuranceName", "Blue Shield United"),- ("policyNumber", "MBR123456789"),- ("groupNumber", "GRP789XYZ"),- ("income", "$48,500"),- ("householdMembers", "2"),- // ("otherSpecify", "N/A"), // Uncomment if needed- ("signature", "Johnathan M. Sterling"),- ("signatureDate", "11/02/2023"),- // ("relationship", ""), // Leave blank- ];-- // Define the AutomationIds for radio buttons to click- let radio_click_fields = vec![- "insuranceYes",- "medicareNo",- "medicaidNo",- ];-- // Define the AutomationIds for checkboxes to click- let checkbox_click_fields = vec![- "taxReturn",- "payStubs",- // Add other checkbox IDs here if needed, e.g., "socialSecurity", "other"- ];+ // Define the data to be filled using AutomationId+ let text_fields = vec![+ ("patientName", "Johnathan Michael Sterling"),+ ("dob", "03/15/1968"),+ ("address", "123 Meadow Lane"),+ ("phone", "(555) 123-4567"),+ ("cityState", "Anytown, CA 90210"),+ ("email", "[email protected]"),+ ("physicianName", "Dr. Evelyn Reed"),+ ("npiNumber", "1234567890"),+ ("facilityName", "Anytown General Hospital"),+ ("officePhone", "(555) 987-6543"),+ ("facilityAddress", "456 Health Plaza, Anytown, CA 90211"),+ ("officeFax", "(555) 987-6544"),+ ("medication", "CardiaCare XR"),+ ("dosage", "100mg"),+ ("frequency", "Once Daily"),+ ("diagnosis", "I10 (Essential Hypertension)"),+ ("insuranceName", "Blue Shield United"),+ ("policyNumber", "MBR123456789"),+ ("groupNumber", "GRP789XYZ"),+ ("income", "$48,500"),+ ("householdMembers", "2"),+ // ("otherSpecify", "N/A"), // Uncomment if needed+ ("signature", "Johnathan M. Sterling"),+ ("signatureDate", "11/02/2023"),+ // ("relationship", ""), // Leave blank+ ];++ // Define the AutomationIds for radio buttons to click+ let radio_click_fields = vec!["insuranceYes", "medicareNo", "medicaidNo"];++ // Define the AutomationIds for checkboxes to click+ let checkbox_click_fields = vec![+ "taxReturn",+ "payStubs",+ // Add other checkbox IDs here if needed, e.g., "socialSecurity", "other"+ ];// for each input field, set the value to "test"for input_field in input_fields {let attrs = input_field.attributes();- let automation_id_raw = attrs.properties.get("AutomationId")+ let automation_id_raw = attrs+ .properties+ .get("AutomationId").and_then(|opt| opt.as_ref()).and_then(|val| val.as_str()).unwrap_or("");// Extract the actual ID from the "STRING(...)" format- let automation_id = if automation_id_raw.starts_with("STRING(") && automation_id_raw.ends_with(')') {- &automation_id_raw[7..automation_id_raw.len() - 1] // Get the substring inside STRING(...)- } else {- automation_id_raw // Use the raw value if it doesn't match the format- };-- println!("input field raw: {:?}, parsed: {:?}", automation_id_raw, automation_id); // Updated log-- let text_to_type = text_fields.iter().find(|(id, _)| {- automation_id == *id // Now compares the parsed ID- }).unwrap_or_else(|| {- println!("no text field found for automation id: {:?}", automation_id); // Log parsed ID- // Log the full properties map for context if not found- println!("full properties for missing id: {:?}", attrs.properties);- &("", "")- }).1;- if text_to_type.is_empty() { // Use is_empty() for clarity+ let automation_id =+ if automation_id_raw.starts_with("STRING(") && automation_id_raw.ends_with(')') {+ &automation_id_raw[7..automation_id_raw.len() - 1] // Get the substring inside STRING(...)+ } else {+ automation_id_raw // Use the raw value if it doesn't match the format+ };++ println!(+ "input field raw: {:?}, parsed: {:?}",+ automation_id_raw, automation_id+ ); // Updated log++ let text_to_type = text_fields+ .iter()+ .find(|(id, _)| {+ automation_id == *id // Now compares the parsed ID+ })+ .unwrap_or_else(|| {+ println!("no text field found for automation id: {:?}", automation_id); // Log parsed ID+ // Log the full properties map for context if not found+ println!("full properties for missing id: {:?}", attrs.properties);+ &("", "")+ })+ .1;+ if text_to_type.is_empty() {+ // Use is_empty() for claritycontinue;}if let Err(e) = input_field.focus() {@@ -116,37 +133,59 @@ fn main() -> Result<()> { // Use anyhow::Resultprintln!("error clicking on input field ({}): {:?}", automation_id, e);}if let Err(e) = input_field.type_text(text_to_type) {- println!("error typing text ('{}') into input field ({}): {:?}", text_to_type, automation_id, e);+ println!(+ "error typing text ('{}') into input field ({}): {:?}",+ text_to_type, automation_id, e+ );}- println!("typed '{}' into input field id: {}", text_to_type, automation_id); // Updated log+ println!(+ "typed '{}' into input field id: {}",+ text_to_type, automation_id+ ); // Updated logthread::sleep(Duration::from_millis(10));}-// get all radio buttons and click the specified ones- let radio_buttons = pharma_app.locator(Selector::Role { role: "radiobutton".to_string(), name: None }).unwrap().all().unwrap();+ let radio_buttons = pharma_app+ .locator(Selector::Role {+ role: "radiobutton".to_string(),+ name: None,+ })+ .unwrap()+ .all()+ .unwrap();for radio_button in radio_buttons {let attrs = radio_button.attributes();- let automation_id_raw = attrs.properties.get("AutomationId")+ let automation_id_raw = attrs+ .properties+ .get("AutomationId").and_then(|opt| opt.as_ref()).and_then(|val| val.as_str()).unwrap_or("");// Extract the actual ID from the "STRING(...)" format- let automation_id = if automation_id_raw.starts_with("STRING(") && automation_id_raw.ends_with(')') {- &automation_id_raw[7..automation_id_raw.len() - 1]- } else {- automation_id_raw- };+ let automation_id =+ if automation_id_raw.starts_with("STRING(") && automation_id_raw.ends_with(')') {+ &automation_id_raw[7..automation_id_raw.len() - 1]+ } else {+ automation_id_raw+ };// Check if this radio button's ID is in the list of fields to click- if radio_click_fields.contains(&automation_id) { // Use the new radio_click_fields vector+ if radio_click_fields.contains(&automation_id) {+ // Use the new radio_click_fields vectorprintln!("attempting to click radio button: {}", automation_id);if let Err(e) = radio_button.focus() {- println!("error focusing on radio button ({}): {:?}", automation_id, e);+ println!(+ "error focusing on radio button ({}): {:?}",+ automation_id, e+ );}if let Err(e) = radio_button.hover() {- println!("error hovering on radio button ({}): {:?}", automation_id, e);+ println!(+ "error hovering on radio button ({}): {:?}",+ automation_id, e+ );}if let Err(e) = radio_button.click() {println!("error clicking radio button ({}): {:?}", automation_id, e);@@ -155,30 +194,41 @@ fn main() -> Result<()> { // Use anyhow::Result}thread::sleep(Duration::from_millis(50)); // Small delay after clicking} else {- // Optional: Log radio buttons that are found but not in the click_fields list- // println!("skipping radio button (not in click_fields): {}", automation_id);+ // Optional: Log radio buttons that are found but not in the click_fields list+ // println!("skipping radio button (not in click_fields): {}", automation_id);}}// get all checkboxes and click the specified ones- let checkboxes = pharma_app.locator(Selector::Role { role: "checkbox".to_string(), name: None }).unwrap().all().unwrap();+ let checkboxes = pharma_app+ .locator(Selector::Role {+ role: "checkbox".to_string(),+ name: None,+ })+ .unwrap()+ .all()+ .unwrap();for checkbox in checkboxes {let attrs = checkbox.attributes();- let automation_id_raw = attrs.properties.get("AutomationId")+ let automation_id_raw = attrs+ .properties+ .get("AutomationId").and_then(|opt| opt.as_ref()).and_then(|val| val.as_str()).unwrap_or("");// Extract the actual ID from the "STRING(...)" format- let automation_id = if automation_id_raw.starts_with("STRING(") && automation_id_raw.ends_with(')') {- &automation_id_raw[7..automation_id_raw.len() - 1]- } else {- automation_id_raw- };+ let automation_id =+ if automation_id_raw.starts_with("STRING(") && automation_id_raw.ends_with(')') {+ &automation_id_raw[7..automation_id_raw.len() - 1]+ } else {+ automation_id_raw+ };println!("checkbox automation id: {}", automation_id);// Check if this checkbox's ID is in the list of fields to click- if checkbox_click_fields.contains(&automation_id) { // Use the new checkbox_click_fields vector+ if checkbox_click_fields.contains(&automation_id) {+ // Use the new checkbox_click_fields vectorprintln!("attempting to click checkbox: {}", automation_id);if let Err(e) = checkbox.focus() {println!("error focusing on checkbox ({}): {:?}", automation_id, e);@@ -195,11 +245,10 @@ fn main() -> Result<()> { // Use anyhow::Result}thread::sleep(Duration::from_millis(50)); // Small delay after clicking} else {- // Optional: Log checkboxes found but not in the click list- // println!("skipping checkbox (not in click_fields): {}", automation_id);+ // Optional: Log checkboxes found but not in the click list+ // println!("skipping checkbox (not in click_fields): {}", automation_id);}}-Ok(()) // Use Ok(()) for anyhow::Result}diff --git a/screenpipe-core/src/embedding/mod.rs b/screenpipe-core/src/embedding/mod.rsindex 757b2013c..65880be0e 100644--- a/screenpipe-core/src/embedding/mod.rs+++ b/screenpipe-core/src/embedding/mod.rs@@ -1,2 +1 @@pub mod model;-diff --git a/screenpipe-core/src/operator/platforms/windows.rs b/screenpipe-core/src/operator/platforms/windows.rsindex e04eac066..137a4a907 100644--- a/screenpipe-core/src/operator/platforms/windows.rs+++ b/screenpipe-core/src/operator/platforms/windows.rs@@ -2,25 +2,20 @@ use crate::operator::element::UIElementImpl;use crate::operator::platforms::AccessibilityEngine;use crate::operator::ClickResult;use crate::operator::{AutomationError, Locator, Selector, UIElement, UIElementAttributes};+use std::collections::{hash_map::DefaultHasher, HashMap};use std::error::Error;-use std::sync::Arc;use std::fmt::Debug;use std::hash::{Hash, Hasher};-use uiautomation::filters::{ControlTypeFilter, NameFilter, OrFilter};-use uiautomation::UIAutomation;+use std::sync::Arc;+use tracing::debug;use uiautomation::controls::ControlType;-use uiautomation::inputs::Mouse;+use uiautomation::filters::{ControlTypeFilter, NameFilter, OrFilter};use uiautomation::inputs::Keyboard;-use uiautomation::variants::Variant;+use uiautomation::inputs::Mouse;use uiautomation::patterns;-use tracing::debug;-use std::collections::{- HashMap,- hash_map::DefaultHasher-};-use uiautomation::types::{- Point, PropertyConditionFlags, ScrollAmount, TreeScope, UIProperty-};+use uiautomation::types::{Point, PropertyConditionFlags, ScrollAmount, TreeScope, UIProperty};+use uiautomation::variants::Variant;+use uiautomation::UIAutomation;// thread-safety#[derive(Clone)]@@ -32,7 +27,7 @@ unsafe impl Sync for ThreadSafeWinUIAutomation {}#[allow(unused)]// there is no need of `use_background_apps` or `activate_app`-// windows IUIAutomation will get current running app &+// windows IUIAutomation will get current running app &// background running app spontaneously, keeping it anyway!!pub struct WindowsEngine {automation: ThreadSafeWinUIAutomation,@@ -42,7 +37,8 @@ pub struct WindowsEngine {impl WindowsEngine {pub fn new(use_background_apps: bool, activate_app: bool) -> Result<Self, AutomationError> {- let automation = UIAutomation::new().map_err(|e| AutomationError::PlatformError(e.to_string()))?;+ let automation =+ UIAutomation::new().map_err(|e| AutomationError::PlatformError(e.to_string()))?;let arc_automation = ThreadSafeWinUIAutomation(Arc::new(automation));Ok(Self {automation: arc_automation,@@ -61,40 +57,55 @@ impl AccessibilityEngine for WindowsEngine {fn get_element_by_id(&self, id: i32) -> Result<UIElement, AutomationError> {let root_element = self.automation.0.get_root_element().unwrap();- let condition = self.automation.0.create_property_condition(- UIProperty::ProcessId,- Variant::from(id),- None- ).unwrap();- let ele = root_element.find_first(TreeScope::Subtree, &condition)+ let condition = self+ .automation+ .0+ .create_property_condition(UIProperty::ProcessId, Variant::from(id), None)+ .unwrap();+ let ele = root_element+ .find_first(TreeScope::Subtree, &condition).map_err(|e| AutomationError::ElementNotFound(e.to_string()))?;let arc_ele = ThreadSafeWinUIElement(Arc::new(ele));- Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })))+ Ok(UIElement::new(Box::new(WindowsUIElement {+ element: arc_ele,+ })))}fn get_focused_element(&self) -> Result<UIElement, AutomationError> {- let element = self.automation.0.get_focused_element()+ let element = self+ .automation+ .0+ .get_focused_element().map_err(|e| AutomationError::ElementNotFound(e.to_string()))?;let arc_element = ThreadSafeWinUIElement(Arc::new(element));-- Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_element })))++ Ok(UIElement::new(Box::new(WindowsUIElement {+ element: arc_element,+ })))}fn get_applications(&self) -> Result<Vec<UIElement>, AutomationError> {let root = self.automation.0.get_root_element().unwrap();- let condition = self.automation.0.create_property_condition(- UIProperty::ControlType,- Variant::from(ControlType::Window as i32),- None- ).unwrap();- let elements = root.find_all(TreeScope::Subtree, &condition)+ let condition = self+ .automation+ .0+ .create_property_condition(+ UIProperty::ControlType,+ Variant::from(ControlType::Window as i32),+ None,+ )+ .unwrap();+ let elements = root+ .find_all(TreeScope::Subtree, &condition).map_err(|e| AutomationError::ElementNotFound(e.to_string()))?;- let arc_elements: Vec<UIElement> = elements.into_iter()+ let arc_elements: Vec<UIElement> = elements+ .into_iter().map(|ele| {let arc_ele = ThreadSafeWinUIElement(Arc::new(ele));UIElement::new(Box::new(WindowsUIElement { element: arc_ele }))- }).collect();+ })+ .collect();Ok(arc_elements)}@@ -106,13 +117,17 @@ impl AccessibilityEngine for WindowsEngine {let root_ele = self.automation.0.get_root_element().unwrap();let automation = WindowsEngine::new(false, false).map_err(|e| AutomationError::PlatformError(e.to_string()))?;- let matcher = automation.automation.0.create_matcher()+ let matcher = automation+ .automation+ .0+ .create_matcher().control_type(ControlType::Window).contains_name(name).from_ref(&root_ele).depth(7).timeout(5000);- let ele_res = matcher.find_first()+ let ele_res = matcher+ .find_first().map_err(|e| AutomationError::ElementNotFound(e.to_string()));// fallback to find by pid@@ -122,30 +137,37 @@ impl AccessibilityEngine for WindowsEngine {let pid = match get_pid_by_name(name) {Some(pid) => pid,None => {- return Err(AutomationError::PlatformError(- format!("no running application found from name: {:?}", name)- ));+ return Err(AutomationError::PlatformError(format!(+ "no running application found from name: {:?}",+ name+ )));}};- let condition = automation.automation.0.create_property_condition(- UIProperty::ProcessId,- Variant::from(pid as i32),- None- ).unwrap();- root_ele.find_first(TreeScope::Subtree, &condition)+ let condition = automation+ .automation+ .0+ .create_property_condition(+ UIProperty::ProcessId,+ Variant::from(pid as i32),+ None,+ )+ .unwrap();+ root_ele+ .find_first(TreeScope::Subtree, &condition).map_err(|e| AutomationError::ElementNotFound(e.to_string()))?}};let arc_ele = ThreadSafeWinUIElement(Arc::new(ele));- return Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })));+ return Ok(UIElement::new(Box::new(WindowsUIElement {+ element: arc_ele,+ })));}fn find_elements(&self,selector: &Selector,- root: Option<&UIElement>+ root: Option<&UIElement>,) -> Result<Vec<UIElement>, AutomationError> {-let root_ele = if let Some(el) = root {if let Some(ele) = el.as_any().downcast_ref::<WindowsUIElement>() {&ele.element.0@@ -160,75 +182,119 @@ impl AccessibilityEngine for WindowsEngine {let condition = match selector {Selector::Role { role, name: _ } => {let roles = map_generic_role_to_win_roles(role);- let role_condition = self.automation.0.create_property_condition(- UIProperty::ControlType,- Variant::from(roles as i32),- None- ).unwrap();- debug!("role conditions: {:#?} for finding element: {:#?}",- role_condition, root_ele);+ let role_condition = self+ .automation+ .0+ .create_property_condition(+ UIProperty::ControlType,+ Variant::from(roles as i32),+ None,+ )+ .unwrap();+ debug!(+ "role conditions: {:#?} for finding element: {:#?}",+ role_condition, root_ele+ );role_condition- },- Selector::Id(id) => self.automation.0.create_property_condition(- UIProperty::AutomationId,- Variant::from(id.as_str()),- None- ).unwrap(),- Selector::Name(_name) => self.automation.0.create_property_condition(- UIProperty::ControlType,- Variant::from(ControlType::Window as i32),- None- ).unwrap(),+ }+ Selector::Id(id) => self+ .automation+ .0+ .create_property_condition(+ UIProperty::AutomationId,+ Variant::from(id.as_str()),+ None,+ )+ .unwrap(),+ Selector::Name(_name) => self+ .automation+ .0+ .create_property_condition(+ UIProperty::ControlType,+ Variant::from(ControlType::Window as i32),+ None,+ )+ .unwrap(),Selector::Text(text) => {-let filter = OrFilter {- left: Box::new(NameFilter { value: String::from(text), casesensitive: false, partial: true }),- right: Box::new(ControlTypeFilter { control_type: ControlType::Text }),+ left: Box::new(NameFilter {+ value: String::from(text),+ casesensitive: false,+ partial: true,+ }),+ right: Box::new(ControlTypeFilter {+ control_type: ControlType::Text,+ }),};// Create a matcher that uses contains_name which is more reliable for text searching- let matcher = self.automation.0.create_matcher()+ let matcher = self+ .automation+ .0+ .create_matcher().from_ref(root_ele)- .filter(Box::new(filter))// This is the key improvement from the example- .depth(10) // Search deep enough to find most elements- .timeout(3000); // Allow enough time for search-+ .filter(Box::new(filter)) // This is the key improvement from the example+ .depth(10) // Search deep enough to find most elements+ .timeout(3000); // Allow enough time for search+// Get the first matching element- let elements = matcher.find_all()- .map_err(|e| AutomationError::ElementNotFound(- format!("Text: '{}', Err: {}", text, e.to_string())))?;-- return Ok(- elements.into_iter()- .map(|ele| UIElement::new(Box::new(WindowsUIElement { element: ThreadSafeWinUIElement(Arc::new(ele)) })))- .collect()- );- },+ let elements = matcher.find_all().map_err(|e| {+ AutomationError::ElementNotFound(format!(+ "Text: '{}', Err: {}",+ text,+ e.to_string()+ ))+ })?;++ return Ok(elements+ .into_iter()+ .map(|ele| {+ UIElement::new(Box::new(WindowsUIElement {+ element: ThreadSafeWinUIElement(Arc::new(ele)),+ }))+ })+ .collect());+ }Selector::Path(_) => {- return Err(AutomationError::UnsupportedOperation("`Path` selector not supported".to_string()));- },+ return Err(AutomationError::UnsupportedOperation(+ "`Path` selector not supported".to_string(),+ ));+ }Selector::Attributes(_attributes) => {- return Err(AutomationError::UnsupportedOperation("`Attributes` selector not supported".to_string()));- },+ return Err(AutomationError::UnsupportedOperation(+ "`Attributes` selector not supported".to_string(),+ ));+ }Selector::Filter(_filter) => {- return Err(AutomationError::UnsupportedOperation("`Filter` selector not supported".to_string()));- },+ return Err(AutomationError::UnsupportedOperation(+ "`Filter` selector not supported".to_string(),+ ));+ }Selector::Chain(_selectors) => {- return Err(AutomationError::UnsupportedOperation("`selectors` selector not supported".to_string()));- },+ return Err(AutomationError::UnsupportedOperation(+ "`selectors` selector not supported".to_string(),+ ));+ }};- let elements = root_ele.find_all(TreeScope::Subtree, &condition)+ let elements = root_ele+ .find_all(TreeScope::Subtree, &condition).map_err(|e| AutomationError::ElementNotFound(e.to_string()))?;- let arc_elements: Vec<UIElement> = elements.into_iter()+ let arc_elements: Vec<UIElement> = elements+ .into_iter().map(|ele| {let arc_ele = ThreadSafeWinUIElement(Arc::new(ele));UIElement::new(Box::new(WindowsUIElement { element: arc_ele }))- }).collect();-+ })+ .collect();+Ok(arc_elements)}- fn find_element(&self, selector: &Selector, root: Option<&UIElement>) -> Result<UIElement, AutomationError> {+ fn find_element(+ &self,+ selector: &Selector,+ root: Option<&UIElement>,+ ) -> Result<UIElement, AutomationError> {let root_ele = if let Some(el) = root {if let Some(ele) = el.as_any().downcast_ref::<WindowsUIElement>() {&ele.element.0@@ -243,88 +309,146 @@ impl AccessibilityEngine for WindowsEngine {Selector::Role { role, name: _ } => {let roles = map_generic_role_to_win_roles(role);// use create matcher api- let matcher = self.automation.0.create_matcher()+ let matcher = self+ .automation+ .0+ .create_matcher().from_ref(root_ele).control_type(roles).timeout(3000);- let element = matcher.find_first()+ let element = matcher+ .find_first().map_err(|e| AutomationError::ElementNotFound(e.to_string()))?;let arc_ele = ThreadSafeWinUIElement(Arc::new(element));- Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })))- },+ Ok(UIElement::new(Box::new(WindowsUIElement {+ element: arc_ele,+ })))+ }Selector::Id(id) => {- let condition = self.automation.0.create_property_condition(- UIProperty::AutomationId,- Variant::from(id.as_str()),- None- ).unwrap();-- let ele = root_ele.find_first(TreeScope::Subtree, &condition)- .map_err(|e| AutomationError::ElementNotFound(- format!("ID: '{}', Err: {}", id, e.to_string())))?;+ let condition = self+ .automation+ .0+ .create_property_condition(+ UIProperty::AutomationId,+ Variant::from(id.as_str()),+ None,+ )+ .unwrap();++ let ele = root_ele+ .find_first(TreeScope::Subtree, &condition)+ .map_err(|e| {+ AutomationError::ElementNotFound(format!(+ "ID: '{}', Err: {}",+ id,+ e.to_string()+ ))+ })?;let arc_ele = ThreadSafeWinUIElement(Arc::new(ele));- Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })))- },+ Ok(UIElement::new(Box::new(WindowsUIElement {+ element: arc_ele,+ })))+ }Selector::Name(name) => {- // find use create matcher api+ // find use create matcher api- let matcher = self.automation.0.create_matcher()+ let matcher = self+ .automation+ .0+ .create_matcher().from_ref(root_ele).contains_name(name).depth(10).timeout(3000);- let element = matcher.find_first()- .map_err(|e| AutomationError::ElementNotFound(- format!("Name: '{}', Err: {}", name, e.to_string())))?;+ let element = matcher.find_first().map_err(|e| {+ AutomationError::ElementNotFound(format!(+ "Name: '{}', Err: {}",+ name,+ e.to_string()+ ))+ })?;let arc_ele = ThreadSafeWinUIElement(Arc::new(element));- return Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })));- },+ return Ok(UIElement::new(Box::new(WindowsUIElement {+ element: arc_ele,+ })));+ }Selector::Text(text) => {-let filter = OrFilter {- left: Box::new(NameFilter { value: String::from(text), casesensitive: false, partial: true }),- right: Box::new(ControlTypeFilter { control_type: ControlType::Text }),+ left: Box::new(NameFilter {+ value: String::from(text),+ casesensitive: false,+ partial: true,+ }),+ right: Box::new(ControlTypeFilter {+ control_type: ControlType::Text,+ }),};// Create a matcher that uses contains_name which is more reliable for text searching- let matcher = self.automation.0.create_matcher()+ let matcher = self+ .automation+ .0+ .create_matcher().from_ref(root_ele)- .filter(Box::new(filter))// This is the key improvement from the example- .depth(10) // Search deep enough to find most elements- .timeout(3000); // Allow enough time for search-+ .filter(Box::new(filter)) // This is the key improvement from the example+ .depth(10) // Search deep enough to find most elements+ .timeout(3000); // Allow enough time for search+// Get the first matching element- let element = matcher.find_first()- .map_err(|e| AutomationError::ElementNotFound(- format!("Text: '{}', Err: {}", text, e.to_string())))?;-+ let element = matcher.find_first().map_err(|e| {+ AutomationError::ElementNotFound(format!(+ "Text: '{}', Err: {}",+ text,+ e.to_string()+ ))+ })?;+let arc_ele = ThreadSafeWinUIElement(Arc::new(element));- return Ok(UIElement::new(Box::new(WindowsUIElement { element: arc_ele })));- },+ return Ok(UIElement::new(Box::new(WindowsUIElement {+ element: arc_ele,+ })));+ }Selector::Path(_) => {- return Err(AutomationError::UnsupportedOperation("`Path` selector not supported".to_string()));- },+ return Err(AutomationError::UnsupportedOperation(+ "`Path` selector not supported".to_string(),+ ));+ }Selector::Attributes(_attributes) => {- return Err(AutomationError::UnsupportedOperation("`Attributes` selector not supported".to_string()));- },+ return Err(AutomationError::UnsupportedOperation(+ "`Attributes` selector not supported".to_string(),+ ));+ }Selector::Filter(_filter) => {- return Err(AutomationError::UnsupportedOperation("`Filter` selector not supported".to_string()));- },+ return Err(AutomationError::UnsupportedOperation(+ "`Filter` selector not supported".to_string(),+ ));+ }Selector::Chain(_selectors) => {- return Err(AutomationError::UnsupportedOperation("`selectors` selector not supported".to_string()));- },+ return Err(AutomationError::UnsupportedOperation(+ "`selectors` selector not supported".to_string(),+ ));+ }}}fn open_application(&self, app_name: &str) -> Result<UIElement, AutomationError> {let status = std::process::Command::new("powershell")- .args(["-NoProfile", "-WindowStyle", "hidden", "-Command","start", app_name])+ .args([+ "-NoProfile",+ "-WindowStyle",+ "hidden",+ "-Command",+ "start",+ app_name,+ ]).status().map_err(|e| AutomationError::PlatformError(e.to_string()))?;if !status.success() {- return Err(AutomationError::PlatformError("Failed to open application".to_string()));+ return Err(AutomationError::PlatformError(+ "Failed to open application".to_string(),+ ));}std::thread::sleep(std::time::Duration::from_millis(200));@@ -335,11 +459,21 @@ impl AccessibilityEngine for WindowsEngine {fn open_url(&self, url: &str, browser: Option<&str>) -> Result<UIElement, AutomationError> {let browser = browser.unwrap_or(""); // when empty it'll open url in system's default browserlet status = std::process::Command::new("powershell")- .args(["-NoProfile", "-WindowStyle", "hidden", "-Command", "start", browser, url])+ .args([+ "-NoProfile",+ "-WindowStyle",+ "hidden",+ "-Command",+ "start",+ browser,+ url,+ ]).status().map_err(|e| AutomationError::PlatformError(e.to_string()))?;if !status.success() {- return Err(AutomationError::PlatformError("Failed to open URL".to_string()));+ return Err(AutomationError::PlatformError(+ "Failed to open URL".to_string(),+ ));}std::thread::sleep(std::time::Duration::from_millis(200));@@ -369,8 +503,10 @@ impl Debug for WindowsUIElement {impl UIElementImpl for WindowsUIElement {fn object_id(&self) -> usize {// use hashed `AutomationId` as object_id- let stable_id = format!("{:?}",- self.element.0.get_automation_id().unwrap_or_default());+ let stable_id = format!(+ "{:?}",+ self.element.0.get_automation_id().unwrap_or_default()+ );let mut hasher = DefaultHasher::new();stable_id.hash(&mut hasher);let id = hasher.finish() as usize;@@ -412,24 +548,37 @@ impl UIElementImpl for WindowsUIElement {}UIElementAttributes {role: self.role(),- label: self.element.0.get_labeled_by().ok()+ label: self+ .element+ .0+ .get_labeled_by()+ .ok().map(|e| e.get_name().unwrap_or_default()),- value: self.element.0.get_property_value(UIProperty::ValueValue)- .ok().and_then(|v| v.get_string().ok()),+ value: self+ .element+ .0+ .get_property_value(UIProperty::ValueValue)+ .ok()+ .and_then(|v| v.get_string().ok()),description: self.element.0.get_help_text().ok(),properties,}}fn children(&self) -> Result<Vec<UIElement>, AutomationError> {- let children = self.element.0.get_cached_children()+ let children = self+ .element+ .0+ .get_cached_children().map_err(|e| AutomationError::ElementNotFound(e.to_string()))?;- Ok(children.into_iter()- .map(|ele| UIElement::new(- Box::new(WindowsUIElement {- element: ThreadSafeWinUIElement(Arc::new(ele))- }))).collect()- )+ Ok(children+ .into_iter()+ .map(|ele| {+ UIElement::new(Box::new(WindowsUIElement {+ element: ThreadSafeWinUIElement(Arc::new(ele)),+ }))+ })+ .collect())}fn parent(&self) -> Result<Option<UIElement>, AutomationError> {@@ -446,7 +595,11 @@ impl UIElementImpl for WindowsUIElement {}fn bounds(&self) -> Result<(f64, f64, f64, f64), AutomationError> {- let rect = self.element.0.get_bounding_rectangle().map_err(|e| AutomationError::ElementNotFound(e.to_string()))?;+ let rect = self+ .element+ .0+ .get_bounding_rectangle()+ .map_err(|e| AutomationError::ElementNotFound(e.to_string()))?;Ok((rect.get_left() as f64,rect.get_top() as f64,@@ -458,7 +611,7 @@ impl UIElementImpl for WindowsUIElement {fn click(&self) -> Result<ClickResult, AutomationError> {self.element.0.try_focus();debug!("attempting to click element: {:?}", self.element.0);-+let click_result = self.element.0.click();if click_result.is_ok() {@@ -469,7 +622,10 @@ impl UIElementImpl for WindowsUIElement {});}// First try using the standard clickable point- let click_result = self.element.0.get_clickable_point()+ let click_result = self+ .element+ .0+ .get_clickable_point().and_then(|maybe_point| {if let Some(point) = maybe_point {debug!("using clickable point: {:?}", point);@@ -480,10 +636,14 @@ impl UIElementImpl for WindowsUIElement {details: "Clicked by Mouse using element's clickable point".to_string(),})} else {- Err(AutomationError::PlatformError("No clickable point found".to_string()).to_string().into())+ Err(+ AutomationError::PlatformError("No clickable point found".to_string())+ .to_string()+ .into(),+ )}});-+// If first method fails, try using the bounding rectangleif let Err(_) = click_result {debug!("clickable point unavailable, falling back to bounding rectangle");@@ -492,14 +652,15 @@ impl UIElementImpl for WindowsUIElement {// Calculate center point of the elementlet center_x = rect.get_left() + rect.get_width() / 2;let center_y = rect.get_top() + rect.get_height() / 2;-+let point = Point::new(center_x, center_y);let mouse = Mouse::default();-+debug!("clicking at center point: ({}, {})", center_x, center_y);- mouse.click(point)+ mouse+ .click(point).map_err(|e| AutomationError::PlatformError(e.to_string()))?;-+return Ok(ClickResult {method: "Single Click (Fallback)".to_string(),coordinates: Some((center_x as f64, center_y as f64)),@@ -507,18 +668,25 @@ impl UIElementImpl for WindowsUIElement {});}}-+// Return the result of the first attempt or propagate the errorclick_result.map_err(|e| AutomationError::PlatformError(e.to_string()))}fn double_click(&self) -> Result<ClickResult, AutomationError> {self.element.0.try_focus();- let point = self.element.0.get_clickable_point()+ let point = self+ .element+ .0+ .get_clickable_point().map_err(|e| AutomationError::PlatformError(e.to_string()))?- .ok_or_else(|| AutomationError::PlatformError("No clickable point found".to_string()))?;+ .ok_or_else(|| {+ AutomationError::PlatformError("No clickable point found".to_string())+ })?;let mouse = Mouse::default();- mouse.double_click(point).map_err(|e| AutomationError::PlatformError(e.to_string()))?;+ mouse+ .double_click(point)+ .map_err(|e| AutomationError::PlatformError(e.to_string()))?;Ok(ClickResult {method: "Double Click".to_string(),coordinates: Some((point.get_x() as f64, point.get_y() as f64)),@@ -528,47 +696,66 @@ impl UIElementImpl for WindowsUIElement {fn right_click(&self) -> Result<(), AutomationError> {self.element.0.try_focus();- let point = self.element.0.get_clickable_point()+ let point = self+ .element+ .0+ .get_clickable_point().map_err(|e| AutomationError::PlatformError(e.to_string()))?- .ok_or_else(|| AutomationError::PlatformError("No clickable point found".to_string()))?;+ .ok_or_else(|| {+ AutomationError::PlatformError("No clickable point found".to_string())+ })?;let mouse = Mouse::default();- mouse.right_click(point).map_err(|e| AutomationError::PlatformError(e.to_string()))?;+ mouse+ .right_click(point)+ .map_err(|e| AutomationError::PlatformError(e.to_string()))?;Ok(())}fn hover(&self) -> Result<(), AutomationError> {- return Err(AutomationError::UnsupportedOperation("`hover` doesn't not support".to_string()));+ return Err(AutomationError::UnsupportedOperation(+ "`hover` doesn't not support".to_string(),+ ));}fn focus(&self) -> Result<(), AutomationError> {- self.element.0.set_focus()+ self.element+ .0+ .set_focus().map_err(|e| AutomationError::PlatformError(e.to_string()))}fn type_text(&self, text: &str) -> Result<(), AutomationError> {- let control_type = self.element.0.get_control_type()+ let control_type = self+ .element+ .0+ .get_control_type().map_err(|e| AutomationError::PlatformError(e.to_string()))?;// check if element accepts inputprintln!("control_type: {:#?}", control_type);// if control_type == ControlType::Edit {- let keyboard = Keyboard::default();- keyboard.send_text(text)- .map_err(|e| AutomationError::PlatformError(e.to_string()))?;- Ok(())+ let keyboard = Keyboard::default();+ keyboard+ .send_text(text)+ .map_err(|e| AutomationError::PlatformError(e.to_string()))?;+ Ok(())// } else {// Err(AutomationError::PlatformError("Element is not editable".to_string()))// }}fn press_key(&self, key: &str) -> Result<(), AutomationError> {- let control_type = self.element.0.get_control_type()+ let control_type = self+ .element+ .0+ .get_control_type().map_err(|e| AutomationError::PlatformError(e.to_string()))?;// check if element accepts input, similar :D// if control_type == ControlType::Edit {- let keyboard = Keyboard::default();- keyboard.send_keys(key)- .map_err(|e| AutomationError::PlatformError(e.to_string()))?;- Ok(())+ let keyboard = Keyboard::default();+ keyboard+ .send_keys(key)+ .map_err(|e| AutomationError::PlatformError(e.to_string()))?;+ Ok(())// } else {// Err(AutomationError::PlatformError("Element is not editable".to_string()))// }@@ -576,13 +763,18 @@ impl UIElementImpl for WindowsUIElement {fn get_text(&self, max_depth: usize) -> Result<String, AutomationError> {let mut all_texts = Vec::new();-+// Create a function to extract text recursively- fn extract_text_from_element(element: &uiautomation::UIElement, texts: &mut Vec<String>, current_depth: usize, max_depth: usize) -> Result<(), AutomationError> {+ fn extract_text_from_element(+ element: &uiautomation::UIElement,+ texts: &mut Vec<String>,+ current_depth: usize,+ max_depth: usize,+ ) -> Result<(), AutomationError> {if current_depth > max_depth {return Ok(());}-+// Check Name propertyif let Ok(name) = element.get_property_value(UIProperty::Name) {if let Ok(name_text) = name.get_string() {@@ -591,7 +783,7 @@ impl UIElementImpl for WindowsUIElement {}}}-+// Check Value propertyif let Ok(value) = element.get_property_value(UIProperty::ValueValue) {if let Ok(value_text) = value.get_string() {@@ -600,51 +792,69 @@ impl UIElementImpl for WindowsUIElement {}}}-+// Recursively process childrenif let Ok(children) = element.get_cached_children() {for child in children {let _ = extract_text_from_element(&child, texts, current_depth + 1, max_depth);}}-+Ok(())}-+// Extract text from the element and its descendantsextract_text_from_element(&self.element.0, &mut all_texts, 0, max_depth)?;-+// Join the texts with spacesOk(all_texts.join(" "))}fn set_value(&self, value: &str) -> Result<(), AutomationError> {- let value_par = self.element.0.get_pattern::<patterns::UIValuePattern>()+ let value_par = self+ .element+ .0+ .get_pattern::<patterns::UIValuePattern>().map_err(|e| AutomationError::PlatformError(e.to_string()));- debug!("setting value: {:#?} to ui element {:#?}", &value, &self.element.0);+ debug!(+ "setting value: {:#?} to ui element {:#?}",+ &value, &self.element.0+ );if let Ok(v) = value_par {- v.set_value(value).map_err(|e| AutomationError::PlatformError(e.to_string()))+ v.set_value(value)+ .map_err(|e| AutomationError::PlatformError(e.to_string()))} else {- Err(AutomationError::PlatformError("`UIValuePattern` is not found".to_string()))+ Err(AutomationError::PlatformError(+ "`UIValuePattern` is not found".to_string(),+ ))}}fn is_enabled(&self) -> Result<bool, AutomationError> {- self.element.0.is_enabled().map_err(|e| AutomationError::ElementNotFound(e.to_string()))+ self.element+ .0+ .is_enabled()+ .map_err(|e| AutomationError::ElementNotFound(e.to_string()))}fn is_visible(&self) -> Result<bool, AutomationError> {// offscreen means invisible, right?- self.element.0.is_offscreen().map_err(|e| AutomationError::ElementNotFound(e.to_string()))+ self.element+ .0+ .is_offscreen()+ .map_err(|e| AutomationError::ElementNotFound(e.to_string()))}fn is_focused(&self) -> Result<bool, AutomationError> {- // start a instance of `uiautomation` just to check the+ // start a instance of `uiautomation` just to check the// current focused element is same as focused element or notlet automation = WindowsEngine::new(false, false).map_err(|e| AutomationError::PlatformError(e.to_string()))?;- let focused_element = automation.automation.0.get_focused_element()+ let focused_element = automation+ .automation+ .0+ .get_focused_element().map_err(|e| AutomationError::PlatformError(e.to_string()))?;if Arc::ptr_eq(&self.element.0, &Arc::new(focused_element)) {Ok(true)@@ -658,24 +868,42 @@ impl UIElementImpl for WindowsUIElement {match action {"focus" => self.focus(),"invoke" => {- let invoke_pat = self.element.0.get_pattern::<patterns::UIInvokePattern>()+ let invoke_pat = self+ .element+ .0+ .get_pattern::<patterns::UIInvokePattern>().map_err(|e| AutomationError::PlatformError(e.to_string()))?;- invoke_pat.invoke().map_err(|e| AutomationError::PlatformError(e.to_string()))- },+ invoke_pat+ .invoke()+ .map_err(|e| AutomationError::PlatformError(e.to_string()))+ }"click" => self.click().map(|_| ()),"double_click" => self.double_click().map(|_| ()),"right_click" => self.right_click().map(|_| ()),"toggle" => {- let toggle_pattern = self.element.0.get_pattern::<patterns::UITogglePattern>()+ let toggle_pattern = self+ .element+ .0+ .get_pattern::<patterns::UITogglePattern>().map_err(|e| AutomationError::PlatformError(e.to_string()))?;- toggle_pattern.toggle().map_err(|e| AutomationError::PlatformError(e.to_string()))- },+ toggle_pattern+ .toggle()+ .map_err(|e| AutomationError::PlatformError(e.to_string()))+ }"expand_collapse" => {- let expand_collapse_pattern = self.element.0.get_pattern::<patterns::UIExpandCollapsePattern>()+ let expand_collapse_pattern = self+ .element+ .0+ .get_pattern::<patterns::UIExpandCollapsePattern>().map_err(|e| AutomationError::PlatformError(e.to_string()))?;- expand_collapse_pattern.expand().map_err(|e| AutomationError::PlatformError(e.to_string()))- },- _ => Err(AutomationError::UnsupportedOperation(format!("action '{}' not supported", action))),+ expand_collapse_pattern+ .expand()+ .map_err(|e| AutomationError::PlatformError(e.to_string()))+ }+ _ => Err(AutomationError::UnsupportedOperation(format!(+ "action '{}' not supported",+ action+ ))),}}@@ -688,8 +916,10 @@ impl UIElementImpl for WindowsUIElement {.map_err(|e| AutomationError::PlatformError(e.to_string()))?;let attrs = self.attributes();- debug!("creating locator for element: control_type={:#?}, label={:#?}",- attrs.role, attrs.label);+ debug!(+ "creating locator for element: control_type={:#?}, label={:#?}",+ attrs.role, attrs.label+ );let self_element = UIElement::new(Box::new(WindowsUIElement {element: self.element.clone(),@@ -699,11 +929,17 @@ impl UIElementImpl for WindowsUIElement {}fn clone_box(&self) -> Box<dyn UIElementImpl> {- Box::new(WindowsUIElement { element: self.element.clone() })+ Box::new(WindowsUIElement {+ element: self.element.clone(),+ })}- fn scroll(&self, direction: &str, amount: f64) -> Result<(), AutomationError> { // TODO does not work- let scroll_pattern = self.element.0.get_pattern::<patterns::UIScrollPattern>()+ fn scroll(&self, direction: &str, amount: f64) -> Result<(), AutomationError> {+ // TODO does not work+ let scroll_pattern = self+ .element+ .0+ .get_pattern::<patterns::UIScrollPattern>().map_err(|e| AutomationError::PlatformError(e.to_string()))?;let scroll_amount = if amount > 0.0 {@@ -717,15 +953,21 @@ impl UIElementImpl for WindowsUIElement {let times = amount.abs() as usize;for _ in 0..times {match direction {- "up" => scroll_pattern.scroll(ScrollAmount::NoAmount, scroll_amount)+ "up" => scroll_pattern+ .scroll(ScrollAmount::NoAmount, scroll_amount).map_err(|e| AutomationError::PlatformError(e.to_string())),- "down" => scroll_pattern.scroll(ScrollAmount::NoAmount, scroll_amount)+ "down" => scroll_pattern+ .scroll(ScrollAmount::NoAmount, scroll_amount).map_err(|e| AutomationError::PlatformError(e.to_string())),- "left" => scroll_pattern.scroll(scroll_amount, ScrollAmount::NoAmount)+ "left" => scroll_pattern+ .scroll(scroll_amount, ScrollAmount::NoAmount).map_err(|e| AutomationError::PlatformError(e.to_string())),- "right" => scroll_pattern.scroll(scroll_amount, ScrollAmount::NoAmount)+ "right" => scroll_pattern+ .scroll(scroll_amount, ScrollAmount::NoAmount).map_err(|e| AutomationError::PlatformError(e.to_string())),- _ => Err(AutomationError::UnsupportedOperation("Invalid scroll direction".to_string())),+ _ => Err(AutomationError::UnsupportedOperation(+ "Invalid scroll direction".to_string(),+ )),}?}Ok(())@@ -738,26 +980,26 @@ fn map_generic_role_to_win_roles(role: &str) -> ControlType {"window" => ControlType::Window,"button" => ControlType::Button,"checkbox" => ControlType::CheckBox,- "menu" => ControlType::Menu,+ "menu" => ControlType::Menu,"menuitem" => ControlType::MenuItem,"dialog" => ControlType::Window,- "text" => ControlType::Text,- "tree" => ControlType::Tree,- "treeitem" => ControlType::TreeItem,+ "text" => ControlType::Text,+ "tree" => ControlType::Tree,+ "treeitem" => ControlType::TreeItem,"data" | "dataitem" => ControlType::DataGrid,"datagrid" => ControlType::DataGrid,- "url" | "urlfield" => ControlType::Edit,- "list" => ControlType::List,- "image" => ControlType::Image,+ "url" | "urlfield" => ControlType::Edit,+ "list" => ControlType::List,+ "image" => ControlType::Image,"title" => ControlType::TitleBar,"listitem" => ControlType::ListItem,"combobox" => ControlType::ComboBox,- "tab" => ControlType::Tab,+ "tab" => ControlType::Tab,"tabitem" => ControlType::TabItem,"toolbar" => ControlType::ToolBar,"appbar" => ControlType::AppBar,"calendar" => ControlType::Calendar,- "edit" => ControlType::Edit,+ "edit" => ControlType::Edit,"hyperlink" => ControlType::Hyperlink,"progressbar" => ControlType::ProgressBar,"radiobutton" => ControlType::RadioButton,@@ -767,14 +1009,14 @@ fn map_generic_role_to_win_roles(role: &str) -> ControlType {"statusbar" => ControlType::StatusBar,"tooltip" => ControlType::ToolTip,"custom" => ControlType::Custom,- "group" => ControlType::Group,- "thumb" => ControlType::Thumb,+ "group" => ControlType::Group,+ "thumb" => ControlType::Thumb,"document" => ControlType::Document,"splitbutton" => ControlType::SplitButton,- "pane" => ControlType::Pane,+ "pane" => ControlType::Pane,"header" => ControlType::Header,"headeritem" => ControlType::HeaderItem,- "table" => ControlType::Table,+ "table" => ControlType::Table,"titlebar" => ControlType::TitleBar,"separator" => ControlType::Separator,"semanticzoom" => ControlType::SemanticZoom,diff --git a/screenpipe-core/tests/pipes_test.rs b/screenpipe-core/tests/pipes_test.rsindex b395282e4..18c95691e 100644--- a/screenpipe-core/tests/pipes_test.rs+++ b/screenpipe-core/tests/pipes_test.rs@@ -2,21 +2,16 @@mod tests {use chrono::{TimeZone, Utc};use screenpipe_core::{- run_pipe,- download_pipe,- sanitize_pipe_name,- save_cron_execution,- download_pipe_private,- get_last_cron_execution,- PipeState+ download_pipe, download_pipe_private, get_last_cron_execution, run_pipe,+ sanitize_pipe_name, save_cron_execution, PipeState,};- use tokio::io::AsyncWriteExt;use serde_json::json;use std::sync::Arc;use std::sync::Once;use std::time::{Duration, SystemTime, UNIX_EPOCH};use tempfile::TempDir;+ use tokio::io::AsyncWriteExt;use tokio::sync::Mutex;use tokio::time::sleep;use tracing::subscriber::set_global_default;@@ -269,13 +264,17 @@ mod tests {let temp_dir = TempDir::new().unwrap();let source_dir = temp_dir.path().join("test-pipe-name");tokio::fs::create_dir_all(&source_dir).await.unwrap();- assert_eq!(sanitize_pipe_name(- source_dir.to_str().expect("failed to convert path to str")- ), "test-pipe-name");+ assert_eq!(+ sanitize_pipe_name(source_dir.to_str().expect("failed to convert path to str")),+ "test-pipe-name"+ );// test with a non-GitHub URLlet non_github_url = "https://example.com/some/path";- assert_eq!(sanitize_pipe_name(non_github_url), "https---example-com-some-path");+ assert_eq!(+ sanitize_pipe_name(non_github_url),+ "https---example-com-some-path"+ );// url including invalid characterslet invalid_chars = "invalid:name/with*chars";@@ -289,10 +288,17 @@ mod tests {let screenpipe_dir = temp_dir.path().to_path_buf();let source_dir = temp_dir.path().join("source_pipe");- let result = download_pipe(&source_dir.to_str().expect("failed bathbuf to str"),- screenpipe_dir.clone()).await;-- assert!(result.is_err(), "test failed for non existence local pipe: {:?}", result.err());+ let result = download_pipe(+ &source_dir.to_str().expect("failed bathbuf to str"),+ screenpipe_dir.clone(),+ )+ .await;++ assert!(+ result.is_err(),+ "test failed for non existence local pipe: {:?}",+ result.err()+ );}#[tokio::test]@@ -314,10 +320,11 @@ mod tests {.unwrap();// Try to download the pipe using the Windows path- let result = download_pipe(&source_dir.to_str().expect("failed to convert to str"),- screenpipe_dir.clone()- ).await;-+ let result = download_pipe(+ &source_dir.to_str().expect("failed to convert to str"),+ screenpipe_dir.clone(),+ )+ .await;// The function should succeed for every osassert!(@@ -331,7 +338,10 @@ mod tests {let dest_path = screenpipe_dir.join("pipes").join(pipe_name);assert!(dest_path.exists(), "Destination pipe directory not found");- assert!(dest_path.join("pipe.js").exists(), "pipe.js not found in destination");+ assert!(+ dest_path.join("pipe.js").exists(),+ "pipe.js not found in destination"+ );// tests for urlslet urls = vec![@@ -346,12 +356,17 @@ mod tests {let pipe_name = sanitize_pipe_name(url);let dest_path = screenpipe_dir.join("pipes").join(&pipe_name);- assert!(dest_path.exists(), "Destination pipe directory not found for URL: {}", url);+ assert!(+ dest_path.exists(),+ "Destination pipe directory not found for URL: {}",+ url+ );// verify pipe.jsonlet pipe_json_path = dest_path.join("pipe.json");let pipe_json_content = tokio::fs::read_to_string(&pipe_json_path).await.unwrap();- let pipe_json: serde_json::Value = serde_json::from_str(&pipe_json_content).expect("Invalid JSON format");+ let pipe_json: serde_json::Value =+ serde_json::from_str(&pipe_json_content).expect("Invalid JSON format");assert!(pipe_json.is_object(), "expected json to be an object");// enable side loaded pipe, even tho its enabled by default@@ -362,7 +377,9 @@ mod tests {pipe_config["enabled"] = json!(true);let updated_pipe_json = serde_json::to_string_pretty(&pipe_config);let mut file = tokio::fs::File::create(&pipe_json_path).await.unwrap();- file.write_all(updated_pipe_json.expect("failed to write").as_bytes()).await.unwrap();+ file.write_all(updated_pipe_json.expect("failed to write").as_bytes())+ .await+ .unwrap();// run pipelet run_result = run_pipe(&pipe_name, screenpipe_dir.clone()).await;@@ -376,9 +393,16 @@ mod tests {PipeState::Port(port) => {// verify the pipe is running on the expected portlet client = reqwest::Client::new();- let response = client.get(format!("http://localhost:{}", port)).send().await;+ let response = client+ .get(format!("http://localhost:{}", port))+ .send()+ .await;- assert!(response.is_ok(), "Failed to connect to the pipe on port {}", port);+ assert!(+ response.is_ok(),+ "Failed to connect to the pipe on port {}",+ port+ );// if successfull clean up the process#[cfg(windows)]@@ -400,9 +424,8 @@ mod tests {assert!(output.status.success(),"{} hasn't ran successfully",- pipe_name+ pipe_name);-}#[cfg(unix)]@@ -431,7 +454,6 @@ mod tests {// check by `ps axuw | grep pipes | grep -v grep`}}-}}@@ -450,13 +472,16 @@ mod tests {"Failed to download private pipe: {:?}",result.err());- assert!(screenpipe_dir.join("pipes").join(pipe_name).exists(),+ assert!(+ screenpipe_dir.join("pipes").join(pipe_name).exists(),"test failed for downloading private pipe: {:?}",result.err());// any zip shouldn't exists- let mut entries = tokio::fs::read_dir(screenpipe_dir.join("pipes").join(pipe_name)).await.unwrap();+ let mut entries = tokio::fs::read_dir(screenpipe_dir.join("pipes").join(pipe_name))+ .await+ .unwrap();let mut zip_exists = false;while let Some(entry) = entries.next_entry().await.unwrap() {let path = entry.path();@@ -465,15 +490,20 @@ mod tests {break;}}- assert!(!zip_exists,+ assert!(+ !zip_exists,"failed zip extraction for downloading private pipe: {:?}",result.err());// verify pipe.json- let pipe_json_path = screenpipe_dir.join("pipes").join(pipe_name).join("pipe.json");+ let pipe_json_path = screenpipe_dir+ .join("pipes")+ .join(pipe_name)+ .join("pipe.json");let pipe_json_content = tokio::fs::read_to_string(&pipe_json_path).await.unwrap();- let pipe_json: serde_json::Value = serde_json::from_str(&pipe_json_content).expect("Invalid JSON format");+ let pipe_json: serde_json::Value =+ serde_json::from_str(&pipe_json_content).expect("Invalid JSON format");assert!(pipe_json.is_object(), "expected json to be an object");@@ -485,7 +515,9 @@ mod tests {pipe_config["enabled"] = json!(true);let updated_pipe_json = serde_json::to_string_pretty(&pipe_config);let mut file = tokio::fs::File::create(&pipe_json_path).await.unwrap();- file.write_all(updated_pipe_json.expect("failed to write").as_bytes()).await.unwrap();+ file.write_all(updated_pipe_json.expect("failed to write").as_bytes())+ .await+ .unwrap();// run pipelet run_result = run_pipe(pipe_name, screenpipe_dir.clone()).await;@@ -499,9 +531,16 @@ mod tests {PipeState::Port(port) => {// verify the pipe is running on the expected portlet client = reqwest::Client::new();- let response = client.get(format!("http://localhost:{}", port)).send().await;+ let response = client+ .get(format!("http://localhost:{}", port))+ .send()+ .await;- assert!(response.is_ok(), "Failed to connect to the pipe on port {}", port);+ assert!(+ response.is_ok(),+ "Failed to connect to the pipe on port {}",+ port+ );// if successfull clean up the process#[cfg(windows)]@@ -523,9 +562,8 @@ mod tests {assert!(output.status.success(),"{} hasn't ran successfully",- pipe_name+ pipe_name);-}#[cfg(unix)]@@ -545,7 +583,7 @@ mod tests {assert!(output.status.success(),"{} hasn't ran successfully",- pipe_name+ pipe_name);}}diff --git a/screenpipe-integrations/src/lib.rs b/screenpipe-integrations/src/lib.rsindex 69422a1a1..ecff2e03e 100644--- a/screenpipe-integrations/src/lib.rs+++ b/screenpipe-integrations/src/lib.rs@@ -1 +1 @@-pub mod unstructured_ocr;\ No newline at end of file+pub mod unstructured_ocr;diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 15e88186d..b1ff8b2a6 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -2,9 +2,10 @@ use clap::Parser;#[allow(unused_imports)]use colored::Colorize;use dirs::home_dir;-use reqwest::Client;use futures::pin_mut;use port_check::is_local_ipv4_port_free;+use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};+use reqwest::Client;use screenpipe_audio::{audio_manager::AudioManagerBuilder,core::device::{@@ -17,8 +18,8 @@ use screenpipe_db::{};use screenpipe_server::{cli::{- AudioCommand, Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, MigrationSubCommand,- OutputFormat, PipeCommand, VisionCommand, McpCommand,+ AudioCommand, Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, McpCommand,+ MigrationSubCommand, OutputFormat, PipeCommand, VisionCommand,},handle_index_command,pipe_manager::PipeInfo,@@ -27,10 +28,18 @@ use screenpipe_server::{use screenpipe_vision::monitor::list_monitors;#[cfg(target_os = "macos")]use screenpipe_vision::run_ui;+use serde::Deserialize;use serde_json::{json, Value};+use std::path::Path;use std::{- env, fs, io::Write, net::SocketAddr, ops::Deref, path::PathBuf, sync::Arc, time::Duration,+ env, fs,+ io::Write,+ net::SocketAddr,net::{IpAddr, Ipv4Addr},+ ops::Deref,+ path::PathBuf,+ sync::Arc,+ time::Duration,};use tokio::{runtime::Runtime, signal, sync::broadcast};use tracing::{debug, error, info, warn};@@ -39,9 +48,6 @@ use tracing_appender::rolling::{RollingFileAppender, Rotation};use tracing_subscriber::util::SubscriberInitExt;use tracing_subscriber::{fmt, EnvFilter};use tracing_subscriber::{prelude::__tracing_subscriber_SubscriberExt, Layer};-use serde::Deserialize;-use std::path::Path;-use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};const DISPLAY: &str = r"_@@ -1177,7 +1183,6 @@ async fn handle_pipe_command(pipe_manager: &Arc<PipeManager>,enable_pipe_manager: bool,) -> anyhow::Result<()> {-if !enable_pipe_manager {println!("note: pipe functionality is disabled");return Ok(());@@ -1423,7 +1428,10 @@ async fn handle_pipe_command(Ok(())}-pub async fn handle_mcp_command(command: &McpCommand, local_data_dir: &PathBuf) -> Result<(), anyhow::Error> {+pub async fn handle_mcp_command(+ command: &McpCommand,+ local_data_dir: &PathBuf,+) -> Result<(), anyhow::Error> {let client = Client::new();// Check if Python is installed@@ -1437,7 +1445,13 @@ pub async fn handle_mcp_command(command: &McpCommand, local_data_dir: &PathBuf)}match command {- McpCommand::Setup { directory, output, port, update, purge } => {+ McpCommand::Setup {+ directory,+ output,+ port,+ update,+ purge,+ } => {let mcp_dir = directory.as_ref().map(PathBuf::from)@@ -1448,7 +1462,7 @@ pub async fn handle_mcp_command(command: &McpCommand, local_data_dir: &PathBuf)if mcp_dir.exists() {info!("Purging MCP directory: {}", mcp_dir.display());tokio::fs::remove_dir_all(&mcp_dir).await?;-+match output {OutputFormat::Json => println!("{}",@@ -1524,7 +1538,7 @@ pub async fn handle_mcp_command(command: &McpCommand, local_data_dir: &PathBuf)if should_download {tokio::fs::create_dir_all(&mcp_dir).await?;-+// Log the start of the download processinfo!("starting download process for MCP directory");@@ -1561,7 +1575,8 @@ pub async fn handle_mcp_command(command: &McpCommand, local_data_dir: &PathBuf)// Handle download resultmatch download_result {Ok(_) => {- tokio::fs::write(&config_path, serde_json::to_string_pretty(&config)?).await?;+ tokio::fs::write(&config_path, serde_json::to_string_pretty(&config)?)+ .await?;}Err(e) => {// Clean up on failure@@ -1627,7 +1642,11 @@ async fn download_mcp_directory(if !response.status().is_success() {let status = response.status();let error_text = response.text().await.unwrap_or_default();- return Err(anyhow::anyhow!("GitHub API error (status {}): {}", status, error_text));+ return Err(anyhow::anyhow!(+ "GitHub API error (status {}): {}",+ status,+ error_text+ ));}let contents: Vec<GitHubContent> = response@@ -1637,40 +1656,46 @@ async fn download_mcp_directory(for item in contents {let target_path = target_dir.join(&item.name);-+match item.content_type.as_str() {"file" => {if let Some(download_url) = item.download_url {- let file_response = client- .get(&download_url)- .send()- .await- .map_err(|e| anyhow::anyhow!("Failed to download file {}: {}", download_url, e))?;+ let file_response = client.get(&download_url).send().await.map_err(|e| {+ anyhow::anyhow!("Failed to download file {}: {}", download_url, e)+ })?;let content = file_response.bytes().await.map_err(|e| anyhow::anyhow!("Failed to get file content: {}", e))?;- tokio::fs::write(&target_path, content)- .await- .map_err(|e| anyhow::anyhow!("Failed to write file {}: {}", target_path.display(), e))?;+ tokio::fs::write(&target_path, content).await.map_err(|e| {+ anyhow::anyhow!("Failed to write file {}: {}", target_path.display(), e)+ })?;debug!("Downloaded file: {}", target_path.display());}}"dir" => {- tokio::fs::create_dir_all(&target_path)- .await- .map_err(|e| anyhow::anyhow!("Failed to create directory {}: {}", target_path.display(), e))?;+ tokio::fs::create_dir_all(&target_path).await.map_err(|e| {+ anyhow::anyhow!(+ "Failed to create directory {}: {}",+ target_path.display(),+ e+ )+ })?;let subdir_api_url = format!("https://api.github.com/repos/{}/{}/contents/{}?ref={}","mediar-ai", "screenpipe", item.path, "main");-+// Fix recursion with Box::pin- let future = Box::pin(download_mcp_directory(client, &subdir_api_url, &target_path));+ let future = Box::pin(download_mcp_directory(+ client,+ &subdir_api_url,+ &target_path,+ ));future.await?;}_ => {diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rsindex 503f0a837..d06e156df 100644--- a/screenpipe-server/src/cli.rs+++ b/screenpipe-server/src/cli.rs@@ -1,14 +1,17 @@use std::{path::PathBuf, sync::Arc};-use clap::{Parser, Subcommand, ValueHint};-use clap_complete::{generate, Shell};use clap::CommandFactory;-use screenpipe_audio::{vad::{VadSensitivity, VadEngineEnum}, core::engine::AudioTranscriptionEngine as CoreAudioTranscriptionEngine};-use screenpipe_vision::{custom_ocr::CustomOcrConfig, utils::OcrEngine as CoreOcrEngine};use clap::ValueEnum;+use clap::{Parser, Subcommand, ValueHint};+use clap_complete::{generate, Shell};+use screenpipe_audio::{+ core::engine::AudioTranscriptionEngine as CoreAudioTranscriptionEngine,+ vad::{VadEngineEnum, VadSensitivity},+};use screenpipe_core::Language;-use screenpipe_db::OcrEngine as DBOcrEngine;use screenpipe_db::CustomOcrConfig as DBCustomOcrConfig;+use screenpipe_db::OcrEngine as DBOcrEngine;+use screenpipe_vision::{custom_ocr::CustomOcrConfig, utils::OcrEngine as CoreOcrEngine};#[derive(Clone, Debug, ValueEnum, PartialEq)]pub enum CliAudioTranscriptionEngine {#[clap(name = "deepgram")]@@ -32,9 +35,15 @@ impl From<CliAudioTranscriptionEngine> for CoreAudioTranscriptionEngine {match cli_engine {CliAudioTranscriptionEngine::Deepgram => CoreAudioTranscriptionEngine::Deepgram,CliAudioTranscriptionEngine::WhisperTiny => CoreAudioTranscriptionEngine::WhisperTiny,- CliAudioTranscriptionEngine::WhisperTinyQuantized => CoreAudioTranscriptionEngine::WhisperTinyQuantized,- CliAudioTranscriptionEngine::WhisperLargeV3 => CoreAudioTranscriptionEngine::WhisperLargeV3,- CliAudioTranscriptionEngine::WhisperLargeV3Quantized => CoreAudioTranscriptionEngine::WhisperLargeV3Quantized,+ CliAudioTranscriptionEngine::WhisperTinyQuantized => {+ CoreAudioTranscriptionEngine::WhisperTinyQuantized+ }+ CliAudioTranscriptionEngine::WhisperLargeV3 => {+ CoreAudioTranscriptionEngine::WhisperLargeV3+ }+ CliAudioTranscriptionEngine::WhisperLargeV3Quantized => {+ CoreAudioTranscriptionEngine::WhisperLargeV3Quantized+ }CliAudioTranscriptionEngine::WhisperLargeV3Turbo => {CoreAudioTranscriptionEngine::WhisperLargeV3Turbo}@@ -135,9 +144,9 @@ impl From<CliVadSensitivity> for VadSensitivity {#[derive(Parser)]#[command(- author,+ author,version,- about,+ about,long_about = None,name = "screenpipe")]@@ -148,9 +157,9 @@ pub struct Cli {/// Optimise based on your needs./// Your screen rarely change more than 1 times within a second, right?#[cfg_attr(not(target_os = "macos"), arg(short, long, default_value_t = 1.0))]- #[cfg_attr(target_os = "macos", arg(short, long, default_value_t = 0.5))]+ #[cfg_attr(target_os = "macos", arg(short, long, default_value_t = 0.5))]pub fps: f64, // ! not crazy about this (inconsistent behaviour across platforms) see https://github.com/mediar-ai/screenpipe/issues/173-+/// Audio chunk duration in seconds#[arg(short = 'd', long, default_value_t = 30)]pub audio_chunk_duration: u64,@@ -272,7 +281,7 @@ pub struct Cli {/// Enable UI monitoring (macOS only)#[arg(long, default_value_t = false)]pub enable_ui_monitoring: bool,-+/// Enable experimental video frame cache (may increase CPU usage) - makes timeline UI available, frame streaming, etc.#[arg(long, default_value_t = true)]pub enable_frame_cache: bool,@@ -287,11 +296,8 @@ pub struct Cli {#[command(subcommand)]pub command: Option<Command>,-}--impl Cli {pub fn unique_languages(&self) -> Result<Vec<Language>, String> {let mut unique_langs = std::collections::HashSet::new();diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rsindex c0cb4070d..d11c0cffd 100644--- a/screenpipe-server/src/pipe_manager.rs+++ b/screenpipe-server/src/pipe_manager.rs@@ -626,7 +626,7 @@ impl PipeManager {Ok(dir) => {debug!("downloaded new version to temp dir: {:?}", dir);dir- },+ }Err(e) => {// Update build status to indicate download failureif let Some(obj) = config.as_object_mut() {@@ -660,7 +660,7 @@ impl PipeManager {let updated_config = serde_json::to_string_pretty(&config)?;tokio::fs::write(&pipe_json_path, updated_config).await?;}-+error!("temp pipe directory not found: {:?}", tmp_pipe_dir);return Err(anyhow::anyhow!("temp pipe directory not found: {:?}",@@ -705,7 +705,7 @@ impl PipeManager {return Err(anyhow::anyhow!("failed to parse new package.json: {}", e));}}- },+ }Err(e) => {// Update build status to indicate reading failureif let Some(obj) = config.as_object_mut() {@@ -745,7 +745,7 @@ impl PipeManager {"version".to_string(),Value::String(new_version.to_string()),);-+// Write updated config back to filelet updated_config = serde_json::to_string_pretty(&config)?;tokio::fs::write(&pipe_json_path, updated_config).await?;@@ -873,7 +873,7 @@ impl PipeManager {Ok(future) => {tokio::spawn(future);debug!("restarted pipe");-+// Update build status to indicate successif let Some(obj) = config.as_object_mut() {obj.insert(@@ -887,7 +887,7 @@ impl PipeManager {let updated_config = serde_json::to_string_pretty(&config)?;tokio::fs::write(&pipe_json_path, updated_config).await?;}- },+ }Err(e) => {// Update build status to indicate restart failureif let Some(obj) = config.as_object_mut() {diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 6125355af..dac092532 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -1091,7 +1091,9 @@ async fn get_pipe_info_handler(}#[oasgen]-async fn list_pipes_handler(State(state): State<Arc<AppState>>) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {+async fn list_pipes_handler(+ State(state): State<Arc<AppState>>,+) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {if !state.enable_pipe_manager {return Err((StatusCode::FORBIDDEN,diff --git a/screenpipe-server/src/text_embeds.rs b/screenpipe-server/src/text_embeds.rsindex 189ffa87d..d8ce86114 100644--- a/screenpipe-server/src/text_embeds.rs+++ b/screenpipe-server/src/text_embeds.rs@@ -17,11 +17,18 @@ struct OllamaResponse {/// Generates embeddings for text using Ollama's nomic-embed-text modelpub async fn generate_embedding(text: &str, frame_id: i64) -> Result<Vec<f32>> {let client = Client::new();-- debug!("generating embedding for frame_id: {}, text: {}", frame_id, text);++ debug!(+ "generating embedding for frame_id: {}, text: {}",+ frame_id, text+ );// Check if Ollama server is running- if let Err(e) = client.get("http://localhost:11434/api/version").send().await {+ if let Err(e) = client+ .get("http://localhost:11434/api/version")+ .send()+ .await+ {error!("ollama server not running: {}", e);return Err(anyhow::anyhow!("ollama server not running"));}@@ -44,6 +51,6 @@ pub async fn generate_embedding(text: &str, frame_id: i64) -> Result<Vec<f32>> {let embedding = response.json::<OllamaResponse>().await?;info!("generated embedding for frame_id: {}", frame_id);-+Ok(embedding.embedding)}diff --git a/screenpipe-vision/src/apple.rs b/screenpipe-vision/src/apple.rsindex 57743c1c6..8b24b300a 100644--- a/screenpipe-vision/src/apple.rs+++ b/screenpipe-vision/src/apple.rs@@ -6,12 +6,12 @@ use cidre::{};use image::DynamicImage;use image::GenericImageView;-use tracing::error;use screenpipe_core::Language;use serde::{Deserialize, Serialize};use std::collections::HashMap;use std::sync::OnceLock;use std::{ffi::c_void, ptr::null_mut};+use tracing::error;static APPLE_LANGUAGE_MAP: OnceLock<HashMap<Language, &'static str>> = OnceLock::new();diff --git a/screenpipe-vision/src/browser_utils/linux.rs b/screenpipe-vision/src/browser_utils/linux.rsindex 83ae4397b..9dcab41e4 100644--- a/screenpipe-vision/src/browser_utils/linux.rs+++ b/screenpipe-vision/src/browser_utils/linux.rs@@ -1,16 +1,16 @@-use anyhow::{Result, anyhow};-use tracing::{debug, error};+use anyhow::{anyhow, Result};use atspi::{connection::set_session_accessibility,proxy::accessible::{AccessibleProxy, ObjectRefExt},zbus::{proxy::CacheProperties, Connection},AccessibilityConnection, RelationType, Role,};-use atspi_proxies::document::DocumentProxy;use atspi_common::State;-use zbus::fdo::DBusProxy;-use std::pin::Pin;+use atspi_proxies::document::DocumentProxy;use std::future::Future;+use std::pin::Pin;+use tracing::{debug, error};+use zbus::fdo::DBusProxy;use super::BrowserUrlDetector;@@ -69,14 +69,18 @@ impl LinuxUrlDetector {target_pid: i32,) -> Result<(AccessibleProxy<'a>, bool)> {let child_objects = root.get_children().await?;-+for child in child_objects {let proxy = child.into_accessible_proxy(conn).await?;if let Ok(application) = proxy.get_application().await {// Only create DBusProxy if we have a potential matchlet dbus_proxy = DBusProxy::new(conn).await?;- if let Ok(unique_name) = dbus_proxy.get_name_owner((&application.name).into()).await {- if let Ok(pid) = dbus_proxy.get_connection_unix_process_id(unique_name.into()).await {+ if let Ok(unique_name) = dbus_proxy.get_name_owner((&application.name).into()).await+ {+ if let Ok(pid) = dbus_proxy+ .get_connection_unix_process_id(unique_name.into())+ .await+ {if pid == target_pid as u32 {debug!("Found browser process with PID: {}", pid);return Ok((proxy, false));@@ -95,7 +99,7 @@ impl LinuxUrlDetector {window_title: &str,) -> Result<Option<AccessibleProxy<'a>>> {let frames = browser_proxy.get_children().await?;-+for frame in frames {let frame_proxy = frame.into_accessible_proxy(conn).await?;if frame_proxy.get_role().await? == Role::Frame {@@ -106,13 +110,17 @@ impl LinuxUrlDetector {return Ok(Some(frame_proxy));}}-+// Then try statelet state = frame_proxy.get_state().await?;- if state.contains(State::Focused) ||- state.contains(State::Active) ||- state.contains(State::Selected) {- debug!("Found active frame by state: {}", frame_proxy.name().await.unwrap_or_default());+ if state.contains(State::Focused)+ || state.contains(State::Active)+ || state.contains(State::Selected)+ {+ debug!(+ "Found active frame by state: {}",+ frame_proxy.name().await.unwrap_or_default()+ );return Ok(Some(frame_proxy));}}@@ -204,8 +212,12 @@ impl LinuxUrlDetector {}// Box the recursive call to fix the recursion issue- let future: Pin<Box<dyn Future<Output = Result<AccessibleProxy<'a>>> + 'a>> =- Box::pin(Self::find_document_web_with_url(conn, child_proxies, is_vivaldi));+ let future: Pin<Box<dyn Future<Output = Result<AccessibleProxy<'a>>> + 'a>> =+ Box::pin(Self::find_document_web_with_url(+ conn,+ child_proxies,+ is_vivaldi,+ ));if let Ok(result) = future.await {return Ok(result);}@@ -221,12 +233,17 @@ impl LinuxUrlDetector {is_vivaldi: bool,) -> Result<Option<String>> {let embed_targets = Self::get_embed_relation(conn, frame_proxy).await?;- let document_proxy = Self::find_document_web_with_url(conn, embed_targets, is_vivaldi).await?;+ let document_proxy =+ Self::find_document_web_with_url(conn, embed_targets, is_vivaldi).await?;let document = Self::create_document_proxy(conn, &document_proxy).await?;Self::get_url_from_document(&document, is_vivaldi).await}- async fn get_active_url_from_window(pid: i32, window_title: &str, app_name: &str) -> Result<Option<String>> {+ async fn get_active_url_from_window(+ pid: i32,+ window_title: &str,+ app_name: &str,+ ) -> Result<Option<String>> {let (connection, root) = Self::setup_connection().await?;let conn = connection.connection();let is_vivaldi = app_name.to_lowercase().contains("vivaldi");@@ -234,8 +251,11 @@ impl LinuxUrlDetector {match Self::find_browser_process(conn, &root, pid).await {Ok((browser_proxy, _)) => {// Find the active frame first- if let Ok(Some(frame_proxy)) = Self::find_active_frame(conn, &browser_proxy, window_title).await {- match Self::get_document_url_from_relation(conn, &frame_proxy, is_vivaldi).await {+ if let Ok(Some(frame_proxy)) =+ Self::find_active_frame(conn, &browser_proxy, window_title).await+ {+ match Self::get_document_url_from_relation(conn, &frame_proxy, is_vivaldi).await+ {Ok(Some(url)) => {debug!("Found URL: {}", url);Ok(Some(url))@@ -263,9 +283,18 @@ impl LinuxUrlDetector {}impl BrowserUrlDetector for LinuxUrlDetector {- fn get_active_url(&self, app_name: &str, process_id: i32, window_title: &str) -> Result<Option<String>> {+ fn get_active_url(+ &self,+ app_name: &str,+ process_id: i32,+ window_title: &str,+ ) -> Result<Option<String>> {tokio::runtime::Runtime::new().unwrap()- .block_on(Self::get_active_url_from_window(process_id, window_title, app_name))+ .block_on(Self::get_active_url_from_window(+ process_id,+ window_title,+ app_name,+ ))}-}\ No newline at end of file+}diff --git a/screenpipe-vision/src/browser_utils/macos.rs b/screenpipe-vision/src/browser_utils/macos.rsindex 5cb697a05..da3d4676e 100644--- a/screenpipe-vision/src/browser_utils/macos.rs+++ b/screenpipe-vision/src/browser_utils/macos.rs@@ -139,7 +139,12 @@ impl MacOSUrlDetector {}impl BrowserUrlDetector for MacOSUrlDetector {- fn get_active_url(&self, app_name: &str, process_id: i32, _window_title: &str) -> Result<Option<String>> {+ fn get_active_url(+ &self,+ app_name: &str,+ process_id: i32,+ _window_title: &str,+ ) -> Result<Option<String>> {if app_name == "Arc" {let script = r#"tell application "Arc" to return URL of active tab of front window"#;self.get_url_via_applescript(script)diff --git a/screenpipe-vision/src/browser_utils/mod.rs b/screenpipe-vision/src/browser_utils/mod.rsindex 733c6d578..344a7a4b5 100644--- a/screenpipe-vision/src/browser_utils/mod.rs+++ b/screenpipe-vision/src/browser_utils/mod.rs@@ -2,17 +2,22 @@ use anyhow::Result;// Trait definitionpub trait BrowserUrlDetector {- fn get_active_url(&self, app_name: &str, process_id: i32, window_title: &str) -> Result<Option<String>>;+ fn get_active_url(+ &self,+ app_name: &str,+ process_id: i32,+ window_title: &str,+ ) -> Result<Option<String>>;}// Factory functionpub fn create_url_detector() -> Box<dyn BrowserUrlDetector> {#[cfg(target_os = "macos")]return Box::new(MacOSUrlDetector::new());-+#[cfg(target_os = "windows")]return Box::new(WindowsUrlDetector::new());-+#[cfg(target_os = "linux")]return Box::new(LinuxUrlDetector::new());}@@ -32,4 +37,3 @@ pub use windows::WindowsUrlDetector;mod linux;#[cfg(target_os = "linux")]pub use linux::LinuxUrlDetector;-diff --git a/screenpipe-vision/src/browser_utils/windows.rs b/screenpipe-vision/src/browser_utils/windows.rsindex dc674e638..a3cab0bf1 100644--- a/screenpipe-vision/src/browser_utils/windows.rs+++ b/screenpipe-vision/src/browser_utils/windows.rs@@ -1,11 +1,11 @@+use anyhow::{anyhow, Result};+use reqwest::blocking::Client;use reqwest::Error;-use anyhow::{Result, anyhow};use tracing::{debug, error};-use reqwest::blocking::Client;-use uiautomation::variants::Variant;use uiautomation::types::UIProperty::ProcessId;-use uiautomation::{UIAutomation, controls::ControlType};-use uiautomation::types::{UIProperty, TreeScope};+use uiautomation::types::{TreeScope, UIProperty};+use uiautomation::variants::Variant;+use uiautomation::{controls::ControlType, UIAutomation};use super::BrowserUrlDetector;@@ -24,25 +24,25 @@ impl WindowsUrlDetector {Err(_) => Ok(false),}}-+fn get_active_url_from_window(pid: i32) -> Result<Option<String>> {let automation = UIAutomation::new().unwrap();let root_ele = automation.get_root_element().unwrap();- let condition = automation.create_property_condition(- ProcessId,- Variant::from(pid as i32),- None- ).unwrap();+ let condition = automation+ .create_property_condition(ProcessId, Variant::from(pid as i32), None)+ .unwrap();match root_ele.find_first(TreeScope::Subtree, &condition) {Ok(ele) => {- let control_condition = automation.create_property_condition(- UIProperty::ControlType,- Variant::from(ControlType::Edit as i32),- None,- ).unwrap();+ let control_condition = automation+ .create_property_condition(+ UIProperty::ControlType,+ Variant::from(ControlType::Edit as i32),+ None,+ )+ .unwrap();- if let Ok(address_bar) = ele.find_first(TreeScope::Subtree, &control_condition){+ if let Ok(address_bar) = ele.find_first(TreeScope::Subtree, &control_condition) {debug!("address bar: {:?}", address_bar);if let Ok(value) = address_bar.get_property_value(UIProperty::ValueValue) {if let Ok(url) = value.get_string() {@@ -81,8 +81,12 @@ impl WindowsUrlDetector {}impl BrowserUrlDetector for WindowsUrlDetector {- fn get_active_url(&self, _app_name: &str, process_id: i32, _window_title: &str) -> Result<Option<String>> {- return Self::get_active_url_from_window(process_id);+ fn get_active_url(+ &self,+ _app_name: &str,+ process_id: i32,+ _window_title: &str,+ ) -> Result<Option<String>> {+ return Self::get_active_url_from_window(process_id);}}-diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rsindex 68fad28fb..9d1e506af 100644--- a/screenpipe-vision/src/capture_screenshot_by_window.rs+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs@@ -225,7 +225,7 @@ pub async fn capture_all_visible_windows(debug!("Window {} ({}) is_minimized", app_name, title);return None;}- },+ }Err(e) => {// Log warning and skip this window// mostly noisediff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex 3467f72e4..b16939200 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -578,7 +578,11 @@ impl UIFrame {}}-fn get_active_browser_url_sync(app_name: &str, process_id: i32, window_title: &str) -> Result<String, std::io::Error> {+fn get_active_browser_url_sync(+ app_name: &str,+ process_id: i32,+ window_title: &str,+) -> Result<String, std::io::Error> {let detector = create_url_detector();match detector.get_active_url(app_name, process_id, window_title) {Ok(Some(url)) => Ok(url),diff --git a/screenpipe-vision/src/microsoft.rs b/screenpipe-vision/src/microsoft.rsindex d881014d6..f9e4bd1d4 100644--- a/screenpipe-vision/src/microsoft.rs+++ b/screenpipe-vision/src/microsoft.rs@@ -1,5 +1,5 @@-use image::{DynamicImage, GenericImageView};use anyhow::Result;+use image::{DynamicImage, GenericImageView};#[cfg(target_os = "windows")]pub async fn perform_ocr_windows(image: &DynamicImage) -> Result<(String, String, Option<f64>)> {@@ -29,8 +29,8 @@ pub async fn perform_ocr_windows(image: &DynamicImage) -> Result<(String, Stringwriter.FlushAsync()?.get()?;stream.Seek(0)?;- let decoder = BitmapDecoder::CreateWithIdAsync(BitmapDecoder::PngDecoderId()?, &stream)?- .get()?;+ let decoder =+ BitmapDecoder::CreateWithIdAsync(BitmapDecoder::PngDecoderId()?, &stream)?.get()?;let bitmap = decoder.GetSoftwareBitmapAsync()?.get()?;diff --git a/screenpipe-vision/src/run_ui_monitoring_macos.rs b/screenpipe-vision/src/run_ui_monitoring_macos.rsindex 03cd73993..96f503613 100644--- a/screenpipe-vision/src/run_ui_monitoring_macos.rs+++ b/screenpipe-vision/src/run_ui_monitoring_macos.rs@@ -1,6 +1,5 @@use crate::UIFrame;use anyhow::Result;-use tracing::{debug, error, info, warn};use screenpipe_events::send_event;use std::fs;use std::io;@@ -13,6 +12,7 @@ use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};use tokio::process::Command;use tokio::signal;use tokio::time::{sleep, timeout, Duration};+use tracing::{debug, error, info, warn};use which::which;pub async fn run_ui() -> Result<()> {diff --git a/screenpipe-vision/src/utils.rs b/screenpipe-vision/src/utils.rsindex b8f646e4e..8e0c2f0b2 100644--- a/screenpipe-vision/src/utils.rs+++ b/screenpipe-vision/src/utils.rs@@ -6,10 +6,10 @@ use crate::custom_ocr::CustomOcrConfig;use crate::monitor::SafeMonitor;use image::DynamicImage;use image_compare::{Algorithm, Metric, Similarity};-use tracing::{debug, warn};use screenpipe_db::CustomOcrConfig as DBCustomOcrConfig;use std::hash::{DefaultHasher, Hash, Hasher};use std::time::{Duration, Instant};+use tracing::{debug, warn};#[derive(Clone, Debug, Default)]pub enum OcrEngine {diff --git a/screenpipe-vision/tests/custom_ocr_test.rs b/screenpipe-vision/tests/custom_ocr_test.rsindex 1346c7cca..e24c2ad78 100644--- a/screenpipe-vision/tests/custom_ocr_test.rs+++ b/screenpipe-vision/tests/custom_ocr_test.rs@@ -55,7 +55,7 @@ async def read_ocr(payload: dict):## Configure your "CustomOcrConfig" in Rust to point to http://localhost:8000/ocr-# Clean up+# Clean updeactivaterm -rf venv app.py*/