Skip to content

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

release-app: make monitor thread safe & impl device list sub commands

Louis Beaumont916a986144ea
diff --git a/.github/workflows/release-app.yml b/.github/workflows/release-app.yml
index 8923b469c..3ce7b1414 100644
--- a/.github/workflows/release-app.yml
+++ b/.github/workflows/release-app.yml
@@ -134,11 +134,11 @@ jobs:
matrix:
include:
- platform: "macos-latest"
- args: "--target aarch64-apple-darwin --features metal,beta"
+ args: "--target aarch64-apple-darwin --features metal"
target: aarch64-apple-darwin
tauri-args: "--target aarch64-apple-darwin --config src-tauri/tauri.conf.prod.json"
- platform: "macos-latest"
- args: "--target x86_64-apple-darwin --features metal,beta"
+ args: "--target x86_64-apple-darwin --features metal"
target: x86_64-apple-darwin
tauri-args: "--target x86_64-apple-darwin --config src-tauri/tauri.conf.prod.json"
- platform: ${{ needs.check_runner.outputs.runner_type }}
diff --git a/Cargo.toml b/Cargo.toml
index d56943602..6dc76e638 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,7 +13,7 @@ resolver = "2"
[workspace.package]
-version = "0.2.44"
+version = "0.2.45"
authors = ["louis030195 <[email protected]>"]
description = ""
repository = "https://github.com/mediar-ai/screenpipe"
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index ac61b8f85..f5669579e 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.33.4"
+version = "0.33.6"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index f02fce26b..0f5c7ac7d 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -11,7 +11,10 @@ use screenpipe_audio::{
};
use screenpipe_core::find_ffmpeg_path;
use screenpipe_server::{
- cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, OutputFormat, PipeCommand},
+ cli::{
+ AudioCommand, Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, OutputFormat,
+ PipeCommand, VisionCommand,
+ },
handle_index_command,
pipe_manager::PipeInfo,
start_continuous_recording, watch_pid, DatabaseManager, PipeManager, ResourceMonitor, Server,
@@ -38,16 +41,6 @@ use tracing_subscriber::prelude::__tracing_subscriber_SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, EnvFilter};
-fn print_devices(devices: &[AudioDevice]) {
- println!("available audio devices:");
- for device in devices.iter() {
- println!(" {}", device);
- }
-
- #[cfg(target_os = "macos")]
- println!("on macos, it's not intuitive but output devices are your displays");
-}
-
const DISPLAY: &str = r"
_
__________________ ___ ____ ____ (_____ ___
@@ -199,6 +192,55 @@ async fn main() -> anyhow::Result<()> {
let pipe_manager = Arc::new(PipeManager::new(local_data_dir_clone.clone()));
if let Some(ref command) = cli.command {
match command {
+ Command::Audio { subcommand } => match subcommand {
+ AudioCommand::List { output } => {
+ let devices = list_audio_devices().await?;
+ match output {
+ OutputFormat::Json => println!(
+ "{}",
+ serde_json::to_string_pretty(&json!({
+ "data": devices,
+ "success": true
+ }))?
+ ),
+ OutputFormat::Text => {
+ println!("available audio devices:");
+ for device in devices.iter() {
+ println!(" {}", device);
+ }
+ #[cfg(target_os = "macos")]
+ println!("note: on macos, output devices are your displays");
+ }
+ }
+ return Ok(());
+ }
+ },
+ Command::Vision { subcommand } => match subcommand {
+ VisionCommand::List { output } => {
+ let monitors = list_monitors().await;
+ match output {
+ OutputFormat::Json => println!(
+ "{}",
+ serde_json::to_string_pretty(&json!({
+ "data": futures::future::join_all(monitors.iter().map(|m| async move {
+ json!({
+ "id": m.id(),
+ "name": m.inner().await.name()
+ })
+ })).await,
+ "success": true
+ }))?
+ ),
+ OutputFormat::Text => {
+ println!("available monitors:");
+ for monitor in monitors.iter() {
+ println!(" {}. {:?}", monitor.id(), monitor.inner().await.name());
+ }
+ }
+ }
+ return Ok(());
+ }
+ },
Command::Completions { shell } => {
cli.handle_completions(shell.clone())?;
return Ok(());
@@ -346,6 +388,8 @@ async fn main() -> anyhow::Result<()> {
std::process::exit(1);
}
+ let mut devices_status = HashMap::new();
+
if !is_local_ipv4_port_free(cli.port) {
error!(
"you're likely already running screenpipe instance in a different environment, e.g. terminal/ide, close it and restart or use different port"
@@ -354,19 +398,8 @@ async fn main() -> anyhow::Result<()> {
}
let all_audio_devices = list_audio_devices().await?;
- let mut devices_status = HashMap::new();
- if cli.list_audio_devices {
- print_devices(&all_audio_devices);
- return Ok(());
- }
+
let all_monitors = list_monitors().await;
- if cli.list_monitors {
- println!("available monitors:");
- for monitor in all_monitors.iter() {
- println!(" {}. {:?}", monitor.id(), monitor);
- }
- return Ok(());
- }
let mut audio_devices = Vec::new();
diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rs
index 0ba41f2c6..b53d3b2a7 100644
--- a/screenpipe-server/src/cli.rs
+++ b/screenpipe-server/src/cli.rs
@@ -147,10 +147,6 @@ pub struct Cli {
#[arg(short = 'r', long)]
pub realtime_audio_device: Vec<String>,
- /// List available audio devices
- #[arg(long)]
- pub list_audio_devices: bool,
-
/// Data directory. Default to $HOME/.screenpipe
#[arg(long, value_hint = ValueHint::DirPath)]
pub data_dir: Option<String>,
@@ -190,10 +186,6 @@ pub struct Cli {
)]
pub ocr_engine: CliOcrEngine,
- /// List available monitors, then you can use --monitor-id to select one (with the ID)
- #[arg(long)]
- pub list_monitors: bool,
-
/// Monitor IDs to use, these will be used to select the monitors to record
#[arg(short = 'm', long)]
pub monitor_id: Vec<u32>,
@@ -292,6 +284,16 @@ impl Cli {
#[derive(Subcommand)]
pub enum Command {
+ /// Audio device management commands
+ Audio {
+ #[command(subcommand)]
+ subcommand: AudioCommand,
+ },
+ /// Vision device management commands
+ Vision {
+ #[command(subcommand)]
+ subcommand: VisionCommand,
+ },
/// Pipe management commands
Pipe {
#[command(subcommand)]
@@ -342,6 +344,25 @@ pub enum Command {
},
}
+#[derive(Subcommand)]
+pub enum AudioCommand {
+ /// List available audio devices
+ List {
+ /// Output format
+ #[arg(short, long, value_enum, default_value_t = OutputFormat::Text)]
+ output: OutputFormat,
+ },
+}
+
+#[derive(Subcommand)]
+pub enum VisionCommand {
+ /// List available monitors and vision devices
+ List {
+ /// Output format
+ #[arg(short, long, value_enum, default_value_t = OutputFormat::Text)]
+ output: OutputFormat,
+ },
+}
#[derive(Subcommand)]
pub enum PipeCommand {
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index ec40648ca..003726285 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -33,7 +33,9 @@ use crate::{
};
use crate::{plugin::ApiPluginLayer, video_utils::extract_frame};
use chrono::{DateTime, Utc};
-use screenpipe_audio::{default_input_device, default_output_device, list_audio_devices, AudioDevice, DeviceType};
+use screenpipe_audio::{
+ default_input_device, default_output_device, list_audio_devices, AudioDevice, DeviceType,
+};
use tracing::{debug, error, info};
use screenpipe_vision::monitor::list_monitors;
@@ -69,7 +71,6 @@ use std::str::FromStr;
use crate::text_embeds::generate_embedding;
-
pub struct AppState {
pub db: Arc<DatabaseManager>,
// pub device_manager: Arc<DeviceManager>,
@@ -463,16 +464,17 @@ pub(crate) async fn api_list_audio_devices(
pub async fn api_list_monitors(
) -> Result<JsonResponse<Vec<MonitorInfo>>, (StatusCode, JsonResponse<serde_json::Value>)> {
let monitors = list_monitors().await;
- let monitor_info: Vec<MonitorInfo> = monitors
- .into_iter()
- .map(|monitor| MonitorInfo {
+ let monitor_info = futures::future::join_all(monitors.into_iter().map(|monitor| async move {
+ let monitor = monitor.inner().await;
+ MonitorInfo {
id: monitor.id(),
name: monitor.name().to_string(),
width: monitor.width(),
height: monitor.height(),
is_default: monitor.is_primary(),
- })
- .collect();
+ }
+ }))
+ .await;
if monitor_info.is_empty() {
Err((
diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rs
index 4524ce7b3..266165172 100644
--- a/screenpipe-vision/src/capture_screenshot_by_window.rs
+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs
@@ -7,7 +7,9 @@ use std::fmt;
use std::time::Duration;
use tokio::time;
-use xcap::{Monitor, Window, XCapError};
+use xcap::{Window, XCapError};
+
+use crate::monitor::SafeMonitor;
#[derive(Debug)]
enum CaptureError {
@@ -189,7 +191,7 @@ impl WindowFilters {
}
pub async fn capture_all_visible_windows(
- monitor: &Monitor,
+ monitor: &SafeMonitor,
window_filters: &WindowFilters,
capture_unfocused_windows: bool,
) -> Result<Vec<CapturedWindow>, Box<dyn Error>> {
@@ -240,7 +242,7 @@ pub async fn capture_all_visible_windows(
Err(e) => error!(
"Failed to capture image for window {} on monitor {}: {}",
window_name,
- monitor.name(),
+ monitor.inner().await.name(),
e
),
}
@@ -251,7 +253,7 @@ pub async fn capture_all_visible_windows(
pub fn is_valid_window(
window: &Window,
- monitor: &Monitor,
+ monitor: &SafeMonitor,
filters: &WindowFilters,
capture_unfocused_windows: bool,
) -> bool {
diff --git a/screenpipe-vision/src/monitor.rs b/screenpipe-vision/src/monitor.rs
index 133a0889a..83205203f 100644
--- a/screenpipe-vision/src/monitor.rs
+++ b/screenpipe-vision/src/monitor.rs
@@ -1,13 +1,57 @@
+use anyhow::Result;
+use image::DynamicImage;
+use std::sync::Arc;
+use tokio::sync::Mutex;
use xcap::Monitor;
-pub async fn list_monitors() -> Vec<Monitor> {
- Monitor::all().unwrap().to_vec()
+// Thread-safe wrapper around Monitor
+#[derive(Clone)]
+pub struct SafeMonitor {
+ monitor_id: u32,
+ // We use Arc<Mutex> since we need to share state between threads
+ monitor: Arc<Mutex<Monitor>>,
}
-pub async fn get_default_monitor() -> Monitor {
- list_monitors().await.first().unwrap().clone()
+impl SafeMonitor {
+ pub fn new(monitor: Monitor) -> Self {
+ let monitor_id = monitor.id();
+ Self {
+ monitor_id,
+ monitor: Arc::new(Mutex::new(monitor)),
+ }
+ }
+
+ pub async fn capture_image(&self) -> Result<DynamicImage> {
+ let monitor = self.monitor.lock().await;
+ let image = monitor.capture_image()?;
+ Ok(image.into())
+ }
+
+ pub fn id(&self) -> u32 {
+ self.monitor_id
+ }
+
+ pub async fn inner(&self) -> tokio::sync::MutexGuard<'_, Monitor> {
+ self.monitor.lock().await
+ }
+}
+
+pub async fn list_monitors() -> Vec<SafeMonitor> {
+ Monitor::all()
+ .unwrap()
+ .into_iter()
+ .map(SafeMonitor::new)
+ .collect()
+}
+
+pub async fn get_default_monitor() -> SafeMonitor {
+ SafeMonitor::new(Monitor::all().unwrap().first().unwrap().clone())
}
-pub async fn get_monitor_by_id(id: u32) -> Option<Monitor> {
- list_monitors().await.iter().find(|m| m.id() == id).cloned()
+pub async fn get_monitor_by_id(id: u32) -> Option<SafeMonitor> {
+ Monitor::all()
+ .unwrap()
+ .into_iter()
+ .find(|m| m.id() == id)
+ .map(SafeMonitor::new)
}
diff --git a/screenpipe-vision/src/utils.rs b/screenpipe-vision/src/utils.rs
index 9a21585a7..a3cea7102 100644
--- a/screenpipe-vision/src/utils.rs
+++ b/screenpipe-vision/src/utils.rs
@@ -3,14 +3,13 @@ use crate::capture_screenshot_by_window::{
};
use crate::core::MaxAverageFrame;
use crate::custom_ocr::CustomOcrConfig;
+use crate::monitor::SafeMonitor;
use image::DynamicImage;
use image_compare::{Algorithm, Metric, Similarity};
use log::{debug, error, warn};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::time::{Duration, Instant};
-use xcap::Monitor;
-
#[derive(Clone, Debug, Default)]
pub enum OcrEngine {
Unstructured,
@@ -47,17 +46,16 @@ pub fn compare_images_ssim(image1: &DynamicImage, image2: &DynamicImage) -> f64
}
pub async fn capture_screenshot(
- monitor: &Monitor,
+ monitor: &SafeMonitor,
window_filters: &WindowFilters,
capture_unfocused_windows: bool,
) -> Result<(DynamicImage, Vec<CapturedWindow>, u64, Duration), anyhow::Error> {
// info!("Starting screenshot capture for monitor: {:?}", monitor);
let capture_start = Instant::now();
- let buffer = monitor.capture_image().map_err(|e| {
+ let image = monitor.capture_image().await.map_err(|e| {
error!("Failed to capture monitor image: {}", e);
anyhow::anyhow!("Monitor capture failed")
})?;
- let image = DynamicImage::ImageRgba8(buffer);
let image_hash = calculate_hash(&image);
let capture_duration = capture_start.elapsed();