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

refactor: make CaptureSession::stop() self-contained, fix lock ordering

Louis Beaumont3ebaacd5228b
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index 701ab02c5..405da4707 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -9727,7 +9727,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.3.74"
+version = "2.3.75"
dependencies = [
"anyhow",
"arboard",
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/capture_session.rs b/apps/screenpipe-app-tauri/src-tauri/src/capture_session.rs
index 9b5d9f3d8..8cf5c23c4 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/capture_session.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/capture_session.rs
@@ -25,9 +25,14 @@ use crate::server_core::ServerCore;
///
/// Dropping this without calling [`CaptureSession::stop`] will leak tasks.
/// Always use `stop()` for clean shutdown.
+///
+/// Holds its own `Arc<AudioManager>` so `stop()` is self-contained —
+/// callers don't need to reach into `ServerCore` to stop capture.
pub struct CaptureSession {
shutdown_tx: broadcast::Sender<()>,
ui_recorder_handle: Option<screenpipe_engine::UiRecorderHandle>,
+ audio_manager: Arc<screenpipe_audio::audio_manager::AudioManager>,
+ audio_disabled: bool,
}
impl CaptureSession {
@@ -186,11 +191,17 @@ impl CaptureSession {
Ok(Self {
shutdown_tx,
ui_recorder_handle,
+ audio_manager: server.audio_manager.clone(),
+ audio_disabled: config.disable_audio,
})
}
/// Stop all capture pipelines. The server stays alive.
- pub async fn stop(mut self, audio_manager: &Arc<screenpipe_audio::audio_manager::AudioManager>) {
+ ///
+ /// This is self-contained — no external references needed.
+ /// Audio is stopped (not shutdown), keeping the `Arc<AudioManager>` valid
+ /// for the next capture session or for HTTP API queries.
+ pub async fn stop(mut self) {
info!("Stopping capture session");
// Signal UI recorder to stop
@@ -201,9 +212,11 @@ impl CaptureSession {
// Broadcast shutdown to VisionManager, meeting watcher, schedule monitor, compaction
let _ = self.shutdown_tx.send(());
- // Stop audio recording (but don't shutdown — keep the Arc valid)
- if let Err(e) = audio_manager.stop().await {
- warn!("Error stopping audio manager: {:?}", e);
+ // Stop audio recording (but don't shutdown — keep the Arc valid for queries)
+ if !self.audio_disabled {
+ if let Err(e) = self.audio_manager.stop().await {
+ warn!("Error stopping audio manager: {:?}", e);
+ }
}
// Wait for UI recorder tasks to finish
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 695e95bcc..b65c29966 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -1807,11 +1807,9 @@ async fn main() {
if let Some(recording_state) =
app_handle_shutdown.try_state::<recording::RecordingState>()
{
- // Stop capture first, then server
+ // Stop capture first (self-contained), then server
if let Some(session) = recording_state.capture.lock().await.take() {
- if let Some(ref server) = *recording_state.server.lock().await {
- session.stop(&server.audio_manager).await;
- }
+ session.stop().await;
}
if let Some(server) = recording_state.server.lock().await.take() {
server.shutdown().await;
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
index bfeef940b..688af5922 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
@@ -16,18 +16,31 @@ use crate::store::SettingsStore;
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
+use screenpipe_engine::RecordingConfig;
use tauri::{Emitter, State};
use tokio::sync::Mutex;
use tracing::{debug, error, info, warn};
+/// Build a `RecordingConfig` from the current settings store.
+fn build_config(app: &tauri::AppHandle) -> Result<RecordingConfig, String> {
+ let store = SettingsStore::get(app).ok().flatten().unwrap_or_default();
+ let (data_dir, _) = config::resolve_data_dir(&store.data_dir);
+ Ok(store.to_recording_config(data_dir))
+}
+
/// Minimum seconds between consecutive stop→spawn cycles.
const RESTART_COOLDOWN_SECS: u64 = 30;
/// Two-phase state: server (long-lived) + capture (togglable).
+///
+/// **Lock ordering**: `capture` may be locked independently (it's self-contained).
+/// When both locks are needed (e.g. `start_capture`), always lock `capture` first,
+/// then `server`. Never hold `server` while waiting on `capture`.
pub struct RecordingState {
/// Long-lived server core (DB, HTTP, pipes). None until first start.
pub server: Arc<Mutex<Option<ServerCore>>>,
/// Current capture session. None when recording is stopped/paused.
+ /// Self-contained — `CaptureSession::stop()` needs no external references.
pub capture: Arc<Mutex<Option<CaptureSession>>>,
/// True while a server start is in progress (prevents race between main.rs boot and frontend)
pub is_starting: Arc<AtomicBool>,
@@ -142,13 +155,7 @@ pub async fn stop_capture(
let mut capture_guard = state.capture.lock().await;
if let Some(session) = capture_guard.take() {
- let server_guard = state.server.lock().await;
- if let Some(ref server) = *server_guard {
- session.stop(&server.audio_manager).await;
- } else {
- // Server gone — just drop the session
- drop(session);
- }
+ session.stop().await;
info!("Capture session stopped");
} else {
debug!("No capture session running");
@@ -179,10 +186,7 @@ pub async fn start_capture(
.as_ref()
.ok_or_else(|| "Server not running — cannot start capture".to_string())?;
- let store = SettingsStore::get(&app).ok().flatten().unwrap_or_default();
- let (data_dir, _) = config::resolve_data_dir(&store.data_dir);
- let config = store.to_recording_config(data_dir);
-
+ let config = build_config(&app)?;
let session = CaptureSession::start(server, &config).await?;
drop(server_guard);
@@ -209,12 +213,7 @@ pub async fn stop_screenpipe(
let mut capture_guard = state.capture.lock().await;
if let Some(session) = capture_guard.take() {
- let server_guard = state.server.lock().await;
- if let Some(ref server) = *server_guard {
- session.stop(&server.audio_manager).await;
- } else {
- drop(session);
- }
+ session.stop().await;
info!("Capture stopped");
} else {
debug!("No capture session to stop");
@@ -347,15 +346,9 @@ pub async fn spawn_screenpipe(
}
// --- Full start: server + capture ---
- // Stop any existing capture first
- {
- let mut capture_guard = state.capture.lock().await;
- if let Some(session) = capture_guard.take() {
- let server_guard = state.server.lock().await;
- if let Some(ref server) = *server_guard {
- session.stop(&server.audio_manager).await;
- }
- }
+ // Stop any existing capture first (self-contained, no server lock needed)
+ if let Some(session) = state.capture.lock().await.take() {
+ session.stop().await;
}
// Shutdown existing server if any
{
@@ -554,10 +547,7 @@ async fn start_capture_internal(
.as_ref()
.ok_or_else(|| "Server not running".to_string())?;
- let store = SettingsStore::get(app).ok().flatten().unwrap_or_default();
- let (data_dir, _) = config::resolve_data_dir(&store.data_dir);
- let config = store.to_recording_config(data_dir);
-
+ let config = build_config(app)?;
let session = CaptureSession::start(server, &config).await?;
drop(server_guard);
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
index c7b07ef40..57c69afcd 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
@@ -843,11 +843,9 @@ fn handle_menu_event(app_handle: &AppHandle, event: tauri::menu::MenuEvent) {
tauri::async_runtime::spawn(async move {
info!("Stopping screenpipe recording before quit...");
if let Some(recording_state) = app_handle_clone.try_state::<RecordingState>() {
- // Stop capture first
+ // Stop capture first (self-contained)
if let Some(session) = recording_state.capture.lock().await.take() {
- if let Some(ref server) = *recording_state.server.lock().await {
- session.stop(&server.audio_manager).await;
- }
+ session.stop().await;
}
// Then shutdown server
if let Some(server) = recording_state.server.lock().await.take() {