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 disk usage in ph

Louis Beaumont2e2bde64d031
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index ed704be9e..f3496bec1 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.29.4"
+version = "0.29.5"
description = ""
authors = ["you"]
license = ""
@@ -84,6 +84,8 @@ notify = "8.0.0"
futures = "0.3.30"
async-stream = "0.3"
+chrono = "0.4.39"
+
[target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies]
tauri-plugin-cli = "2.0.0"
tauri-plugin-global-shortcut = "2"
diff --git a/screenpipe-app-tauri/src-tauri/src/analytics.rs b/screenpipe-app-tauri/src-tauri/src/analytics.rs
index b97aa3a6b..be5afdca9 100755
--- a/screenpipe-app-tauri/src-tauri/src/analytics.rs
+++ b/screenpipe-app-tauri/src-tauri/src/analytics.rs
@@ -2,6 +2,7 @@ use log::{error, info, warn};
use reqwest::Client;
use serde_derive::Deserialize;
use serde_json::json;
+use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use sysinfo::{System, SystemExt};
@@ -12,27 +13,33 @@ pub struct AnalyticsManager {
client: Client,
posthog_api_key: String,
distinct_id: String,
+ email: String,
interval: Duration,
enabled: Arc<Mutex<bool>>,
api_host: String,
local_api_base_url: String,
+ screenpipe_dir_path: PathBuf,
}
impl AnalyticsManager {
pub fn new(
posthog_api_key: String,
distinct_id: String,
+ email: String,
interval_hours: u64,
local_api_base_url: String,
+ screenpipe_dir_path: PathBuf,
) -> Self {
Self {
client: Client::new(),
posthog_api_key,
distinct_id,
+ email,
interval: Duration::from_secs(interval_hours * 3600),
enabled: Arc::new(Mutex::new(!cfg!(debug_assertions))),
api_host: "https://eu.i.posthog.com".to_string(),
local_api_base_url,
+ screenpipe_dir_path,
}
}
@@ -54,6 +61,7 @@ impl AnalyticsManager {
"properties": {
"distinct_id": self.distinct_id,
"$lib": "rust-reqwest",
+ "$email": self.email,
"os_name": system.name().unwrap_or_default(),
"os_version": system.os_version().unwrap_or_default(),
"kernel_version": system.kernel_version().unwrap_or_default(),
@@ -63,6 +71,26 @@ impl AnalyticsManager {
},
});
+ // Add disk usage information
+ if let Ok(Some(disk_usage)) = crate::disk_usage::disk_usage(&self.screenpipe_dir_path).await
+ {
+ if let Some(payload_props) = payload["properties"].as_object_mut() {
+ payload_props.extend(
+ json!({
+ "disk_total_data_size": disk_usage.total_data_size,
+ "disk_total_cache_size": disk_usage.total_cache_size,
+ "disk_available_space": disk_usage.avaiable_space,
+ "disk_media_videos_size": disk_usage.media.videos_size,
+ "disk_media_audios_size": disk_usage.media.audios_size,
+ "disk_total_pipes_size": disk_usage.pipes.total_pipes_size,
+ })
+ .as_object()
+ .unwrap()
+ .clone(),
+ );
+ }
+ }
+
if let Some(props) = properties {
if let Some(payload_props) = payload["properties"].as_object_mut() {
payload_props.extend(props.as_object().unwrap_or(&serde_json::Map::new()).clone());
@@ -100,7 +128,10 @@ impl AnalyticsManager {
};
// Send periodic event with health data
- if let Err(e) = self.send_event("app_still_running", Some(health_status)).await {
+ if let Err(e) = self
+ .send_event("app_still_running", Some(health_status))
+ .await
+ {
error!("failed to send periodic posthog event: {}", e);
}
@@ -112,10 +143,12 @@ impl AnalyticsManager {
}
}
- async fn check_recording_health(&self) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
+ async fn check_recording_health(
+ &self,
+ ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
let health_url = format!("{}/health", self.local_api_base_url);
let response = self.client.get(&health_url).send().await?;
-
+
if !response.status().is_success() {
return Ok(json!({
"is_healthy": false,
@@ -127,16 +160,16 @@ impl AnalyticsManager {
}
let health: serde_json::Value = response.json().await?;
-
+
// Extract relevant status fields
let frame_status = health["frame_status"].as_str().unwrap_or("unknown");
let audio_status = health["audio_status"].as_str().unwrap_or("unknown");
let ui_status = health["ui_status"].as_str().unwrap_or("unknown");
-
+
// Consider healthy if all enabled systems are "ok"
- let is_healthy = (frame_status == "ok" || frame_status == "disabled") &&
- (audio_status == "ok" || audio_status == "disabled") &&
- (ui_status == "ok" || ui_status == "disabled");
+ let is_healthy = (frame_status == "ok" || frame_status == "disabled")
+ && (audio_status == "ok" || audio_status == "disabled")
+ && (ui_status == "ok" || ui_status == "disabled");
Ok(json!({
"is_healthy": is_healthy,
@@ -169,9 +202,11 @@ impl AnalyticsManager {
pub fn start_analytics(
unique_id: String,
+ email: String,
posthog_api_key: String,
interval_hours: u64,
local_api_base_url: String,
+ screenpipe_dir_path: PathBuf,
) -> Result<Arc<AnalyticsManager>, Box<dyn std::error::Error>> {
let is_debug = std::env::var("TAURI_ENV_DEBUG").unwrap_or("false".to_string()) == "true";
if cfg!(debug_assertions) || is_debug {
@@ -179,16 +214,20 @@ pub fn start_analytics(
return Ok(Arc::new(AnalyticsManager::new(
posthog_api_key,
unique_id,
+ email,
interval_hours,
local_api_base_url,
+ screenpipe_dir_path,
)));
}
let analytics_manager = Arc::new(AnalyticsManager::new(
posthog_api_key,
unique_id,
+ email,
interval_hours,
local_api_base_url,
+ screenpipe_dir_path,
));
// Send initial event at boot
diff --git a/screenpipe-app-tauri/src-tauri/src/disk_usage.rs b/screenpipe-app-tauri/src-tauri/src/disk_usage.rs
index 1c3634a0b..2f8d9bc4e 100644
--- a/screenpipe-app-tauri/src-tauri/src/disk_usage.rs
+++ b/screenpipe-app-tauri/src-tauri/src/disk_usage.rs
@@ -1,11 +1,13 @@
+use chrono;
use serde::{Deserialize, Serialize};
+use serde_json;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use sysinfo::{DiskExt, System, SystemExt};
use tracing::info;
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DiskUsage {
pub pipes: DiskUsedByPipes,
pub media: DiskUsedByMedia,
@@ -14,19 +16,25 @@ pub struct DiskUsage {
pub avaiable_space: String,
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DiskUsedByPipes {
pub pipes: Vec<(String, String)>, // why not pipes' size??
pub total_pipes_size: String,
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DiskUsedByMedia {
pub videos_size: String,
pub audios_size: String,
pub total_media_size: String,
}
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct CachedDiskUsage {
+ pub timestamp: i64,
+ pub usage: DiskUsage,
+}
+
pub fn get_cache_dir() -> Result<Option<PathBuf>, String> {
let proj_dirs = dirs::cache_dir().ok_or_else(|| "failed to get cache dir".to_string())?;
Ok(Some(proj_dirs.join("screenpipe")))
@@ -62,7 +70,28 @@ pub fn readable(size: u64) -> String {
}
pub async fn disk_usage(screenpipe_dir: &PathBuf) -> Result<Option<DiskUsage>, String> {
- info!("Getting total disk usage, path {:?}", screenpipe_dir);
+ let cache_dir = match get_cache_dir()? {
+ Some(dir) => dir,
+ None => return Err("Cache directory not found".to_string()),
+ };
+ let cache_file = cache_dir.join("screenpipe").join("disk_usage.json");
+
+ // Check if cache exists and is recent
+ if let Ok(content) = fs::read_to_string(&cache_file) {
+ if let Ok(cached) = serde_json::from_str::<CachedDiskUsage>(&content) {
+ let now = chrono::Utc::now().timestamp();
+ let two_days = 2 * 24 * 60 * 60; // 2 days in seconds
+ if now - cached.timestamp < two_days {
+ return Ok(Some(cached.usage));
+ }
+ }
+ }
+
+ // Calculate new disk usage
+ info!(
+ "Cache miss or expired, calculating disk usage for path {:?}",
+ screenpipe_dir
+ );
let mut pipes = Vec::new();
let mut total_video_size = 0;
let mut total_audio_size = 0;
@@ -131,5 +160,17 @@ pub async fn disk_usage(screenpipe_dir: &PathBuf) -> Result<Option<DiskUsage>, S
avaiable_space: readable(avaiable_space),
};
+ // Cache the result
+ let cached = CachedDiskUsage {
+ timestamp: chrono::Utc::now().timestamp(),
+ usage: disk_usage.clone(),
+ };
+
+ if let Err(e) = fs::create_dir_all(&cache_dir) {
+ info!("Failed to create cache directory: {}", e);
+ } else if let Err(e) = fs::write(&cache_file, serde_json::to_string_pretty(&cached).unwrap()) {
+ info!("Failed to write cache file: {}", e);
+ }
+
Ok(Some(disk_usage))
}
diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rs
index b24c83ebc..047811616 100755
--- a/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -1,9 +1,11 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+use analytics::AnalyticsManager;
use commands::load_pipe_config;
use commands::save_pipe_config;
use commands::show_main_window;
+use serde_json::json;
use serde_json::Value;
use sidecar::SidecarManager;
use std::env;
@@ -33,7 +35,6 @@ use tracing_appender::rolling::{RollingFileAppender, Rotation};
use tracing_subscriber::prelude::*;
use tracing_subscriber::EnvFilter;
use updates::start_update_check;
-use uuid::Uuid;
mod analytics;
mod icons;
use crate::analytics::start_analytics;
@@ -64,7 +65,7 @@ use std::collections::HashMap;
use tauri::AppHandle;
use tauri_plugin_global_shortcut::GlobalShortcutExt;
use tauri_plugin_global_shortcut::{Code, Modifiers, Shortcut};
-use tauri_plugin_sentry::{sentry};
+use tauri_plugin_sentry::sentry;
mod health;
use health::start_health_check;
pub struct SidecarState(Arc<tokio::sync::Mutex<Option<SidecarManager>>>);
@@ -368,8 +369,10 @@ async fn list_pipes() -> anyhow::Result<Value> {
Ok(response)
}
-
-pub fn get_base_dir(app: &tauri::AppHandle, custom_path: Option<String>) -> anyhow::Result<PathBuf> {
+pub fn get_base_dir(
+ app: &tauri::AppHandle,
+ custom_path: Option<String>,
+) -> anyhow::Result<PathBuf> {
let default_path = app.path().local_data_dir().unwrap().join("screenpipe");
let local_data_dir = custom_path.map(PathBuf::from).unwrap_or(default_path);
@@ -950,24 +953,23 @@ async fn main() {
.unwrap_or(true);
let unique_id = store
- .get("userId")
+ .get("user.id")
.and_then(|v| v.as_str().map(String::from))
- .unwrap_or_else(|| {
- let new_id = Uuid::new_v4().to_string();
- store.set(
- "userId".to_string(),
- serde_json::Value::String(new_id.clone()),
- );
- store.save().unwrap();
- new_id
- });
+ .unwrap_or_default();
+
+ let email = store
+ .get("user.email")
+ .and_then(|v| v.as_str().map(String::from))
+ .unwrap_or_default();
if is_analytics_enabled {
match start_analytics(
unique_id,
+ email,
posthog_api_key,
interval_hours,
"http://localhost:3030".to_string(),
+ base_dir.clone(),
) {
Ok(analytics_manager) => {
app.manage(analytics_manager);
@@ -1061,11 +1063,40 @@ async fn main() {
app.run(|app_handle, event| match event {
tauri::RunEvent::Ready { .. } => {
debug!("Ready event");
+ // Send app started event
+ let app_handle = app_handle.app_handle().clone();
+ tauri::async_runtime::spawn(async move {
+ if let Some(analytics) = app_handle.try_state::<Arc<AnalyticsManager>>() {
+ let _ = analytics
+ .send_event(
+ "app_started",
+ Some(json!({
+ "startup_type": "normal"
+ })),
+ )
+ .await;
+ }
+ });
}
tauri::RunEvent::ExitRequested { .. } => {
debug!("ExitRequested event");
- // Add this to shut down the server
+ // Send app closed event before shutdown
+ let app_handle_v2 = app_handle.app_handle().clone();
+ tauri::async_runtime::spawn(async move {
+ if let Some(analytics) = app_handle_v2.try_state::<Arc<AnalyticsManager>>() {
+ let _ = analytics
+ .send_event(
+ "app_closed",
+ Some(json!({
+ "shutdown_type": "normal"
+ })),
+ )
+ .await;
+ }
+ });
+
+ // Shutdown server
if let Some(server_shutdown_tx) = app_handle.try_state::<mpsc::Sender<()>>() {
drop(server_shutdown_tx.send(()));
}