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

fix: retain database shutdown across recording restart timeouts (#7173)

Ezra Ellette63cce9d594fa
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/db_relaunch.rs b/apps/screenpipe-app-tauri/src-tauri/src/db_relaunch.rs
index aefe0ad42..9bb4abb85 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/db_relaunch.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/db_relaunch.rs
@@ -130,12 +130,15 @@ pub async fn note_respawn_failure(app: &tauri::AppHandle, err: &str) {
DB_BOOT_FAILURES.store(0, Ordering::SeqCst);
return;
}
- crate::health::set_boot_error(
- "database unavailable; recording interrupted — retrying automatically",
- );
+ crate::health::set_boot_error(&format!(
+ "database unavailable; recording interrupted — retrying automatically: {err}",
+ ));
let n = DB_BOOT_FAILURES
.fetch_add(1, Ordering::SeqCst)
.saturating_add(1);
+ if n == 1 {
+ crate::recording::recovery_log::append(&active_data_dir(), "database_reopen_failed", err);
+ }
warn!(
"engine respawn failed at DB init ({}/{} before availability notification): {}",
n, DB_BOOT_FAILURES_BEFORE_NOTICE, err
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rs b/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rs
index 7b5eb158a..7009a4951 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rs
@@ -63,7 +63,7 @@ pub async fn collect_redacted(app: &AppHandle) -> Result<String, String> {
///
/// Enterprise's mandatory collector uses this entry point so both managed and
/// opted-in builds share one filesystem, size, timeout, and redaction policy.
-#[cfg(feature = "enterprise-build")]
+#[cfg(any(test, feature = "enterprise-build"))]
pub async fn collect_redacted_from_dirs(dirs: &[std::path::PathBuf]) -> Result<String, String> {
let files = crate::log_files::collect_log_files(dirs).await;
redact_files(&owned_log_files(files)).await
@@ -78,6 +78,7 @@ fn owned_log_files(files: Vec<LogFile>) -> Vec<LogFile> {
fn is_screenpipe_owned_log_name(name: &str) -> bool {
crate::log_files::is_panic_log(name)
+ || name == crate::recording::recovery_log::LOG_NAME
|| matches!(
name,
"screenpipe.log"
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs b/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs
index 3050521d2..956e7231a 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs
@@ -94,8 +94,8 @@ pub async fn get_active_data_dir(app: AppHandle) -> Result<String, String> {
}
/// Gather `.log` files and the rotated panic log from the given directories.
-/// Panic logs come first so report limits do not displace crash evidence after
-/// a restart; within each group, files are newest first.
+/// Panic and recording-recovery logs come first so report limits do not
+/// displace failure evidence after a restart; each group is newest first.
///
/// Resilience is the whole point of this helper: a directory that can't be read
/// (missing, unmounted, permission denied — all common on Windows with a custom
@@ -119,7 +119,9 @@ pub(crate) async fn collect_log_files(dirs: &[PathBuf]) -> Vec<LogFile> {
!path
.file_name()
.and_then(|name| name.to_str())
- .is_some_and(is_panic_log),
+ .is_some_and(|name| {
+ is_panic_log(name) || name == crate::recording::recovery_log::LOG_NAME
+ }),
std::cmp::Reverse(
metadata
.modified()
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index b7b424fdc..084196532 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -906,6 +906,7 @@ async fn main() {
let recording_state = RecordingState {
server_lifecycle: Arc::new(tokio::sync::Mutex::new(())),
server: Arc::new(tokio::sync::Mutex::new(None)),
+ server_shutdown: Default::default(),
capture: Arc::new(tokio::sync::Mutex::new(None)),
is_starting: Arc::new(AtomicBool::new(false)),
is_starting_capture: Arc::new(AtomicBool::new(false)),
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
index 279e022bc..9c29317d1 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
@@ -297,9 +297,12 @@ const RESTART_COOLDOWN_SECS: u64 = 30;
const CAPTURE_RESTART_MEETING_REATTACH_WINDOW: Duration = Duration::from_secs(120);
mod db_wedge;
+pub(crate) mod recovery_log;
+mod server_shutdown;
pub use db_wedge::{
make_database_restart_hook, new_db_wedge_breaker, DbWedgeBreaker, DbWedgeState,
};
+pub(crate) use server_shutdown::ServerShutdown;
#[derive(Clone, Debug)]
pub(crate) struct InterruptedMeeting {
@@ -323,6 +326,7 @@ pub struct RecordingState {
pub server_lifecycle: Arc<Mutex<()>>,
/// Long-lived server core (DB, HTTP, pipes). None until first start.
pub server: Arc<Mutex<Option<ServerCore>>>,
+ pub(crate) server_shutdown: ServerShutdown,
/// Current capture session. None when recording is stopped/paused.
/// Self-contained — `CaptureSession::stop()` needs no external references.
pub capture: Arc<Mutex<Option<CaptureSession>>>,
@@ -887,7 +891,13 @@ pub(crate) async fn stop_screenpipe_inner(state: &RecordingState) -> Result<(),
// Shut down the server so the next spawn_screenpipe does a full restart
// with fresh settings (auth key, port, etc.). Without this, spawn_screenpipe
// sees the server as healthy and skips the restart entirely.
- shutdown_server(&state.server, ServerCore::shutdown).await;
+ shutdown_server(
+ &state.server,
+ &state.server_shutdown,
+ &crate::db_relaunch::active_data_dir(),
+ ServerCore::shutdown,
+ )
+ .await?;
info!("Server stopped");
// Reset flags so the next spawn_screenpipe takes the full-start path
@@ -898,19 +908,23 @@ pub(crate) async fn stop_screenpipe_inner(state: &RecordingState) -> Result<(),
Ok(())
}
-async fn shutdown_server<T, F, Fut>(slot: &Mutex<Option<T>>, shutdown: F)
+async fn shutdown_server<T, F, Fut>(
+ slot: &Mutex<Option<T>>,
+ pending: &ServerShutdown,
+ data_dir: &std::path::Path,
+ shutdown: F,
+) -> Result<(), String>
where
+ T: Send + 'static,
F: FnOnce(T) -> Fut,
- Fut: std::future::Future<Output = ()>,
+ Fut: std::future::Future<Output = ()> + Send + 'static,
{
// Full stop/start callers retain server_lifecycle while cleanup runs. Only
// the slot lock must be released: readers can need it before returning a
// connection or storage pin that database close is waiting to drain.
// Keep this separate from `if let`, whose temporary guard spans the body.
let server = slot.lock().await.take();
- if let Some(server) = server {
- shutdown(server).await;
- }
+ pending.finish(server, data_dir, shutdown).await
}
/// Hard ceiling on capture/server teardown that runs *immediately before* the
@@ -1254,6 +1268,22 @@ async fn spawn_screenpipe_after_migration(
}
}
+ // A timed-out stop can leave the old core draining outside this caller.
+ // Join it before probing the port (which may still be ours) or opening DB.
+ if let Err(error) = state
+ .server_shutdown
+ .finish(
+ None::<ServerCore>,
+ &crate::db_relaunch::active_data_dir(),
+ ServerCore::shutdown,
+ )
+ .await
+ {
+ state.is_starting.store(false, Ordering::SeqCst);
+ state.is_starting_capture.store(false, Ordering::SeqCst);
+ return Err(error);
+ }
+
// --- Check existing server ---
{
let server_guard = state.server.lock().await;
@@ -1312,7 +1342,18 @@ async fn spawn_screenpipe_after_migration(
session.stop().await;
}
// Shutdown existing server if any
- shutdown_server(&state.server, ServerCore::shutdown).await;
+ if let Err(error) = shutdown_server(
+ &state.server,
+ &state.server_shutdown,
+ &crate::db_relaunch::active_data_dir(),
+ ServerCore::shutdown,
+ )
+ .await
+ {
+ state.is_starting.store(false, Ordering::SeqCst);
+ state.is_starting_capture.store(false, Ordering::SeqCst);
+ return Err(error);
+ }
// The health probe above ruled out a healthy Screenpipe owner. Reclaim an
// unhealthy or unrelated owner gracefully first, with a forced fallback.
@@ -1632,6 +1673,15 @@ async fn spawn_screenpipe_after_migration(
Ok(Ok(())) => {
info!("Screenpipe started successfully");
crate::db_relaunch::reset_db_boot_failures();
+ recovery_log::append(
+ &crate::db_relaunch::active_data_dir(),
+ "engine_started",
+ if state.capture_intended() {
+ "recording requested; server and capture startup completed"
+ } else {
+ "server started; recording deliberately stopped"
+ },
+ );
state.is_starting.store(false, Ordering::SeqCst);
state.is_starting_capture.store(false, Ordering::SeqCst);
// A meeting that was in progress when this restart began is still
@@ -1718,7 +1768,7 @@ mod shutdown_storage_tests {
use screenpipe_db::DatabaseManager;
use tokio::sync::oneshot;
- async fn shutdown_with_reader(hybrid: bool) {
+ async fn shutdown_with_reader(hybrid: bool, cancel_waiter: bool) {
let root = tempfile::tempdir().unwrap();
let data_dir = root.path().to_path_buf();
let (runtime_lifetime, runtime_finished) = oneshot::channel::<()>();
@@ -1762,12 +1812,21 @@ mod shutdown_storage_tests {
let connection = db.pool.acquire().await.unwrap();
let slot = Arc::new(Mutex::new(Some((Arc::clone(&db), runtime_lifetime))));
let closing_slot = Arc::clone(&slot);
- let closing = tokio::spawn(async move {
- shutdown_server(&closing_slot, |(db, runtime_lifetime)| async move {
- db.close().await;
- drop(runtime_lifetime);
- })
- .await;
+ let pending = Arc::new(ServerShutdown::default());
+ let pending_for_close = Arc::clone(&pending);
+ let close_root = root.path().to_path_buf();
+ let mut closing = tokio::spawn(async move {
+ shutdown_server(
+ &closing_slot,
+ &pending_for_close,
+ &close_root,
+ |(db, runtime_lifetime)| async move {
+ db.close().await;
+ drop(runtime_lifetime);
+ },
+ )
+ .await
+ .unwrap();
});
db.pool.close_event().await;
assert!(
@@ -1775,6 +1834,37 @@ mod shutdown_storage_tests {
"shutdown must drain admitted readers"
);
+ if cancel_waiter {
+ // The health overlay bounds stop_screenpipe with a timeout. Dropping
+ // that caller must neither abandon close nor release the old lease.
+ closing.abort();
+ assert!(closing.await.unwrap_err().is_cancelled());
+ let reopen = DatabaseManager::new(
+ root.path().join("db.sqlite").to_str().unwrap(),
+ Default::default(),
+ )
+ .await;
+ assert!(reopen
+ .err()
+ .unwrap()
+ .to_string()
+ .contains("already owns a live DatabaseManager"));
+ let closing_slot = Arc::clone(&slot);
+ let close_root = root.path().to_path_buf();
+ closing = tokio::spawn(async move {
+ shutdown_server(
+ &closing_slot,
+ &pending,
+ &close_root,
+ |(_db, _lifetime)| async {
+ panic!("the next start must join the original shutdown, not replace it");
+ },
+ )
+ .await
+ .unwrap();
+ });
+ }
+
// A reader on the server runtime needs the state slot before releasing
// its connection/export pin. Shutdown must neither lock it out nor tear
// down its runtime merely because the core was taken from the slot.
@@ -1839,16 +1929,48 @@ mod shutdown_storage_tests {
Some("recording after migration")
);
reopened.close().await;
+
+ if cancel_waiter {
+ recovery_log::append(
+ root.path(),
+ "engine_started",
+ "old and new recording payloads verified after database reopen",
+ );
+ // Simulate app-log rotation/restart and enough noisy logs to fill
+ // the normal five-file support limit. Lifecycle evidence persists.
+ for day in 1..=7 {
+ std::fs::write(
+ root.path()
+ .join(format!("screenpipe-app.2026-09-{day:02}.log")),
+ "app restarted\npassword=hunter2\n",
+ )
+ .unwrap();
+ }
+ let report =
+ crate::diagnostic_logs::collect_redacted_from_dirs(&[root.path().to_path_buf()])
+ .await
+ .unwrap();
+ assert!(report.contains("shutdown_wait_cancelled"));
+ assert!(report.contains("cleanup continues and database reopen must wait"));
+ assert!(report.contains("shutdown_completed"));
+ assert!(report.contains("engine_started"));
+ assert!(!report.contains("hunter2"));
+ }
}
#[tokio::test]
async fn legacy_reader_drains_then_migration_completes_and_recording_can_resume() {
- shutdown_with_reader(false).await;
+ shutdown_with_reader(false, false).await;
}
#[tokio::test]
async fn hybrid_reader_releases_storage_pin_before_runtime_exits() {
- shutdown_with_reader(true).await;
+ shutdown_with_reader(true, false).await;
+ }
+
+ #[tokio::test]
+ async fn cancelled_shutdown_drains_old_owner_then_reopens_migrated_recordings() {
+ shutdown_with_reader(true, true).await;
}
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording/db_wedge.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording/db_wedge.rs
index 1ef140afe..0b85ce099 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/recording/db_wedge.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording/db_wedge.rs
@@ -238,10 +238,14 @@ async fn recover_from_db_wedge(
if let Some(session) = capture {
session.stop().await;
}
- let shutdown_outcome = bounded_teardown(DB_WEDGE_SERVER_SHUTDOWN_TIMEOUT, async {
- server.shutdown().await;
- Ok(())
- })
+ let shutdown_outcome = bounded_teardown(
+ DB_WEDGE_SERVER_SHUTDOWN_TIMEOUT,
+ recording_state.server_shutdown.finish(
+ Some(server),
+ &crate::db_relaunch::active_data_dir(),
+ super::ServerCore::shutdown,
+ ),
+ )
.await;
match db_wedge_shutdown_action(shutdown_outcome, hard_faulted) {
DbWedgeShutdownAction::RespawnInProcess => {}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording/recovery_log.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording/recovery_log.rs
new file mode 100644
index 000000000..8eca93f91
--- /dev/null
+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording/recovery_log.rs
@@ -0,0 +1,54 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+//! Bounded lifecycle evidence kept separately from noisy rolling application
+//! logs. Included in the normal support bundle and its on-device redaction.
+
+use std::io::{Read, Seek, SeekFrom, Write};
+use std::path::Path;
+use std::sync::Mutex;
+
+pub(crate) const LOG_NAME: &str = "recording-recovery.log";
+const MAX_BYTES: u64 = 16 * 1024;
+static WRITER: Mutex<()> = Mutex::new(());
+
+pub(crate) fn append(root: &Path, event: &str, detail: &str) {
+ let _guard = WRITER.lock().unwrap_or_else(|error| error.into_inner());
+ let result = (|| -> std::io::Result<()> {
+ let path = root.join(LOG_NAME);
+ // A caller cannot redirect diagnostic collection through a symlink.
+ if std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) {
+ return Ok(());
+ }
+ let mut file = std::fs::OpenOptions::new()
+ .create(true)
+ .read(true)
+ .write(true)
+ .truncate(false)
+ .open(&path)?;
+ if file.metadata()?.len() > MAX_BYTES {
+ file.seek(SeekFrom::End(-(MAX_BYTES as i64 / 2)))?;
+ let mut tail = Vec::new();
+ file.read_to_end(&mut tail)?;
+ let start = tail
+ .iter()
+ .position(|byte| *byte == b'\n')
+ .map_or(tail.len(), |i| i + 1);
+ file.set_len(0)?;
+ file.rewind()?;
+ file.write_all(&tail[start..])?;
+ }
+ file.seek(SeekFrom::End(0))?;
+ let detail: String = detail.chars().take(2048).collect();
+ writeln!(
+ file,
+ "{} {event}: {}",
+ chrono::Utc::now().to_rfc3339(),
+ detail.replace(['\r', '\n'], " ")
+ )?;
+ file.flush()
+ })();
+ if let Err(error) = result {
+ tracing::warn!(%error, "could not persist recording recovery diagnostic");
+ }
+}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording/server_shutdown.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording/server_shutdown.rs
new file mode 100644
index 000000000..ab9d64ec2
--- /dev/null
+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording/server_shutdown.rs
@@ -0,0 +1,84 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+use std::future::Future;
+use std::path::Path;
+use tokio::sync::Mutex;
+
+/// A caller's timeout must not drop an engine whose SQLite owners are still
+/// draining. Keep the task in app state and join it before admitting a new core.
+#[derive(Default)]
+pub(crate) struct ServerShutdown {
+ pending: Mutex<Option<tauri::async_runtime::JoinHandle<()>>>,
+}
+
+impl ServerShutdown {
+ pub(super) async fn finish<T, F, Fut>(
+ &self,
+ server: Option<T>,
+ data_dir: &Path,
+ shutdown: F,
+ ) -> Result<(), String>
+ where
+ T: Send + 'static,
+ F: FnOnce(T) -> Fut,
+ Fut: Future<Output = ()> + Send + 'static,
+ {
+ let mut pending = self.pending.lock().await;
+ if let Some(server) = server {
+ assert!(
+ pending.is_none(),
+ "server generations must not overlap shutdown"
+ );
+ // The dedicated engine runtime stays alive via ServerCore's sender.
+ // This task must belong to the process runtime, which outlives it.
+ let work = shutdown(server);
+ let root = data_dir.to_path_buf();
+ super::recovery_log::append(
+ &root,
+ "shutdown_started",
+ "draining old engine before reopening database",
+ );
+ *pending = Some(tauri::async_runtime::spawn(async move {
+ work.await;
+ super::recovery_log::append(
+ &root,
+ "shutdown_completed",
+ "old database owners released",
+ );
+ }));
+ }
+ if let Some(task) = pending.as_mut() {
+ let mut waiting = ShutdownWait {
+ data_dir,
+ completed: false,
+ };
+ let result = task.await;
+ waiting.completed = true;
+ *pending = None;
+ result.map_err(|error| {
+ let error = format!("server shutdown task failed: {error}");
+ super::recovery_log::append(data_dir, "shutdown_failed", &error);
+ error
+ })?;
+ }
+ Ok(())
+ }
+}
+
+struct ShutdownWait<'a> {
+ data_dir: &'a Path,
+ completed: bool,
+}
+
+impl Drop for ShutdownWait<'_> {
+ fn drop(&mut self) {
+ if !self.completed {
+ super::recovery_log::append(
+ self.data_dir,
+ "shutdown_wait_cancelled",
+ "caller timed out or cancelled; cleanup continues and database reopen must wait",
+ );
+ }
+ }
+}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
index 53c19ffe6..9faba5a49 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
@@ -99,6 +99,20 @@ const PORT_HOLDER_LOOKUP_TIMEOUT: Duration = Duration::from_secs(2);
const OPENAI_COMPATIBLE_FAILURE_POLL_INTERVAL: Duration = Duration::from_secs(15);
const OPENAI_COMPATIBLE_FAILURE_NOTIFICATION_COOLDOWN: Duration = Duration::from_secs(5 * 60);
+async fn initialize_frame_privacy_policy(
+ db: &DatabaseManager,
+ data_dir: &std::path::Path,
+) -> Result<(), String> {
+ if let Err(error) = db.set_frame_privacy_policy(&Default::default()).await {
+ let message = format!("Failed to initialize database frame privacy policy: {error}");
+ crate::health::set_boot_error(&message);
+ crate::recording::recovery_log::append(data_dir, "database_startup_failed", &message);
+ db.close().await;
+ return Err(message);
+ }
+ Ok(())
+}
+
fn should_notify_openai_compatible_failure(
previous_error_count: u64,
current_error_count: u64,
@@ -458,6 +472,12 @@ impl ServerCore {
};
info!("Database initialized at {}", db_path);
+ // Finish fallible database setup before sharing the owner with pipes,
+ // HTTP, or background workers. A failure must close this generation.
+ if !config.async_pii_redaction {
+ initialize_frame_privacy_policy(&db, &local_data_dir).await?;
+ }
+
// A pending update may interrupt database recovery, but must exclude
// native model initialization until the old process exits. Retain the
// read guard through all remaining startup work, including errors.
@@ -1160,11 +1180,6 @@ impl ServerCore {
}
}
- if !config.async_pii_redaction {
- db.set_frame_privacy_policy(&Default::default())
- .await
- .map_err(|error| format!("initialize frame privacy policy: {error}"))?;
- }
if config.async_pii_redaction {
use screenpipe_redact::adapters::onnx::{OnnxConfig, OnnxRedactor};
use screenpipe_redact::adapters::opf::{OpfAdapter, OpfConfig};
@@ -1529,6 +1544,82 @@ impl ServerCore {
mod tests {
use super::*;
+ #[tokio::test]
+ async fn failed_privacy_setup_releases_owner_and_preserves_recordings() {
+ let root = tempfile::tempdir().unwrap();
+ let db = Arc::new(
+ DatabaseManager::new_hybrid(root.path(), Default::default(), Default::default())
+ .await
+ .unwrap(),
+ );
+ db.insert_audio_chunk("before-privacy-startup-failure.wav", None)
+ .await
+ .unwrap();
+ db.execute_raw_sql_write("UPDATE storage_metadata SET policy='previous-policy'")
+ .await
+ .unwrap();
+ db.execute_raw_sql_write("CREATE TRIGGER reject_privacy_setup BEFORE UPDATE ON storage_metadata BEGIN SELECT RAISE(ABORT, 'privacy setup unavailable; [email protected]'); END").await.unwrap();
+
+ let error = initialize_frame_privacy_policy(&db, root.path())
+ .await
+ .unwrap_err();
+ assert!(error.contains("privacy setup unavailable"));
+ assert!(db.pool.is_closed());
+ assert!(crate::db_relaunch::is_db_shaped(&error));
+ // Retain the old Arc, just as pipe callbacks may do. Reopening must
+ // depend on completed close, not the last Arc being dropped.
+ let reopened = DatabaseManager::new(
+ root.path().join("db.sqlite").to_str().unwrap(),
+ Default::default(),
+ )
+ .await
+ .unwrap();
+ reopened
+ .execute_raw_sql_write("DROP TRIGGER reject_privacy_setup")
+ .await
+ .unwrap();
+ initialize_frame_privacy_policy(&reopened, root.path())
+ .await
+ .unwrap();
+ reopened
+ .insert_audio_chunk("after-privacy-startup-failure.wav", None)
+ .await
+ .unwrap();
+ assert!(reopened
+ .find_audio_chunk_id("before-privacy-startup-failure.wav")
+ .await
+ .unwrap()
+ .is_some());
+ assert!(reopened
+ .find_audio_chunk_id("after-privacy-startup-failure.wav")
+ .await
+ .unwrap()
+ .is_some());
+ reopened.close().await;
+ crate::recording::recovery_log::append(
+ root.path(),
+ "engine_started",
+ "database reopened after privacy setup retry",
+ );
+
+ for day in 1..=7 {
+ std::fs::write(
+ root.path()
+ .join(format!("screenpipe-app.2026-09-{day:02}.log")),
+ "app restarted\n",
+ )
+ .unwrap();
+ }
+ let report =
+ crate::diagnostic_logs::collect_redacted_from_dirs(&[root.path().to_path_buf()])
+ .await
+ .unwrap();
+ assert!(report.contains("database_startup_failed"));
+ assert!(report.contains("privacy setup unavailable"));
+ assert!(report.contains("database reopened after privacy setup retry"));
+ assert!(!report.contains("[email protected]"));
+ }
+
fn localhost(port: u16) -> SocketAddr {
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)
}