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: disk usages (#1624)
tribhuwanf014228d14db
diff --git a/screenpipe-app-tauri/components/settings/disk-usage.tsx b/screenpipe-app-tauri/components/settings/disk-usage.tsxindex dcec51d0e..411a7ba10 100644--- a/screenpipe-app-tauri/components/settings/disk-usage.tsx+++ b/screenpipe-app-tauri/components/settings/disk-usage.tsx@@ -66,28 +66,10 @@ export default function DiskUsage() {const getDisk = async () => {setLoading(true);try {- // const cachedData = await localforage.getItem<{- // diskData: DiskUsageData;- // lastUpdated: number;- // }>("diskUsage");- const now = Date.now();- const twoDaysInMillis = 2 * 24 * 60 * 60 * 1000;- // if (cachedData && now - cachedData.lastUpdated < twoDaysInMillis) {- // setDiskUsage(cachedData.diskData);- // setLoading(false);- // } else {const result = await invoke<DiskUsageData>("get_disk_usage");console.log("result", result);- // await new Promise<DiskUsageData>((resolve) => {- // setTimeout(() => resolve(result), 3000);- // });- // await localforage.setItem("diskUsage", {- // diskData: result,- // lastUpdated: now,- // });setDiskUsage(result);setLoading(false);- // }} catch (error) {console.error("Failed to fetch disk usage:", error);toast({diff --git a/screenpipe-app-tauri/src-tauri/src/disk_usage.rs b/screenpipe-app-tauri/src-tauri/src/disk_usage.rsindex c46160c57..f670e0cca 100644--- a/screenpipe-app-tauri/src-tauri/src/disk_usage.rs+++ b/screenpipe-app-tauri/src-tauri/src/disk_usage.rs@@ -5,7 +5,7 @@ use std::fs;use std::io;use std::path::{Path, PathBuf};use sysinfo::{DiskExt, System, SystemExt};-use tracing::info;+use tracing::{info, warn};#[derive(Debug, Serialize, Deserialize, Clone)]pub struct DiskUsage {@@ -40,18 +40,21 @@ pub fn get_cache_dir() -> Result<Option<PathBuf>, String> {Ok(Some(proj_dirs.join("screenpipe")))}-pub fn directory_size(path: &Path) -> io::Result<u64> {+pub fn directory_size(path: &Path) -> io::Result<Option<u64>> {+ if !path.exists() {+ return Ok(None);+ }let mut size = 0;for entry in fs::read_dir(path)? {let entry = entry?;let metadata = entry.metadata()?;if metadata.is_dir() {- size += directory_size(&entry.path())?;+ size += directory_size(&entry.path())?.unwrap_or(0);} else {size += metadata.len();}}- Ok(size)+ Ok(Some(size))}pub fn readable(size: u64) -> String {@@ -70,81 +73,96 @@ pub fn readable(size: u64) -> String {}pub async fn disk_usage(screenpipe_dir: &PathBuf) -> Result<Option<DiskUsage>, String> {- // Create base directories if they don't exist- fs::create_dir_all(screenpipe_dir).map_err(|e| e.to_string())?;-let pipes_dir = screenpipe_dir.join("pipes");let data_dir = screenpipe_dir.join("data");- // Create required subdirectories- fs::create_dir_all(&pipes_dir).map_err(|e| e.to_string())?;- fs::create_dir_all(&data_dir).map_err(|e| e.to_string())?;-let cache_dir = match get_cache_dir()? {Some(dir) => dir,None => return Err("Cache directory not found".to_string()),};+fs::create_dir_all(&cache_dir).map_err(|e| e.to_string())?;-- // Create screenpipe subdirectory in cache- let screenpipe_cache_dir = cache_dir.join("screenpipe");- fs::create_dir_all(&screenpipe_cache_dir).map_err(|e| e.to_string())?;-- let cache_file = screenpipe_cache_dir.join("disk_usage.json");+ let cache_file = cache_dir.join("disk_usage.json");- // Check if cache exists and is recentif let Ok(content) = fs::read_to_string(&cache_file) {- info!("cache file found: {}", cache_file.to_string_lossy());- if let Ok(cached) = serde_json::from_str::<CachedDiskUsage>(&content) {- info!("cached: {:?}", cached);- 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));+ warn!("disk cache file found: {}", cache_file.to_string_lossy());+ if content.contains("---") {+ info!("possibly some values in disk usgae haven't calculated, recalculating...");+ } else {+ if let Ok(cached) = serde_json::from_str::<CachedDiskUsage>(&content) {+ let now = chrono::Local::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;-- for entry in fs::read_dir(&pipes_dir).map_err(|e| e.to_string())? {- let entry = entry.map_err(|e| e.to_string())?;- let path = entry.path();- if path.is_dir() {- let size = directory_size(&path).map_err(|e| e.to_string())?;- pipes.push((- path.file_name().unwrap().to_string_lossy().to_string(),- readable(size),- ));+ let mut total_video_size: Option<u64> = Some(0);+ let mut total_audio_size: Option<u64> = Some(0);++ if pipes_dir.exists() {+ for entry in fs::read_dir(&pipes_dir).map_err(|e| e.to_string())? {+ let entry = entry.map_err(|e| e.to_string())?;+ let path = entry.path();+ if path.is_dir() {+ let size = directory_size(&path).map_err(|e| e.to_string())?;+ let size_str = match size {+ Some(s) => readable(s),+ None => "---".to_string(),+ };+ pipes.push((+ path.file_name().unwrap().to_string_lossy().to_string(),+ size_str,+ ));+ }}+ } else {+ warn!("there are no pipes to calculate sizes");}- let total_data_size = directory_size(screenpipe_dir).map_err(|e| e.to_string())?;- let total_media_size = directory_size(&data_dir).map_err(|e| e.to_string())?;- let total_pipes_size = directory_size(&pipes_dir).map_err(|e| e.to_string())?;- let total_cache_size = directory_size(&screenpipe_cache_dir).map_err(|e| e.to_string())?;-- for entry in fs::read_dir(&data_dir).map_err(|e| e.to_string())? {- let entry = entry.map_err(|e| e.to_string())?;- let path = entry.path();- if path.is_file() {- let size = entry.metadata().map_err(|e| e.to_string())?.len();- let file_name = path.file_name().unwrap().to_string_lossy().to_string();- if file_name.contains("input") || file_name.contains("output") {- total_audio_size += size;- } else {- total_video_size += size;+ let total_data_size = match directory_size(screenpipe_dir).map_err(|e| e.to_string())? {+ Some(size) => readable(size),+ None => "---".to_string(),+ };+ let total_media_size = match directory_size(&data_dir).map_err(|e| e.to_string())? {+ Some(size) => readable(size),+ None => "---".to_string(),+ };+ let total_pipes_size = match directory_size(&pipes_dir).map_err(|e| e.to_string())? {+ Some(size) => readable(size),+ None => "---".to_string(),+ };+ let total_cache_size = match directory_size(&cache_dir).map_err(|e| e.to_string())? {+ Some(size) => readable(size),+ None => "---".to_string(),+ };++ if data_dir.exists() {+ for entry in fs::read_dir(&data_dir).map_err(|e| e.to_string())? {+ let entry = entry.map_err(|e| e.to_string())?;+ let path = entry.path();+ if path.is_file() {+ let size = entry.metadata().map_err(|e| e.to_string())?.len();+ let file_name = path.file_name().unwrap().to_string_lossy().to_string();+ if file_name.contains("input") || file_name.contains("output") {+ total_audio_size = total_audio_size.map(|s| s + size);+ } else {+ total_video_size = total_video_size.map(|s| s + size);+ }}}+ } else {+ warn!("no data dir to calculate disk usage");+ total_audio_size = None;+ total_video_size = None;}+ let videos_size_str = total_video_size.map_or("---".to_string(), |s| readable(s));+ let audios_size_str = total_audio_size.map_or("---".to_string(), |s| readable(s));+let avaiable_space = {let mut sys = System::new();sys.refresh_disks_list();@@ -159,30 +177,29 @@ pub async fn disk_usage(screenpipe_dir: &PathBuf) -> Result<Option<DiskUsage>, Slet disk_usage = DiskUsage {pipes: DiskUsedByPipes {pipes,- total_pipes_size: readable(total_pipes_size),+ total_pipes_size,},media: DiskUsedByMedia {- videos_size: readable(total_video_size),- audios_size: readable(total_audio_size),- total_media_size: readable(total_media_size),+ videos_size: videos_size_str,+ audios_size: audios_size_str,+ total_media_size,},- total_data_size: readable(total_data_size + total_cache_size),- total_cache_size: readable(total_cache_size),+ total_data_size,+ total_cache_size,avaiable_space: readable(avaiable_space),};// Cache the resultlet cached = CachedDiskUsage {- timestamp: chrono::Utc::now().timestamp(),+ timestamp: chrono::Local::now().timestamp(),usage: disk_usage.clone(),};- info!("writing cache file: {}", cache_file.to_string_lossy());+ info!("writing disk usage cache file: {}", cache_file.to_string_lossy());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))}