YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
release-app improve health check (display each audio device status), remove noise from vision code, try to make audio device restart when lid is closed/open
Louis Beaumont6ce8744dba6f
diff --git a/screenpipe-app-tauri/components/screenpipe-status.tsx b/screenpipe-app-tauri/components/screenpipe-status.tsxindex 4928ec406..5493fd6a7 100644--- a/screenpipe-app-tauri/components/screenpipe-status.tsx+++ b/screenpipe-app-tauri/components/screenpipe-status.tsx@@ -12,7 +12,7 @@ import { toast } from "./ui/use-toast";import { Button } from "./ui/button";import { Separator } from "./ui/separator";import { useHealthCheck } from "@/lib/hooks/use-health-check";-import { Folder, Power, Settings, Activity } from "lucide-react";+import { Folder, Activity, Mic } from "lucide-react";import { open as openUrl } from "@tauri-apps/plugin-shell";import { LogFileButton } from "./log-file-button";@@ -213,6 +213,69 @@ const HealthStatus = ({ className }: { className?: string }) => {</div></div>+ {/* Audio Devices Status */}+ {!settings.disableAudio && health?.device_status_details && (+ <div className="mt-1 mb-2">+ <div className="flex items-center">+ <Button+ variant="ghost"+ size="sm"+ className="h-6 p-2"+ onClick={() => {+ const audioDevicesEl = document.getElementById(+ "audio-devices-container"+ );+ if (audioDevicesEl) {+ audioDevicesEl.classList.toggle("hidden");+ }+ }}+ >+ <Mic className="h-4 w-4 mr-2" />+ <span className="text-xs font-medium">audio devices</span>+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ className="ml-1 h-4 w-4"+ >+ <path d="m6 9 6 6 6-6" />+ </svg>+ </Button>+ </div>++ <div+ id="audio-devices-container"+ className="mt-1 max-h-32 overflow-y-auto rounded border border-border p-2 hidden"+ >+ {health.device_status_details+ .split(", ")+ .map((deviceStatus: string, index: number) => {+ const isActive = deviceStatus.includes("active");++ return (+ <div+ key={index}+ className="flex items-center mb-1 last:mb-0"+ >+ <div+ className={`w-2 h-2 rounded-full mr-2 ${+ isActive ? "bg-green-500" : "bg-red-500"+ }`}+ ></div>+ <span className="text-xs">{deviceStatus}</span>+ </div>+ );+ })}+ </div>+ </div>+ )}+{/* UI Monitoring Status */}{settings.enableUiMonitoring && (<div className="flex items-center justify-between">diff --git a/screenpipe-app-tauri/lib/hooks/use-health-check.tsx b/screenpipe-app-tauri/lib/hooks/use-health-check.tsxindex 77fb0f212..e7fb157e6 100644--- a/screenpipe-app-tauri/lib/hooks/use-health-check.tsx+++ b/screenpipe-app-tauri/lib/hooks/use-health-check.tsx@@ -11,6 +11,8 @@ interface HealthCheckResponse {audio_status: string;ui_status: string;message: string;+ verbose_instructions?: string | null;+ device_status_details?: string | null;}function isHealthChanged(diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lockindex 8fb063cb9..eeb3903e6 100755--- a/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -5300,7 +5300,7 @@ dependencies = [[[package]]name = "screenpipe-app"-version = "0.41.8"+version = "0.41.10"dependencies = ["anyhow","async-stream",diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 2caa54e2d..874896e0c 100644--- a/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "screenpipe-app"-version = "0.41.10"+version = "0.41.11"description = ""authors = ["you"]license = ""diff --git a/screenpipe-audio/src/audio_manager/device_monitor.rs b/screenpipe-audio/src/audio_manager/device_monitor.rsindex 537f47547..bb8fababd 100644--- a/screenpipe-audio/src/audio_manager/device_monitor.rs+++ b/screenpipe-audio/src/audio_manager/device_monitor.rs@@ -51,8 +51,20 @@ pub async fn start_device_monitor(&& !currently_available_devices.contains(&device){info!("Device {device_name} disconnected");++ // we try to restart the device+let _ = audio_manager.stop_device(device_name).await;- disconnected_devices.insert(device_name.clone());+ // disconnected_devices.insert(device_name.clone());+ match audio_manager.start_device(&device).await {+ Ok(()) => {+ let _ = audio_manager.stop_device(device_name).await;+ disconnected_devices.insert(device_name.clone());+ }+ Err(e) => {+ error!("restarting device {device_name} failed: {e}");+ }+ }} else {if audio_manager.status().await != AudioManagerStatus::Running {break;diff --git a/screenpipe-audio/src/core/mod.rs b/screenpipe-audio/src/core/mod.rsindex af9892490..6f4cd3b42 100644--- a/screenpipe-audio/src/core/mod.rs+++ b/screenpipe-audio/src/core/mod.rs@@ -5,6 +5,7 @@ pub mod stream;use crate::transcription::deepgram::streaming::stream_transcription_deepgram;use crate::AudioInput;use anyhow::Result;+use dashmap::DashMap;use lazy_static::lazy_static;use screenpipe_core::Language;use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};@@ -14,12 +15,41 @@ use stream::AudioStream;use tracing::error;lazy_static! {+ // Global fallback timestamp for backward compatibilitypub static ref LAST_AUDIO_CAPTURE: AtomicU64 = AtomicU64::new(SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs());++ // Per-device tracking of last audio capture+ pub static ref DEVICE_AUDIO_CAPTURES: DashMap<String, AtomicU64> = DashMap::new();+}++/// Updates the last capture time for a specific device+pub fn update_device_capture_time(device_name: &str) {+ let now = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs();++ // Update the global timestamp for backward compatibility+ LAST_AUDIO_CAPTURE.store(now, Ordering::Relaxed);++ // Update or insert the device-specific timestamp+ DEVICE_AUDIO_CAPTURES+ .entry(device_name.to_string())+ .or_insert_with(|| AtomicU64::new(now))+ .store(now, Ordering::Relaxed);+}++/// Gets the last capture time for a specific device+pub fn get_device_capture_time(device_name: &str) -> u64 {+ DEVICE_AUDIO_CAPTURES+ .get(device_name)+ .map(|atomic| atomic.load(Ordering::Relaxed))+ .unwrap_or_else(|| LAST_AUDIO_CAPTURE.load(Ordering::Relaxed))}fn is_normal_shutdown(is_running: &Arc<AtomicBool>) -> bool {diff --git a/screenpipe-audio/src/core/run_record_and_transcribe.rs b/screenpipe-audio/src/core/run_record_and_transcribe.rsindex aba7f3546..46989e996 100644--- a/screenpipe-audio/src/core/run_record_and_transcribe.rs+++ b/screenpipe-audio/src/core/run_record_and_transcribe.rs@@ -9,7 +9,7 @@ use std::{use anyhow::{anyhow, Result};use tracing::{debug, error, info, warn};-use crate::{core::LAST_AUDIO_CAPTURE, AudioInput};+use crate::{core::update_device_capture_time, AudioInput};use super::AudioStream;@@ -20,10 +20,11 @@ pub async fn run_record_and_transcribe(is_running: Arc<AtomicBool>,) -> Result<()> {let mut receiver = audio_stream.subscribe().await;+ let device_name = audio_stream.device.to_string();info!("starting continuous recording for {} ({}s segments)",- audio_stream.device.to_string(),+ device_name,duration.as_secs());@@ -41,13 +42,7 @@ pub async fn run_record_and_transcribe(match receiver.recv().await {Ok(chunk) => {collected_audio.extend(chunk);- LAST_AUDIO_CAPTURE.store(- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap()- .as_secs(),- Ordering::Relaxed,- );+ update_device_capture_time(&device_name);}Err(e) => {error!("error receiving audio data: {}", e);@@ -84,6 +79,6 @@ pub async fn run_record_and_transcribe(}}- info!("stopped recording for {}", audio_stream.device.to_string());+ info!("stopped recording for {}", device_name);Ok(())}diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex f23871d84..6aa9f4d17 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -287,6 +287,7 @@ pub struct HealthCheckResponse {pub ui_status: String,pub message: String,pub verbose_instructions: Option<String>,+ pub device_status_details: Option<String>,}#[derive(OaSchema, Serialize, Deserialize)]@@ -594,12 +595,39 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<Helet app_uptime = (now as i64) - (state.app_start_time.timestamp());let grace_period = 120; // 2 minutes in seconds- let last_capture = screenpipe_audio::core::LAST_AUDIO_CAPTURE.load(Ordering::Relaxed);- let audio_active = if app_uptime < grace_period {- true // Consider active during grace period- } else {- now - last_capture < 5 // Consider active if captured in last 5 seconds- };+ // Get the status of all devices+ let audio_devices = state.audio_manager.current_devices();+ let mut device_statuses = Vec::new();+ let mut global_audio_active = false;++ // Check each device+ for device in &audio_devices {+ let device_name = device.to_string();+ let last_capture = screenpipe_audio::core::get_device_capture_time(&device_name);+ let device_active = if app_uptime < grace_period {+ true // Consider active during grace period+ } else {+ now - last_capture < 5 // Consider active if captured in last 5 seconds+ };++ // Track if any device is active+ if device_active {+ global_audio_active = true;+ }+ debug!(target: "server", "device status: {} {}", device_name, device_active);++ device_statuses.push((device_name, device_active, last_capture));+ }++ // Fallback to global timestamp if no devices are detected+ if audio_devices.is_empty() {+ let last_capture = screenpipe_audio::core::LAST_AUDIO_CAPTURE.load(Ordering::Relaxed);+ global_audio_active = if app_uptime < grace_period {+ true // Consider active during grace period+ } else {+ now - last_capture < 5 // Consider active if captured in last 5 seconds+ };+ }let (last_frame, audio, last_ui) = match state.db.get_latest_timestamps().await {Ok((frame, audio, ui)) => (frame, audio, ui),@@ -623,16 +651,45 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He"ok"}Some(_) => "stale",- None => "no data",+ None => "not_started",}};let audio_status = if state.audio_disabled {- "disabled"- } else if audio_active {- "ok"+ "disabled".to_string()+ } else if global_audio_active {+ "ok".to_string()+ } else {+ match audio {+ Some(timestamp)+ if now.signed_duration_since(timestamp)+ < chrono::Duration::from_std(threshold).unwrap() =>+ {+ "stale".to_string()+ }+ Some(_) => "stale".to_string(),+ None => "not_started".to_string(),+ }+ };++ // Format device statuses as a string for a more detailed view+ let device_status_details = if !device_statuses.is_empty() {+ let now_secs = now.timestamp() as u64;+ let device_details: Vec<String> = device_statuses+ .iter()+ .map(|(name, active, last_capture)| {+ format!(+ "{}: {} (last activity: {}s ago)",+ name,+ if *active { "active" } else { "inactive" },+ now_secs.saturating_sub(*last_capture)+ )+ })+ .collect();++ Some(device_details.join(", "))} else {- "stale"+ None};let ui_status = if !state.ui_monitoring_enabled {@@ -646,7 +703,7 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He"ok"}Some(_) => "stale",- None => "no data",+ None => "not_started",}};@@ -670,15 +727,15 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<Heunhealthy_systems.push("audio");}if ui_status != "ok" && ui_status != "disabled" {- unhealthy_systems.push("ui monitoring");+ unhealthy_systems.push("ui");}+ let systems_str = unhealthy_systems.join(", ");(- "unhealthy",- format!("some systems are not functioning properly: {}. frame status: {}, audio status: {}, ui status: {}",- unhealthy_systems.join(", "), frame_status, audio_status, ui_status),- Some("if you're experiencing issues, please try contacting us on discord".to_string()),- 500,+ "degraded",+ format!("some systems are not healthy: {}", systems_str),+ Some(get_verbose_instructions(&unhealthy_systems)),+ 503,)};@@ -689,12 +746,37 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<Helast_audio_timestamp: audio,last_ui_timestamp: last_ui,frame_status: frame_status.to_string(),- audio_status: audio_status.to_string(),+ audio_status,ui_status: ui_status.to_string(),message,verbose_instructions,+ device_status_details,})}++fn get_verbose_instructions(unhealthy_systems: &[&str]) -> String {+ let mut instructions = String::new();++ if unhealthy_systems.contains(&"vision") {+ instructions.push_str("Vision system is not working properly. Check if screen recording permissions are enabled.\n");+ }++ if unhealthy_systems.contains(&"audio") {+ instructions.push_str("Audio system is not working properly. Check if microphone permissions are enabled and devices are connected.\n");+ }++ if unhealthy_systems.contains(&"ui") {+ instructions.push_str("UI monitoring is not working properly. Check if accessibility permissions are enabled.\n");+ }++ if instructions.is_empty() {+ instructions =+ "If you're experiencing issues, please try contacting us on Discord.".to_string();+ }++ instructions+}+// Request and response structs#[derive(OaSchema, Deserialize)]struct DownloadPipeRequest {@@ -1068,10 +1150,6 @@ impl SCServer {.post("/v1/embeddings", create_embeddings).post("/audio/device/start", start_audio_device).post("/audio/device/stop", stop_audio_device)- // .post("/vision/start", start_vision_device)- // .post("/vision/stop", stop_vision_device)- // .post("/audio/restart", restart_audio_devices)- // .post("/vision/restart", restart_vision_devices).route_yaml_spec("/openapi.yaml").route_json_spec("/openapi.json").freeze();diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rsindex a9b8326f2..81ef3231a 100644--- a/screenpipe-vision/src/core.rs+++ b/screenpipe-vision/src/core.rs@@ -32,7 +32,6 @@ use tokio::sync::mpsc::Sender;use tokio::time::sleep;use crate::browser_utils::create_url_detector;-use crate::monitor::SafeMonitor;fn serialize_image<S>(image: &Option<DynamicImage>, serializer: S) -> Result<S::Ok, S::Error>where@@ -146,69 +145,33 @@ pub async fn continuous_capture(let mut max_average: Option<MaxAverageFrame> = None;let mut max_avg_value = 0.0;- // Add failure tracking- let mut consecutive_failures = 0;- let failure_threshold = 10;-- // Add heartbeat counter- let mut last_heartbeat = Instant::now();- let heartbeat_interval = Duration::from_secs(60);-- // Add monitor retrieval failure tracking- let mut monitor_retrieval_failures = 0;- let max_monitor_retrieval_attempts = 3;-debug!("continuous_capture: Starting using monitor: {:?}",monitor_id);+ // 1. Get monitor+ let monitor = match get_monitor_by_id(monitor_id).await {+ Some(m) => m,+ None => {+ error!("Monitor not found");+ return;+ }+ };loop {- // 1. Get monitor- let monitor = match get_monitor(- &monitor_id,- &mut monitor_retrieval_failures,- max_monitor_retrieval_attempts,- )- .await- {- Some(m) => m,- None => {- sleep(Duration::from_secs(1)).await;- continue;- }- };-- // 2. Log heartbeat if needed- log_heartbeat_if_needed(- &mut last_heartbeat,- heartbeat_interval,- monitor_id,- frame_counter,- );-// 3. Capture screenshot- let capture_result = match capture_screenshot_with_retry(- &monitor,- &window_filters,- capture_unfocused_windows,- &mut consecutive_failures,- failure_threshold,- monitor_id,- frame_counter,- )- .await- {- Some(result) => result,- None => {- frame_counter += 1;- tokio::time::sleep(interval).await;- continue;- }- };+ let capture_result =+ match capture_screenshot(&monitor, &window_filters, capture_unfocused_windows).await {+ Ok(result) => result,+ Err(e) => {+ error!("Error capturing screenshot: {}", e);+ sleep(Duration::from_secs(1)).await;+ continue;+ }+ };// 4. Process captured image- let (image, window_images, image_hash) = capture_result;+ let (image, window_images, image_hash, _capture_duration) = capture_result;let should_skip = should_skip_frame(&previous_image,@@ -242,88 +205,6 @@ pub async fn continuous_capture(}}-// Helper functions to break down the complex continuous_capture function-async fn get_monitor(- monitor_id: &u32,- retrieval_failures: &mut u32,- max_attempts: u32,-) -> Option<SafeMonitor> {- match get_monitor_by_id(*monitor_id).await {- Some(m) => {- // Reset the counter when successful- *retrieval_failures = 0;- Some(m)- }- None => {- *retrieval_failures += 1;- error!(- "continuous_capture: Failed to get monitor {} (attempt {}/{})",- monitor_id, retrieval_failures, max_attempts- );-- if *retrieval_failures >= max_attempts {- error!("continuous_capture: Failed to get monitor after {} attempts, stopping capture process",- max_attempts);- None- } else {- None- }- }- }-}--fn log_heartbeat_if_needed(- last_heartbeat: &mut Instant,- heartbeat_interval: Duration,- monitor_id: u32,- frame_counter: u64,-) {- if last_heartbeat.elapsed() >= heartbeat_interval {- debug!(- "continuous_capture: Heartbeat for monitor {} - frame {}",- monitor_id, frame_counter- );- *last_heartbeat = Instant::now();- }-}--async fn capture_screenshot_with_retry(- monitor: &SafeMonitor,- window_filters: &Arc<WindowFilters>,- capture_unfocused_windows: bool,- consecutive_failures: &mut u32,- failure_threshold: u32,- monitor_id: u32,- frame_counter: u64,-) -> Option<(DynamicImage, Vec<CapturedWindow>, u64)> {- match capture_screenshot(monitor, window_filters, capture_unfocused_windows).await {- Ok((image, window_images, image_hash, _capture_duration)) => {- debug!(- "Captured screenshot on monitor {} with hash: {} (frame {})",- monitor_id, image_hash, frame_counter- );- *consecutive_failures = 0; // Reset failure counter on success- Some((image, window_images, image_hash))- }- Err(e) => {- *consecutive_failures += 1;- error!(- "Failed to capture screenshot on monitor {} (attempt {}/{} failures): {}",- monitor_id, consecutive_failures, failure_threshold, e- );-- if *consecutive_failures >= failure_threshold {- error!(- "continuous_capture: Too many consecutive capture failures, will retry in 5s"- );- sleep(Duration::from_secs(5)).await;- *consecutive_failures = 0; // Reset after longer wait- }- None- }- }-}-async fn should_skip_frame(previous_image: &Option<DynamicImage>,current_image: &DynamicImage,