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 recording restart requests being dropped during onboarding (#7180)
Louis Beaumont8f9048d2995e
diff --git a/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-permission-monitor.test.tsx b/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-permission-monitor.test.tsxnew file mode 100644index 000000000..a7a9dccf7--- /dev/null+++ b/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-permission-monitor.test.tsx@@ -0,0 +1,208 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com++import React from "react";+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { usePermissionMonitor } from "../use-permission-monitor";++const mocks = vi.hoisted(() => ({+ pathname: "/onboarding",+ spawnScreenpipe: vi.fn(),+ retryScreenpipe: vi.fn(),+ listen: vi.fn(),+ isCapturePaused: vi.fn(),+ showWindow: vi.fn(),+ listeners: new Map<string, Set<(event: { payload: unknown }) => Promise<void>>>(),+}));++vi.mock("next/navigation", () => ({ usePathname: () => mocks.pathname }));+vi.mock("@/lib/utils/tauri", () => ({ commands: mocks }));+vi.mock("@tauri-apps/api/event", () => ({ listen: (...args: unknown[]) => mocks.listen(...args) }));++async function emit(name: string, payload: unknown = null) {+ await act(async () => {+ for (const handler of mocks.listeners.get(name) ?? []) await handler({ payload });+ });+}++beforeEach(() => {+ vi.clearAllMocks();+ mocks.listeners.clear();+ mocks.listen.mockReset().mockImplementation(async (name: string, handler: (event: { payload: unknown }) => Promise<void>) => {+ const handlers = mocks.listeners.get(name) ?? new Set();+ handlers.add(handler);+ mocks.listeners.set(name, handlers);+ return () => handlers.delete(handler);+ });+ mocks.pathname = "/onboarding";+ mocks.retryScreenpipe.mockResolvedValue({ status: "ok", data: null });++ mocks.showWindow.mockResolvedValue({ status: "ok", data: null });+});++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe("native server restart requests", () => {+ for (const path of ["/onboarding", "/onboarding/setup", "/permission-recovery", "/shortcut-reminder", "/"]) {+ it(`recovers a missing recording server on ${path}`, async () => {+ mocks.pathname = path;+ renderHook(() => usePermissionMonitor());+ expect(mocks.retryScreenpipe).not.toHaveBeenCalled();+ await emit("request-server-restart");+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(1);+ expect(mocks.retryScreenpipe).toHaveBeenCalledWith();+ expect(mocks.showWindow).not.toHaveBeenCalled();+ });+ }++ it("keeps one restart listener when navigation enters and leaves setup", async () => {+ const hook = renderHook(() => usePermissionMonitor());+ for (const path of ["/", "/onboarding", "/permission-recovery", "/"]) {+ mocks.pathname = path;+ await act(async () => hook.rerender());+ expect(mocks.listeners.get("request-server-restart")?.size).toBe(1);+ await emit("request-server-restart");+ }+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(4);+ await act(async () => hook.unmount());+ await emit("request-server-restart");+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(4);+ });++ it("reports a native startup error without retrying or claiming recovery", async () => {+ const error = vi.spyOn(console, "error").mockImplementation(() => {});+ mocks.retryScreenpipe.mockResolvedValue({ status: "error", error: "recording access denied" });+ renderHook(() => usePermissionMonitor());+ await emit("request-server-restart");+ expect(error).toHaveBeenCalledWith("Deferred server restart failed:", expect.objectContaining({ message: "recording access denied" }));+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(1);+ });++ it("handles a rejected startup invocation", async () => {+ const error = vi.spyOn(console, "error").mockImplementation(() => {});+ const failure = new Error("native invoke unavailable");+ mocks.retryScreenpipe.mockRejectedValue(failure);+ renderHook(() => usePermissionMonitor());+ await emit("request-server-restart");+ expect(error).toHaveBeenCalledWith("Deferred server restart failed:", failure);+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(1);+ });++ it("uses native intent-preserving retry instead of a racy pause-check and user-start pair", async () => {+ renderHook(() => usePermissionMonitor());+ await emit("request-server-restart");+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(1);+ expect(mocks.isCapturePaused).not.toHaveBeenCalled();+ expect(mocks.spawnScreenpipe).not.toHaveBeenCalled();+ });++ it("coalesces overlapping requests and allows a later recovery attempt", async () => {+ let finish!: (result: { status: "ok"; data: null }) => void;+ mocks.retryScreenpipe.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }));+ renderHook(() => usePermissionMonitor());+ const handler = [...mocks.listeners.get("request-server-restart")!][0];+ await act(async () => {+ const first = handler({ payload: null });+ await waitFor(() => expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(1));+ await handler({ payload: null });+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(1);+ finish({ status: "ok", data: null });+ await first;+ });+ await emit("request-server-restart");+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(2);+ });++ it("ignores a stale callback immediately after unmount", async () => {+ const hook = renderHook(() => usePermissionMonitor());+ const handler = [...mocks.listeners.get("request-server-restart")!][0];+ hook.unmount();+ await handler({ payload: null });+ expect(mocks.retryScreenpipe).not.toHaveBeenCalled();+ });++ it("unsubscribes even when native listener registration completes after unmount", async () => {+ let registered!: (unlisten: () => void) => void;+ const unlisten = vi.fn();+ mocks.listen.mockReturnValueOnce(new Promise(resolve => { registered = resolve; }));+ const hook = renderHook(() => usePermissionMonitor());+ const handler = mocks.listen.mock.calls[0][1];+ hook.unmount();+ await act(async () => {+ await handler({ payload: null });+ registered(unlisten);+ });+ expect(mocks.retryScreenpipe).not.toHaveBeenCalled();+ expect(unlisten).toHaveBeenCalledTimes(1);+ });++ it("handles failed listener registration without an unhandled rejection on cleanup", async () => {+ const failure = new Error("event bridge unavailable");+ const error = vi.spyOn(console, "error").mockImplementation(() => {});+ mocks.listen.mockRejectedValueOnce(failure);+ const hook = renderHook(() => usePermissionMonitor());+ await act(async () => {});+ expect(error).toHaveBeenCalledWith("Failed to listen for server restart requests:", failure);+ await act(async () => hook.unmount());+ expect(mocks.retryScreenpipe).not.toHaveBeenCalled();+ });++ it("survives React StrictMode setup and cleanup without duplicate recovery", async () => {+ renderHook(() => usePermissionMonitor(), {+ wrapper: ({ children }) => <React.StrictMode>{children}</React.StrictMode>,+ });+ await act(async () => {});+ expect(mocks.listeners.get("request-server-restart")?.size).toBe(1);+ await emit("request-server-restart");+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(1);+ });++ it("allows independent windows to retry through the native serializer", async () => {+ const first = renderHook(() => usePermissionMonitor());+ mocks.pathname = "/shortcut-reminder";+ const second = renderHook(() => usePermissionMonitor());+ await emit("request-server-restart");+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(2);+ expect(mocks.spawnScreenpipe).not.toHaveBeenCalled();+ await act(async () => first.unmount());+ await emit("request-server-restart");+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(3);+ await act(async () => second.unmount());+ expect(mocks.listeners.get("request-server-restart")?.size).toBe(0);+ });++ it("accepts a later event after the previous native retry fails", async () => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ mocks.retryScreenpipe.mockRejectedValueOnce(new Error("temporary startup error"));+ renderHook(() => usePermissionMonitor());+ await emit("request-server-restart");+ await emit("request-server-restart");+ expect(mocks.retryScreenpipe).toHaveBeenCalledTimes(2);+ });+});++describe("permission dialogs remain separate from server recovery", () => {+ for (const path of ["/onboarding", "/permission-recovery", "/shortcut-reminder"]) {+ it(`does not interrupt ${path} with another permission window`, async () => {+ mocks.pathname = path;+ renderHook(() => usePermissionMonitor());+ await emit("permission-lost", { screen_recording: true });+ await emit("permission_needed", { kind: "screen_recording" });+ expect(mocks.showWindow).not.toHaveBeenCalled();+ expect(mocks.retryScreenpipe).not.toHaveBeenCalled();+ });+ }++ it("still opens permission recovery from Home", async () => {+ mocks.pathname = "/";+ renderHook(() => usePermissionMonitor());+ await emit("permission-lost", { screen_recording: true });+ expect(mocks.showWindow).toHaveBeenCalledTimes(1);+ expect(mocks.showWindow).toHaveBeenCalledWith("PermissionRecovery");+ expect(mocks.retryScreenpipe).not.toHaveBeenCalled();+ });+});diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-permission-monitor.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-permission-monitor.tsxindex a7fa7bace..88bdf0151 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-permission-monitor.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/use-permission-monitor.tsx@@ -35,6 +35,38 @@ export function usePermissionMonitor() {const cooldownRef = useRef<ReturnType<typeof setTimeout> | null>(null);const pathname = usePathname();+ // Recording recovery is independent of permission dialogs. In particular,+ // onboarding may be the only open webview when the tray asks to restart a+ // missing server. Skipping this listener there strands capture until relaunch.+ useEffect(() => {+ if (typeof window === "undefined") return;+ let disposed = false;+ let restartInFlight = false;+ const unlistenRestart = listen("request-server-restart", async () => {+ if (disposed || restartInFlight) return;+ restartInFlight = true;+ try {+ console.log("Deferred server restart requested by backend");+ // The native retry checks intent under its lifecycle lock and never+ // re-enables capture. A separate pause check followed by spawn has a+ // race where a later user pause can be overwritten by the stale event.+ const result = await commands.retryScreenpipe();+ if (result.status === "error") throw new Error(result.error);+ } catch (error) {+ console.error("Deferred server restart failed:", error);+ } finally {+ restartInFlight = false;+ }+ }).catch((error) => {+ console.error("Failed to listen for server restart requests:", error);+ return null;+ });+ return () => {+ disposed = true;+ unlistenRestart.then((fn) => fn?.());+ };+ }, []);+useEffect(() => {if (typeof window === "undefined") return;@@ -70,18 +102,6 @@ export function usePermissionMonitor() {}, 300000);});- // Listen for deferred restart requests from the cooldown logic in recording.rs.- // When a restart is blocked by cooldown, the backend schedules a deferred check- // and emits this event if the server is still dead after cooldown expires.- const unlistenRestart = listen("request-server-restart", async () => {- console.log("Deferred server restart requested by backend");- try {- await commands.spawnScreenpipe(null);- } catch (error) {- console.error("Deferred server restart failed:", error);- }- });-// Listen for permission_needed events emitted when capture is blocked// waiting for user to grant permission via onboarding.// This signals that the app should show the permission flow UI.@@ -102,7 +122,6 @@ export function usePermissionMonitor() {return () => {unlisten.then((fn) => fn());- unlistenRestart.then((fn) => fn());unlistenNeeded.then((fn) => fn());if (cooldownRef.current) {clearTimeout(cooldownRef.current);diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.tsindex 08c9cefb9..41ab9100f 100644--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts@@ -2381,6 +2381,18 @@ async resumeGlobalShortcuts() : Promise<Result<null, string>> {else return { status: "error", error: e as any };}},+/**+ * Automatic retry preserves capture intent; unlike the user command it must+ * not turn recording back on after the user stopped it.+ */+async retryScreenpipe() : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("retry_screenpipe") };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},/*** Reveal a file in the OS file browser (Finder / Explorer / etc).*/@@ -3877,10 +3889,9 @@ enableSemanticContext?: boolean;*/semanticContextMode?: SemanticContextMode;/**- * Disable the timeline / rewind feature. When true, the engine skips- * timeline-only work: warming the hot frame cache from the DB at startup- * and buffering captured frames/audio into the in-memory hot cache that- * only the timeline streaming endpoint reads.+ * Legacy timeline gate retained for managed deployments and compatibility.+ * Consumer installs migrate visibility to sidebarNavLayout. Screenshot+ * capture controls cache work through `timeline_cache_disabled`.*/disableTimeline?: boolean;/**diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rsindex 730fa551c..a2f205fd8 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs@@ -298,6 +298,7 @@ const CAPTURE_RESTART_MEETING_REATTACH_WINDOW: Duration = Duration::from_secs(12mod db_wedge;pub(crate) mod recovery_log;+mod retry;mod server_shutdown;pub use db_wedge::{make_database_restart_hook, new_db_wedge_breaker, DbWedgeBreaker, DbWedgeState,@@ -812,7 +813,7 @@ pub async fn start_capture(let server_guard = state.server.lock().await;let Some(ref core) = *server_guard else {warn!("Server not running — requesting full restart");- let _ = app.emit("request-server-restart", ());+ request_server_restart(&app, "server missing when Start recording was requested");return Err("Server not running — full restart requested".to_string());};(core.port, core.local_api_key.clone())@@ -828,7 +829,10 @@ pub async fn start_capture("Server unresponsive on port {} — requesting full restart",port);- let _ = app.emit("request-server-restart", ());+ request_server_restart(+ &app,+ "server health probe failed when Start recording was requested",+ );return Err(format!("Server not responding on port {} — full restart requested",port@@ -1060,27 +1064,41 @@ pub(crate) fn resume_deferred_account_start(app: tauri::AppHandle) {/// Automatic retry preserves capture intent; unlike the user command it must/// not turn recording back on after the user stopped it.-pub(crate) async fn retry_screenpipe(+#[tauri::command]+#[specta::specta]+pub async fn retry_screenpipe(state: State<'_, RecordingState>,app: tauri::AppHandle,) -> Result<(), String> {- let Ok(_lifecycle_guard) = state.server_lifecycle.try_lock() else {- return Ok(());- };- if !state.capture_intended() || crate::process_exit::QUIT_REQUESTED.load(Ordering::SeqCst) {- return Ok(());- }// The watchdog owns retry timing. Do not enter the user command's// cooldown path, which schedules a frontend restart request later.let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs();- let last_spawn = state.last_spawn_epoch.load(Ordering::SeqCst);- if last_spawn > 0 && now.saturating_sub(last_spawn) < RESTART_COOLDOWN_SECS {+ let Some(_lifecycle_guard) = retry::admit(+ &state.server_lifecycle,+ &state.wants_recording,+ &crate::process_exit::QUIT_REQUESTED,+ &state.last_spawn_epoch,+ now,+ ) else {return Ok(());+ };+ retry::run(+ &crate::db_relaunch::active_data_dir(),+ &state.wants_recording,+ spawn_screenpipe_inner(&state, app),+ )+ .await+}++fn request_server_restart(app: &tauri::AppHandle, reason: &str) {+ let data_dir = crate::db_relaunch::active_data_dir();+ recovery_log::append(&data_dir, "retry_requested", reason);+ if let Err(error) = app.emit("request-server-restart", ()) {+ recovery_log::append(&data_dir, "retry_event_failed", &error.to_string());}- spawn_screenpipe_inner(&state, app).await}pub(crate) async fn spawn_screenpipe_inner(@@ -1148,7 +1166,7 @@ async fn spawn_screenpipe_after_migration(info!("Deferred spawn: server dead, triggering restart");is_starting.store(false, Ordering::SeqCst);last_spawn_epoch.store(0, Ordering::SeqCst);- let _ = app_handle.emit("request-server-restart", ());+ request_server_restart(&app_handle, "server missing after restart cooldown");});return Ok(());}@@ -1532,7 +1550,11 @@ async fn spawn_screenpipe_after_migration(let app_for_chat_destination = app.clone();let app_for_owned = app.clone();let app_for_port_conflict = app.clone();- let workflow_catalog_dir = app.path().app_local_data_dir().ok().map(|dir| dir.join("workflows"));+ let workflow_catalog_dir = app+ .path()+ .app_local_data_dir()+ .ok()+ .map(|dir| dir.join("workflows"));// Owned-browser: create the connect-side instance and kick off the// webview install in the background. The engine starts immediately;@@ -1743,7 +1765,13 @@ async fn start_capture_internal(let store = SettingsStore::get(app).ok().flatten().unwrap_or_default();require_recording_access(app, &store)?;- let mut capture_guard = state.capture.lock().await;+ let Some(mut capture_guard) =+ retry::lock_intended_capture(&state.capture, &state.wants_recording).await+ else {+ state.is_starting.store(false, Ordering::SeqCst);+ info!("Capture was deliberately stopped while recovery waited; leaving server running");+ return Ok(());+ };if capture_guard.is_some() {// A concurrent start_capture beat us to it.state.is_starting.store(false, Ordering::SeqCst);diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording/retry.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording/retry.rsnew file mode 100644index 000000000..c022c24b0--- /dev/null+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording/retry.rs@@ -0,0 +1,265 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com++use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use tokio::sync::{Mutex, MutexGuard};++/// Keep the originating startup error in the bounded log collected by support.+/// A completed invocation only describes startup; durable capture and upload+/// remain independently observable outcomes.+pub(super) async fn run(+ data_dir: &std::path::Path,+ wants_recording: &AtomicBool,+ startup: impl std::future::Future<Output = Result<(), String>>,+) -> Result<(), String> {+ super::recovery_log::append(data_dir, "retry_started", "recording recovery admitted");+ let result = startup.await;+ let capture_intended = wants_recording.load(Ordering::SeqCst);+ match &result {+ Ok(()) => super::recovery_log::append(+ data_dir,+ "retry_completed",+ &format!("startup command completed; capture_intended={capture_intended}"),+ ),+ Err(error) => super::recovery_log::append(+ data_dir,+ "retry_failed",+ &format!("startup failed; capture_intended={capture_intended}; cause={error}"),+ ),+ }+ result+}++/// Shared admission for watchdog and webview recovery. Inspect current intent+/// only after acquiring the native lifecycle slot; never publish new intent.+pub(super) fn admit<'a>(+ lifecycle: &'a Mutex<()>,+ wants_recording: &AtomicBool,+ quit_requested: &AtomicBool,+ last_spawn: &AtomicU64,+ now: u64,+) -> Option<MutexGuard<'a, ()>> {+ let guard = lifecycle.try_lock().ok()?;+ if !wants_recording.load(Ordering::SeqCst) || quit_requested.load(Ordering::SeqCst) {+ return None;+ }+ let last = last_spawn.load(Ordering::SeqCst);+ if last > 0 && now.saturating_sub(last) < super::RESTART_COOLDOWN_SECS {+ return None;+ }+ Some(guard)+}++/// A pause may complete after retry admission but before a healthy server's+/// capture slot becomes available. Recheck intent while owning that slot.+pub(super) async fn lock_intended_capture<'a, T>(+ capture: &'a Mutex<Option<T>>,+ wants_recording: &AtomicBool,+) -> Option<MutexGuard<'a, Option<T>>> {+ let guard = capture.lock().await;+ wants_recording.load(Ordering::SeqCst).then_some(guard)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn retry_failure_and_paused_completion_survive_collected_redacted_support_report() {+ let dir = tempfile::tempdir().unwrap();+ let intent = AtomicBool::new(true);+ let failure = run(dir.path(), &intent, async {+ // Exercise a real startup prerequisite failure, retaining its OS+ // cause rather than replacing it with a generic retry error.+ std::fs::read(dir.path().join("missing-config"))+ .map(|_| ())+ .map_err(|error| format!("recording configuration unavailable: {error}"))+ })+ .await+ .unwrap_err();+ run(dir.path(), &intent, async {+ // Pause races an admitted recovery. Completing startup must leave+ // that newer user intent intact and describe it accurately.+ intent.store(false, Ordering::SeqCst);+ Ok(())+ })+ .await+ .unwrap();++ // Simulate application-log rotation and restart. The recovery log+ // must retain priority despite newer noisy application logs.+ for day in 1..=7 {+ std::fs::write(+ dir.path()+ .join(format!("screenpipe-app.2026-09-{day:02}.log")),+ "app restarted; [email protected]\n",+ )+ .unwrap();+ }+ let report =+ crate::diagnostic_logs::collect_redacted_from_dirs(&[dir.path().to_path_buf()])+ .await+ .unwrap();+ assert!(report.contains("retry_started: recording recovery admitted"));+ assert!(report.contains("retry_failed: startup failed; capture_intended=true"));+ assert!(report.contains(&failure));+ assert!(+ report.contains("retry_completed: startup command completed; capture_intended=false")+ );+ assert!(!report.contains("[email protected]"));+ assert!(!intent.load(Ordering::SeqCst));+ }++ #[test]+ fn pause_after_a_webview_observed_recording_cancels_native_retry() {+ let lifecycle = Mutex::new(());+ let intent = AtomicBool::new(true);+ assert!(intent.load(Ordering::SeqCst)); // old UI snapshot+ intent.store(false, Ordering::SeqCst); // user pauses before IPC arrives+ assert!(admit(+ &lifecycle,+ &intent,+ &AtomicBool::new(false),+ &AtomicU64::new(0),+ 100+ )+ .is_none());+ assert!(!intent.load(Ordering::SeqCst));+ assert!(lifecycle.try_lock().is_ok());+ }++ #[test]+ fn concurrent_windows_share_one_lifecycle_slot() {+ let lifecycle = Mutex::new(());+ let intent = AtomicBool::new(true);+ let quit = AtomicBool::new(false);+ let last = AtomicU64::new(0);+ let first = admit(&lifecycle, &intent, &quit, &last, 100).unwrap();+ assert!(admit(&lifecycle, &intent, &quit, &last, 100).is_none());+ // Successful startup sets the shared cooldown before releasing the slot.+ last.store(100, Ordering::SeqCst);+ drop(first);+ assert!(admit(&lifecycle, &intent, &quit, &last, 100).is_none());+ assert!(admit(&lifecycle, &intent, &quit, &last, 130).is_some());+ }++ #[test]+ fn busy_lifecycle_does_not_queue_a_restart_that_outlives_pause() {+ let lifecycle = Mutex::new(());+ let intent = AtomicBool::new(true);+ let guard = lifecycle.try_lock().unwrap();+ assert!(admit(+ &lifecycle,+ &intent,+ &AtomicBool::new(false),+ &AtomicU64::new(0),+ 100+ )+ .is_none());+ intent.store(false, Ordering::SeqCst);+ drop(guard);+ assert!(admit(+ &lifecycle,+ &intent,+ &AtomicBool::new(false),+ &AtomicU64::new(0),+ 100+ )+ .is_none());+ }++ #[test]+ fn quit_cancels_retry_and_releases_lifecycle_slot() {+ let lifecycle = Mutex::new(());+ assert!(admit(+ &lifecycle,+ &AtomicBool::new(true),+ &AtomicBool::new(true),+ &AtomicU64::new(0),+ 100+ )+ .is_none());+ assert!(lifecycle.try_lock().is_ok());+ }++ #[test]+ fn cooldown_honors_boundary_and_backwards_clock() {+ let lifecycle = Mutex::new(());+ let intent = AtomicBool::new(true);+ let quit = AtomicBool::new(false);+ let last = AtomicU64::new(100);+ for now in [99, 100, 129] {+ assert!(admit(&lifecycle, &intent, &quit, &last, now).is_none());+ }+ assert!(admit(&lifecycle, &intent, &quit, &last, 130).is_some());+ }++ #[test]+ fn never_started_server_can_recover_without_modifying_capture_intent() {+ let lifecycle = Mutex::new(());+ let intent = AtomicBool::new(true);+ let guard = admit(+ &lifecycle,+ &intent,+ &AtomicBool::new(false),+ &AtomicU64::new(0),+ 0,+ )+ .unwrap();+ assert!(intent.load(Ordering::SeqCst));+ drop(guard);+ assert!(lifecycle.try_lock().is_ok());+ }++ #[test]+ fn pause_during_admitted_start_remains_visible_to_capture_creation() {+ let lifecycle = Mutex::new(());+ let intent = AtomicBool::new(true);+ let _guard = admit(+ &lifecycle,+ &intent,+ &AtomicBool::new(false),+ &AtomicU64::new(0),+ 100,+ )+ .unwrap();+ intent.store(false, Ordering::SeqCst);+ // Server startup uses this same last-moment check before CaptureSession.+ assert!(!super::super::capture_intended_now(&intent));+ }++ #[tokio::test]+ async fn healthy_server_retry_honors_pause_while_waiting_for_capture_slot() {+ let capture = Mutex::new(None::<()>);+ let intent = AtomicBool::new(true);+ let pause_guard = capture.lock().await;+ let retry = lock_intended_capture(&capture, &intent);+ tokio::pin!(retry);+ assert!(futures::poll!(retry.as_mut()).is_pending());++ // The pause completes with no capture to stop before retry gets the+ // slot. A stale pre-lock intent check would create a new session here.+ intent.store(false, Ordering::SeqCst);+ drop(pause_guard);+ let mut starts = 0;+ if let Some(mut slot) = retry.await {+ starts += 1;+ *slot = Some(());+ }+ assert_eq!(starts, 0);+ assert!(capture.lock().await.is_none());+ assert!(!intent.load(Ordering::SeqCst));+ }++ #[tokio::test]+ async fn intended_capture_start_keeps_slot_until_session_is_installed() {+ let capture = Mutex::new(None::<()>);+ let intent = AtomicBool::new(true);+ let mut slot = lock_intended_capture(&capture, &intent).await.unwrap();+ assert!(capture.try_lock().is_err());+ *slot = Some(());+ drop(slot);+ assert!(capture.lock().await.is_some());+ assert!(intent.load(Ordering::SeqCst));+ }+}diff --git a/docs/COVERAGE.md b/docs/COVERAGE.mdindex d1cf74901..b62ef5413 100644--- a/docs/COVERAGE.md+++ b/docs/COVERAGE.md@@ -38,25 +38,15 @@ results and `cargo llvm-cov` data on top when judging release confidence.- Mapped suites: 34- Mapped Rust files: 367-- Active test blocks: 3586+- Active test blocks: 3599- Ignored/manual test blocks: 150-- Weighted coverage points: 2964.6+- Weighted coverage points: 2975.2| Platform | Suites | Active tests | Ignored tests | Weighted points | Layers | Flows | Critical score || --- | --- | --- | --- | --- | --- | --- | --- |-| windows | 31 | 3442 | 144 | 2899.1 | 21 | 11 | 100% |-| macos | 31 | 3502 | 124 | 2911.4 | 22 | 11 | 100% |-| linux | 27 | 3061 | 116 | 2548.3 | 20 | 11 | 100% |-- Active test blocks: 3588-- Active test blocks: 3598-- Ignored/manual test blocks: 150-- Weighted coverage points: 2974.2--| Platform | Suites | Active tests | Ignored tests | Weighted points | Layers | Flows | Critical score |-| --- | --- | --- | --- | --- | --- | --- | --- |-| windows | 31 | 3454 | 144 | 2908.7 | 21 | 11 | 100% |-| macos | 31 | 3514 | 124 | 2921.0 | 22 | 11 | 100% |-| linux | 27 | 3073 | 116 | 2557.9 | 20 | 11 | 100% |+| windows | 31 | 3455 | 144 | 2909.7 | 21 | 11 | 100% |+| macos | 31 | 3515 | 124 | 2922.0 | 22 | 11 | 100% |+| linux | 27 | 3074 | 116 | 2558.9 | 20 | 11 | 100% |## Refreshdiff --git a/docs/coverage/CORE.md b/docs/coverage/CORE.mdindex 7d862c67d..8b0e6e9b5 100644--- a/docs/coverage/CORE.md+++ b/docs/coverage/CORE.md@@ -9,15 +9,10 @@ confidence, and criticality.- Tracked crates: screenpipe-engine, screenpipe-db, screenpipe-sqlite-coordinator, screenpipe-audio, screenpipe-screen, screenpipe-a11y, screenpipe-fs- Mapped suites: 34- Mapped Rust files: 367-- Active test blocks: 3586+- Active test blocks: 3599- Ignored/manual test blocks: 150-- Declared test blocks: 3736-- Weighted coverage points: 2964.6-- Active test blocks: 3588-- Active test blocks: 3598-- Ignored/manual test blocks: 150-- Declared test blocks: 3748-- Weighted coverage points: 2974.2+- Declared test blocks: 3749+- Weighted coverage points: 2975.2Confidence weights: strong=1.0, partial=0.7, conditional=0.4, smoke=0.3.Criticality weights: high=1.0, medium=0.7, low=0.4.@@ -28,26 +23,16 @@ are explicitly enabled in a runtime lane.| Platform | Suites | Active tests | Ignored tests | Weighted points | Layers | Flows | Critical score || --- | --- | --- | --- | --- | --- | --- | --- |-| windows | 31 | 3442 | 144 | 2899.1 | 21 | 11 | 100% |-| macos | 31 | 3502 | 124 | 2911.4 | 22 | 11 | 100% |-| linux | 27 | 3061 | 116 | 2548.3 | 20 | 11 | 100% |-| windows | 31 | 3444 | 144 | 2901.1 | 21 | 11 | 100% |-| macos | 31 | 3504 | 124 | 2913.4 | 22 | 11 | 100% |-| linux | 27 | 3063 | 116 | 2550.3 | 20 | 11 | 100% |-| windows | 31 | 3454 | 144 | 2908.7 | 21 | 11 | 100% |-| macos | 31 | 3514 | 124 | 2921.0 | 22 | 11 | 100% |-| linux | 27 | 3073 | 116 | 2557.9 | 20 | 11 | 100% |+| windows | 31 | 3455 | 144 | 2909.7 | 21 | 11 | 100% |+| macos | 31 | 3515 | 124 | 2922.0 | 22 | 11 | 100% |+| linux | 27 | 3074 | 116 | 2558.9 | 20 | 11 | 100% |## Crate Summary| Crate | Suites | Integration files | Source unit files | Active tests | Ignored tests | Weighted points | Flows || --- | --- | --- | --- | --- | --- | --- | --- |-| screenpipe-engine | 11 | 21 | 121 | 1744 | 43 | 1344.3 | 10 |-| screenpipe-db | 5 | 62 | 24 | 572 | 25 | 544.7 | 9 |-| screenpipe-engine | 11 | 21 | 121 | 1747 | 43 | 1347.3 | 10 |-| screenpipe-db | 5 | 62 | 24 | 571 | 25 | 543.7 | 9 || screenpipe-engine | 11 | 21 | 121 | 1753 | 43 | 1351.5 | 10 |-| screenpipe-db | 5 | 62 | 24 | 574 | 25 | 546.1 | 9 |+| screenpipe-db | 5 | 62 | 24 | 575 | 25 | 547.1 | 9 || screenpipe-sqlite-coordinator | 1 | 0 | 3 | 27 | 0 | 27.0 | 2 || screenpipe-audio | 6 | 25 | 51 | 626 | 44 | 550.6 | 5 || screenpipe-screen | 6 | 9 | 18 | 257 | 9 | 232.1 | 4 |@@ -81,33 +66,21 @@ bun run coverage:core -- --llvm-cov-summary ../../docs/coverage/core-llvm-cov-su| audio | 8 suites / 742 active / 45 ignored / 666.6 pts | 8 suites / 742 active / 45 ignored / 666.6 pts | 7 suites / 667 active / 44 ignored / 614.1 pts || audio-device | 2 suites / 222 active / 7 ignored / 199.5 pts | 2 suites / 222 active / 7 ignored / 199.5 pts | 1 suites / 147 active / 6 ignored / 147.0 pts || configuration | 2 suites / 143 active / 3 ignored / 129.2 pts | 2 suites / 143 active / 3 ignored / 129.2 pts | 2 suites / 143 active / 3 ignored / 129.2 pts |-| database | 7 suites / 523 active / 21 ignored / 495.7 pts | 7 suites / 523 active / 21 ignored / 495.7 pts | 7 suites / 523 active / 21 ignored / 495.7 pts |-| database | 7 suites / 525 active / 21 ignored / 497.7 pts | 7 suites / 525 active / 21 ignored / 497.7 pts | 7 suites / 525 active / 21 ignored / 497.7 pts |-| database | 7 suites / 528 active / 21 ignored / 500.1 pts | 7 suites / 528 active / 21 ignored / 500.1 pts | 7 suites / 528 active / 21 ignored / 500.1 pts |+| database | 7 suites / 529 active / 21 ignored / 501.1 pts | 7 suites / 529 active / 21 ignored / 501.1 pts | 7 suites / 529 active / 21 ignored / 501.1 pts || db-search | 2 suites / 113 active / 9 ignored / 113.0 pts | 2 suites / 113 active / 9 ignored / 113.0 pts | 2 suites / 113 active / 9 ignored / 113.0 pts || engine-lifecycle | 6 suites / 247 active / 1 ignored / 222.0 pts | 6 suites / 247 active / 1 ignored / 222.0 pts | 5 suites / 241 active / 1 ignored / 220.3 pts || local-api | 3 suites / 447 active / 10 ignored / 315.3 pts | 3 suites / 447 active / 10 ignored / 315.3 pts | 3 suites / 447 active / 10 ignored / 315.3 pts || meeting | 6 suites / 1645 active / 21 ignored / 1343.5 pts | 6 suites / 1645 active / 21 ignored / 1343.5 pts | 4 suites / 1300 active / 17 ignored / 1021.0 pts || ocr | 4 suites / 125 active / 7 ignored / 119.0 pts | 4 suites / 129 active / 7 ignored / 124.5 pts | 3 suites / 120 active / 6 ignored / 115.5 pts || os-integration | 1 suites / 6 active / 0 ignored / 1.7 pts | 1 suites / 6 active / 0 ignored / 1.7 pts | - |-| performance | 13 suites / 1581 active / 76 ignored / 1400.0 pts | 14 suites / 1689 active / 80 ignored / 1443.2 pts | 13 suites / 1581 active / 76 ignored / 1400.0 pts |-| pipes | 1 suites / 512 active / 3 ignored / 358.4 pts | 1 suites / 512 active / 3 ignored / 358.4 pts | 1 suites / 512 active / 3 ignored / 358.4 pts |-| privacy | 5 suites / 946 active / 37 ignored / 766.6 pts | 5 suites / 1002 active / 17 ignored / 773.4 pts | 5 suites / 921 active / 14 ignored / 743.4 pts |-| real-app | - | 1 suites / 108 active / 4 ignored / 43.2 pts | - |-| speaker | 2 suites / 369 active / 9 ignored / 369.0 pts | 2 suites / 369 active / 9 ignored / 369.0 pts | 2 suites / 369 active / 9 ignored / 369.0 pts |-| storage | 4 suites / 646 active / 38 ignored / 536.8 pts | 4 suites / 646 active / 38 ignored / 536.8 pts | 4 suites / 646 active / 38 ignored / 536.8 pts |-| sync | 1 suites / 512 active / 3 ignored / 358.4 pts | 1 suites / 512 active / 3 ignored / 358.4 pts | 1 suites / 512 active / 3 ignored / 358.4 pts |-| timeline | 4 suites / 1186 active / 43 ignored / 972.1 pts | 4 suites / 1186 active / 43 ignored / 972.1 pts | 4 suites / 1186 active / 43 ignored / 972.1 pts |-| transcription | 5 suites / 815 active / 42 ignored / 638.5 pts | 5 suites / 815 active / 42 ignored / 638.5 pts | 5 suites / 815 active / 42 ignored / 638.5 pts |-| ui-events | 4 suites / 762 active / 29 ignored / 579.0 pts | 3 suites / 710 active / 5 ignored / 542.6 pts | 3 suites / 710 active / 5 ignored / 542.6 pts |-| performance | 13 suites / 1583 active / 76 ignored / 1401.4 pts | 14 suites / 1691 active / 80 ignored / 1444.6 pts | 13 suites / 1583 active / 76 ignored / 1401.4 pts |+| performance | 13 suites / 1584 active / 76 ignored / 1402.4 pts | 14 suites / 1692 active / 80 ignored / 1445.6 pts | 13 suites / 1584 active / 76 ignored / 1402.4 pts || pipes | 1 suites / 515 active / 3 ignored / 360.5 pts | 1 suites / 515 active / 3 ignored / 360.5 pts | 1 suites / 515 active / 3 ignored / 360.5 pts || privacy | 5 suites / 949 active / 37 ignored / 768.7 pts | 5 suites / 1005 active / 17 ignored / 775.5 pts | 5 suites / 924 active / 14 ignored / 745.5 pts || real-app | - | 1 suites / 108 active / 4 ignored / 43.2 pts | - || speaker | 2 suites / 370 active / 9 ignored / 370.0 pts | 2 suites / 370 active / 9 ignored / 370.0 pts | 2 suites / 370 active / 9 ignored / 370.0 pts |-| storage | 4 suites / 646 active / 38 ignored / 536.8 pts | 4 suites / 646 active / 38 ignored / 536.8 pts | 4 suites / 646 active / 38 ignored / 536.8 pts |+| storage | 4 suites / 647 active / 38 ignored / 537.8 pts | 4 suites / 647 active / 38 ignored / 537.8 pts | 4 suites / 647 active / 38 ignored / 537.8 pts || sync | 1 suites / 515 active / 3 ignored / 360.5 pts | 1 suites / 515 active / 3 ignored / 360.5 pts | 1 suites / 515 active / 3 ignored / 360.5 pts |-| timeline | 4 suites / 1189 active / 43 ignored / 974.2 pts | 4 suites / 1189 active / 43 ignored / 974.2 pts | 4 suites / 1189 active / 43 ignored / 974.2 pts |+| timeline | 4 suites / 1190 active / 43 ignored / 975.2 pts | 4 suites / 1190 active / 43 ignored / 975.2 pts | 4 suites / 1190 active / 43 ignored / 975.2 pts || transcription | 5 suites / 819 active / 42 ignored / 641.6 pts | 5 suites / 819 active / 42 ignored / 641.6 pts | 5 suites / 819 active / 42 ignored / 641.6 pts || ui-events | 4 suites / 765 active / 29 ignored / 581.1 pts | 3 suites / 713 active / 5 ignored / 544.7 pts | 3 suites / 713 active / 5 ignored / 544.7 pts || vision-capture | 6 suites / 552 active / 32 ignored / 436.8 pts | 6 suites / 556 active / 32 ignored / 442.3 pts | 5 suites / 547 active / 31 ignored / 433.3 pts |@@ -160,8 +133,7 @@ bun run coverage:core -- --llvm-cov-summary ../../docs/coverage/core-llvm-cov-su| db-audio-meetings-speakers | screenpipe-db | windows, macos, linux | database, audio, meeting, speaker | audio-record-transcribe, audio-device-health, meeting-live-notes | high | strong | integration | 15 | 113 | 1 | Audio transcript dedupe, live meeting mirroring, end-generation and open-meeting invariants, liveness, and speaker reassignment coverage. || db-runtime-reliability | screenpipe-db | windows, macos, linux | database, performance | performance-liveness | high | partial | mixed | 16 | 47 | 6 | SQLite hard-fault classification, failpoint VFS injection, fresh-identity recovery verification with integrity/FK/write canaries, query cancellation, close-severs-connections regressions, multi-pool WAL parity, runtime version pinning, and WAL chaos plus memory-pressure probes, plus read-only quarantine self-heal verification for transient IOERR faults. || db-search-indexing | screenpipe-db | windows, macos, linux | db-search, ocr, accessibility, performance | local-api-search, capture-ocr-pipeline, accessibility-ui-events, performance-liveness | high | strong | mixed | 13 | 105 | 4 | FTS, tokenizer, OCR snapshot search, query planning, ordering, accessibility search, and contention coverage. |-| db-timeline-frames | screenpipe-db | windows, macos, linux | database, timeline, storage, performance | timeline-streaming, performance-liveness | high | strong | mixed | 35 | 282 | 12 | Frame/audio joins, timeline query shape, suggestions frames, write queue, DB primitives (src/db.rs split into src/db/ modules), feedback record upserts, media eviction anti-join regressions, SAF output registry, semantic storage, and timeline performance. |-| engine-api-routes | screenpipe-engine | windows, macos, linux | local-api, timeline, meeting, transcription | local-api-search, timeline-streaming, meeting-live-notes, audio-record-transcribe | high | partial | mixed | 41 | 412 | 5 | Route/unit coverage for search, health, streaming, meetings, time/timezone, and transcription. Legacy endpoint/websocket tests require local data and remain ignored. |+| db-timeline-frames | screenpipe-db | windows, macos, linux | database, timeline, storage, performance | timeline-streaming, performance-liveness | high | strong | mixed | 35 | 283 | 12 | Frame/audio joins, timeline query shape, suggestions frames, write queue, DB primitives (src/db.rs split into src/db/ modules), feedback record upserts, media eviction anti-join regressions, SAF output registry, semantic storage, and timeline performance. || engine-api-routes | screenpipe-engine | windows, macos, linux | local-api, timeline, meeting, transcription | local-api-search, timeline-streaming, meeting-live-notes, audio-record-transcribe | high | partial | mixed | 41 | 415 | 5 | Route/unit coverage for search, health, streaming, meetings, time/timezone, and transcription. Legacy endpoint/websocket tests require local data and remain ignored. || engine-capture-timeline | screenpipe-engine | windows, macos, linux | vision-capture, timeline, storage, performance | capture-ocr-pipeline, timeline-streaming, performance-liveness | high | partial | mixed | 25 | 301 | 26 | Covers capture trigger logic, frame/audio linking, hot cache, timeline refresh regressions, fragmented MP4 extraction, and HD-mode control. Several real-data tests are intentionally ignored by default. || engine-config-lifecycle | screenpipe-engine | windows, macos, linux | configuration, engine-lifecycle, performance | settings-to-engine-config, engine-health-lifecycle, performance-liveness | high | strong | mixed | 12 | 116 | 1 | Fast logic coverage for the config bridge, health-endpoint identity, tray health debounce, sleep/power policies, and queue backpressure. |@@ -307,8 +279,6 @@ bun run coverage:core -- --llvm-cov-summary ../../docs/coverage/core-llvm-cov-su| db-runtime-reliability | screenpipe-db | src/recovery.rs | source | 5 | 0 | 5 || db-runtime-reliability | screenpipe-db | src/sqlite_error.rs | source | 5 | 0 | 5 || db-timeline-frames | screenpipe-db | src/storage/bulk/tests.rs | source | 9 | 0 | 9 |-| db-timeline-frames | screenpipe-db | src/storage/diagnostics.rs | source | 6 | 0 | 6 |-| db-timeline-frames | screenpipe-db | src/storage/bulk/tests.rs | source | 8 | 0 | 8 || db-timeline-frames | screenpipe-db | src/storage/diagnostics.rs | source | 7 | 0 | 7 || db-timeline-frames | screenpipe-db | src/storage/lifecycle.rs | source | 2 | 1 | 3 || db-timeline-frames | screenpipe-db | src/storage/parity.rs | source | 2 | 0 | 2 |