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
Bump app to v2.0.59
Louis Beaumontac4da50a770d
diff --git a/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsx b/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsxindex 58f50ebd2..93157a074 100644--- a/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsx+++ b/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsx@@ -404,6 +404,7 @@ export function AIPanel({{!isExpanded && (<div className="p-4 space-y-2">+ <ExportButton /><buttonclassName="px-3 py-1 bg-background hover:bg-accent border text-foreground text-xs rounded flex items-center gap-2 transition-colors"onClick={(e) => {@@ -420,7 +421,6 @@ export function AIPanel({{osType === "macos" ? "⌘L" : "Ctrl+L"}</span></button>- <ExportButton /></div>)}</div>diff --git a/screenpipe-app-tauri/components/rewind/timeline/timeline-controls.tsx b/screenpipe-app-tauri/components/rewind/timeline/timeline-controls.tsxindex ac8a0874d..ab5e94687 100644--- a/screenpipe-app-tauri/components/rewind/timeline/timeline-controls.tsx+++ b/screenpipe-app-tauri/components/rewind/timeline/timeline-controls.tsx@@ -13,8 +13,6 @@ import { cn } from "@/lib/utils";import { motion, AnimatePresence } from "framer-motion";import { useMemo } from "react";import { usePlatform } from "@/lib/hooks/use-platform";-import { useTimelineSelection } from "@/lib/hooks/use-timeline-selection";-import { ExportButton } from "@/components/rewind/export-button";interface TimeRange {start: Date;@@ -37,8 +35,6 @@ export function TimelineControls({className,}: TimelineControlsProps) {const { isMac } = usePlatform();- const { selectionRange } = useTimelineSelection();- const hasSelection = selectionRange && selectionRange.frameIds.length > 0;const jumpDay = async (days: number) => {const today = new Date();@@ -131,19 +127,6 @@ export function TimelineControls({</Button></div>- <AnimatePresence>- {hasSelection && (- <motion.div- initial={{ opacity: 0, scale: 0.9 }}- animate={{ opacity: 1, scale: 1 }}- exit={{ opacity: 0, scale: 0.9 }}- transition={{ duration: 0.15 }}- >- <ExportButton />- </motion.div>- )}- </AnimatePresence>-<div className="flex items-center h-10 gap-1.5 bg-card/80 backdrop-blur-sm border border-border rounded-full px-4 shadow-lg"><span className="text-xs text-muted-foreground">{isMac ? "⌘K" : "Ctrl+K"}</span><span className="text-xs text-muted-foreground">search</span>diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 65bbca72b..9af3ed21e 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 = "2.0.57"+version = "2.0.59"description = "24/7 memory for your desktop. 100% local."authors = ["you"]license = ""diff --git a/screenpipe-app-tauri/src-tauri/src/sidecar.rs b/screenpipe-app-tauri/src-tauri/src/sidecar.rsindex dad173d37..821e25725 100644--- a/screenpipe-app-tauri/src-tauri/src/sidecar.rs+++ b/screenpipe-app-tauri/src-tauri/src/sidecar.rs@@ -473,6 +473,10 @@ async fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>if cfg!(windows) {let mut c = app.shell().sidecar("screenpipe").unwrap();++ // Set file descriptor limit to prevent "Too many open files" errors+ c = c.env("SCREENPIPE_FD_LIMIT", "8192");+if use_chinese_mirror {c = c.env("HF_ENDPOINT", "https://hf-mirror.com");}@@ -510,6 +514,10 @@ async fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>let mut c = app.shell().sidecar("screenpipe").unwrap();+ // Set file descriptor limit to prevent "Too many open files" errors+ // This is especially important for WebSocket connections and video processing+ c = c.env("SCREENPIPE_FD_LIMIT", "8192");+if use_chinese_mirror {c = c.env("HF_ENDPOINT", "https://hf-mirror.com");}diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 709d51f31..b2bf35a23 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -48,6 +48,65 @@ use tracing_subscriber::util::SubscriberInitExt;use tracing_subscriber::{fmt, EnvFilter};use tracing_subscriber::{prelude::__tracing_subscriber_SubscriberExt, Layer};+/// Set the file descriptor limit for the process.+/// This helps prevent "Too many open files" errors during heavy WebSocket/video usage.+#[cfg(unix)]+fn set_fd_limit() {+ use nix::libc;+ use std::env;++ // Check if a custom limit was set via environment variable+ let desired_limit: u64 = env::var("SCREENPIPE_FD_LIMIT")+ .ok()+ .and_then(|s| s.parse().ok())+ .unwrap_or(8192); // Default to 8192 if not set++ // Get current limits+ let mut rlim = libc::rlimit {+ rlim_cur: 0,+ rlim_max: 0,+ };++ unsafe {+ if libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) == 0 {+ let current_soft = rlim.rlim_cur;+ let current_hard = rlim.rlim_max;++ // Only increase if current limit is lower than desired+ if current_soft < desired_limit {+ // Set new soft limit (capped by hard limit)+ let new_soft = std::cmp::min(desired_limit, current_hard);+ rlim.rlim_cur = new_soft;++ if libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) == 0 {+ eprintln!(+ "increased file descriptor limit from {} to {} (hard limit: {})",+ current_soft, new_soft, current_hard+ );+ } else {+ eprintln!(+ "warning: failed to increase file descriptor limit (current: {}, requested: {})",+ current_soft, new_soft+ );+ }+ } else {+ eprintln!(+ "file descriptor limit already sufficient: {} (requested: {})",+ current_soft, desired_limit+ );+ }+ } else {+ eprintln!("warning: failed to get current file descriptor limits");+ }+ }+}++#[cfg(not(unix))]+fn set_fd_limit() {+ // On Windows, file handle limits work differently and are generally not an issue+ // No action needed+}+const DISPLAY: &str = r"___________________ ___ ____ ____ (_____ ___@@ -175,6 +234,9 @@ fn setup_logging(local_data_dir: &PathBuf, cli: &Cli) -> anyhow::Result<WorkerGu#[tokio::main]#[tracing::instrument]async fn main() -> anyhow::Result<()> {+ // Set file descriptor limit early, before any resources are allocated+ set_fd_limit();+debug!("starting screenpipe server");let cli = Cli::parse();diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 857b2dd64..835abad56 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -60,10 +60,17 @@ use std::{net::SocketAddr,num::NonZeroUsize,path::PathBuf,- sync::{atomic::Ordering, Arc},+ sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+ },time::{Duration, Instant},};+/// Maximum number of concurrent WebSocket connections allowed.+/// This prevents file descriptor exhaustion from too many open connections.+const MAX_WEBSOCKET_CONNECTIONS: usize = 100;+use lru::LruCache;use tokio::{@@ -98,6 +105,8 @@ pub struct AppState {pub frame_cache: Option<Arc<FrameCache>>,pub frame_image_cache: Option<Arc<Mutex<FrameImageCache>>>,pub element_cache: Arc<Mutex<Option<(Vec<UIElement>, Instant, String)>>>,+ /// Counter for active WebSocket connections to prevent resource exhaustion+ pub ws_connection_count: Arc<AtomicUsize>,}// Update the SearchQuery struct@@ -1192,6 +1201,7 @@ impl SCServer {None},element_cache: Arc::new(Mutex::new(None)),+ ws_connection_count: Arc::new(AtomicUsize::new(0)),});let cors = CorsLayer::new()@@ -2212,12 +2222,69 @@ pub struct VisionDeviceControlRequest {// }))// }+/// Guard that decrements the WebSocket connection counter when dropped.+/// This ensures the counter is always decremented, even on panics or early returns.+struct WsConnectionGuard {+ counter: Arc<AtomicUsize>,+}++impl Drop for WsConnectionGuard {+ fn drop(&mut self) {+ let prev = self.counter.fetch_sub(1, Ordering::SeqCst);+ debug!("WebSocket connection closed, count: {} -> {}", prev, prev - 1);+ }+}++/// Try to acquire a WebSocket connection slot.+/// Returns Some(guard) if successful, None if the limit is reached.+fn try_acquire_ws_connection(counter: &Arc<AtomicUsize>) -> Option<WsConnectionGuard> {+ loop {+ let current = counter.load(Ordering::SeqCst);+ if current >= MAX_WEBSOCKET_CONNECTIONS {+ error!(+ "WebSocket connection limit reached ({}/{}), rejecting new connection",+ current, MAX_WEBSOCKET_CONNECTIONS+ );+ return None;+ }++ // Try to atomically increment the counter+ match counter.compare_exchange(current, current + 1, Ordering::SeqCst, Ordering::SeqCst) {+ Ok(_) => {+ debug!(+ "WebSocket connection acquired, count: {} -> {}",+ current,+ current + 1+ );+ return Some(WsConnectionGuard {+ counter: counter.clone(),+ });+ }+ Err(_) => {+ // Another thread changed the counter, retry+ continue;+ }+ }+ }+}+// websocket events handler-async fn ws_events_handler(ws: WebSocketUpgrade, query: Query<EventsQuery>) -> Response {- ws.on_upgrade(|socket| handle_socket(socket, query))+async fn ws_events_handler(+ ws: WebSocketUpgrade,+ State(state): State<Arc<AppState>>,+ query: Query<EventsQuery>,+) -> Response {+ // Check connection limit before upgrading+ match try_acquire_ws_connection(&state.ws_connection_count) {+ Some(guard) => ws.on_upgrade(|socket| handle_socket(socket, query, guard)),+ None => Response::builder()+ .status(StatusCode::SERVICE_UNAVAILABLE)+ .body(Body::from("Too many WebSocket connections"))+ .unwrap(),+ }}-async fn handle_socket(socket: WebSocket, query: Query<EventsQuery>) {+async fn handle_socket(socket: WebSocket, query: Query<EventsQuery>, _guard: WsConnectionGuard) {let (mut sender, mut receiver) = socket.split();let incoming = tokio::spawn(async move {@@ -2268,13 +2335,21 @@ async fn handle_socket(socket: WebSocket, query: Query<EventsQuery>) {}debug!("WebSocket connection closed");+ // _guard is dropped here, decrementing the connection counter}async fn ws_health_handler(ws: WebSocketUpgrade, State(state): State<Arc<AppState>>) -> Response {- ws.on_upgrade(move |socket| handle_health_socket(socket, state))+ // Check connection limit before upgrading+ match try_acquire_ws_connection(&state.ws_connection_count) {+ Some(guard) => ws.on_upgrade(move |socket| handle_health_socket(socket, state, guard)),+ None => Response::builder()+ .status(StatusCode::SERVICE_UNAVAILABLE)+ .body(Body::from("Too many WebSocket connections"))+ .unwrap(),+ }}-async fn handle_health_socket(mut socket: WebSocket, state: Arc<AppState>) {+async fn handle_health_socket(mut socket: WebSocket, state: Arc<AppState>, _guard: WsConnectionGuard) {let mut interval = tokio::time::interval(Duration::from_secs(5));loop {@@ -2296,6 +2371,7 @@ async fn handle_health_socket(mut socket: WebSocket, state: Arc<AppState>) {}debug!("WebSocket connection closed gracefully");+ // _guard is dropped here, decrementing the connection counter}#[derive(Debug, Deserialize)]@@ -2423,7 +2499,7 @@ pub async fn handle_video_export_ws(ws: WebSocketUpgrade,State(state): State<Arc<AppState>>,Query(payload): Query<VideoExportRequest>,-) -> impl IntoResponse {+) -> Response {if payload.frame_ids.is_empty() {return (StatusCode::BAD_REQUEST,@@ -2432,13 +2508,25 @@ pub async fn handle_video_export_ws(.into_response();}- ws.on_upgrade(move |socket| async move { handle_video_export(socket, state, payload).await })+ // Check connection limit before upgrading+ match try_acquire_ws_connection(&state.ws_connection_count) {+ Some(guard) => ws+ .on_upgrade(move |socket| async move {+ handle_video_export(socket, state, payload, guard).await+ })+ .into_response(),+ None => Response::builder()+ .status(StatusCode::SERVICE_UNAVAILABLE)+ .body(Body::from("Too many WebSocket connections"))+ .unwrap(),+ }}async fn handle_video_export(mut socket: WebSocket,state: Arc<AppState>,payload: VideoExportRequest,+ _guard: WsConnectionGuard,) {let temp_dir = match tempfile::tempdir() {Ok(dir) => dir,@@ -3095,7 +3183,7 @@ fn create_time_series_frame(chunk: FrameData) -> TimeSeriesFrame {}}-async fn handle_stream_frames_socket(socket: WebSocket, state: Arc<AppState>) {+async fn handle_stream_frames_socket(socket: WebSocket, state: Arc<AppState>, _guard: WsConnectionGuard) {let (mut sender, mut receiver) = socket.split();let (frame_tx, frame_rx) = tokio::sync::mpsc::channel(100);let db = state.db.clone();@@ -3451,8 +3539,17 @@ async fn send_batch(async fn stream_frames_handler(ws: WebSocketUpgrade,State(state): State<Arc<AppState>>,-) -> impl IntoResponse {- ws.on_upgrade(move |socket| handle_stream_frames_socket(socket, state))+) -> Response {+ // Check connection limit before upgrading+ match try_acquire_ws_connection(&state.ws_connection_count) {+ Some(guard) => ws+ .on_upgrade(move |socket| handle_stream_frames_socket(socket, state, guard))+ .into_response(),+ None => Response::builder()+ .status(StatusCode::SERVICE_UNAVAILABLE)+ .body(Body::from("Too many WebSocket connections"))+ .unwrap(),+ }}#[oasgen]