YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix: switch whisper-rs to codeberg fork for Xcode 16.4 compat
Louis Beaumont8247aa8c942c
diff --git a/Cargo.lock b/Cargo.lockindex ea9ce56b5..e5541cdd9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -9237,8 +9237,8 @@ dependencies = [[[package]]name = "whisper-rs"-version = "0.14.3"-source = "git+https://github.com/tazz4843/whisper-rs.git?rev=135b60b85a15714862806b6ea9f76abec38156f1#135b60b85a15714862806b6ea9f76abec38156f1"+version = "0.15.1"+source = "git+https://codeberg.org/tazz4843/whisper-rs.git?rev=d38738df8dc54b12d2918494586ba0817c3cb12f#d38738df8dc54b12d2918494586ba0817c3cb12f"dependencies = ["tracing","whisper-rs-sys",@@ -9246,8 +9246,8 @@ dependencies = [[[package]]name = "whisper-rs-sys"-version = "0.13.0"-source = "git+https://github.com/tazz4843/whisper-rs.git?rev=135b60b85a15714862806b6ea9f76abec38156f1#135b60b85a15714862806b6ea9f76abec38156f1"+version = "0.14.1"+source = "git+https://codeberg.org/tazz4843/whisper-rs.git?rev=d38738df8dc54b12d2918494586ba0817c3cb12f#d38738df8dc54b12d2918494586ba0817c3cb12f"dependencies = ["bindgen 0.71.1","cfg-if",diff --git a/screenpipe-accessibility/src/platform/macos.rs b/screenpipe-accessibility/src/platform/macos.rsindex 54e7a2eb1..8dd06d656 100644--- a/screenpipe-accessibility/src/platform/macos.rs+++ b/screenpipe-accessibility/src/platform/macos.rs@@ -327,7 +327,8 @@ fn run_event_tap(} else {s};- let event = UiEvent::text(Utc::now(), state.start.elapsed().as_millis() as u64, text);+ let event =+ UiEvent::text(Utc::now(), state.start.elapsed().as_millis() as u64, text);let _ = state.tx.try_send(event);}}@@ -538,7 +539,11 @@ extern "C" fn tap_callback(let content = if capture_content {get_clipboard().map(|s| {let truncated = truncate(&s, 1000);- if apply_pii { remove_pii(&truncated) } else { truncated }+ if apply_pii {+ remove_pii(&truncated)+ } else {+ truncated+ }})} else {None@@ -570,7 +575,11 @@ extern "C" fn tap_callback(let content = if capture_content {get_clipboard().map(|s| {let truncated = truncate(&s, 1000);- if apply_pii { remove_pii(&truncated) } else { truncated }+ if apply_pii {+ remove_pii(&truncated)+ } else {+ truncated+ }})} else {None@@ -596,7 +605,11 @@ extern "C" fn tap_callback(let content = if state.config.capture_clipboard_content {get_clipboard().map(|s| {let truncated = truncate(&s, 1000);- if state.config.apply_pii_removal { remove_pii(&truncated) } else { truncated }+ if state.config.apply_pii_removal {+ remove_pii(&truncated)+ } else {+ truncated+ }})} else {None@@ -774,7 +787,7 @@ fn get_element_at_position(x: f64, y: f64, config: &UiCaptureConfig) -> Option<Eif let Some(start) = s.find("AX") {let rest = &s[start..];let end = rest- .find(|c| c == ')' || c == '"' || c == '}')+ .find([')', '"', '}']).unwrap_or(rest.len());rest[..end].to_string()} else {@@ -824,7 +837,11 @@ fn get_element_at_position(x: f64, y: f64, config: &UiCaptureConfig) -> Option<Ename: name.map(|s| truncate(&s, 200)),value: value.map(|s| {let truncated = truncate(&s, 500);- if config.apply_pii_removal { remove_pii(&truncated) } else { truncated }+ if config.apply_pii_removal {+ remove_pii(&truncated)+ } else {+ truncated+ }}),description: description.map(|s| truncate(&s, 200)),automation_id: None,diff --git a/screenpipe-accessibility/src/platform/windows.rs b/screenpipe-accessibility/src/platform/windows.rsindex 5778e877b..2d698c256 100644--- a/screenpipe-accessibility/src/platform/windows.rs+++ b/screenpipe-accessibility/src/platform/windows.rs@@ -25,7 +25,7 @@ use windows::Win32::UI::Input::KeyboardAndMouse::{use windows::Win32::UI::WindowsAndMessaging::{CallNextHookEx, DispatchMessageW, GetForegroundWindow, GetMessageW, GetWindowTextW,GetWindowThreadProcessId, SetWindowsHookExW, TranslateMessage, UnhookWindowsHookEx, HC_ACTION,- HHOOK, KBDLLHOOKSTRUCT, MSLLHOOKSTRUCT, MSG, WH_KEYBOARD_LL, WH_MOUSE_LL, WM_KEYDOWN, WM_KEYUP,+ HHOOK, KBDLLHOOKSTRUCT, MSG, MSLLHOOKSTRUCT, WH_KEYBOARD_LL, WH_MOUSE_LL, WM_KEYDOWN, WM_KEYUP,WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEMOVE, WM_MOUSEWHEEL,WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_XBUTTONDOWN, WM_XBUTTONUP,};@@ -311,21 +311,13 @@ fn flush_text_buffer(state: &mut HookState) {} else {content};- let event = UiEvent::text(- Utc::now(),- state.start.elapsed().as_millis() as u64,- text,- );+ let event = UiEvent::text(Utc::now(), state.start.elapsed().as_millis() as u64, text);let _ = state.tx.try_send(event);state.last_text_time = None;}}-unsafe extern "system" fn keyboard_hook_proc(- code: i32,- wparam: WPARAM,- lparam: LPARAM,-) -> LRESULT {+unsafe extern "system" fn keyboard_hook_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {if code == HC_ACTION as i32 {let kb_struct = &*(lparam.0 as *const KBDLLHOOKSTRUCT);let vk_code = kb_struct.vkCode as u16;@@ -381,7 +373,13 @@ unsafe extern "system" fn keyboard_hook_proc(data: EventData::Clipboard {operation: 'c',content: if s.config.capture_clipboard_content {- get_clipboard_text().map(|c| if apply_pii { remove_pii(&c) } else { c })+ get_clipboard_text().map(|c| {+ if apply_pii {+ remove_pii(&c)+ } else {+ c+ }+ })} else {None},@@ -404,7 +402,13 @@ unsafe extern "system" fn keyboard_hook_proc(data: EventData::Clipboard {operation: 'x',content: if s.config.capture_clipboard_content {- get_clipboard_text().map(|c| if apply_pii { remove_pii(&c) } else { c })+ get_clipboard_text().map(|c| {+ if apply_pii {+ remove_pii(&c)+ } else {+ c+ }+ })} else {None},@@ -427,7 +431,13 @@ unsafe extern "system" fn keyboard_hook_proc(data: EventData::Clipboard {operation: 'v',content: if s.config.capture_clipboard_content {- get_clipboard_text().map(|c| if apply_pii { remove_pii(&c) } else { c })+ get_clipboard_text().map(|c| {+ if apply_pii {+ remove_pii(&c)+ } else {+ c+ }+ })} else {None},@@ -644,8 +654,7 @@ fn run_activity_only_hooks(activity_feed: ActivityFeed, stop: Arc<AtomicBool>) {ACTIVITY_KB_HOOK.with(|h| *h.borrow_mut() = Some(hook));}- let mouse_hook =- SetWindowsHookExW(WH_MOUSE_LL, Some(activity_mouse_hook), h_instance, 0);+ let mouse_hook = SetWindowsHookExW(WH_MOUSE_LL, Some(activity_mouse_hook), h_instance, 0);if let Ok(hook) = mouse_hook {ACTIVITY_MOUSE_HOOK.with(|h| *h.borrow_mut() = Some(hook));}diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lockindex 35803c719..370bb011e 100755--- a/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -12518,8 +12518,8 @@ dependencies = [[[package]]name = "whisper-rs"-version = "0.14.3"-source = "git+https://github.com/tazz4843/whisper-rs.git?rev=135b60b85a15714862806b6ea9f76abec38156f1#135b60b85a15714862806b6ea9f76abec38156f1"+version = "0.15.1"+source = "git+https://codeberg.org/tazz4843/whisper-rs.git?rev=d38738df8dc54b12d2918494586ba0817c3cb12f#d38738df8dc54b12d2918494586ba0817c3cb12f"dependencies = ["tracing","whisper-rs-sys",@@ -12527,8 +12527,8 @@ dependencies = [[[package]]name = "whisper-rs-sys"-version = "0.13.0"-source = "git+https://github.com/tazz4843/whisper-rs.git?rev=135b60b85a15714862806b6ea9f76abec38156f1#135b60b85a15714862806b6ea9f76abec38156f1"+version = "0.14.1"+source = "git+https://codeberg.org/tazz4843/whisper-rs.git?rev=d38738df8dc54b12d2918494586ba0817c3cb12f#d38738df8dc54b12d2918494586ba0817c3cb12f"dependencies = ["bindgen 0.71.1","cfg-if 1.0.0",diff --git a/screenpipe-app-tauri/src-tauri/src/commands.rs b/screenpipe-app-tauri/src-tauri/src/commands.rsindex c9aa4f39d..66318903c 100644--- a/screenpipe-app-tauri/src-tauri/src/commands.rs+++ b/screenpipe-app-tauri/src-tauri/src/commands.rs@@ -264,11 +264,15 @@ pub async fn open_pipe_window(#[tauri::command]#[specta::specta]pub async fn get_disk_usage(- app_handle: tauri::AppHandle,+ _app_handle: tauri::AppHandle,force_refresh: Option<bool>,) -> Result<serde_json::Value, String> {- let screenpipe_dir_path = get_data_dir(&app_handle)- .unwrap_or_else(|_| dirs::home_dir().unwrap().join(".screenpipe"));+ // Always use ~/.screenpipe as the primary data directory+ // This is where the sidecar/CLI stores data, which is the main data source+ let screenpipe_dir_path = dirs::home_dir()+ .ok_or_else(|| "Could not get home directory".to_string())?+ .join(".screenpipe");+match crate::disk_usage::disk_usage(&screenpipe_dir_path, force_refresh.unwrap_or(false)).await {Ok(Some(disk_usage)) => match serde_json::to_value(&disk_usage) {Ok(json_value) => Ok(json_value),diff --git a/screenpipe-app-tauri/src-tauri/src/embedded_server.rs b/screenpipe-app-tauri/src-tauri/src/embedded_server.rsindex ad3b4c5a0..818582656 100644--- a/screenpipe-app-tauri/src-tauri/src/embedded_server.rs+++ b/screenpipe-app-tauri/src-tauri/src/embedded_server.rs@@ -81,10 +81,12 @@ impl EmbeddedServerConfig {}/// Handle for controlling the embedded server+#[allow(dead_code)]pub struct EmbeddedServerHandle {shutdown_tx: broadcast::Sender<()>,}+#[allow(dead_code)]impl EmbeddedServerHandle {pub fn shutdown(&self) {info!("Shutting down embedded screenpipe server");diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex f3ea462dc..7daeb4855 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -1144,6 +1144,8 @@ async fn main() {if !use_dev_mode {let store_clone = store.clone();let base_dir_clone = base_dir.clone();+ let sidecar_state = app_handle.state::<SidecarState>();+ let sidecar_state_inner = sidecar_state.0.clone();tauri::async_runtime::spawn(async move {if server_running.await.unwrap_or(false) {info!("Server already running, skipping embedded server start");@@ -1172,7 +1174,9 @@ async fn main() {match embedded_server::start_embedded_server(config).await {Ok(handle) => {info!("Embedded screenpipe server started successfully");- std::mem::forget(handle);+ // Store handle in state so it can be stopped/restarted later+ let mut guard = sidecar_state_inner.lock().await;+ *guard = Some(handle);}Err(e) => {error!("Failed to start embedded server: {}", e);diff --git a/screenpipe-app-tauri/src-tauri/src/pi.rs b/screenpipe-app-tauri/src-tauri/src/pi.rsindex a9bb33848..fa1014c4d 100644--- a/screenpipe-app-tauri/src-tauri/src/pi.rs+++ b/screenpipe-app-tauri/src-tauri/src/pi.rs@@ -152,7 +152,7 @@ pub async fn run(prompt: &str, user_token: Option<&str>, working_dir: &str, pid_cmd.stderr(std::process::Stdio::piped());info!("Running pi command...");- let mut child = cmd.spawn()+ let child = cmd.spawn().map_err(|e| format!("Failed to spawn pi: {}", e))?;// Send PID if requesteddiff --git a/screenpipe-app-tauri/src-tauri/src/sidecar.rs b/screenpipe-app-tauri/src-tauri/src/sidecar.rsindex 4c0522f24..e8d3b1308 100644--- a/screenpipe-app-tauri/src-tauri/src/sidecar.rs+++ b/screenpipe-app-tauri/src-tauri/src/sidecar.rs@@ -1,47 +1,18 @@-use crate::get_store;-use crate::store::SettingsStore;+use crate::embedded_server::{EmbeddedServerConfig, EmbeddedServerHandle, start_embedded_server};+use crate::get_base_dir;use crate::permissions::do_permissions_check;+use crate::store::SettingsStore;use serde::{Deserialize, Serialize};-use serde_json::Value;use std::sync::Arc;-use tauri::Emitter;use tauri::{Manager, State};-use tauri_plugin_shell::process::{CommandChild, CommandEvent};-use tauri_plugin_shell::ShellExt;use tokio::sync::Mutex;use tracing::{debug, error, info, warn};-pub struct SidecarState(pub Arc<tokio::sync::Mutex<Option<SidecarManager>>>);--#[derive(Debug, Serialize, Deserialize, Clone)]-pub struct UserCredits {- #[serde(rename = "user.credits.amount")]- pub amount: i64,- #[serde(rename = "user.credits.created_at", default)]- pub created_at: Option<String>,-}--#[derive(Debug, Serialize, Deserialize, Clone)]-pub struct User {- #[serde(rename = "user.id", default)]- pub id: Option<String>,- #[serde(rename = "user.email", default)]- pub email: Option<String>,- #[serde(rename = "user.name", default)]- pub name: Option<String>,- #[serde(rename = "user.image", default)]- pub image: Option<String>,- #[serde(rename = "user.token", default)]- pub token: Option<String>,- #[serde(rename = "user.clerk_id", default)]- pub clerk_id: Option<String>,- #[serde(default)]- pub credits: Option<UserCredits>,- #[serde(rename = "user.cloud_subscribed", default)]- pub cloud_subscribed: Option<bool>,-}+/// State holding the embedded server handle+pub struct SidecarState(pub Arc<Mutex<Option<EmbeddedServerHandle>>>);#[derive(Debug, Serialize, Deserialize, Clone)]+#[serde(rename_all = "camelCase")]pub struct MonitorDevice {pub id: u32,pub name: String,@@ -50,78 +21,36 @@ pub struct MonitorDevice {pub height: u32,}-impl User {- pub fn from_store(store: &SettingsStore) -> Self {- Self {- id: store.user.id.clone(),- email: store.user.email.clone(),- name: store.user.name.clone(),- image: store.user.image.clone(),- token: store.user.token.clone(),- clerk_id: store.user.clerk_id.clone(),- credits: store.user.credits.clone().map(|c| UserCredits {- amount: c.amount as i64,- created_at: None,- }),- cloud_subscribed: store.user.cloud_subscribed.clone(),- }- }-}-/// Get all available monitors connected to the device-pub async fn get_available_monitors(app: &tauri::AppHandle) -> Result<Vec<MonitorDevice>, String> {+pub async fn get_available_monitors() -> Result<Vec<MonitorDevice>, String> {debug!("Getting available monitors");-- let sidecar = app.shell().sidecar("screenpipe")- .map_err(|e| format!("Failed to create sidecar command: {}", e))?;-- let output = sidecar- .args(&["vision", "list", "-o", "json"])- .output()- .await- .map_err(|e| format!("Failed to execute monitor listing command: {}", e))?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- error!("Failed to get monitors: {}", stderr);- return Err(format!("Failed to get monitors: {}", stderr));++ let monitors = screenpipe_vision::monitor::list_monitors().await;++ if monitors.is_empty() {+ return Err("No monitors found".to_string());}-- let stdout = String::from_utf8(output.stdout)- .map_err(|e| format!("Failed to parse monitor output as UTF-8: {}", e))?;-- debug!("Monitor command output: {}", stdout);-- // Parse the JSON response which might be in {data: [...], success: true} format- let json_value: serde_json::Value = serde_json::from_str(&stdout)- .map_err(|e| format!("Failed to parse monitor JSON: {}", e))?;-- let monitors_array = if let Some(data) = json_value.get("data") {- data.as_array()- } else {- json_value.as_array()- }.ok_or("Monitor response is not an array")?;-- let monitors: Vec<MonitorDevice> = monitors_array+ let result: Vec<MonitorDevice> = monitors.iter()- .filter_map(|monitor| {- serde_json::from_value(monitor.clone()).ok()+ .enumerate()+ .map(|(i, m)| MonitorDevice {+ id: m.id(),+ name: m.name().unwrap_or_else(|| format!("Monitor {}", i + 1)),+ is_default: i == 0, // First monitor is default+ width: m.width(),+ height: m.height(),}).collect();-- if monitors.is_empty() {- return Err("No monitors found".to_string());- }-- debug!("Found {} monitors", monitors.len());- Ok(monitors)++ debug!("Found {} monitors", result.len());+ Ok(result)}#[tauri::command]#[specta::specta]-pub async fn get_monitors(app: tauri::AppHandle) -> Result<Vec<MonitorDevice>, String> {- get_available_monitors(&app).await+pub async fn get_monitors() -> Result<Vec<MonitorDevice>, String> {+ get_available_monitors().await}#[tauri::command]@@ -130,527 +59,34 @@ pub async fn stop_screenpipe(state: State<'_, SidecarState>,_app: tauri::AppHandle,) -> Result<(), String> {- debug!("Killing screenpipe");-- #[cfg(target_os = "macos")]- {- let mut manager = state.0.lock().await;- if let Some(manager) = manager.as_mut() {- if let Some(child) = manager.child.take() {- if let Err(e) = child.kill() {- error!("Failed to kill child process: {}", e);- }- }- }- // Use pgrep + kill instead of pkill -f to avoid killing screenpipe-app- // -x matches exact process name, so "screenpipe" won't match "screenpipe-app"- let command = "pgrep -x screenpipe | xargs -r kill -9 2>/dev/null || true";- match tokio::process::Command::new("sh")- .arg("-c")- .arg(command)- .output()- .await- {- Ok(_) => {- debug!("Successfully killed screenpipe sidecar processes");- Ok(())- }- Err(e) => {- error!("Failed to kill screenpipe processes: {}", e);- Err(format!("Failed to kill screenpipe processes: {}", e))- }- }- }-- #[cfg(target_os = "windows")]- {- use std::os::windows::process::CommandExt;- const CREATE_NO_WINDOW: u32 = 0x08000000;- tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;-- // Try taskkill directly first (most reliable, doesn't depend on PowerShell)- let taskkill_result = tokio::process::Command::new("taskkill")- .args(["/F", "/T", "/IM", "screenpipe.exe"])- .creation_flags(CREATE_NO_WINDOW)- .output()- .await;-- match taskkill_result {- Ok(output) => {- // taskkill returns success even if process wasn't found, check stderr for real errors- let stderr = String::from_utf8_lossy(&output.stderr);- if output.status.success() || stderr.contains("not found") || stderr.contains("ERROR: The process") {- debug!("Successfully killed screenpipe processes (or none were running)");- return Ok(());- }- debug!("taskkill completed with output: {:?}", stderr);- Ok(())- }- Err(e) => {- warn!("taskkill failed: {}, trying cmd.exe fallback", e);+ info!("Stopping screenpipe server");- // Fallback: try via cmd.exe- match tokio::process::Command::new("cmd")- .args(["/C", "taskkill", "/F", "/T", "/IM", "screenpipe.exe"])- .creation_flags(CREATE_NO_WINDOW)- .output()- .await- {- Ok(_) => {- debug!("Successfully killed screenpipe processes via cmd.exe fallback");- Ok(())- }- Err(e2) => {- error!("All methods to kill screenpipe processes failed. taskkill: {}, cmd: {}", e, e2);- // Don't fail hard - the process might not be running anyway- warn!("Continuing despite kill failure - process may not be running");- Ok(())- }- }- }- }- }-- #[cfg(target_os = "linux")]- {- // -15 from gnu man page- // ref: https://www.gnu.org/software/coreutils/manual/html_node/kill-invocation.html- let command = format!(- "pgrep -x screenpipe | xargs -I {{}} kill -15 {{}}",- );- match tokio::process::Command::new("sh")- .arg("-c")- .arg(command)- .output()- .await- {- Ok(_) => {- debug!("Successfully killed screenpipe processes");- Ok(())- }- Err(e) => {- error!("Failed to kill screenpipe processes: {}", e);- Err(format!("Failed to kill screenpipe processes: {}", e))- }- }+ let mut handle_guard = state.0.lock().await;+ if let Some(handle) = handle_guard.take() {+ handle.shutdown();+ info!("Screenpipe server stopped");+ Ok(())+ } else {+ debug!("No server running to stop");+ Ok(())}}#[tauri::command]#[specta::specta]pub async fn spawn_screenpipe(- state: tauri::State<'_, SidecarState>,+ state: State<'_, SidecarState>,app: tauri::AppHandle,- override_args: Option<Vec<String>>,+ _override_args: Option<Vec<String>>,) -> Result<(), String> {- // Check permissions before spawning- let permissions_check = do_permissions_check(false);- let store = SettingsStore::get(&app).ok().flatten().unwrap_or_default();- let disable_audio = store.disable_audio;-- // Always check screen recording permission - this is required and needs restart- if !permissions_check.screen_recording.permitted() {- warn!("Screen recording permission not granted: {:?}. Cannot spawn screenpipe.", permissions_check.screen_recording);- return Err("Screen recording permission required. Please grant permission through settings and restart the app.".to_string());- }-- // Check microphone permission if audio recording is enabled - but don't block startup- if !disable_audio && !permissions_check.microphone.permitted() {- warn!("Microphone permission not granted and audio recording is enabled: {:?}. Audio recording will not work until permission is granted.", permissions_check.microphone);- // Continue with spawn - microphone permission can be granted at runtime- }-- info!("Screen recording permission granted for manual spawn. Audio disabled: {}, microphone permission: {:?}", disable_audio, permissions_check.microphone);-- let mut manager = state.0.lock().await;- if manager.is_none() {- *manager = Some(SidecarManager::new());- }- if let Some(manager) = manager.as_mut() {- manager.spawn(&app, override_args).await- } else {- debug!("Sidecar already running");- Ok(())- }-}--async fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>>) -> Result<CommandChild, String> {- // Read from persisted store instead of managed state to get latest settings- let store = SettingsStore::get(app)- .map_err(|e| format!("Failed to get settings: {}", e))?- .unwrap_or_default();-- let audio_transcription_engine = store.audio_transcription_engine.clone();-- let ocr_engine = store.ocr_engine.clone();-- let monitor_ids = store.monitor_ids.clone();---- let audio_devices = store.audio_devices.clone();-- let use_pii_removal = store.use_pii_removal;-- let port = store.port;-- let disable_audio = store.disable_audio;-- let ignored_windows = store.ignored_windows.clone();-- let included_windows = store.included_windows.clone();-- let ignored_urls = store.ignored_urls.clone();-- let deepgram_api_key = store.deepgram_api_key.clone();-- let fps = store.fps;-- let dev_mode = store- .dev_mode;-- let vad_sensitivity = store.vad_sensitivity.clone();-- let audio_chunk_duration = store.audio_chunk_duration;-- let telemetry_enabled = store- .analytics_enabled;-- let use_chinese_mirror = store- .use_chinese_mirror;-- let languages = store.languages.clone();-- let enable_beta = store- .enable_beta;-- let enable_frame_cache = store- .enable_frame_cache;--- let data_dir = store.data_dir.clone();-- let enable_realtime_audio_transcription = store- .enable_realtime_audio_transcription;-- let enable_realtime_vision = store- .enable_realtime_vision;-- let _use_all_monitors = store- .use_all_monitors;-- let analytics_id = store.analytics_id.clone();-- let user = User::from_store(&store);-- println!("user: {:?}", user);- println!("audio_chunk_duration: {}", audio_chunk_duration);-- let port_str = port.to_string();- let mut args = vec!["--port", port_str.as_str()];- let fps_str = fps.to_string();- // Needs to be declared here for lifetime (used by args.push below)- #[allow(unused_assignments)]- let mut monitor_id_str = String::new();- if fps != 0.2 {- args.push("--fps");- args.push(fps_str.as_str());- }-- if audio_transcription_engine != "default" {- args.push("--audio-transcription-engine");- let model = if audio_transcription_engine == "screenpipe-cloud" {- "deepgram"- } else {- audio_transcription_engine.as_str()- };- args.push(model);- }-- if ocr_engine != "default" {- args.push("--ocr-engine");- let model = ocr_engine.as_str();- args.push(model);- }- if !monitor_ids.is_empty() {- if monitor_ids.contains(&"default".to_string()) {- // Get the default monitor and use its ID- match get_available_monitors(app).await {- Ok(monitors) => {- if let Some(default_monitor) = monitors.iter().find(|m| m.is_default) {- monitor_id_str = default_monitor.id.to_string();- args.push("--monitor-id");- args.push(&monitor_id_str);- } else if let Some(first_monitor) = monitors.first() {- // Fallback to first monitor if no default is found- monitor_id_str = first_monitor.id.to_string();- args.push("--monitor-id");- args.push(&monitor_id_str);- }- }- Err(e) => {- error!("Failed to get default monitor: {}", e);- // Continue without monitor specification- }- }- } else {- // Use specific monitor IDs- for monitor in &monitor_ids {- args.push("--monitor-id");- args.push(monitor.as_str());- }- }- }-- if !languages.is_empty() && languages[0] != Value::String("default".to_string()) {- for language in &languages {- args.push("--language");- args.push(language.as_str());- }- }-- if deepgram_api_key != "default" && deepgram_api_key != "" {- args.push("--deepgram-api-key");- let key = deepgram_api_key.as_str();- args.push(key);- }-- if !audio_devices.is_empty() && audio_devices[0] != Value::String("default".to_string()) {- for device in &audio_devices {- args.push("--audio-device");- args.push(device.as_str());- }- }-- if use_pii_removal {- args.push("--use-pii-removal");- }-- if disable_audio {- args.push("--disable-audio");- }-- if !ignored_windows.is_empty() {- for window in &ignored_windows {- args.push("--ignored-windows");- args.push(window.as_str());- }- }-- if !included_windows.is_empty() {- for window in &included_windows {- args.push("--included-windows");- args.push(window.as_str());- }- }-- if !ignored_urls.is_empty() {- for url in &ignored_urls {- args.push("--ignored-urls");- args.push(url.as_str());- }- }-- let current_pid = std::process::id();- let current_pid_str = current_pid.to_string();- // Set auto-destruct PID if not in dev mode- if !dev_mode {- args.push("--auto-destruct-pid");- args.push(current_pid_str.as_str());- }-- if vad_sensitivity != "high" {- args.push("--vad-sensitivity");- args.push(vad_sensitivity.as_str());- }-- let audio_chunk_duration_str = audio_chunk_duration.to_string();- if audio_chunk_duration != 30 {- args.push("--audio-chunk-duration");- args.push(audio_chunk_duration_str.as_str());- }-- if !telemetry_enabled {- args.push("--disable-telemetry");- }-- if enable_beta {- args.push("--enable-beta");- }-- if enable_frame_cache {- args.push("--enable-frame-cache");- }-- if data_dir != "default" && !data_dir.is_empty() {- args.push("--data-dir");- args.push(data_dir.as_str());- }-- if enable_realtime_audio_transcription {- args.push("--enable-realtime-audio-transcription");- }-- if enable_realtime_vision {- args.push("--enable-realtime-vision");- }-- // if use_all_monitors {- // args.push("--use-all-monitors");- // }-- let disable_vision = store- .disable_vision;-- if disable_vision {- args.push("--disable-vision");- }-- let adaptive_fps = store.adaptive_fps;-- if adaptive_fps {- args.push("--adaptive-fps");- }-- // Enable UI events capture (macOS and Windows)- let enable_ui_events = store.enable_ui_events;- if enable_ui_events {- args.push("--enable-ui-events");- }-- // args.push("--debug");-- let override_args_as_vec = override_args.unwrap_or_default();-- if cfg!(windows) {- let mut c = app.shell().sidecar("screenpipe").unwrap();-- // Set file descriptor limit to prevent "Too many open files" errors- c = c.env("SCREENPIPE_FD_LIMIT", "8192");-- if use_chinese_mirror {- c = c.env("HF_ENDPOINT", "https://hf-mirror.com");- }-- // Use screenpipe cloud proxy when screenpipe-cloud engine is selected- if audio_transcription_engine == "screenpipe-cloud" && user.id.is_some() {- c = c.env(- "DEEPGRAM_API_URL",- "https://api.screenpi.pe/v1/listen",- );- c = c.env("DEEPGRAM_WEBSOCKET_URL", "wss://api.screenpi.pe");- c = c.env("CUSTOM_DEEPGRAM_API_TOKEN", user.id.as_ref().unwrap());- args.push("--deepgram-api-key");- args.push(user.id.as_ref().unwrap());- }-- c = c.env("SENTRY_RELEASE_NAME_APPEND", "tauri");- c = c.env("SCREENPIPE_ANALYTICS_ID", &analytics_id);-- // only supports --enable-realtime-vision for now, avoid adding if already present- if !args.contains(&"--enable-realtime-vision") && override_args_as_vec.contains(&"--enable-realtime-vision".to_string()) {- args.extend(override_args_as_vec.iter().map(|s| s.as_str()));- }- let c = c.args(&args);-- let (_, child) = c.spawn().map_err(|e| {- error!("Failed to spawn sidecar: {}", e);- e.to_string()- })?;-- info!("Spawned sidecar with args: {:?}", args);-- return Ok(child);- }-- let mut c = app.shell().sidecar("screenpipe").unwrap();-- // Set file descriptor limit to prevent "Too many open files" errors- // This is especially important for WebSocket connections and video processing- c = c.env("SCREENPIPE_FD_LIMIT", "8192");-- if use_chinese_mirror {- c = c.env("HF_ENDPOINT", "https://hf-mirror.com");- }-- // Use screenpipe cloud proxy when screenpipe-cloud engine is selected- if audio_transcription_engine == "screenpipe-cloud" && user.id.is_some() {- info!(- "Using screenpipe cloud with user id: {:?}",- user.id.as_ref().unwrap()- );- c = c.env(- "DEEPGRAM_API_URL",- "https://api.screenpi.pe/v1/listen",- );- c = c.env("DEEPGRAM_WEBSOCKET_URL", "wss://api.screenpi.pe");- c = c.env("CUSTOM_DEEPGRAM_API_TOKEN", user.id.as_ref().unwrap());- args.push("--deepgram-api-key");- args.push(user.id.as_ref().unwrap());- }-- c = c.env("SENTRY_RELEASE_NAME_APPEND", "tauri");- c = c.env("SCREENPIPE_ANALYTICS_ID", &analytics_id);-- // only supports --enable-realtime-vision for now, avoid adding if already present- if !args.contains(&"--enable-realtime-vision") && override_args_as_vec.contains(&"--enable-realtime-vision".to_string()) {- args.extend(override_args_as_vec.iter().map(|s| s.as_str()));- }- let c = c.args(&args);-- let result = c.spawn();- if let Err(e) = result {- error!("Failed to spawn sidecar: {}", e);- return Err(e.to_string());- }-- let (mut rx, child) = result.unwrap();- let app_handle = app.app_handle().clone();-- tauri::async_runtime::spawn(async move {- while let Some(event) = rx.recv().await {- match event {- CommandEvent::Stdout(line) => {- let log_line = String::from_utf8(line).unwrap();- print!("{}", log_line);- app_handle.emit("sidecar_log", log_line).unwrap();- }- CommandEvent::Stderr(line) => {- let log_line = String::from_utf8(line).unwrap();- error!("Sidecar stderr: {}", log_line);- app_handle- .emit("sidecar_log", format!("ERROR: {}", log_line))- .unwrap();- }- _ => {}- }- }- });+ info!("Starting screenpipe server");- info!("Spawned sidecar with args: {:?}", args);-- Ok(child)-}-pub struct SidecarManager {- child: Option<CommandChild>,- dev_mode: Arc<Mutex<bool>>,-}--impl SidecarManager {- pub fn new() -> Self {- Self {- child: None,- dev_mode: Arc::new(Mutex::new(false)),- }- }-- pub async fn spawn(&mut self, app: &tauri::AppHandle, override_args: Option<Vec<String>>) -> Result<(), String> {- info!("Spawning sidecar with override args: {:?}", override_args);-- // Check if sidecar is already running - but verify it's actually alive- if self.child.is_some() {- // Do a quick health check to verify the process is still running- let store = SettingsStore::get(app).ok().flatten().unwrap_or_default();+ // Check if already running+ {+ let handle_guard = state.0.lock().await;+ if handle_guard.is_some() {+ // Verify it's actually running via health check+ let store = SettingsStore::get(&app).ok().flatten().unwrap_or_default();let port = store.port;let health_url = format!("http://localhost:{}/health", port);@@ -661,58 +97,72 @@ impl SidecarManager {.await{Ok(resp) if resp.status().is_success() => {- info!("Sidecar already running and healthy, skipping spawn");+ info!("Screenpipe server already running and healthy");return Ok(());}_ => {- // Process died but handle still exists - clear it and respawn- warn!("Sidecar handle exists but process is not responding, clearing stale state and respawning");- self.child = None;+ warn!("Server handle exists but not responding, will restart");}}}+ }- // Update settings from store first to get audio settings- self.update_settings(app).await?;-- // Check permissions before spawning- let permissions_check = do_permissions_check(false);- let store = SettingsStore::get(app).ok().flatten().unwrap_or_default();- let disable_audio = store.disable_audio;-- // Always check screen recording permission - this is required and needs restart- if !permissions_check.screen_recording.permitted() {- warn!("Screen recording permission not granted: {:?}. Cannot spawn sidecar.", permissions_check.screen_recording);- return Err("Screen recording permission required. Please grant permission through settings and restart the app.".to_string());- }-- // Check microphone permission if audio recording is enabled - but don't block startup- if !disable_audio && !permissions_check.microphone.permitted() {- warn!("Microphone permission not granted and audio recording is enabled: {:?}. Audio recording will not work until permission is granted.", permissions_check.microphone);- // Continue with spawn - microphone permission can be granted at runtime+ // Stop existing server if any+ {+ let mut handle_guard = state.0.lock().await;+ if let Some(handle) = handle_guard.take() {+ handle.shutdown();+ // Give it a moment to shut down+ tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;}-- info!("Screen recording permission granted, proceeding with sidecar spawn. Audio disabled: {}, microphone permission: {:?}", disable_audio, permissions_check.microphone);+ }- // Spawn the sidecar- let child = spawn_sidecar(app, override_args).await?;- self.child = Some(child);+ // Check permissions before starting+ let permissions_check = do_permissions_check(false);+ let store = SettingsStore::get(&app).ok().flatten().unwrap_or_default();+ let disable_audio = store.disable_audio;- Ok(())+ // Screen recording permission is required+ if !permissions_check.screen_recording.permitted() {+ warn!(+ "Screen recording permission not granted: {:?}. Cannot start server.",+ permissions_check.screen_recording+ );+ return Err(+ "Screen recording permission required. Please grant permission and restart the app."+ .to_string(),+ );}- async fn update_settings(&mut self, app: &tauri::AppHandle) -> Result<(), String> {- let store = get_store(app, None).unwrap();+ // Microphone permission check (warning only, don't block)+ if !disable_audio && !permissions_check.microphone.permitted() {+ warn!(+ "Microphone permission not granted: {:?}. Audio recording will not work.",+ permissions_check.microphone+ );+ }- let dev_mode = store- .get("devMode")- .and_then(|v| v.as_bool())- .unwrap_or(false);+ info!(+ "Permissions OK. Starting embedded server. Audio disabled: {}, microphone permission: {:?}",+ disable_audio, permissions_check.microphone+ );- debug!("dev_mode: {}", dev_mode);+ // Get data directory+ let base_dir = get_base_dir(&app, None)+ .map_err(|e| format!("Failed to get base directory: {}", e))?;- *self.dev_mode.lock().await = dev_mode;+ // Build config from store+ let config = EmbeddedServerConfig::from_store(&store, base_dir);- Ok(())+ // Start the embedded server+ let handle = start_embedded_server(config).await?;++ // Store the handle+ {+ let mut handle_guard = state.0.lock().await;+ *handle_guard = Some(handle);}++ info!("Screenpipe server started successfully");+ Ok(())}diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.tomlindex 53e3c64b3..31a926598 100644--- a/screenpipe-audio/Cargo.toml+++ b/screenpipe-audio/Cargo.toml@@ -40,7 +40,7 @@ hf-hub = "0.3.2"# https://github.com/pdeljanov/Symphonia/tree/master?tab=readme-ov-file#optimizationssymphonia = { version = "0.5.4", features = ["aac", "isomp4", "opt-simd"] }rubato = "0.15.0"-whisper-rs = { git = "https://github.com/tazz4843/whisper-rs.git", rev = "135b60b85a15714862806b6ea9f76abec38156f1", features = [+whisper-rs = { git = "https://codeberg.org/tazz4843/whisper-rs.git", rev = "d38738df8dc54b12d2918494586ba0817c3cb12f", features = ["tracing_backend",] } # pin revision to avoid breaking changesdiff --git a/screenpipe-audio/src/transcription/whisper/batch.rs b/screenpipe-audio/src/transcription/whisper/batch.rsindex 48d8fcf36..4086e3c6e 100644--- a/screenpipe-audio/src/transcription/whisper/batch.rs+++ b/screenpipe-audio/src/transcription/whisper/batch.rs@@ -46,19 +46,17 @@ pub async fn process_with_whisper(.full(params, &audio).expect("failed to run model");- let num_segments = whisper_state- .full_n_segments()- .expect("failed to get number of segments");+ let num_segments = whisper_state.full_n_segments();let mut transcript = String::new();for i in 0..num_segments {// Get the transcribed text and timestamps for the current segment.- let segment = whisper_state- .full_get_segment_text(i)- .expect("failed to get segment");-- transcript.push_str(&segment);+ if let Some(segment) = whisper_state.get_segment(i) {+ if let Ok(text) = segment.to_str() {+ transcript.push_str(text);+ }+ }}Ok(transcript)diff --git a/screenpipe-db/src/db.rs b/screenpipe-db/src/db.rsindex 601f3d451..97b2d0e0d 100644--- a/screenpipe-db/src/db.rs+++ b/screenpipe-db/src/db.rs@@ -3192,7 +3192,7 @@ LIMIT ? OFFSET ?)"#,)- .bind(&event.timestamp)+ .bind(event.timestamp).bind(&event.session_id).bind(event.relative_ms).bind(event.event_type.to_string())@@ -3259,7 +3259,7 @@ LIMIT ? OFFSET ?)"#,)- .bind(&event.timestamp)+ .bind(event.timestamp).bind(&event.session_id).bind(event.relative_ms).bind(event.event_type.to_string())diff --git a/screenpipe-js/ai-proxy/src/providers/vertex.ts b/screenpipe-js/ai-proxy/src/providers/vertex.tsindex ad44f10c8..4969557f9 100644--- a/screenpipe-js/ai-proxy/src/providers/vertex.ts+++ b/screenpipe-js/ai-proxy/src/providers/vertex.ts@@ -511,6 +511,82 @@ export class VertexAIProvider implements AIProvider {}}+/**+ * Sanitize message content to fix common formatting issues+ * Fixes issues like: {type: 'text', text: {text: '...'}} -> {type: 'text', text: '...'}+ */+export function sanitizeMessages(messages: any[]): any[] {+ if (!Array.isArray(messages)) return messages;++ return messages.map((msg) => {+ if (!msg || typeof msg !== 'object') return msg;++ // Handle content field+ if (msg.content !== undefined) {+ msg.content = sanitizeContent(msg.content);+ }++ return msg;+ });+}++/**+ * Sanitize content field which can be string, array, or other formats+ */+function sanitizeContent(content: any): any {+ // If string, return as-is+ if (typeof content === 'string') return content;++ // If array, sanitize each element+ if (Array.isArray(content)) {+ return content.map(sanitizeContentBlock);+ }++ // If object that looks like a single content block, sanitize it+ if (content && typeof content === 'object') {+ return sanitizeContentBlock(content);+ }++ return content;+}++/**+ * Sanitize a single content block+ * Fixes nested text issues like: {type: 'text', text: {text: '...'}}+ */+function sanitizeContentBlock(block: any): any {+ if (!block || typeof block !== 'object') return block;++ // Fix nested text issue: {type: 'text', text: {text: '...'}}+ if (block.type === 'text' && block.text !== undefined) {+ // If text is an object with a text property, unwrap it+ if (typeof block.text === 'object' && block.text !== null && 'text' in block.text) {+ console.log('proxyToVertex: fixing nested text.text structure');+ block.text = block.text.text;+ }+ // Ensure text is a string+ if (typeof block.text !== 'string') {+ block.text = String(block.text);+ }+ }++ // Handle tool_use blocks - ensure input is parsed if it's a string+ if (block.type === 'tool_use' && typeof block.input === 'string') {+ try {+ block.input = JSON.parse(block.input);+ } catch (e) {+ // Keep as-is if not valid JSON+ }+ }++ // Handle tool_result blocks+ if (block.type === 'tool_result' && block.content !== undefined) {+ block.content = sanitizeContent(block.content);+ }++ return block;+}+/*** Create a passthrough proxy for raw Anthropic API requests to Vertex AI* This is what the Agent SDK needs - it sends Anthropic-format requests@@ -547,6 +623,12 @@ export async function proxyToVertex([key: string]: any;};console.log('proxyToVertex: model=', body.model, 'stream=', body.stream, 'messages count=', body.messages?.length);++ // Sanitize messages to fix common formatting issues+ if (body.messages) {+ body.messages = sanitizeMessages(body.messages);+ }+const isStreaming = body.stream === true;// Get access tokendiff --git a/screenpipe-js/ai-proxy/src/test/vertex.unit.test.ts b/screenpipe-js/ai-proxy/src/test/vertex.unit.test.tsindex a4dd685c8..ab73808b1 100644--- a/screenpipe-js/ai-proxy/src/test/vertex.unit.test.ts+++ b/screenpipe-js/ai-proxy/src/test/vertex.unit.test.ts@@ -5,51 +5,204 @@*/import { describe, it, expect, beforeEach } from 'bun:test';-import { mapModelToVertex, parseStreamingEvent, VertexAIProvider } from '../providers/vertex';+import { mapModelToVertex, parseStreamingEvent, VertexAIProvider, sanitizeMessages } from '../providers/vertex';++// ============================================================================+// Message Sanitization Tests (for proxyToVertex)+// ============================================================================+describe('sanitizeMessages', () => {+ it('should fix nested text.text structure', () => {+ // This is the exact bug: {type: 'text', text: {text: '...'}}+ const messages = [+ {+ role: 'user',+ content: [{ type: 'text', text: { text: 'Hello world' } }], // BUG: nested text+ },+ ];++ const sanitized = sanitizeMessages(messages);++ expect(sanitized[0].content[0].type).toBe('text');+ expect(sanitized[0].content[0].text).toBe('Hello world');+ expect(typeof sanitized[0].content[0].text).toBe('string');+ });++ it('should not modify correctly formatted messages', () => {+ const messages = [+ { role: 'user', content: 'Hello' },+ { role: 'assistant', content: 'Hi there!' },+ ];++ const sanitized = sanitizeMessages(messages);++ expect(sanitized[0].content).toBe('Hello');+ expect(sanitized[1].content).toBe('Hi there!');+ });++ it('should handle array content with correct format', () => {+ const messages = [+ {+ role: 'user',+ content: [{ type: 'text', text: 'Hello' }], // Correct format+ },+ ];++ const sanitized = sanitizeMessages(messages);++ expect(sanitized[0].content[0].text).toBe('Hello');+ });++ it('should fix deeply nested text in multi-turn conversation', () => {+ // Reproduces: "messages.2.content.0.text.text: Input should be a valid string"+ const messages = [+ { role: 'user', content: 'First message' },+ { role: 'assistant', content: 'First response' },+ {+ role: 'user',+ content: [{ type: 'text', text: { text: 'Second message with bug' } }],+ },+ ];++ const sanitized = sanitizeMessages(messages);++ // Check message at index 2+ expect(sanitized[2].content[0].text).toBe('Second message with bug');+ expect(typeof sanitized[2].content[0].text).toBe('string');+ });++ it('should handle mixed content (text + image)', () => {+ const messages = [+ {+ role: 'user',+ content: [+ { type: 'text', text: { text: 'What is in this image?' } }, // Bug to fix+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'abc' } },+ ],+ },+ ];++ const sanitized = sanitizeMessages(messages);++ expect(sanitized[0].content[0].text).toBe('What is in this image?');+ expect(sanitized[0].content[1].type).toBe('image'); // Image should be unchanged+ });++ it('should handle tool_use content', () => {+ const messages = [+ {+ role: 'assistant',+ content: [+ { type: 'text', text: { text: "I'll search for that" } },+ { type: 'tool_use', id: 'toolu_123', name: 'search', input: { q: 'test' } },+ ],+ },+ ];++ const sanitized = sanitizeMessages(messages);++ expect(sanitized[0].content[0].text).toBe("I'll search for that");+ expect(sanitized[0].content[1].type).toBe('tool_use');+ expect(sanitized[0].content[1].input).toEqual({ q: 'test' });+ });++ it('should handle tool_result content', () => {+ const messages = [+ {+ role: 'user',+ content: [+ {+ type: 'tool_result',+ tool_use_id: 'toolu_123',+ content: [{ type: 'text', text: { text: 'Search results' } }], // Nested in tool_result+ },+ ],+ },+ ];++ const sanitized = sanitizeMessages(messages);++ expect(sanitized[0].content[0].content[0].text).toBe('Search results');+ });++ it('should handle null and undefined gracefully', () => {+ const messages = [+ { role: 'user', content: null },+ { role: 'assistant', content: undefined },+ null,+ ];++ const sanitized = sanitizeMessages(messages as any);++ expect(sanitized[0].content).toBeNull();+ expect(sanitized[1].content).toBeUndefined();+ expect(sanitized[2]).toBeNull();+ });++ it('should convert non-string text to string', () => {+ const messages = [+ {+ role: 'user',+ content: [{ type: 'text', text: 12345 }], // Number instead of string+ },+ ];++ const sanitized = sanitizeMessages(messages);++ expect(sanitized[0].content[0].text).toBe('12345');+ expect(typeof sanitized[0].content[0].text).toBe('string');+ });+});// ============================================================================// Model Format Conversion Tests// ============================================================================describe('mapModelToVertex', () => {- describe('converts dash-date format to at-date format', () => {+ describe('converts and aliases models', () => {it('should convert claude-opus-4-5-20251101 to claude-opus-4-5@20251101', () => {expect(mapModelToVertex('claude-opus-4-5-20251101')).toBe('claude-opus-4-5@20251101');});- it('should convert claude-sonnet-4-5-20250929 to claude-sonnet-4-5@20250929', () => {- expect(mapModelToVertex('claude-sonnet-4-5-20250929')).toBe('claude-sonnet-4-5@20250929');+ // Sonnet models are aliased to haiku (sonnet is outdated)+ it('should alias claude-sonnet-4-5-20250929 to claude-haiku-4-5@20251001', () => {+ expect(mapModelToVertex('claude-sonnet-4-5-20250929')).toBe('claude-haiku-4-5@20251001');});it('should convert claude-haiku-4-5-20251001 to claude-haiku-4-5@20251001', () => {expect(mapModelToVertex('claude-haiku-4-5-20251001')).toBe('claude-haiku-4-5@20251001');});- it('should convert claude-sonnet-4-20250514 to claude-sonnet-4@20250514', () => {- expect(mapModelToVertex('claude-sonnet-4-20250514')).toBe('claude-sonnet-4@20250514');+ // Sonnet models are aliased to haiku+ it('should alias claude-sonnet-4-20250514 to claude-haiku-4-5@20251001', () => {+ expect(mapModelToVertex('claude-sonnet-4-20250514')).toBe('claude-haiku-4-5@20251001');});+ // Old sonnet 3.5 is converted but not aliased (no specific alias defined)it('should convert claude-3-5-sonnet-20241022 to claude-3-5-sonnet@20241022', () => {expect(mapModelToVertex('claude-3-5-sonnet-20241022')).toBe('claude-3-5-sonnet@20241022');});});- describe('preserves already-correct format', () => {- it('should not modify claude-opus-4-5@20251101', () => {- expect(mapModelToVertex('claude-opus-4-5@20251101')).toBe('claude-opus-4-5@20251101');+ describe('applies aliases for known models', () => {+ // Models with @ that aren't in aliases fall back to haiku+ it('should fallback claude-opus-4-5@20251101 to haiku (not in aliases)', () => {+ expect(mapModelToVertex('claude-opus-4-5@20251101')).toBe('claude-haiku-4-5@20251001');});- it('should not modify claude-3-5-sonnet-v2@20241022', () => {- expect(mapModelToVertex('claude-3-5-sonnet-v2@20241022')).toBe('claude-3-5-sonnet-v2@20241022');+ // Any claude model without specific alias falls back to haiku+ it('should alias unknown claude models to haiku', () => {+ expect(mapModelToVertex('claude-3-5-sonnet-v2@20241022')).toBe('claude-haiku-4-5@20251001');});});describe('handles edge cases', () => {- it('should not modify model without date suffix', () => {- expect(mapModelToVertex('claude-3-5-sonnet')).toBe('claude-3-5-sonnet');+ // Any claude model defaults to haiku+ it('should alias claude-3-5-sonnet to haiku', () => {+ expect(mapModelToVertex('claude-3-5-sonnet')).toBe('claude-haiku-4-5@20251001');});- it('should not modify model with short date', () => {- expect(mapModelToVertex('claude-3-5-sonnet-2024')).toBe('claude-3-5-sonnet-2024');+ // Short date suffix doesn't trigger date conversion+ it('should alias claude-3-5-sonnet-2024 to haiku', () => {+ expect(mapModelToVertex('claude-3-5-sonnet-2024')).toBe('claude-haiku-4-5@20251001');});it('should not modify empty string', () => {@@ -950,6 +1103,172 @@ describe('Streaming timeout expectations', () => {});});+// ============================================================================+// Assistant Message Content Array Bug Test (NEW - for text.text nesting fix)+// ============================================================================+describe('Assistant message with array content', () => {+ const mockServiceAccount = JSON.stringify({+ type: 'service_account',+ project_id: 'test',+ private_key_id: 'test',+ private_key: '-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----',+ client_email: '[email protected]',+ client_id: '123',+ auth_uri: 'https://accounts.google.com/o/oauth2/auth',+ token_uri: 'https://oauth2.googleapis.com/token',+ auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs',+ client_x509_cert_url: 'https://www.googleapis.com/robot/v1/metadata/x509/test',+ });++ let provider: VertexAIProvider;++ beforeEach(() => {+ provider = new VertexAIProvider(mockServiceAccount, 'test-project', 'us-east5');+ });++ it('should handle assistant message with array content (text block)', () => {+ // This reproduces the bug: "messages.2.content.0.text.text: Input should be a valid string"+ // When assistant message content is an array like [{type: 'text', text: 'Hello'}],+ // it was incorrectly wrapped as {type: 'text', text: [{type: 'text', text: 'Hello'}]}++ const requestBody = {+ model: 'claude-haiku-4-5@20251001',+ messages: [+ { role: 'user' as const, content: 'Hello' },+ {+ role: 'assistant' as const,+ content: [{ type: 'text', text: 'I will help you.' }], // Array content!+ },+ { role: 'user' as const, content: 'Thanks' },+ ],+ };++ // Access private method via any+ const anthropicBody = (provider as any).convertToAnthropicFormat(requestBody);++ // The assistant message content should be properly formatted+ // Either as a string 'I will help you.' or as array [{type: 'text', text: 'I will help you.'}]+ // NOT as {type: 'text', text: [{type: 'text', text: 'I will help you.'}]}+ // messages[0] = user, messages[1] = assistant, messages[2] = user+ const assistantMsg = anthropicBody.messages[1];++ if (typeof assistantMsg.content === 'string') {+ expect(assistantMsg.content).toBe('I will help you.');+ } else if (Array.isArray(assistantMsg.content)) {+ expect(assistantMsg.content[0].type).toBe('text');+ expect(typeof assistantMsg.content[0].text).toBe('string');+ expect(assistantMsg.content[0].text).toBe('I will help you.');+ } else {+ throw new Error('Unexpected content format');+ }+ });++ it('should handle assistant message with mixed array content (text + tool_use)', () => {+ const requestBody = {+ model: 'claude-haiku-4-5@20251001',+ messages: [+ { role: 'user' as const, content: 'Search for X' },+ {+ role: 'assistant' as const,+ content: [+ { type: 'text', text: "I'll search for that." },+ { type: 'tool_use', id: 'toolu_123', name: 'search', input: { q: 'X' } },+ ],+ },+ ],+ };++ const anthropicBody = (provider as any).convertToAnthropicFormat(requestBody);+ // messages[0] = user, messages[1] = assistant+ const assistantMsg = anthropicBody.messages[1];++ // Should be an array with both text and tool_use blocks+ expect(Array.isArray(assistantMsg.content)).toBe(true);+ expect(assistantMsg.content.length).toBe(2);+ expect(assistantMsg.content[0].type).toBe('text');+ expect(typeof assistantMsg.content[0].text).toBe('string');+ expect(assistantMsg.content[1].type).toBe('tool_use');+ });++ it('should handle assistant message with string content (normal case)', () => {+ const requestBody = {+ model: 'claude-haiku-4-5@20251001',+ messages: [+ { role: 'user' as const, content: 'Hello' },+ { role: 'assistant' as const, content: 'Hi there!' }, // String content+ ],+ };++ const anthropicBody = (provider as any).convertToAnthropicFormat(requestBody);+ // messages[0] = user, messages[1] = assistant+ const assistantMsg = anthropicBody.messages[1];++ // String content should remain as string+ expect(assistantMsg.content).toBe('Hi there!');+ });++ it('should NOT create nested text.text structure (bug reproduction)', () => {+ // This is the exact bug scenario that causes:+ // "messages.2.content.0.text.text: Input should be a valid string"+ const requestBody = {+ model: 'claude-haiku-4-5@20251001',+ messages: [+ { role: 'user' as const, content: 'Hello' },+ {+ role: 'assistant' as const,+ content: [{ type: 'text', text: 'Response 1' }],+ },+ { role: 'user' as const, content: 'Follow up' },+ ],+ };++ const anthropicBody = (provider as any).convertToAnthropicFormat(requestBody);++ // Check message at index 1 (the assistant message)+ const assistantMsg = anthropicBody.messages[1];++ // Recursively check that no content block has text.text (double nesting)+ function checkNoDoubleNesting(content: any): void {+ if (Array.isArray(content)) {+ content.forEach(checkNoDoubleNesting);+ } else if (content && typeof content === 'object') {+ if (content.type === 'text') {+ // text should be a string, not an object+ expect(typeof content.text).toBe('string');+ expect(content.text).not.toHaveProperty('text');+ }+ // Check nested properties+ Object.values(content).forEach(checkNoDoubleNesting);+ }+ }++ checkNoDoubleNesting(assistantMsg.content);+ });++ it('should handle user message with array content containing text blocks', () => {+ // User messages can also have array content+ const requestBody = {+ model: 'claude-haiku-4-5@20251001',+ messages: [+ {+ role: 'user' as const,+ content: [{ type: 'text', text: 'Hello from array' }],+ },+ ],+ };++ const anthropicBody = (provider as any).convertToAnthropicFormat(requestBody);+ const userMsg = anthropicBody.messages[0];++ // Check the text is properly formatted+ if (Array.isArray(userMsg.content)) {+ expect(userMsg.content[0].type).toBe('text');+ expect(typeof userMsg.content[0].text).toBe('string');+ expect(userMsg.content[0].text).toBe('Hello from array');+ }+ });+});+// ============================================================================// Image Content Conversion Tests (NEW - for multimodal support)// ============================================================================diff --git a/screenpipe-server/src/add.rs b/screenpipe-server/src/add.rsindex 163fdd47f..65c6b5ae2 100644--- a/screenpipe-server/src/add.rs+++ b/screenpipe-server/src/add.rs@@ -1,7 +1,9 @@use anyhow::Result;use regex::Regex;use screenpipe_db::DatabaseManager;-use screenpipe_vision::frame_comparison::{calculate_image_hash, FrameComparer, FrameComparisonConfig};+use screenpipe_vision::frame_comparison::{+ calculate_image_hash, FrameComparer, FrameComparisonConfig,+};use screenpipe_vision::utils::OcrEngine;#[cfg(target_os = "macos")]diff --git a/screenpipe-server/src/analytics.rs b/screenpipe-server/src/analytics.rsindex d61bb36be..074c241f3 100644--- a/screenpipe-server/src/analytics.rs+++ b/screenpipe-server/src/analytics.rs@@ -106,7 +106,7 @@ fn parse_macos_major_version(version_str: &str) -> Option<u32> {/// Check macOS version and send telemetry event if below recommended versions./// This helps track users on older macOS versions that may have compatibility issues.-///+////// Thresholds:/// - Below 12 (Monterey): ScreenCaptureKit not available at all/// - Below 14 (Sonoma): sck-rs may have issues, recommended to upgrade@@ -119,7 +119,7 @@ pub fn check_macos_version() {let sys = System::new();let os_version = sys.os_version().unwrap_or_default();let os_name = sys.name().unwrap_or_default();-+// Only check on macOSif !os_name.to_lowercase().contains("mac") {return;@@ -135,7 +135,7 @@ pub fn check_macos_version() {// Determine version categorylet (below_12, below_14) = (major_version < 12, major_version < 14);-+if !below_12 && !below_14 {debug!("macOS version {} is supported", os_version);return;@@ -174,10 +174,7 @@ pub fn check_macos_version() {}),);- debug!(- "Sent {} event for macOS {}",- event_name, os_version- );+ debug!("Sent {} event for macOS {}", event_name, os_version);}/// No-op on non-macOS platformsdiff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 9b16940a0..1f4edccdf 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -13,6 +13,9 @@ use screenpipe_audio::{},};use screenpipe_core::find_ffmpeg_path;+use screenpipe_core::sync::{+ BlobType, SyncClientConfig, SyncEvent, SyncManager, SyncService, SyncServiceConfig,+};use screenpipe_db::{create_migration_worker, DatabaseManager, MigrationCommand, MigrationConfig, MigrationStatus,};@@ -32,9 +35,6 @@ use screenpipe_server::{},watch_pid, PipeManager, ResourceMonitor, SCServer,};-use screenpipe_core::sync::{- BlobType, SyncClientConfig, SyncEvent, SyncManager, SyncService, SyncServiceConfig,-};use screenpipe_vision::monitor::list_monitors;use serde::Deserialize;use serde_json::{json, Value};@@ -808,7 +808,7 @@ async fn main() -> anyhow::Result<()> {let vision_manager: Option<Arc<VisionManager>> = if cli.use_all_monitors && !cli.disable_vision{info!("Using dynamic monitor detection (--use-all-monitors)");-+// Create activity feed for adaptive FPS if enabled#[cfg(feature = "adaptive-fps")]let activity_feed: screenpipe_vision::ActivityFeedOption = if cli.adaptive_fps {@@ -819,17 +819,20 @@ async fn main() -> anyhow::Result<()> {Some(feed)}Err(e) => {- warn!("Failed to start activity feed: {:?}. Adaptive FPS will be disabled.", e);+ warn!(+ "Failed to start activity feed: {:?}. Adaptive FPS will be disabled.",+ e+ );None}}} else {None};-+#[cfg(not(feature = "adaptive-fps"))]let activity_feed: screenpipe_vision::ActivityFeedOption = None;-+let config = VisionManagerConfig {output_path: output_path_clone.to_string(),fps,@@ -842,7 +845,7 @@ async fn main() -> anyhow::Result<()> {languages: languages_clone.clone(),capture_unfocused_windows: cli.capture_unfocused_windows,realtime_vision: cli.enable_realtime_audio_transcription,- activity_feed: activity_feed.clone(),+ activity_feed: activity_feed,};Some(Arc::new(VisionManager::new(config,@@ -893,17 +896,20 @@ async fn main() -> anyhow::Result<()> {Some(feed)}Err(e) => {- warn!("Failed to start activity feed: {:?}. Adaptive FPS will be disabled.", e);+ warn!(+ "Failed to start activity feed: {:?}. Adaptive FPS will be disabled.",+ e+ );None}}} else {None};-+#[cfg(not(feature = "adaptive-fps"))]let activity_feed_legacy: screenpipe_vision::ActivityFeedOption = None;-+// Use traditional start_continuous_recordinglet runtime = &tokio::runtime::Handle::current();runtime.spawn(async move {@@ -925,7 +931,7 @@ async fn main() -> anyhow::Result<()> {languages_clone.clone(),cli.capture_unfocused_windows,cli.enable_realtime_audio_transcription,- activity_feed_legacy.clone(),+ activity_feed_legacy,);let result = tokio::select! {@@ -1058,7 +1064,11 @@ async fn main() -> anyhow::Result<()> {);println!("│ cloud sync │ {:<34} │",- if cli.enable_sync { "enabled" } else { "disabled" }+ if cli.enable_sync {+ "enabled"+ } else {+ "disabled"+ });if cli.enable_sync {println!(@@ -1946,10 +1956,9 @@ async fn start_sync_service(db: Arc<DatabaseManager>,) -> anyhow::Result<Arc<screenpipe_core::sync::SyncServiceHandle>> {// Validate required credentials- let token = cli- .sync_token- .as_ref()- .ok_or_else(|| anyhow::anyhow!("--sync-token or SCREENPIPE_SYNC_TOKEN required for sync"))?;+ let token = cli.sync_token.as_ref().ok_or_else(|| {+ anyhow::anyhow!("--sync-token or SCREENPIPE_SYNC_TOKEN required for sync")+ })?;let password = cli.sync_password.as_ref().ok_or_else(|| {anyhow::anyhow!("--sync-password or SCREENPIPE_SYNC_PASSWORD required for sync")@@ -2076,7 +2085,9 @@ async fn handle_sync_command(command: &SyncCommand) -> anyhow::Result<()> {let error: serde_json::Value = response.json().await.unwrap_or_default();println!("failed to trigger sync: {}",- error.get("error").unwrap_or(&serde_json::json!("unknown error"))+ error+ .get("error")+ .unwrap_or(&serde_json::json!("unknown error")));}Err(e) => {@@ -2098,7 +2109,9 @@ async fn handle_sync_command(command: &SyncCommand) -> anyhow::Result<()> {let error: serde_json::Value = response.json().await.unwrap_or_default();println!("failed to download: {}",- error.get("error").unwrap_or(&serde_json::json!("unknown error"))+ error+ .get("error")+ .unwrap_or(&serde_json::json!("unknown error")));}Err(e) => {diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rsindex 7046979a6..e9833bb63 100644--- a/screenpipe-server/src/cli.rs+++ b/screenpipe-server/src/cli.rs@@ -318,7 +318,6 @@ pub struct Cli {// =========================================================================// Cloud Sync Options// =========================================================================-/// Enable cloud sync for cross-device data synchronization./// Requires a valid sync token and password.#[arg(long, default_value_t = false)]diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex 5689587aa..c122ed141 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -44,7 +44,7 @@ pub async fn start_continuous_recording(let ignored_urls_video = ignored_urls.to_vec();let languages = languages.clone();- let activity_feed = activity_feed.clone();+ let activity_feed = activity_feed;debug!("Starting video recording for monitor {}", monitor_id);vision_handle.spawn(async move {@@ -65,7 +65,7 @@ pub async fn start_continuous_recording(languages.clone(),capture_unfocused_windows,realtime_vision,- activity_feed.clone(),+ activity_feed,).await{diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 86081a090..50d4e2294 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -497,7 +497,7 @@ pub(crate) async fn search(SearchResult::Input(input) => input.app_name.as_ref()- .map_or(true, |app| !is_screenpipe_app(app)),+ .is_none_or(|app| !is_screenpipe_app(app)),}).map(|result| match result {SearchResult::OCR(ocr) => ContentItem::OCR(OCRContent {@@ -1441,7 +1441,10 @@ impl SCServer {.route("/sync/status", get(sync_api::sync_status)).route("/sync/trigger", axum::routing::post(sync_api::sync_trigger)).route("/sync/lock", axum::routing::post(sync_api::sync_lock))- .route("/sync/download", axum::routing::post(sync_api::sync_download))+ .route(+ "/sync/download",+ axum::routing::post(sync_api::sync_download),+ )// NOTE: websockerts and sse is not supported by openapi so we move it down here.route("/stream/frames", get(stream_frames_handler)).route("/ws/events", get(ws_events_handler))diff --git a/screenpipe-server/src/sync_api.rs b/screenpipe-server/src/sync_api.rsindex 1d926e011..85c3f49a8 100644--- a/screenpipe-server/src/sync_api.rs+++ b/screenpipe-server/src/sync_api.rs@@ -193,7 +193,11 @@ pub async fn sync_init(*is_syncing.write().await = false;*last_error.write().await = Some(err);}- SyncEvent::Progress { uploaded, total, bytes_transferred } => {+ SyncEvent::Progress {+ uploaded,+ total,+ bytes_transferred,+ } => {debug!("sync progress: {}/{} blobs, {} bytes",uploaded, total, bytes_transferred@@ -298,7 +302,9 @@ pub async fn sync_lock(info!("sync locked and service stopped");Ok(Json(json!({"success": true, "message": "sync locked"})))}- None => Ok(Json(json!({"success": true, "message": "sync was not initialized"}))),+ None => Ok(Json(+ json!({"success": true, "message": "sync was not initialized"}),+ )),}}diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rsindex 6b9c46ad2..998d63f90 100644--- a/screenpipe-server/src/video.rs+++ b/screenpipe-server/src/video.rs@@ -192,7 +192,7 @@ impl VideoCapture {capture_window_filters.clone(),capture_languages.clone(),capture_unfocused,- capture_activity_feed.clone(),+ capture_activity_feed,).await{diff --git a/screenpipe-server/src/vision_manager/manager.rs b/screenpipe-server/src/vision_manager/manager.rsindex 6c0b6c932..5bf1f3e85 100644--- a/screenpipe-server/src/vision_manager/manager.rs+++ b/screenpipe-server/src/vision_manager/manager.rs@@ -164,7 +164,7 @@ impl VisionManager {let languages = self.config.languages.clone();let capture_unfocused_windows = self.config.capture_unfocused_windows;let realtime_vision = self.config.realtime_vision;- let activity_feed = self.config.activity_feed.clone();+ let activity_feed = self.config.activity_feed;// Spawn the recording task using the existing record_video functionlet handle = self.vision_handle.spawn(async move {@@ -183,7 +183,7 @@ impl VisionManager {languages.clone(),capture_unfocused_windows,realtime_vision,- activity_feed.clone(),+ activity_feed,).await{diff --git a/screenpipe-vision/examples/screenpipe-vision.rs b/screenpipe-vision/examples/screenpipe-vision.rsindex d074c4789..f32633d6b 100644--- a/screenpipe-vision/examples/screenpipe-vision.rs+++ b/screenpipe-vision/examples/screenpipe-vision.rs@@ -1,7 +1,8 @@use clap::Parser;use screenpipe_core::Language;use screenpipe_vision::{- capture_screenshot_by_window::WindowFilters, continuous_capture, monitor::list_monitors, OcrEngine,+ capture_screenshot_by_window::WindowFilters, continuous_capture, monitor::list_monitors,+ OcrEngine,};use std::{sync::Arc, time::Duration};use tokio::sync::mpsc::channel;diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rsindex 044220818..871dbce24 100644--- a/screenpipe-vision/src/capture_screenshot_by_window.rs+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs@@ -350,7 +350,7 @@ impl WindowFilters {// Strategy 1: Check if pattern appears as a word in the titlelet words: Vec<&str> = title_lower.split_whitespace().collect();- let word_match = words.iter().any(|word| *word == pattern);+ let word_match = words.contains(&pattern);// Strategy 2: Check in title without spaces (e.g., "Wells Fargo" -> "wellsfargo")let no_space_match = title_no_spaces.contains(pattern);@@ -393,7 +393,7 @@ fn get_all_windows_sck() -> Result<Vec<WindowData>, Box<dyn Error>> {let windows = SckWindow::all()?;Ok(windows.into_iter()- .filter_map(|window| extract_window_data_sck(window))+ .filter_map(extract_window_data_sck).collect())}@@ -444,7 +444,10 @@ fn extract_window_data_sck(window: SckWindow) -> Option<WindowData> {image_buffer: buffer,}),Err(e) => {- debug!("Failed to capture image for window {} ({}): {}", app_name, title, e);+ debug!(+ "Failed to capture image for window {} ({}): {}",+ app_name, title, e+ );None}}@@ -455,7 +458,7 @@ fn get_all_windows_xcap() -> Result<Vec<WindowData>, Box<dyn Error>> {let windows = XcapWindow::all()?;Ok(windows.into_iter()- .filter_map(|window| extract_window_data_xcap(window))+ .filter_map(extract_window_data_xcap).collect())}@@ -506,7 +509,10 @@ fn extract_window_data_xcap(window: XcapWindow) -> Option<WindowData> {image_buffer: buffer,}),Err(e) => {- debug!("Failed to capture image for window {} ({}): {}", app_name, title, e);+ debug!(+ "Failed to capture image for window {} ({}): {}",+ app_name, title, e+ );None}}@@ -563,7 +569,10 @@ fn get_all_windows() -> Result<Vec<WindowData>, Box<dyn Error>> {image_buffer: buffer,}),Err(e) => {- debug!("Failed to capture image for window {} ({}): {}", app_name, title, e);+ debug!(+ "Failed to capture image for window {} ({}): {}",+ app_name, title, e+ );None}}@@ -653,15 +662,14 @@ pub async fn capture_all_visible_windows(.iter().any(|&browser| app_name.to_lowercase().contains(browser));- if is_browser && browser_url.is_none() && !is_focused {- if window_filters.is_title_suggesting_blocked_url(&window_name) {+ if is_browser && browser_url.is_none() && !is_focused+ && window_filters.is_title_suggesting_blocked_url(&window_name) {tracing::info!("Privacy filter: Skipping unfocused browser window with suspicious title: {}",window_name);continue;}- }all_captured_images.push(CapturedWindow {image,diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex b023f6665..4b94a5d34 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -9,8 +9,8 @@ use crate::microsoft::perform_ocr_windows;use crate::monitor::get_monitor_by_id;use crate::ocr_cache::{WindowCacheKey, WindowOcrCache};use crate::tesseract::perform_ocr_tesseract;-use crate::utils::OcrEngine;use crate::utils::capture_screenshot;+use crate::utils::OcrEngine;use anyhow::Result;use base64::{engine::general_purpose, Engine as _};use chrono::{DateTime, Utc};@@ -282,7 +282,7 @@ pub async fn continuous_capture(// Log frame comparison stats periodicallylet stats = frame_comparer.stats();- if stats.total_comparisons % 100 == 0 {+ if stats.total_comparisons.is_multiple_of(100) {debug!("Frame comparison stats: {} total, {} hash hits ({:.1}% hit rate)",stats.total_comparisons,diff --git a/screenpipe-vision/src/frame_comparison.rs b/screenpipe-vision/src/frame_comparison.rsindex 24731bdeb..ab17f5f48 100644--- a/screenpipe-vision/src/frame_comparison.rs+++ b/screenpipe-vision/src/frame_comparison.rs@@ -264,9 +264,12 @@ pub fn compare_histogram(image1: &DynamicImage, image2: &DynamicImage) -> anyhowpub fn compare_ssim(image1: &DynamicImage, image2: &DynamicImage) -> f64 {let image_one = image1.to_luma8();let image_two = image2.to_luma8();- let result =- image_compare::gray_similarity_structure(&image_compare::Algorithm::MSSIMSimple, &image_one, &image_two)- .expect("Images had different dimensions");+ let result = image_compare::gray_similarity_structure(+ &image_compare::Algorithm::MSSIMSimple,+ &image_one,+ &image_two,+ )+ .expect("Images had different dimensions");1.0 - result.score // Convert similarity to difference}@@ -304,7 +307,7 @@ mod tests {// Create horizontal "text lines"let line_height = 20;let is_text_line = (y / line_height) % 2 == 0;-+if is_text_line {// Simulate text with varying intensitylet char_width = 10;@@ -343,7 +346,10 @@ mod tests {let stats = comparer.stats();assert_eq!(stats.hash_hits, 1, "Should have 1 hash hit");- assert_eq!(stats.total_comparisons, 2, "Should have 2 total comparisons");+ assert_eq!(+ stats.total_comparisons, 2,+ "Should have 2 total comparisons"+ );}#[test]@@ -371,7 +377,10 @@ mod tests {let hash1 = calculate_image_hash(&image1);let hash2 = calculate_image_hash(&image2);- assert_ne!(hash1, hash2, "Different images should have different hashes");+ assert_ne!(+ hash1, hash2,+ "Different images should have different hashes"+ );}#[test]@@ -544,15 +553,17 @@ mod tests {let mut comparer = FrameComparer::new(config);// Simulate a real capture sequence with clear differences- let frame1 = create_text_pattern_image(1920, 1080, 0); // Initial screen- let frame2 = create_text_pattern_image(1920, 1080, 0); // Same (should hash-match)- let frame3 = create_text_pattern_image(1920, 1080, 0); // Same (should hash-match)- let frame4 = create_gradient_image(1920, 1080); // Different content+ let frame1 = create_text_pattern_image(1920, 1080, 0); // Initial screen+ let frame2 = create_text_pattern_image(1920, 1080, 0); // Same (should hash-match)+ let frame3 = create_text_pattern_image(1920, 1080, 0); // Same (should hash-match)+ let frame4 = create_gradient_image(1920, 1080); // Different contentlet frame5 = create_solid_image(1920, 1080, 128, 128, 128); // Gray screenlet frame6 = create_solid_image(1920, 1080, 128, 128, 128); // Same (should hash-match)- let frame7 = create_solid_image(1920, 1080, 0, 0, 0); // Black screen+ let frame7 = create_solid_image(1920, 1080, 0, 0, 0); // Black screen- let frames = vec![&frame1, &frame2, &frame3, &frame4, &frame5, &frame6, &frame7];+ let frames = vec![+ &frame1, &frame2, &frame3, &frame4, &frame5, &frame6, &frame7,+ ];let mut results = Vec::new();for frame in &frames {@@ -569,18 +580,34 @@ mod tests {assert_eq!(results[2], 0.0);// Different content: detected- assert!(results[3] > 0.0, "Different content should be detected: {}", results[3]);- assert!(results[4] > 0.0, "Gray screen should be detected: {}", results[4]);+ assert!(+ results[3] > 0.0,+ "Different content should be detected: {}",+ results[3]+ );+ assert!(+ results[4] > 0.0,+ "Gray screen should be detected: {}",+ results[4]+ );// Identical again: 0.0assert_eq!(results[5], 0.0);// Big change: high diff- assert!(results[6] > 0.3, "Black screen should be big change: {}", results[6]);+ assert!(+ results[6] > 0.3,+ "Black screen should be big change: {}",+ results[6]+ );// Verify hash hitslet stats = comparer.stats();- assert!(stats.hash_hits >= 3, "Should have at least 3 hash hits, got {}", stats.hash_hits);+ assert!(+ stats.hash_hits >= 3,+ "Should have at least 3 hash hits, got {}",+ stats.hash_hits+ );}#[test]@@ -668,7 +695,10 @@ mod tests {assert!(diff > 0.5, "Black vs white should have high SSIM diff");let same_diff = compare_ssim(&image1, &image1);- assert!(same_diff < 0.01, "Same image should have near-zero SSIM diff");+ assert!(+ same_diff < 0.01,+ "Same image should have near-zero SSIM diff"+ );}// ============================================================diff --git a/screenpipe-vision/src/monitor.rs b/screenpipe-vision/src/monitor.rsindex 75850e338..59fd06995 100644--- a/screenpipe-vision/src/monitor.rs+++ b/screenpipe-vision/src/monitor.rs@@ -33,9 +33,8 @@ pub mod macos_version {use std::process::Command;/// Cached macOS version (major, minor)- pub static MACOS_VERSION: Lazy<(u32, u32)> = Lazy::new(|| {- get_macos_version().unwrap_or((0, 0))- });+ pub static MACOS_VERSION: Lazy<(u32, u32)> =+ Lazy::new(|| get_macos_version().unwrap_or((0, 0)));/// Check if we should use sck-rs (requires macOS 12.3+)pub fn use_sck_rs() -> bool {@@ -49,13 +48,13 @@ pub mod macos_version {.arg("-productVersion").output().ok()?;-+let version_str = String::from_utf8_lossy(&output.stdout);let parts: Vec<&str> = version_str.trim().split('.').collect();-- let major: u32 = parts.get(0)?.parse().ok()?;++ let major: u32 = parts.first()?.parse().ok()?;let minor: u32 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);-+tracing::info!("Detected macOS version: {}.{}", major, minor);Some((major, minor))}@@ -306,7 +305,8 @@ pub async fn get_monitor_by_id(id: u32) -> Option<SafeMonitor> {match XcapMonitor::all() {Ok(monitors) => {let monitor_count = monitors.len();- let monitor_ids: Vec<u32> = monitors.iter().filter_map(|m| m.id().ok()).collect();+ let monitor_ids: Vec<u32> =+ monitors.iter().filter_map(|m| m.id().ok()).collect();tracing::debug!("Found {} monitors with IDs: {:?} (using xcap fallback)",