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 add memory profiling

Louis Beaumontcac580865f00
diff --git a/Cargo.toml b/Cargo.toml
index 7a436a7af..d14314f7e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,7 +13,7 @@ resolver = "2"
[workspace.package]
-version = "0.2.40"
+version = "0.2.41"
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 5d1bee079..8f1268eb6 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.0"
+version = "0.33.1"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 4b563b02a..23cc0cb20 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -334,17 +334,6 @@ async fn main() -> anyhow::Result<()> {
}
}
- // Check if Screenpipe is present in PATH
- // TODO: likely should not force user to install in PATH (eg brew, powershell, or button in UI)
- match ensure_screenpipe_in_path().await {
- Ok(_) => info!("screenpipe is available and properly set in the PATH"),
- Err(e) => {
- warn!("screenpipe PATH check failed: {}", e);
- warn!("please ensure screenpipe is installed correctly and is in your PATH");
- // do not crash
- }
- }
-
if find_ffmpeg_path().is_none() {
eprintln!("ffmpeg not found. please install ffmpeg and ensure it is in your path.");
std::process::exit(1);
@@ -399,8 +388,6 @@ async fn main() -> anyhow::Result<()> {
};
devices_status.insert(input_device, device_control);
}
- // audio output only on macos <15.0 atm ?
- // see https://github.com/mediar-ai/screenpipe/pull/106
if let Ok(output_device) = default_output_device() {
audio_devices.push(Arc::new(output_device.clone()));
let device_control = DeviceControl {
@@ -446,8 +433,6 @@ async fn main() -> anyhow::Result<()> {
if let Ok(input_device) = default_input_device() {
realtime_audio_devices.push(Arc::new(input_device.clone()));
}
- // audio output only on macos <15.0 atm ?
- // see https://github.com/mediar-ai/screenpipe/pull/106
if let Ok(output_device) = default_output_device() {
realtime_audio_devices.push(Arc::new(output_device.clone()));
}
@@ -464,8 +449,8 @@ async fn main() -> anyhow::Result<()> {
}
}
- let resource_monitor = ResourceMonitor::new();
- resource_monitor.start_monitoring(Duration::from_secs(10));
+ let resource_monitor = ResourceMonitor::new(!cli.disable_telemetry);
+ resource_monitor.start_monitoring(Duration::from_secs(10), Some(Duration::from_secs(60)));
let db = Arc::new(
DatabaseManager::new(&format!("{}/db.sqlite", local_data_dir.to_string_lossy()))
@@ -1308,149 +1293,6 @@ async fn handle_pipe_command(
Ok(())
}
-async fn ensure_screenpipe_in_path() -> anyhow::Result<()> {
- use tokio::process::Command;
-
- // Check if 'screenpipe' is already in the PATH
- let output = if cfg!(target_os = "windows") {
- Command::new("where").arg("screenpipe").output().await?
- } else {
- Command::new("which").arg("screenpipe").output().await?
- };
-
- // If 'screenpipe' is found, log and return early
- if output.status.success() {
- let stdout = String::from_utf8_lossy(&output.stdout);
- let screenpipe_path = PathBuf::from(stdout.trim());
- info!(
- "screenpipe already in PATH at: {}",
- screenpipe_path.display()
- );
- return Ok(());
- }
-
- // If not found, add 'screenpipe' to the PATH permanently
- let current_exe = env::current_exe()?;
- let current_dir = match current_exe.parent() {
- Some(dir) => dir,
- None => {
- return Err(anyhow::anyhow!(
- "failed to get current executable directory"
- ))
- }
- };
- let screenpipe_bin = current_dir.join("screenpipe");
-
- let paths = env::split_paths(&env::var("PATH")?).collect::<Vec<_>>();
- if !paths.contains(&current_dir.to_path_buf()) {
- // Platform-specific persistence
- if cfg!(target_os = "windows") {
- persist_path_windows(current_dir.to_path_buf())?;
- } else if cfg!(target_os = "macos") || cfg!(target_os = "linux") {
- persist_path_unix(current_dir.to_path_buf())?;
- }
- info!("added {} to the PATH permanently", screenpipe_bin.display());
- }
-
- Ok(())
-}
-
-fn persist_path_windows(new_path: PathBuf) -> anyhow::Result<()> {
- // Try to read the current PATH environment variable
- let current_path =
- env::var("PATH").map_err(|e| anyhow::anyhow!("Failed to read current PATH: {}", e))?;
-
- // Check if the new path is already in the current PATH
- if current_path.contains(new_path.to_str().unwrap_or("")) {
- info!("PATH already contains {}", new_path.display());
- return Ok(());
- }
-
- // Ensure 'setx' command can handle the new PATH length
- if current_path.len() + new_path.to_str().unwrap_or("").len() + 1 > 1024 {
- return Err(anyhow::anyhow!(
- "the PATH is too long to persist using 'setx'. please shorten the PATH."
- ));
- }
-
- // Construct the new PATH string
- let new_path_env = format!("{};{}", current_path, new_path.display());
-
- // Execute the 'setx' command to persist the PATH
- let output = std::process::Command::new("setx")
- .arg("PATH")
- .arg(&new_path_env)
- .output()
- .map_err(|e| anyhow::anyhow!("failed to execute 'setx' command: {}", e))?;
-
- // Check if the 'setx' command was successful
- if output.status.success() {
- info!("persisted PATH on Windows using setx");
- Ok(())
- } else {
- // Capture the stderr output from 'setx' if the command fails
- let error_message = String::from_utf8_lossy(&output.stderr);
- Err(anyhow::anyhow!(
- "failed to persist PATH using 'setx': {}",
- error_message
- ))
- }
-}
-
-fn persist_path_unix(new_path: PathBuf) -> anyhow::Result<()> {
- let home_dir = env::var("HOME")?;
- let shell_config = get_shell_config()?;
- let shell_config_path = PathBuf::from(format!("{}/{}", home_dir, shell_config));
-
- let new_path_entry = format!("\nexport PATH=\"$PATH:{}\"\n", new_path.display());
-
- // Check if the new path is already in the config file
- if let Ok(config_content) = fs::read_to_string(&shell_config_path) {
- if config_content.contains(new_path.to_str().unwrap()) {
- info!(
- "PATH is already persisted in {}",
- shell_config_path.display()
- );
- return Ok(());
- }
- }
-
- // Create the config file if it doesn't exist
- if !shell_config_path.exists() {
- fs::File::create(&shell_config_path)?;
- }
-
- // Append the new path entry to the config file
- let mut file = fs::OpenOptions::new()
- .append(true)
- .open(&shell_config_path)?;
- file.write_all(new_path_entry.as_bytes())?;
- info!("persisted PATH in {}", shell_config_path.display());
- info!(
- "please run 'source {}' or restart your shell to apply the changes.",
- shell_config_path.display()
- );
-
- Ok(())
-}
-
-fn get_shell_config() -> anyhow::Result<&'static str> {
- let shell = env::var("SHELL").unwrap_or_default();
- if shell.contains("zsh") {
- Ok(".zshrc")
- } else if shell.contains("bash") {
- if cfg!(target_os = "macos") {
- Ok(".bash_profile")
- } else {
- Ok(".bashrc")
- }
- } else if shell.contains("fish") {
- Ok(".config/fish/config.fish")
- } else {
- Ok(".profile")
- }
-}
-
// Add this function near the end of the file
async fn check_ffmpeg() -> anyhow::Result<()> {
// TODO: this should also check if it can properly encode mp4 etc
diff --git a/screenpipe-server/src/resource_monitor.rs b/screenpipe-server/src/resource_monitor.rs
index e9672c1a7..2eef1479d 100644
--- a/screenpipe-server/src/resource_monitor.rs
+++ b/screenpipe-server/src/resource_monitor.rs
@@ -1,4 +1,5 @@
use chrono::Local;
+use reqwest::Client;
use serde_json::json;
use serde_json::Value;
use std::env;
@@ -11,14 +12,16 @@ use std::io::Write;
use std::sync::Arc;
use std::time::{Duration, Instant};
use sysinfo::{PidExt, ProcessExt, System, SystemExt};
-use tracing::{error, info};
-
-#[cfg(target_os = "macos")]
-use std::process::Command;
+use tracing::debug;
+use tracing::{error, info, warn};
+use uuid;
pub struct ResourceMonitor {
start_time: Instant,
resource_log_file: Option<String>, // analyse output here: https://colab.research.google.com/drive/1zELlGdzGdjChWKikSqZTHekm5XRxY-1r?usp=sharing
+ posthog_client: Option<Client>,
+ posthog_enabled: bool,
+ distinct_id: String,
}
pub enum RestartSignal {
@@ -26,7 +29,7 @@ pub enum RestartSignal {
}
impl ResourceMonitor {
- pub fn new() -> Arc<Self> {
+ pub fn new(telemetry_enabled: bool) -> Arc<Self> {
let resource_log_file = if env::var("SAVE_RESOURCE_USAGE").is_ok() {
let now = Local::now();
let filename = format!("resource_usage_{}.json", now.format("%Y%m%d_%H%M%S"));
@@ -46,146 +49,261 @@ impl ResourceMonitor {
None
};
+ // Create client once and reuse instead of Option
+ let posthog_client = telemetry_enabled.then(Client::new);
+
+ if telemetry_enabled {
+ debug!("Telemetry enabled, will send performance data to PostHog");
+ } else {
+ debug!("Telemetry disabled, will not send performance data to PostHog");
+ }
+
+ // Generate a unique ID for this installation
+ let distinct_id = uuid::Uuid::new_v4().to_string();
+
Arc::new(Self {
start_time: Instant::now(),
resource_log_file,
+ posthog_client,
+ posthog_enabled: telemetry_enabled,
+ distinct_id,
})
}
- fn log_status(&self, sys: &System) {
- let pid = std::process::id();
- let main_process = sys.process(sysinfo::Pid::from_u32(pid));
+ async fn send_to_posthog(
+ &self,
+ total_memory_gb: f64,
+ system_total_memory: f64,
+ total_cpu: f32,
+ ) {
+ let Some(client) = &self.posthog_client else {
+ return;
+ };
+
+ // Create System only when needed
+ let sys = System::new();
+
+ // Avoid unnecessary cloning by using references
+ let payload = json!({
+ "api_key": "phc_6TUWxXM2NQGPuLhkwgRHxPfXMWqhGGpXqWNIw0GRpMD",
+ "event": "resource_usage",
+ "properties": {
+ "distinct_id": &self.distinct_id,
+ "$lib": "rust-reqwest",
+ "total_memory_gb": total_memory_gb,
+ "system_total_memory_gb": system_total_memory,
+ "memory_usage_percent": (total_memory_gb / system_total_memory) * 100.0,
+ "total_cpu_percent": total_cpu,
+ "runtime_seconds": self.start_time.elapsed().as_secs(),
+ "os_name": sys.name().unwrap_or_default(),
+ "os_version": sys.os_version().unwrap_or_default(),
+ "kernel_version": sys.kernel_version().unwrap_or_default(),
+ "cpu_count": sys.cpus().len(),
+ "release": env!("CARGO_PKG_VERSION"),
+ }
+ });
+
+ debug!("Sending resource usage to PostHog: {:?}", payload);
+ // Send the event to PostHog
+ if let Err(e) = client
+ .post("https://eu.i.posthog.com/capture/")
+ .json(&payload)
+ .send()
+ .await
+ {
+ error!("Failed to send resource usage to PostHog: {}", e);
+ }
+ }
+
+ async fn collect_metrics(&self, sys: &System) -> (f64, f64, f64, f32, f64, Duration) {
+ let pid = std::process::id();
let mut total_memory = 0.0;
+ let mut max_virtual_memory = 0.0; // Changed from total to max
let mut total_cpu = 0.0;
- if let Some(process) = main_process {
- total_memory += process.memory() as f64;
- total_cpu += process.cpu_usage();
+ if let Some(main_process) = sys.process(sysinfo::Pid::from_u32(pid)) {
+ total_memory += main_process.memory() as f64 / (1024.0 * 1024.0 * 1024.0);
- // Iterate through all processes to find children
+ // Take the maximum virtual memory instead of sum
+ max_virtual_memory = main_process.virtual_memory() as f64 / (1024.0 * 1024.0 * 1024.0);
+
+ total_cpu += main_process.cpu_usage();
+
+ // Add child processes
for child_process in sys.processes().values() {
if child_process.parent() == Some(sysinfo::Pid::from_u32(pid)) {
- total_memory += child_process.memory() as f64;
+ total_memory += child_process.memory() as f64 / (1024.0 * 1024.0 * 1024.0);
+
+ // Take max instead of sum
+ max_virtual_memory = max_virtual_memory
+ .max(child_process.virtual_memory() as f64 / (1024.0 * 1024.0 * 1024.0));
+
total_cpu += child_process.cpu_usage();
}
}
+ }
- let total_memory_gb = total_memory / 1048576000.0;
- let system_total_memory = sys.total_memory() as f64 / 1048576000.0;
- let memory_usage_percent = (total_memory_gb / system_total_memory) * 100.0;
- let runtime = self.start_time.elapsed();
-
- let log_message = if cfg!(target_os = "macos") {
- if let Some(npu_usage) = self.get_npu_usage() {
- format!(
- "Runtime: {}s, Total Memory: {:.0}% ({:.0} GB / {:.0} GB), Total CPU: {:.0}%, NPU: {:.0}%",
- runtime.as_secs(), memory_usage_percent, total_memory_gb, system_total_memory, total_cpu, npu_usage
- )
- } else {
- format!(
- "Runtime: {}s, Total Memory: {:.0}% ({:.0} GB / {:.0} GB), Total CPU: {:.0}%, NPU: N/A",
- runtime.as_secs(), memory_usage_percent, total_memory_gb, system_total_memory, total_cpu
- )
- }
- } else {
- format!(
- "Runtime: {}s, Total Memory: {:.0}% ({:.2} GB / {:.2} GB), Total CPU: {:.0}%",
- runtime.as_secs(),
- memory_usage_percent,
- total_memory_gb,
- system_total_memory,
- total_cpu
- )
- };
-
- info!("{}", log_message);
-
- if let Some(filename) = &self.resource_log_file {
- let now = Local::now();
- let json_data = json!({
- "timestamp": now.to_rfc3339(),
- "runtime_seconds": runtime.as_secs(),
- "total_memory_gb": total_memory_gb,
- "system_total_memory_gb": system_total_memory,
- "memory_usage_percent": memory_usage_percent,
- "total_cpu_percent": total_cpu,
- "npu_usage_percent": self.get_npu_usage().unwrap_or(-1.0),
- });
-
- if let Ok(mut file) = OpenOptions::new().read(true).write(true).open(filename) {
- let mut contents = String::new();
- if file.read_to_string(&mut contents).is_ok() {
- if let Ok(mut json_array) = serde_json::from_str::<Value>(&contents) {
- if let Some(array) = json_array.as_array_mut() {
- array.push(json_data);
- if file.set_len(0).is_ok() && file.seek(SeekFrom::Start(0)).is_ok()
- {
- if let Err(e) =
- file.write_all(json_array.to_string().as_bytes())
- {
- error!("Failed to write JSON data to file: {}", e);
- }
- } else {
- error!("Failed to truncate and seek file: {}", filename);
+ let system_total_memory = sys.total_memory() as f64 / (1024.0 * 1024.0 * 1024.0);
+ let memory_usage_percent = (total_memory / system_total_memory) * 100.0;
+ let runtime = self.start_time.elapsed();
+
+ (
+ total_memory,
+ system_total_memory,
+ memory_usage_percent,
+ total_cpu,
+ max_virtual_memory,
+ runtime,
+ )
+ }
+
+ async fn log_to_file(&self, metrics: (f64, f64, f64, f32, f64, Duration)) {
+ let (
+ total_memory_gb,
+ system_total_memory,
+ memory_usage_percent,
+ total_cpu,
+ total_virtual_memory_gb,
+ runtime,
+ ) = metrics;
+
+ if let Some(ref filename) = self.resource_log_file {
+ let json_data = json!({
+ "timestamp": Local::now().to_rfc3339(),
+ "runtime_seconds": runtime.as_secs(),
+ "total_memory_gb": total_memory_gb,
+ "system_total_memory_gb": system_total_memory,
+ "memory_usage_percent": memory_usage_percent,
+ "total_cpu_percent": total_cpu,
+ "total_virtual_memory_gb": total_virtual_memory_gb,
+ });
+
+ if let Ok(mut file) = OpenOptions::new().read(true).write(true).open(filename) {
+ let mut contents = String::new();
+ if file.read_to_string(&mut contents).is_ok() {
+ if let Ok(mut json_array) = serde_json::from_str::<Value>(&contents) {
+ if let Some(array) = json_array.as_array_mut() {
+ array.push(json_data);
+ if file.set_len(0).is_ok() && file.seek(SeekFrom::Start(0)).is_ok() {
+ if let Err(e) = file.write_all(json_array.to_string().as_bytes()) {
+ error!("Failed to write JSON data to file: {}", e);
}
}
- } else {
- error!("Failed to parse JSON from file: {}", filename);
}
- } else {
- error!("Failed to read JSON file: {}", filename);
}
- } else {
- error!("Failed to open JSON file: {}", filename);
}
+ let _ = file.flush();
}
}
}
- pub fn start_monitoring(self: &Arc<Self>, interval: Duration) {
+ async fn log_status(&self, sys: &System) {
+ let metrics = self.collect_metrics(sys).await;
+ let (
+ total_memory_gb,
+ system_total_memory,
+ memory_usage_percent,
+ total_cpu,
+ total_virtual_memory_gb,
+ runtime,
+ ) = metrics;
+
+ // Log to console with virtual memory
+ let log_message = format!(
+ "Runtime: {}s, Memory: {:.0}% ({:.2} GB / {:.2} GB), Virtual: {:.2} GB, CPU: {:.0}%",
+ runtime.as_secs(),
+ memory_usage_percent,
+ total_memory_gb,
+ system_total_memory,
+ total_virtual_memory_gb,
+ total_cpu
+ );
+ info!("{}", log_message);
+
+ // Log to file
+ self.log_to_file(metrics).await;
+
+ // Send to PostHog if enabled
+ if self.posthog_enabled {
+ tokio::select! {
+ _ = self.send_to_posthog(total_memory_gb, system_total_memory, total_cpu) => {},
+ _ = tokio::time::sleep(Duration::from_secs(5)) => {
+ warn!("PostHog request timed out");
+ }
+ }
+ }
+ }
+
+ pub fn start_monitoring(
+ self: &Arc<Self>,
+ interval: Duration,
+ posthog_interval: Option<Duration>,
+ ) {
let monitor = Arc::clone(self);
+ let posthog_interval = posthog_interval.unwrap_or(interval);
+ let mut last_posthog_update = Instant::now();
+
tokio::spawn(async move {
let mut sys = System::new_all();
+
loop {
tokio::select! {
_ = tokio::time::sleep(interval) => {
sys.refresh_all();
- monitor.log_status(&sys);
+ let now = Instant::now();
+ let should_send_to_posthog = now.duration_since(last_posthog_update) >= posthog_interval;
+
+ if should_send_to_posthog {
+ last_posthog_update = now;
+ monitor.log_status(&sys).await;
+ } else {
+ // Log status without sending to PostHog
+ monitor.log_status_local(&sys).await;
+ }
}
}
}
});
}
- #[cfg(target_os = "macos")]
- fn get_npu_usage(&self) -> Option<f32> {
- let output = Command::new("ioreg")
- .args(["-r", "-c", "AppleARMIODevice", "-n", "ane0"])
- .output()
- .ok()?;
-
- let output_str = String::from_utf8_lossy(&output.stdout);
-
- // Parse the output to find the "ane_power" value
- for line in output_str.lines() {
- if line.contains("\"ane_power\"") {
- if let Some(value) = line.split('=').nth(1) {
- if let Ok(power) = value.trim().parse::<f32>() {
- // Assuming max ANE power is 8.0W (adjust if needed)
- let max_ane_power = 8.0;
- let npu_usage_percent = (power / max_ane_power) * 100.0;
- return Some(npu_usage_percent);
- }
- }
- }
- }
+ // New method for logging without PostHog
+ async fn log_status_local(&self, sys: &System) {
+ let metrics = self.collect_metrics(sys).await;
+ let (
+ total_memory_gb,
+ system_total_memory,
+ memory_usage_percent,
+ total_cpu,
+ total_virtual_memory_gb,
+ runtime,
+ ) = metrics;
+
+ // Log to console with virtual memory
+ let log_message = format!(
+ "Runtime: {}s, Memory: {:.0}% ({:.2} GB / {:.2} GB), Virtual: {:.2} GB, CPU: {:.0}%",
+ runtime.as_secs(),
+ memory_usage_percent,
+ total_memory_gb,
+ system_total_memory,
+ total_virtual_memory_gb,
+ total_cpu
+ );
+ info!("{}", log_message);
- None
+ // Log to file
+ self.log_to_file(metrics).await;
}
- #[cfg(not(target_os = "macos"))]
- fn get_npu_usage(&self) -> Option<f32> {
- None
+ pub async fn shutdown(&self) {
+ if let Some(ref file) = self.resource_log_file {
+ if let Ok(mut f) = OpenOptions::new().write(true).open(file) {
+ let _ = f.flush();
+ }
+ }
+
+ if let Some(_) = &self.posthog_client {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
}
}