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: graceful shutdown — stop UI recorder, drain before exit
Louis Beaumonte569f9fe6a0e
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rsindex 937b3495e..91a23ae48 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs@@ -29,12 +29,17 @@ use tracing::{error, info, warn};#[allow(dead_code)]pub struct EmbeddedServerHandle {shutdown_tx: broadcast::Sender<()>,+ ui_recorder_handle: Option<screenpipe_server::UiRecorderHandle>,}#[allow(dead_code)]impl EmbeddedServerHandle {pub fn shutdown(&self) {info!("Shutting down embedded screenpipe server");+ // Signal the UI recorder to stop its tree walker and event loops+ if let Some(ref ui_handle) = self.ui_recorder_handle {+ ui_handle.stop();+ }let _ = self.shutdown_tx.send(());}}@@ -262,22 +267,22 @@ pub async fn start_embedded_server(// Start UI event recording (database recording of accessibility events)let ui_enabled = config.enable_input_capture || config.enable_accessibility;info!("UI events setting: enable_input_capture={}, enable_accessibility={}", config.enable_input_capture, config.enable_accessibility);- if ui_enabled {+ let ui_recorder_handle = if ui_enabled {let ui_config = config.to_ui_recorder_config();let db_clone = db.clone();- tokio::spawn(async move {- match start_ui_recording(db_clone, ui_config, capture_trigger_tx).await {- Ok(handle) => {- info!("UI event recording started successfully");- // Keep the handle alive - don't drop it or UI recording stops- std::mem::forget(handle);- }- Err(e) => {- error!("Failed to start UI event recording: {}", e);- }+ match start_ui_recording(db_clone, ui_config, capture_trigger_tx).await {+ Ok(handle) => {+ info!("UI event recording started successfully");+ Some(handle)}- });- }+ Err(e) => {+ error!("Failed to start UI event recording: {}", e);+ None+ }+ }+ } else {+ None+ };// Start meeting watcher (standalone accessibility listener for smart mode)// Independent of enable_input_capture/enable_accessibility toggles — only needs accessibility permission@@ -399,5 +404,5 @@ pub async fn start_embedded_server(info!("Embedded screenpipe server started successfully");- Ok(EmbeddedServerHandle { shutdown_tx })+ Ok(EmbeddedServerHandle { shutdown_tx, ui_recorder_handle })}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs b/apps/screenpipe-app-tauri/src-tauri/src/tray.rsindex 1b88dfc6b..f8ab7255a 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs@@ -541,6 +541,9 @@ fn handle_menu_event(app_handle: &AppHandle, event: tauri::menu::MenuEvent) {let mut handle_guard = recording_state.handle.lock().await;if let Some(handle) = handle_guard.take() {handle.shutdown();+ // Give the tree walker and other tasks time to notice the stop+ // signal and exit cleanly before we tear down the runtime.+ tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;info!("Screenpipe recording stopped successfully");} else {debug!("No recording running to stop");diff --git a/crates/screenpipe-server/src/ui_recorder.rs b/crates/screenpipe-server/src/ui_recorder.rsindex 68749495a..185a9ae17 100644--- a/crates/screenpipe-server/src/ui_recorder.rs+++ b/crates/screenpipe-server/src/ui_recorder.rs@@ -583,8 +583,6 @@ fn run_tree_walker(}if cache.should_store(&snap) {- // Check stop flag before blocking on the runtime — during shutdown- // the tokio context may be tearing down, causing a panic in block_on.if stop.load(std::sync::atomic::Ordering::Relaxed) {debug!("Stop flag set, skipping DB insert for accessibility text");break;@@ -592,19 +590,21 @@ fn run_tree_walker(metrics.total_text_chars += snap.text_content.len() as u64;- // Wrap block_on in catch_unwind — during shutdown the tokio- // runtime may be tearing down, causing block_on to panic.- // Losing one DB write on shutdown is harmless.- let db_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- rt_handle.block_on(db.insert_accessibility_text(- &snap.app_name,- &snap.window_name,- &snap.text_content,- snap.browser_url.as_deref(),- ))- }));-- match db_result {+ // Spawn the DB write on the runtime and wait via std channel.+ // Unlike block_on, this won't panic during runtime shutdown —+ // the spawned task is silently cancelled and the channel closes.+ let (result_tx, result_rx) = std::sync::mpsc::sync_channel(1);+ let db_c = db.clone();+ let app = snap.app_name.clone();+ let win = snap.window_name.clone();+ let text = snap.text_content.clone();+ let url = snap.browser_url.clone();+ rt_handle.spawn(async move {+ let r = db_c.insert_accessibility_text(&app, &win, &text, url.as_deref()).await;+ let _ = result_tx.send(r);+ });++ match result_rx.recv_timeout(std::time::Duration::from_secs(5)) {Ok(Ok(_id)) => {debug!("Stored accessibility text: app={}, window={}, len={}, nodes={}, walk={}ms",@@ -622,8 +622,13 @@ fn run_tree_walker(metrics.walks_error += 1;}Err(_) => {- debug!("Runtime shutting down, stopping tree-walker DB writes");- break;+ // Channel closed (runtime shutdown) or timed out+ if stop.load(Ordering::Relaxed) {+ debug!("Runtime shutting down, stopping tree-walker DB writes");+ break;+ }+ debug!("DB insert timed out");+ metrics.walks_error += 1;}}} else {