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

feat: keep local search available after quitting

Ezra Ellettefc6022bd629f
diff --git a/Cargo.lock b/Cargo.lock
index 7668d3ae7..08c4ed12c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8832,6 +8832,7 @@ dependencies = [
"screenpipe-cpu-features",
"screenpipe-events",
"screenpipe-fs",
+ "screenpipe-resource",
"screenpipe-secrets",
"screenpipe-sync",
"screenpipe-vault",
diff --git a/apps/screenpipe-app-tauri/components/settings/general-settings.tsx b/apps/screenpipe-app-tauri/components/settings/general-settings.tsx
index ed3dd1ca1..29c0678ed 100644
--- a/apps/screenpipe-app-tauri/components/settings/general-settings.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/general-settings.tsx
@@ -13,7 +13,7 @@ import { Switch } from "@/components/ui/switch";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
-import { Rocket, Moon, Sun, Monitor, FlaskConical, ExternalLink, Layers, RefreshCw } from "lucide-react";
+import { Rocket, Moon, Sun, Monitor, FlaskConical, ExternalLink, Layers, RefreshCw, Search } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import { Button } from "@/components/ui/button";
import {
@@ -41,6 +41,7 @@ import posthog from "posthog-js";
export const searchIndex: SettingsField[] = [
{ label: msg("Language", {}), keywords: ["locale", "translation"] },
{ label: msg("Auto-start", {}), keywords: ["autostart", "launch", "startup"] },
+ { label: msg("Keep search available after quitting", {}), keywords: ["quit", "background", "recording", "api"] },
{ label: msg("Auto-update", {}), keywords: ["updates"] },
{ label: msg("Check for updates", {}), keywords: ["version"] },
{ label: msg("Auto-update scheduled tasks", {}), keywords: ["pipes", "store", "tasks"] },
@@ -273,6 +274,38 @@ export default function GeneralSettings() {
</Card>
</LockedSetting>
+ <Card className="border-border bg-card">
+ <CardContent className="px-3 py-2.5">
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex items-center space-x-2.5">
+ <Search className="h-4 w-4 text-muted-foreground shrink-0" />
+ <div>
+ <Label
+ htmlFor="keep-search-after-quit"
+ className="text-sm font-medium font-sans text-foreground"
+ >
+ {gt("Keep search available after quitting")}
+ </Label>
+ <p className="text-xs text-muted-foreground">
+ {gt(
+ "Quitting stops recording and closes the window. Screenpipe keeps running in the background so connected tools can search your saved history.",
+ )}
+ </p>
+ </div>
+ </div>
+ <Switch
+ id="keep-search-after-quit"
+ checked={settings?.keepSearchAvailableAfterQuit ?? true}
+ onCheckedChange={(checked) =>
+ handleSettingsChange({
+ keepSearchAvailableAfterQuit: checked,
+ })
+ }
+ />
+ </div>
+ </CardContent>
+ </Card>
+
{!isManagedDeployment && (
<Card className="border-border bg-card">
<CardContent className="px-3 py-2.5">
diff --git a/apps/screenpipe-app-tauri/e2e/search-only.e2e.ts b/apps/screenpipe-app-tauri/e2e/search-only.e2e.ts
new file mode 100644
index 000000000..cba673e90
--- /dev/null
+++ b/apps/screenpipe-app-tauri/e2e/search-only.e2e.ts
@@ -0,0 +1,183 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+// Run against an E2E build in a disposable VM after real capture has started.
+// Both URLs must be supplied explicitly; never discover or stop a host app.
+import assert from "node:assert/strict";
+
+const control = process.env.SCREENPIPE_SEARCH_TEST_CONTROL_URL;
+const api = process.env.SCREENPIPE_SEARCH_TEST_API_URL;
+assert(
+ control && api,
+ "Set both SCREENPIPE_SEARCH_TEST_CONTROL_URL and SCREENPIPE_SEARCH_TEST_API_URL for the disposable app",
+);
+const headers: Record<string, string> = { "content-type": "application/json" };
+if (process.env.SCREENPIPE_SEARCH_TEST_API_KEY) {
+ headers.authorization = `Bearer ${process.env.SCREENPIPE_SEARCH_TEST_API_KEY}`;
+}
+type State = {
+ pid: number;
+ search_only: boolean;
+ entering: boolean;
+ capture_intended: boolean;
+ capture_running: boolean;
+ webviews: string[];
+ keep_search_after_quit: boolean;
+};
+async function request(
+ base: string,
+ route: string,
+ method = "GET",
+ body?: unknown,
+) {
+ const res = await fetch(base + route, {
+ method,
+ headers,
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal: AbortSignal.timeout(45_000),
+ });
+ assert(res.ok, `${method} ${route}: ${res.status}`);
+ return res.json();
+}
+const state = (): Promise<State> => request(control, "/e2e/search-only/state");
+async function until(check: () => Promise<boolean>, label: string) {
+ const deadline = Date.now() + 45_000;
+ do {
+ if (await check()) return;
+ await Bun.sleep(300);
+ } while (Date.now() < deadline);
+ throw new Error(`Timed out: ${label}`);
+}
+const historySnapshot = () => request(api, "/search?limit=1&content_type=all");
+const counts = async () => {
+ // Use the caller's authorized history view: free accounts intentionally
+ // cannot use unrestricted raw SQL. Runtime counters cover UI capture too.
+ const [history, health] = await Promise.all([
+ historySnapshot(),
+ request(api, "/health"),
+ ]);
+ return {
+ history,
+ framesWritten: health.pipeline?.frames_db_written,
+ uiEvents: health.ui_recorder?.events_inserted,
+ lastAudio: health.last_audio_timestamp,
+ };
+};
+
+const initial = await state();
+assert(initial.keep_search_after_quit, "The preference defaults On");
+assert(
+ initial.capture_intended && initial.capture_running,
+ "Start real capture before running this check",
+);
+const history = await request(api, "/search?limit=1&content_type=all");
+assert(
+ history.data?.length > 0,
+ "Capture must produce searchable history before Quit",
+);
+
+for (let cycle = 0; cycle < 2; cycle++) {
+ await request(control, "/e2e/search-only/quit", "POST");
+ await until(async () => {
+ const s = await state();
+ return (
+ s.search_only &&
+ !s.entering &&
+ !s.capture_intended &&
+ !s.capture_running &&
+ s.webviews.length === 0
+ );
+ }, "Quit stops capture and destroys webviews");
+ assert.equal(
+ (await state()).pid,
+ initial.pid,
+ "Quit must retain the existing process",
+ );
+ assert(
+ (await request(api, "/search?limit=1&content_type=all")).data.length > 0,
+ "External history request succeeds after Quit",
+ );
+ const stopped = await counts();
+ await Bun.sleep(5_000);
+ assert.deepEqual(
+ await counts(),
+ stopped,
+ "No new screen, audio, or UI captures after Quit",
+ );
+ for (const route of [
+ "/audio/start",
+ "/vision/device/start",
+ "/capture/hd/start",
+ "/pipes/example/run",
+ ]) {
+ const res = await fetch(api + route, {
+ method: "POST",
+ headers,
+ body: "{}",
+ });
+ assert.equal(
+ res.status,
+ 409,
+ `${route} cannot resume capture or background work`,
+ );
+ assert.equal((await res.json()).error, "search_only");
+ }
+ await request(control, "/e2e/search-only/reopen", "POST");
+ await until(
+ async () => (await state()).webviews.includes("home"),
+ "Reopen shows Home",
+ );
+ const reopened = await state();
+ assert.equal(reopened.pid, initial.pid);
+ assert(
+ !reopened.capture_running && !reopened.capture_intended,
+ "Reopen must leave capture paused",
+ );
+ assert(
+ (await request(control, "/e2e/search-only/resume", "POST")).resumed,
+ "Explicit resume works",
+ );
+ await until(
+ async () => (await state()).capture_running,
+ "Recording resumes explicitly",
+ );
+}
+
+await request(control, "/e2e/search-only/quit", "POST");
+await until(async () => {
+ const s = await state();
+ return s.search_only && !s.entering && !s.capture_running;
+}, "Quit before updater relaunch");
+const beforeRestart = await historySnapshot();
+await request(control, "/e2e/search-only/restart", "POST");
+await until(async () => {
+ try {
+ const s = await state();
+ return (
+ s.pid !== initial.pid &&
+ s.search_only &&
+ !s.capture_running &&
+ !s.capture_intended &&
+ s.webviews.length === 0
+ );
+ } catch {
+ return false;
+ }
+}, "Updater relaunch preserves hidden UI and stopped capture");
+await until(async () => {
+ try {
+ return (
+ (await request(api, "/search?limit=1&content_type=all")).data.length > 0
+ );
+ } catch {
+ return false;
+ }
+}, "Search returns after updater relaunch");
+assert.deepEqual(
+ await historySnapshot(),
+ beforeRestart,
+ "Relaunch creates no captures",
+);
+console.log(
+ "PASS: two Quit/search/reopen/resume cycles, same PID, stable capture counts, blocked mutations, updater relaunch restores search with recording paused",
+);
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 0aa50fe15..c9324bfd2 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -862,6 +862,7 @@ let DEFAULT_SETTINGS: Settings = {
hdRecordingIntervalMs: 100,
headless: false,
headlessRecordOnly: false,
+ keepSearchAvailableAfterQuit: true,
fontSize: "16px",
};
diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
index 00c763a73..e003df500 100644
--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -4415,7 +4415,11 @@ headless?: boolean;
* When true, headless mode skips scheduled pipe runs so only recording
* and the local server continue in the background.
*/
-headlessRecordOnly?: boolean }
+headlessRecordOnly?: boolean;
+/**
+ * Quit stops capture and closes the UI while the existing process serves history.
+ */
+keepSearchAvailableAfterQuit?: boolean }
export type ShowRewindWindow = "Main" | { Home: { page: string | null } } | { Search: { query: string | null } } | "Onboarding" | "Chat" | "PermissionRecovery"
export type StartExportRecordingResponse = { jobId: string }
export type StorageMigrationActivity = { root: string | null; busy: boolean; recovering: boolean; message: string; error: string | null; elapsed_seconds: number; completed_records: number | null; total_records: number | null; bytes_saved: number | null; available_bytes: number | null; completed: boolean }
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index d3fc895e8..f91dc2097 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -11522,6 +11522,7 @@ dependencies = [
"screenpipe-cpu-features",
"screenpipe-events",
"screenpipe-fs",
+ "screenpipe-resource",
"screenpipe-secrets",
"screenpipe-sync",
"screenpipe-vault",
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/activity_history.rs b/apps/screenpipe-app-tauri/src-tauri/src/activity_history.rs
index 49edfd1ea..404201f40 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/activity_history.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/activity_history.rs
@@ -1892,6 +1892,9 @@ pub fn start(app: AppHandle) {
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tick.tick().await;
+ if crate::search_only::is_active() {
+ continue;
+ }
let Ok(Some(settings)) = SettingsStore::get(&app) else {
continue;
};
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 bf83c9733..31314ccc7 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/capture_session.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/capture_session.rs
@@ -348,8 +348,16 @@ impl CaptureSession {
/// 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) {
+ pub async fn stop(self) {
+ if let Err(error) = self.stop_checked().await {
+ warn!("Capture shutdown incomplete: {error}");
+ }
+ }
+
+ /// Quit-to-search must report failures before claiming capture is stopped.
+ pub async fn stop_checked(mut self) -> Result<(), String> {
info!("Stopping capture session");
+ let mut failures = Vec::new();
// Signal UI recorder to stop
if let Some(ref ui_handle) = self.ui_recorder_handle {
@@ -363,6 +371,7 @@ impl CaptureSession {
if !self.audio_disabled {
if let Err(e) = self.audio_manager.stop().await {
warn!("Error stopping audio manager: {:?}", e);
+ failures.push(format!("audio_stop: {e}"));
}
}
@@ -374,9 +383,10 @@ impl CaptureSession {
info!("Waiting for VisionManager shutdown...");
match tokio::time::timeout(Duration::from_secs(10), &mut vision_task).await {
Ok(Ok(())) => info!("VisionManager shutdown finished cleanly"),
- Ok(Err(e)) => warn!("VisionManager shutdown task failed: {}", e),
+ Ok(Err(e)) => failures.push(format!("vision_stop: {e}")),
Err(_) => {
warn!("VisionManager shutdown did not finish within 10s; aborting task");
+ failures.push("vision_stop_timeout".into());
vision_task.abort();
let _ = vision_task.await;
}
@@ -387,23 +397,30 @@ impl CaptureSession {
handle.store(Arc::new(None));
}
- invalidate_macos_screen_streams("capture session stop").await;
+ if let Err(error) = invalidate_macos_screen_streams("capture session stop").await {
+ failures.push(error);
+ }
// Wait for UI recorder tasks to finish
if let Some(ui_handle) = self.ui_recorder_handle.take() {
info!("Waiting for UI recorder tasks to finish...");
match tokio::time::timeout(Duration::from_secs(5), ui_handle.join()).await {
Ok(()) => info!("UI recorder tasks finished cleanly"),
- Err(_) => warn!("UI recorder tasks did not finish within 5s"),
+ Err(_) => failures.push("ui_recorder_stop_timeout".into()),
}
}
info!("Capture session stopped");
+ if failures.is_empty() {
+ Ok(())
+ } else {
+ Err(failures.join("; "))
+ }
}
}
#[cfg(target_os = "macos")]
-async fn invalidate_macos_screen_streams(reason: &str) {
+async fn invalidate_macos_screen_streams(reason: &str) -> Result<(), String> {
info!("Invalidating macOS ScreenCaptureKit screenshot streams ({reason})");
let result = tokio::time::timeout(
Duration::from_secs(5),
@@ -413,17 +430,18 @@ async fn invalidate_macos_screen_streams(reason: &str) {
)
.await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
match result {
- Ok(Ok(())) => info!("macOS ScreenCaptureKit screenshot streams invalidated"),
- Ok(Err(e)) => warn!("macOS ScreenCaptureKit invalidation task failed: {}", e),
- Err(_) => warn!("macOS ScreenCaptureKit stream invalidation timed out after 5s"),
+ Ok(Ok(())) => Ok(()),
+ Ok(Err(e)) => Err(format!("screen_stream_invalidation: {e}")),
+ Err(_) => Err("screen_stream_invalidation_timeout".into()),
}
-
- tokio::time::sleep(Duration::from_millis(500)).await;
}
#[cfg(not(target_os = "macos"))]
-async fn invalidate_macos_screen_streams(_reason: &str) {}
+async fn invalidate_macos_screen_streams(_reason: &str) -> Result<(), String> {
+ Ok(())
+}
fn log_capture_transcription_config(config: &RecordingConfig, options: &AudioManagerOptions) {
let deepgram_diag = match &config.deepgram_config {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/data_sync.rs b/apps/screenpipe-app-tauri/src-tauri/src/data_sync.rs
index a5484f542..53d9c86bd 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/data_sync.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/data_sync.rs
@@ -792,6 +792,9 @@ mod imp {
};
let mut cursor = Cursor::load(&config.cursor_path);
loop {
+ if crate::search_only::is_active() {
+ return;
+ }
match run_page(app, &config, &mut cursor, local, http).await {
Ok(true) => continue,
Ok(false) => {
@@ -816,7 +819,9 @@ mod imp {
.expect("data sync ingest client builds");
tokio::time::sleep(STARTUP_DELAY).await;
loop {
- sync_once(&app, &local, &http).await;
+ if !crate::search_only::is_active() {
+ sync_once(&app, &local, &http).await;
+ }
tokio::time::sleep(SYNC_INTERVAL).await;
}
});
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/enterprise/sync.rs b/apps/screenpipe-app-tauri/src-tauri/src/enterprise/sync.rs
index 0d4d1f896..61c05c6f8 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/enterprise/sync.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/enterprise/sync.rs
@@ -1288,6 +1288,9 @@ pub async fn run_sync_burst(
let mut include_snapshot = true;
loop {
+ if crate::search_only::is_active() {
+ break;
+ }
let page = run_one_sync_inner(cfg, cursor, local, http, include_snapshot, None).await?;
include_snapshot = false;
let more_pending = page.may_have_more();
@@ -2067,6 +2070,14 @@ pub async fn run(
));
loop {
+ // The independent native policy watcher and support-log poller remain
+ // available while optional data uploads are suspended.
+ if crate::search_only::is_active() {
+ if sleep_or_shutdown(SYNC_INTERVAL, &mut shutdown).await {
+ break;
+ }
+ continue;
+ }
// Re-resolve before touching local telemetry. Auth rejection recovers
// and reruns resolution before any local read; other failures preserve
// the last safe mode.
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/headless.rs b/apps/screenpipe-app-tauri/src-tauri/src/headless.rs
index d79761e22..eb903eba1 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/headless.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/headless.rs
@@ -39,6 +39,9 @@ fn preserve_window_during_dormancy(label: &str, onboarding_completed: bool) -> b
/// restore shortcuts when the enterprise policy was the reason UI was dormant.
/// Returns true when the app transitioned back to an interactive UI state.
pub fn set_enterprise_hidden(app: &AppHandle, hidden: bool) -> bool {
+ if crate::search_only::is_active() {
+ return false;
+ }
if hidden {
initialize(true, true);
return false;
@@ -94,6 +97,9 @@ pub fn should_suppress_pipe_runs(dormant: bool, record_only: bool) -> bool {
}
pub fn scheduled_pipe_skip_reason() -> Option<String> {
+ if crate::search_only::is_active() {
+ return Some("Screenpipe is serving saved history after Quit".into());
+ }
should_suppress_pipe_runs(
UI_DORMANT.load(Ordering::SeqCst),
RECORD_ONLY.load(Ordering::SeqCst),
@@ -105,7 +111,37 @@ pub fn scheduled_pipe_skip_reason() -> Option<String> {
/// window synchronously from its own CloseRequested callback can re-enter tao's
/// event dispatcher on Windows and can invalidate an NSPanel callback on macOS.
pub fn request_enter(app: AppHandle) {
- let record_only = crate::enterprise_policy::is_app_ui_hidden()
+ mark_dormant(&app);
+ tauri::async_runtime::spawn(async move {
+ if let Err(error) = enter(app).await {
+ warn!("headless: webview teardown failed: {error}");
+ }
+ });
+}
+
+/// Await teardown before allowing a search-only session to reopen its windows.
+pub async fn enter(app: AppHandle) -> Result<(), String> {
+ mark_dormant(&app);
+
+ let _ = crate::commands::hide_shortcut_reminder(app.clone()).await;
+ tokio::task::yield_now().await;
+ let app_for_main = app.clone();
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let result = match app.run_on_main_thread(move || {
+ let _ = tx.send(enter_on_main_thread(&app_for_main));
+ }) {
+ Ok(()) => rx.await.map_err(|e| e.to_string()).and_then(|r| r),
+ Err(error) => Err(error.to_string()),
+ };
+ if result.is_err() {
+ UI_DORMANT.store(false, Ordering::SeqCst);
+ }
+ result
+}
+
+fn mark_dormant(app: &AppHandle) {
+ let record_only = crate::search_only::is_active()
+ || crate::enterprise_policy::is_app_ui_hidden()
|| crate::store::SettingsStore::get(&app)
.ok()
.flatten()
@@ -116,19 +152,9 @@ pub fn request_enter(app: AppHandle) {
// Block shortcuts and other non-tray window entry points immediately, while
// the actual webview destruction is deferred off the close callback.
UI_DORMANT.store(true, Ordering::SeqCst);
-
- tauri::async_runtime::spawn(async move {
- let _ = crate::commands::hide_shortcut_reminder(app.clone()).await;
- tokio::task::yield_now().await;
- let app_for_main = app.clone();
- if let Err(error) = app.run_on_main_thread(move || enter_on_main_thread(&app_for_main)) {
- UI_DORMANT.store(false, Ordering::SeqCst);
- warn!("headless: failed to schedule webview teardown: {error}");
- }
- });
}
-fn enter_on_main_thread(app: &AppHandle) {
+fn enter_on_main_thread(app: &AppHandle) -> Result<(), String> {
if let Err(error) = app.global_shortcut().unregister_all() {
warn!("headless: failed to unregister global shortcuts: {error}");
}
@@ -142,7 +168,7 @@ fn enter_on_main_thread(app: &AppHandle) {
{
UI_DORMANT.store(false, Ordering::SeqCst);
warn!("headless: native keepalive creation failed; preserving webviews: {error}");
- return;
+ return Err(error.to_string());
}
}
@@ -165,43 +191,61 @@ fn enter_on_main_thread(app: &AppHandle) {
.flatten()
.unwrap_or_default()
.is_completed;
+ // Explicit Quit closes permission/onboarding UI too. Policy-driven
+ // dormancy continues preserving those recovery surfaces.
+ let preserve = |label: &str| {
+ !crate::search_only::is_active()
+ && preserve_window_during_dormancy(label, onboarding_completed)
+ };
let mut windows: Vec<_> = app.webview_windows().into_iter().collect();
windows.sort_by_key(|(label, _)| label == "home");
for (label, window) in &windows {
- if preserve_window_during_dormancy(label, onboarding_completed) {
+ if preserve(label) {
continue;
}
let _ = window.hide();
}
let mut count = 0;
+ let mut failures = Vec::new();
for (label, window) in windows {
- if preserve_window_during_dormancy(&label, onboarding_completed) {
+ if preserve(&label) {
info!("headless: preserving incomplete onboarding webview");
continue;
}
#[cfg(target_os = "macos")]
if let Err(error) = prepare_window_for_destroy(app, &label, &window) {
warn!("headless: preserving webview '{label}': {error}");
+ failures.push(format!("{label}: {error}"));
continue;
}
if let Err(error) = window.destroy() {
warn!("headless: failed to destroy webview '{label}': {error}");
+ failures.push(format!("{label}: {error}"));
} else {
count += 1;
}
}
- info!("headless: UI dormant; destroyed {count} webview(s), tray and recording remain active");
+ info!(
+ "headless: UI dormant; destroyed {count} webview(s), search_only={}",
+ crate::search_only::is_active()
+ );
+ if failures.is_empty() {
+ Ok(())
+ } else {
+ Err(failures.join("; "))
+ }
}
/// Tray UI actions are the sole wake path while dormant.
pub fn wake_from_tray(app: &AppHandle) -> bool {
// Enterprise hidden-UI mode has no wake path; the UI stays dormant.
- if crate::enterprise_policy::is_app_ui_hidden() {
+ if crate::enterprise_policy::is_app_ui_hidden() || crate::search_only::is_entering() {
return false;
}
+ crate::search_only::wake();
if !UI_DORMANT.swap(false, Ordering::SeqCst) {
return false;
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index fbef3bbc5..8ab2abbca 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -125,6 +125,7 @@ mod provider_automations;
mod recording;
mod remote_support_logs;
mod remote_sync_commands;
+mod search_only;
mod secrets;
mod server;
mod server_core;
@@ -1071,6 +1072,9 @@ async fn main() {
// during setup; normal subsequent launches retain Home behavior.
let login_duplicate = should_suppress_startup_handoff(&args_clone);
if !crate::enterprise_policy::is_app_ui_hidden() && !login_duplicate {
+ if crate::search_only::is_active() {
+ crate::headless::wake_from_tray(&app_for_closure);
+ }
match deep_link::handoff_window(deep_link_url.as_deref()) {
deep_link::HandoffWindow::AppEntry => {
let _ = ShowRewindWindow::Onboarding.show(&app_for_closure);
@@ -1386,6 +1390,7 @@ async fn main() {
);
std::io::Error::other(e)
})?;
+ let search_only_startup = crate::search_only::initialize();
#[cfg(feature = "e2e")]
e2e::seeds::apply_settings(app.handle(), &mut store);
@@ -1661,14 +1666,14 @@ async fn main() {
// Enterprise hidden-UI deployments always run headless with the
// recorder only, regardless of user settings or onboarding state.
- let headless_startup = app_ui_hidden
+ let headless_startup = search_only_startup || app_ui_hidden
|| crate::headless::should_start_dormant(
store.headless,
onboarding_store.is_completed,
);
crate::headless::initialize(
headless_startup,
- app_ui_hidden || (store.headless && store.headless_record_only),
+ search_only_startup || app_ui_hidden || (store.headless && store.headless_record_only),
);
if from_autostart {
info!("launched from OS startup enrollment; starting in background");
@@ -1780,7 +1785,7 @@ async fn main() {
// Uses retry loop because CGPreflightScreenCaptureAccess can return false
// transiently on startup before TCC fully initializes.
#[cfg(target_os = "macos")]
- if onboarding_store.is_completed || app_ui_hidden {
+ if !search_only_startup && (onboarding_store.is_completed || app_ui_hidden) {
let mut screen_ok = false;
let mut mic_ok = false;
for attempt in 0..3 {
@@ -1993,7 +1998,8 @@ async fn main() {
// `no-recording`, or by user choice in the future)
// the SCK code path is never exercised, so we can
// boot the server + HTTP API + DB without TCC.
- if !disable_vision && !permissions_check.screen_recording.permitted() {
+ if wants_recording.load(std::sync::atomic::Ordering::SeqCst)
+ && !disable_vision && !permissions_check.screen_recording.permitted() {
warn!("Screen recording permission not granted: {:?}. Server will not start.", permissions_check.screen_recording);
// Flip the recording state to a terminal Error
// value so the tray stops showing "Starting…"
@@ -2010,7 +2016,8 @@ async fn main() {
return;
}
- if !disable_audio && !permissions_check.microphone.permitted() {
+ if wants_recording.load(std::sync::atomic::Ordering::SeqCst)
+ && !disable_audio && !permissions_check.microphone.permitted() {
warn!("Microphone permission not granted: {:?}. Audio recording will not work.", permissions_check.microphone);
}
@@ -2574,6 +2581,9 @@ async fn main() {
// Defer off the event stack so run handler stays panic-free.
// Showing Onboarding is the app-entry gate: it focuses setup
// while incomplete and routes to Home once complete.
+ if crate::search_only::is_active() {
+ crate::headless::wake_from_tray(app_handle.app_handle());
+ }
if crate::enterprise_policy::is_app_ui_hidden() || crate::headless::is_dormant()
{
return;
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs b/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs
index b9b702832..e7a610522 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs
@@ -427,7 +427,7 @@ pub(crate) async fn restart_capture_on_mic_grant(app: tauri::AppHandle) {
let mut last_err: Option<String> = None;
for attempt in 1..=MAX_ATTEMPTS {
let state = app.state::<crate::recording::RecordingState>();
- match crate::recording::start_capture(state, app.clone()).await {
+ match crate::recording::restart_capture_after_permission(state, app.clone()).await {
Ok(()) => {
if attempt > 1 {
info!(
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index a539dcd08..ffbdfde7b 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -2882,6 +2882,9 @@ pub async fn pi_start_inner(
coding_workspace: Option<crate::coding_workspace::CodingWorkspaceLaunch>,
) -> Result<PiInfo, String> {
info!("pi_start stage=requested session='{}'", session_id);
+ if crate::search_only::is_active() {
+ return Err("Open Screenpipe before starting an agent.".into());
+ }
let assistant_context = if session_id.starts_with("__title:workflow-assistant-") {
Some(crate::workflows_runtime::assistant_agent_context(&app).await?)
} else { None };
@@ -3067,6 +3070,9 @@ pub async fn pi_start_inner(
info!("pi_start stage=waiting_for_pool session='{}'", sid);
let mut pool = state.0.lock().await;
+ if crate::search_only::is_active() {
+ return Err("Open Screenpipe before starting an agent.".into());
+ }
info!("pi_start stage=pool_acquired session='{}'", sid);
// Stop existing instance for this session if running
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/process_exit.rs b/apps/screenpipe-app-tauri/src-tauri/src/process_exit.rs
index 2abd90874..0f12ac12b 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/process_exit.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/process_exit.rs
@@ -361,6 +361,20 @@ pub fn force_app_relaunch(app: AppHandle, status: i32) -> ! {
/// Request a relaunch from async/UI code while allowing IPC replies and logs to
/// flush briefly before the current process is force-exited.
pub fn request_app_relaunch(app: AppHandle, reason: &'static str, delay: Duration) {
+ if let Err(error) = crate::search_only::prepare_restart() {
+ warn!("relaunch deferred: could not preserve recording mode: {error}");
+ return;
+ }
+ request_prepared_app_relaunch(app, reason, delay);
+}
+
+/// Updater callers already persisted the session before draining the server.
+/// Do not introduce another fallible write after committing the installer.
+pub(crate) fn request_prepared_app_relaunch(
+ app: AppHandle,
+ reason: &'static str,
+ delay: Duration,
+) {
QUIT_REQUESTED.store(true, Ordering::SeqCst);
std::thread::spawn(move || {
@@ -579,7 +593,7 @@ pub fn confirm_and_request_app_quit(app: AppHandle) {
.unwrap_or(false);
if !recording_active {
info!("Quit requested with no active recording — skipping confirmation");
- request_app_quit(app);
+ request_user_quit(app);
return;
}
@@ -695,7 +709,7 @@ fn show_quit_alert(app: &AppHandle, show_minimize: bool, message: &str) {
QUIT_CONFIRM_SHOWING.store(false, Ordering::SeqCst);
match response {
- FIRST_BUTTON => request_app_quit(app.clone()),
+ FIRST_BUTTON => request_user_quit(app.clone()),
SECOND_BUTTON if show_minimize => {
info!("Quit dialog: minimizing to tray instead");
hide_app_to_tray(app);
@@ -707,7 +721,17 @@ fn show_quit_alert(app: &AppHandle, show_minimize: bool, message: &str) {
#[cfg(not(target_os = "macos"))]
pub fn confirm_and_request_app_quit(app: AppHandle) {
- request_app_quit(app);
+ request_user_quit(app);
+}
+
+/// User Quit may retain search. Programmatic exit, OS logout, and updater
+/// handoffs continue through the existing full-exit path.
+pub(crate) fn request_user_quit(app: AppHandle) {
+ if crate::search_only::keep_after_quit(&app) {
+ crate::search_only::request_enter(app);
+ } else {
+ request_app_quit(app);
+ }
}
/// Shared quit entry point for tray menu, app menu (Cmd+Q), etc.
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
index a2f205fd8..7f004e4e5 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
@@ -387,7 +387,10 @@ impl RecordingState {
// An explicit start owns the lifecycle now; an explicit stop must not
// be undone by a later background account refresh.
self.deferred_account_start.cancel();
- self.wants_recording.store(on, Ordering::SeqCst);
+ self.wants_recording.store(
+ on && !crate::search_only::capture_paused() && !crate::search_only::is_active(),
+ Ordering::SeqCst,
+ );
}
/// Whether capture is currently intended to be running.
@@ -558,7 +561,7 @@ pub async fn stop_capture(
let mut capture_guard = state.capture.lock().await;
if let Some(session) = capture_guard.take() {
- session.stop().await;
+ session.stop_checked().await?;
info!("Capture session stopped");
} else {
debug!("No capture session running");
@@ -768,6 +771,22 @@ async fn probe_server_health(health_url: &str, api_key: Option<&str>) -> bool {
pub async fn start_capture(
state: State<'_, RecordingState>,
app: tauri::AppHandle,
+) -> Result<(), String> {
+ start_capture_inner(state, app, true).await
+}
+
+#[cfg(target_os = "macos")]
+pub(crate) async fn restart_capture_after_permission(
+ state: State<'_, RecordingState>,
+ app: tauri::AppHandle,
+) -> Result<(), String> {
+ start_capture_inner(state, app, false).await
+}
+
+async fn start_capture_inner(
+ state: State<'_, RecordingState>,
+ app: tauri::AppHandle,
+ explicit_resume: bool,
) -> Result<(), String> {
if crate::storage_migration::is_running(&app) {
return Err("Storage migration is running. Recording resumes when it finishes.".into());
@@ -776,6 +795,12 @@ pub async fn start_capture(
let store = SettingsStore::get(&app).ok().flatten().unwrap_or_default();
require_recording_access(&app, &store)?;
+ if explicit_resume {
+ crate::search_only::resume_capture()?;
+ } else if crate::search_only::capture_paused() {
+ return Err("Recording was stopped by Quit; explicit resume is required.".into());
+ }
+
// Capture is now intended to run (tray/shortcut start, mic-grant reinit, …)
// — record it so the health watchdog will respawn a crashed engine instead
// of treating the absence of capture as a deliberate stop.
@@ -790,6 +815,9 @@ pub async fn start_capture(
// they observe the installed session and return success only after capture
// is actually running, so their webviews cannot toast success prematurely.
let mut capture_guard = state.capture.lock().await;
+ if !state.capture_intended() {
+ return Err("Recording was stopped while capture startup was pending.".into());
+ }
if capture_guard.is_some() {
info!("Capture session already running");
return Ok(());
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/search_only.rs b/apps/screenpipe-app-tauri/src-tauri/src/search_only.rs
new file mode 100644
index 000000000..7bb2198d0
--- /dev/null
+++ b/apps/screenpipe-app-tauri/src-tauri/src/search_only.rs
@@ -0,0 +1,360 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+//! Quit-to-search uses the current process, API, and database owner.
+
+use std::io::Write;
+use std::path::Path;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+use tauri::{AppHandle, Manager};
+use tracing::{info, warn};
+
+static CAPTURE_PAUSED: AtomicBool = AtomicBool::new(false);
+static ENTERING: AtomicBool = AtomicBool::new(false);
+static SESSION_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+const SESSION_FILE: &str = "search-session.json";
+
+#[derive(Default, Serialize, Deserialize)]
+#[serde(default)]
+struct Session {
+ capture_paused: bool,
+ resume_search_only: bool,
+}
+
+pub fn is_active() -> bool {
+ screenpipe_core::background_work::is_suspended()
+}
+
+pub fn capture_paused() -> bool {
+ CAPTURE_PAUSED.load(Ordering::SeqCst)
+}
+
+pub fn is_entering() -> bool {
+ ENTERING.load(Ordering::SeqCst)
+}
+
+fn persist_at(root: &Path, session: &Session) -> Result<(), String> {
+ std::fs::create_dir_all(root).map_err(|e| e.to_string())?;
+ let mut file = tempfile::NamedTempFile::new_in(root).map_err(|e| e.to_string())?;
+ serde_json::to_writer(&mut file, session).map_err(|e| e.to_string())?;
+ file.flush().map_err(|e| e.to_string())?;
+ file.as_file().sync_all().map_err(|e| e.to_string())?;
+ file.persist(root.join(SESSION_FILE))
+ .map_err(|e| e.to_string())?;
+ #[cfg(unix)]
+ std::fs::File::open(root)
+ .and_then(|dir| dir.sync_all())
+ .map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+fn load_at(root: &Path) -> Result<Session, String> {
+ match std::fs::read(root.join(SESSION_FILE)) {
+ Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| e.to_string()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Session::default()),
+ Err(e) => Err(e.to_string()),
+ }
+}
+
+fn persist(resume_search_only: bool) -> Result<(), String> {
+ let _guard = SESSION_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ persist_at(
+ &crate::config::app_data_dir(),
+ &Session {
+ capture_paused: capture_paused(),
+ resume_search_only,
+ },
+ )
+}
+
+fn diagnostic(event: &str, detail: &str) {
+ crate::recording::recovery_log::append(&crate::config::app_data_dir(), event, detail);
+}
+
+/// Restore stopped capture before any native startup or UI callback can run.
+/// Only an updater/relaunch handoff restores hidden UI; a later manual launch
+/// after a normal process exit opens the UI with recording still stopped.
+pub fn initialize() -> bool {
+ let session = load_at(&crate::config::app_data_dir()).unwrap_or_else(|error| {
+ diagnostic(
+ "search_session_read_failed",
+ &format!("cause={error}; outcome=capture_paused"),
+ );
+ Session {
+ capture_paused: true,
+ resume_search_only: false,
+ }
+ });
+ CAPTURE_PAUSED.store(session.capture_paused, Ordering::SeqCst);
+ let background = session.capture_paused && session.resume_search_only;
+ screenpipe_core::background_work::set_suspended(background);
+ if let Err(error) = persist(false) {
+ diagnostic(
+ "search_session_restore_failed",
+ &format!("cause={error}; outcome=capture_paused"),
+ );
+ CAPTURE_PAUSED.store(true, Ordering::SeqCst);
+ }
+ background
+}
+
+pub fn keep_after_quit(app: &AppHandle) -> bool {
+ crate::store::SettingsStore::get(app)
+ .ok()
+ .flatten()
+ .map(|s| s.keep_search_available_after_quit)
+ .unwrap_or(true)
+}
+
+/// Called only by explicit recording controls, before publishing capture intent.
+pub fn resume_capture() -> Result<(), String> {
+ let _guard = SESSION_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ if ENTERING.load(Ordering::SeqCst) || is_active() {
+ return Err("Open Screenpipe before resuming recording.".into());
+ }
+ persist_at(&crate::config::app_data_dir(), &Session::default())?;
+ CAPTURE_PAUSED.store(false, Ordering::SeqCst);
+ Ok(())
+}
+
+/// Opening a window restores ordinary background work, never capture intent.
+pub fn wake() -> bool {
+ if ENTERING.load(Ordering::SeqCst) || !is_active() {
+ return false;
+ }
+ screenpipe_core::background_work::set_suspended(false);
+ info!("search-only: UI reopened; recording remains paused");
+ true
+}
+
+pub fn prepare_restart() -> Result<(), String> {
+ persist(is_active()).map_err(|error| {
+ diagnostic(
+ "search_restart_persist_failed",
+ &format!("cause={error}; outcome=restart_deferred"),
+ );
+ error
+ })
+}
+
+pub fn cancel_restart() {
+ if let Err(error) = persist(false) {
+ diagnostic("search_restart_cancel_failed", &error);
+ }
+}
+
+/// A deferred installer may already have drained the API. The ordinary start
+/// path joins pending shutdown before opening a database; the paused intent
+/// above prevents this recovery from starting capture.
+pub fn recover_after_failed_update(app: AppHandle) {
+ if !is_active() {
+ return;
+ }
+ tauri::async_runtime::spawn(async move {
+ let result = crate::recording::spawn_screenpipe(
+ app.state::<crate::recording::RecordingState>(),
+ app.clone(),
+ None,
+ )
+ .await;
+ match result {
+ Ok(()) => diagnostic(
+ "search_update_recovered",
+ "outcome=search_restored; capture=paused",
+ ),
+ Err(error) => diagnostic(
+ "search_update_recovery_failed",
+ &format!("cause={error}; outcome=search_unavailable; capture=paused"),
+ ),
+ }
+ });
+}
+
+pub fn request_enter(app: AppHandle) {
+ let guard = SESSION_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ if ENTERING.swap(true, Ordering::SeqCst) {
+ return;
+ }
+ CAPTURE_PAUSED.store(true, Ordering::SeqCst);
+ screenpipe_core::background_work::set_suspended(true);
+ if let Some(state) = app.try_state::<crate::recording::RecordingState>() {
+ state.set_capture_intent(false);
+ }
+ drop(guard);
+
+ // Own the stop future in a task: a deadline must not drop capture midway
+ // through shutdown. On failure, the existing full-exit path owns cleanup.
+ tauri::async_runtime::spawn(async move {
+ let app_for_stop = app.clone();
+ let mut stop = tauri::async_runtime::spawn(async move {
+ let saved = persist(false);
+ // Requests admitted before Quit may still be starting a device.
+ // Finish those before stopping capture; later mutations are denied.
+ screenpipe_engine::search_only::finish_in_flight_mutations().await;
+ crate::recording::stop_capture(
+ app_for_stop.state::<crate::recording::RecordingState>(),
+ app_for_stop.clone(),
+ )
+ .await?;
+ saved?;
+ let pipes = app_for_stop
+ .state::<crate::recording::RecordingState>()
+ .server
+ .lock()
+ .await
+ .as_ref()
+ .map(|server| server.pipe_manager.clone());
+ if let Some(pipes) = pipes {
+ let pipes = pipes.lock().await;
+ for pipe in pipes
+ .list_pipes()
+ .await
+ .into_iter()
+ .filter(|pipe| pipe.is_running)
+ {
+ pipes
+ .stop_pipe(&pipe.config.name)
+ .await
+ .map_err(|e| e.to_string())?;
+ }
+ tokio::time::timeout(Duration::from_secs(10), async {
+ while pipes.list_pipes().await.iter().any(|pipe| pipe.is_running) {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ })
+ .await
+ .map_err(|_| "workflow_stop_timeout".to_string())?;
+ } else {
+ return Err("The local history server is unavailable.".into());
+ }
+ if let Some(pi) = app_for_stop.try_state::<crate::pi::PiState>() {
+ crate::pi::cleanup_pi(&pi).await;
+ }
+ crate::headless::enter(app_for_stop).await?;
+ Ok::<(), String>(())
+ });
+ let result = match tokio::time::timeout(Duration::from_secs(30), &mut stop).await {
+ Ok(result) => result,
+ Err(_) => {
+ diagnostic(
+ "search_only_stop_slow",
+ "cause=quit_transition_timeout; outcome=full_exit",
+ );
+ crate::process_exit::request_app_quit(app);
+ return;
+ }
+ };
+ match result {
+ Ok(Ok(())) => {
+ diagnostic(
+ "search_only_ready",
+ "outcome=capture_stopped; api=retained; ui=closed",
+ );
+ #[cfg(target_os = "macos")]
+ if crate::staged_update::staged_version().is_some() {
+ if let Err(error) = crate::updates::restart_for_update(app.clone(), None).await
+ {
+ diagnostic(
+ "search_only_update_failed",
+ &format!("cause={error}; outcome=update_deferred"),
+ );
+ }
+ }
+ }
+ failure => {
+ let error = format!("{failure:?}");
+ warn!("search-only transition failed: {error}");
+ diagnostic(
+ "search_only_failed",
+ &format!("cause={error}; outcome=full_exit"),
+ );
+ // Quit must stop capture even if retaining search fails.
+ crate::process_exit::request_app_quit(app);
+ return;
+ }
+ }
+ ENTERING.store(false, Ordering::SeqCst);
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn restart_snapshot_keeps_capture_off_and_is_consumed_without_clearing_pause() {
+ let dir = tempfile::tempdir().unwrap();
+ assert!(!load_at(dir.path()).unwrap().capture_paused);
+ persist_at(
+ dir.path(),
+ &Session {
+ capture_paused: true,
+ resume_search_only: true,
+ },
+ )
+ .unwrap();
+ let restored = load_at(dir.path()).unwrap();
+ assert!(restored.capture_paused && restored.resume_search_only);
+ persist_at(
+ dir.path(),
+ &Session {
+ resume_search_only: false,
+ ..restored
+ },
+ )
+ .unwrap();
+ let manual = load_at(dir.path()).unwrap();
+ assert!(manual.capture_paused);
+ assert!(!manual.resume_search_only);
+ persist_at(dir.path(), &Session::default()).unwrap();
+ assert!(!load_at(dir.path()).unwrap().capture_paused);
+ }
+
+ #[test]
+ fn damaged_session_is_an_error_not_permission_to_record() {
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(dir.path().join(SESSION_FILE), b"{interrupted").unwrap();
+ assert!(load_at(dir.path()).is_err());
+ }
+
+ #[tokio::test]
+ async fn quit_failure_reaches_collected_redacted_support_report_after_restart() {
+ let dir = tempfile::tempdir().unwrap();
+ // Exercise a real persistence failure, not an invented log message.
+ std::fs::create_dir(dir.path().join(SESSION_FILE)).unwrap();
+ let cause = persist_at(
+ dir.path(),
+ &Session {
+ capture_paused: true,
+ resume_search_only: true,
+ },
+ )
+ .unwrap_err();
+ crate::recording::recovery_log::append(
+ dir.path(),
+ "search_restart_persist_failed",
+ &format!("cause={cause}; outcome=restart_deferred; [email protected]"),
+ );
+ // Ordinary app log rotation/restart must not discard the lifecycle cause.
+ for day in 1..=7 {
+ std::fs::write(
+ dir.path()
+ .join(format!("screenpipe-app.2026-09-{day:02}.log")),
+ "app restarted\n",
+ )
+ .unwrap();
+ }
+ assert!(load_at(dir.path()).is_err());
+ let report =
+ crate::diagnostic_logs::collect_redacted_from_dirs(&[dir.path().to_path_buf()])
+ .await
+ .unwrap();
+ assert!(report.contains("search_restart_persist_failed"));
+ assert!(report.contains("restart_deferred"));
+ assert!(report.contains(&cause));
+ assert!(!report.contains("[email protected]"));
+ }
+}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server.rs b/apps/screenpipe-app-tauri/src-tauri/src/server.rs
index 457604eb1..64a3ec6a6 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/server.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/server.rs
@@ -172,6 +172,9 @@ async fn handle_focus(
payload.deep_link_url.as_deref(),
payload.target.as_deref(),
);
+ if !startup_handoff && crate::search_only::is_active() {
+ crate::headless::wake_from_tray(&state.app_handle);
+ }
if startup_handoff {
info!("autostart: ignored duplicate OS startup focus handoff");
} else if payload.target.as_deref() == Some("browser_pairing") {
@@ -367,6 +370,11 @@ pub async fn run_server(app_handle: tauri::AppHandle, port: u16) {
// localhost instead. Compiled out of every shipped build.
#[cfg(feature = "e2e")]
let app = app
+ .route("/e2e/search-only/state", axum::routing::get(e2e_search_only_state))
+ .route("/e2e/search-only/quit", axum::routing::post(e2e_search_only_quit))
+ .route("/e2e/search-only/reopen", axum::routing::post(e2e_search_only_reopen))
+ .route("/e2e/search-only/resume", axum::routing::post(e2e_search_only_resume))
+ .route("/e2e/search-only/restart", axum::routing::post(e2e_search_only_restart))
.route("/e2e/updates/state", axum::routing::get(e2e_updates_state))
.route("/e2e/updates/click", axum::routing::post(e2e_updates_click))
.route(
@@ -653,6 +661,53 @@ async fn list_installed_apps_handler(State(_): State<ServerState>) -> impl IntoR
Json(apps)
}
+/// Content-free lifecycle state for the disposable E2E app.
+#[cfg(feature = "e2e")]
+async fn e2e_search_only_state(State(state): State<ServerState>) -> impl IntoResponse {
+ use tauri::Manager;
+ let app = &state.app_handle;
+ let recording = app.state::<crate::recording::RecordingState>();
+ Json(serde_json::json!({
+ "pid": std::process::id(),
+ "search_only": crate::search_only::is_active(),
+ "entering": crate::search_only::is_entering(),
+ "capture_intended": recording.capture_intended(),
+ "capture_running": recording.capture.lock().await.is_some(),
+ "webviews": app.webview_windows().keys().cloned().collect::<Vec<_>>(),
+ "keep_search_after_quit": crate::search_only::keep_after_quit(app),
+ }))
+}
+
+#[cfg(feature = "e2e")]
+async fn e2e_search_only_quit(State(state): State<ServerState>) -> impl IntoResponse {
+ // The same action chosen by the native Quit confirmation's first button.
+ crate::process_exit::request_user_quit(state.app_handle);
+ Json(serde_json::json!({"accepted": true}))
+}
+
+#[cfg(feature = "e2e")]
+async fn e2e_search_only_reopen(State(state): State<ServerState>) -> impl IntoResponse {
+ let app = state.app_handle.clone();
+ let scheduled = state.app_handle.run_on_main_thread(move || {
+ crate::headless::wake_from_tray(&app);
+ let _ = (crate::window::ShowRewindWindow::Home { page: None }).show(&app);
+ });
+ Json(serde_json::json!({"accepted": scheduled.is_ok()}))
+}
+
+#[cfg(feature = "e2e")]
+async fn e2e_search_only_resume(State(state): State<ServerState>) -> impl IntoResponse {
+ use tauri::Manager;
+ let result = crate::recording::start_capture(state.app_handle.state(), state.app_handle.clone()).await;
+ Json(serde_json::json!({"resumed": result.is_ok(), "error": result.err()}))
+}
+
+#[cfg(feature = "e2e")]
+async fn e2e_search_only_restart(State(state): State<ServerState>) -> impl IntoResponse {
+ let result = crate::updates::restart_for_update(state.app_handle, Some(10)).await;
+ Json(serde_json::json!({"result": result}))
+}
+
/// Content-free updater state for the packaged e2e test: what the tray menu
/// item says, whether a staged update exists, and where boot stands. No
/// versions of anything private, no paths, no tokens.
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 ef8c5c915..b309b2cb6 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
@@ -1308,6 +1308,10 @@ impl ServerCore {
let database_error_hook = redact_database_error_hook.clone();
tokio::spawn(async move {
let policy = TextRedactionPolicy::from_labels(&labels);
+ tokio::select! {
+ _ = shutdown.notified() => return,
+ _ = screenpipe_core::background_work::wait_until_resumed() => {}
+ }
// Prefer the local ONNX text redactor (~278 MB INT8,
// sub-10 ms p50, gets CoreML on macOS / DirectML on
// Windows / CPU on Linux via the redact-onnx-* CI
@@ -1436,6 +1440,10 @@ impl ServerCore {
let labels = pii_labels.clone();
let database_error_hook = redact_database_error_hook.clone();
tokio::spawn(async move {
+ tokio::select! {
+ _ = shutdown.notified() => return,
+ _ = screenpipe_core::background_work::wait_until_resumed() => {}
+ }
match RfdetrRedactor::load_or_download(RfdetrConfig::default()).await {
Ok(detector) => {
info!(
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
index 5e18e56c4..1378b56db 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/store.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
@@ -1633,6 +1633,10 @@ pub struct SettingsStore {
/// and the local server continue in the background.
#[serde(rename = "headlessRecordOnly", default)]
pub headless_record_only: bool,
+
+ /// Quit stops capture and closes the UI while the existing process serves history.
+ #[serde(rename = "keepSearchAvailableAfterQuit", default = "default_true")]
+ pub keep_search_available_after_quit: bool,
}
fn generate_device_id() -> String {
@@ -2183,6 +2187,7 @@ Rules:
minimize_to_tray_on_close: false,
headless: false,
headless_record_only: false,
+ keep_search_available_after_quit: true,
extra: remote_control,
}
}
@@ -3574,6 +3579,19 @@ mod tests {
assert!(settings.auto_update);
}
+ #[test]
+ fn search_after_quit_defaults_on_and_preserves_explicit_opt_out() {
+ assert!(SettingsStore::default().keep_search_available_after_quit);
+ let missing: SettingsStore = serde_json::from_value(json!({"aiPresets": []})).unwrap();
+ assert!(missing.keep_search_available_after_quit);
+ let opted_out: SettingsStore = serde_json::from_value(json!({
+ "aiPresets": [], "keepSearchAvailableAfterQuit": false
+ })).unwrap();
+ assert!(!opted_out.keep_search_available_after_quit);
+ let round_trip: SettingsStore = serde_json::from_value(serde_json::to_value(opted_out).unwrap()).unwrap();
+ assert!(!round_trip.keep_search_available_after_quit);
+ }
+
#[test]
fn headless_record_only_defaults_off_and_respects_saved_value() {
assert!(!SettingsStore::default().headless_record_only);
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/suggestions.rs b/apps/screenpipe-app-tauri/src-tauri/src/suggestions.rs
index 1b0675e7c..7799b0fe8 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/suggestions.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/suggestions.rs
@@ -214,6 +214,9 @@ pub async fn auto_start_scheduler(app: AppHandle, state: &SuggestionsState) {
}
// Read current enhanced AI config (picks up setting changes each cycle)
+ if crate::search_only::is_active() {
+ continue;
+ }
let enhanced = enhanced_ai.lock().await.clone();
// Fetch activity & generate suggestions
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
index 4a63b384f..be70ef99a 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
@@ -395,6 +395,9 @@ async fn run_tray_recording_action(
let state = app.state::<RecordingState>();
match action {
TrayRecordingAction::Start => {
+ if crate::search_only::is_active() {
+ crate::headless::wake_from_tray(app);
+ }
let data_dir = crate::db_recovery_notifications::effective_recovery_data_dir(app)?;
let database_path = data_dir.join("db.sqlite");
match tray_start_route_with(|| database_has_confirmed_damage(&database_path))? {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/updates.rs b/apps/screenpipe-app-tauri/src-tauri/src/updates.rs
index 4b5e5d5a4..c7fc36c66 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/updates.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/updates.rs
@@ -70,7 +70,12 @@ fn configured_updater(app: &tauri::AppHandle) -> Result<tauri_plugin_updater::Up
Ok(builder.build()?)
}
-async fn stop_before_update(app: &tauri::AppHandle) {
+async fn stop_before_update(app: &tauri::AppHandle) -> Result<(), String> {
+ let search_only = crate::search_only::is_active();
+ crate::search_only::prepare_restart().map_err(|error| {
+ UPDATE_RESTART_STARTED.store(false, Ordering::SeqCst);
+ error
+ })?;
match bounded_teardown(
PRE_EXIT_TEARDOWN_TIMEOUT,
stop_screenpipe(app.state::<RecordingState>(), app.clone()),
@@ -78,12 +83,24 @@ async fn stop_before_update(app: &tauri::AppHandle) {
.await
{
TeardownOutcome::Completed => {}
+ outcome if search_only => {
+ let error = format!("search-only shutdown did not complete: {outcome:?}");
+ UPDATE_RESTART_STARTED.store(false, Ordering::SeqCst);
+ crate::search_only::cancel_restart();
+ crate::search_only::recover_after_failed_update(app.clone());
+ crate::update_diagnostics::record(
+ "search_shutdown_failed",
+ &format!("cause={error}; outcome=update_deferred"),
+ );
+ return Err(error);
+ }
TeardownOutcome::Failed(error) => warn!("update teardown failed (continuing): {error}"),
TeardownOutcome::TimedOut => warn!(
"update teardown exceeded {}s — continuing with the update",
PRE_EXIT_TEARDOWN_TIMEOUT.as_secs()
),
}
+ Ok(())
}
#[cfg(target_os = "windows")]
@@ -100,13 +117,17 @@ async fn install_windows_update(
crate::store::persist_store_before_restart(app).map_err(std::io::Error::other)?;
let recording = app.state::<RecordingState>();
let wants_recording = recording.capture_intended();
- stop_before_update(app).await;
+ stop_before_update(app)
+ .await
+ .map_err(std::io::Error::other)?;
save_pre_update_version(app, update.body.clone());
record_update_attempt(app, &update.version);
// The NSIS handoff exits this process. Keep native startup excluded until
// that exit; an install error drops the guard so startup can continue.
UPDATE_RESTART_STARTED.store(true, Ordering::SeqCst);
if let Err(error) = update.install(bytes) {
+ crate::search_only::cancel_restart();
+ crate::search_only::recover_after_failed_update(app.clone());
UPDATE_RESTART_STARTED.store(false, Ordering::SeqCst);
recording.set_capture_intent(wants_recording);
crate::update_diagnostics::record(
@@ -119,7 +140,7 @@ async fn install_windows_update(
return Err(error);
}
std::mem::forget(restart);
- crate::process_exit::request_app_relaunch(
+ crate::process_exit::request_prepared_app_relaunch(
app.clone(),
"windows update restart",
Duration::from_millis(250),
@@ -595,17 +616,20 @@ pub async fn restart_for_update(
}) {
record_update_attempt(&app, &to_version);
}
- if persistent_version.is_some() {
- request_persistent_update_for_restart()?;
- }
info!("banner restart: gate passed, shutting down for update");
- // Non-fatal AND time-bounded: a wedged capture/audio teardown must not
- // stall the relaunch (2026-06-26 MacBook Air: VisionManager hung 10s →
- // ~57s frozen before the update applied). server_core.rs retries the
- // port bind if the next boot races teardown.
- stop_before_update(&app).await;
+ // Recording-mode recovery still permits a bounded teardown timeout.
+ // Search-only mode defers the update if the database owner cannot drain.
+ stop_before_update(&app).await?;
+ if persistent_version.is_some() {
+ if let Err(error) = request_persistent_update_for_restart() {
+ UPDATE_RESTART_STARTED.store(false, Ordering::SeqCst);
+ crate::search_only::cancel_restart();
+ crate::search_only::recover_after_failed_update(app.clone());
+ return Err(error);
+ }
+ }
// Off-thread so the IPC reply flushes before runtime teardown.
// Keep the reservation until process exit, including that IPC delay.
@@ -613,7 +637,7 @@ pub async fn restart_for_update(
if persistent_version.is_some() {
crate::process_exit::request_app_quit(app.clone());
} else {
- crate::process_exit::request_app_relaunch(
+ crate::process_exit::request_prepared_app_relaunch(
app.clone(),
"banner update restart",
Duration::from_millis(250),
@@ -1499,7 +1523,28 @@ impl UpdatesManager {
}
};
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
- let result = update.download_and_install(on_chunk, || {}).await;
+ let result = match update.download(on_chunk, || {}).await {
+ Ok(bytes) => {
+ // Verify the download before stopping the one server.
+ // Preserve recording-mode update recovery behavior.
+ let stopped = if crate::search_only::is_active() {
+ stop_before_update(&self.app).await.map_err(std::io::Error::other)
+ } else { Ok(()) };
+ match stopped {
+ Ok(()) => {
+ let installed = update.install(bytes);
+ // Linux replaces the executable in place;
+ // the current process continues serving until
+ // the later automatic or user-driven restart.
+ crate::search_only::cancel_restart();
+ crate::search_only::recover_after_failed_update(self.app.clone());
+ installed
+ }
+ Err(error) => Err(error.into()),
+ }
+ }
+ Err(error) => Err(error),
+ };
match &result {
Ok(_) => break result,
@@ -1703,15 +1748,22 @@ impl UpdatesManager {
let persistent_update =
enterprise_route == EnterpriseUpdateRoute::PersistentPackage;
+ stop_before_update(&self.app)
+ .await
+ .map_err(std::io::Error::other)?;
if persistent_update {
- request_persistent_update_for_restart().map_err(std::io::Error::other)?;
+ if let Err(error) = request_persistent_update_for_restart() {
+ UPDATE_RESTART_STARTED.store(false, Ordering::SeqCst);
+ crate::search_only::cancel_restart();
+ crate::search_only::recover_after_failed_update(self.app.clone());
+ return Err(std::io::Error::other(error).into());
+ }
}
- stop_before_update(&self.app).await;
std::mem::forget(restart);
if persistent_update {
crate::process_exit::request_app_quit(self.app.clone());
} else {
- crate::process_exit::request_app_relaunch(
+ crate::process_exit::request_prepared_app_relaunch(
self.app.clone(),
"auto-update restart",
Duration::from_millis(0),
diff --git a/crates/screenpipe-connect/src/oauth_refresh_scheduler.rs b/crates/screenpipe-connect/src/oauth_refresh_scheduler.rs
index 8da498f81..5f44c462e 100644
--- a/crates/screenpipe-connect/src/oauth_refresh_scheduler.rs
+++ b/crates/screenpipe-connect/src/oauth_refresh_scheduler.rs
@@ -266,7 +266,9 @@ impl OAuthRefreshScheduler {
);
sleep_cancellable(&running, STARTUP_DELAY).await;
while running.load(Ordering::SeqCst) {
- tick(&store, &runner, &metrics, &failures, &refreshable).await;
+ if !screenpipe_core::background_work::is_suspended() {
+ tick(&store, &runner, &metrics, &failures, &refreshable).await;
+ }
sleep_cancellable(&running, SCAN_INTERVAL).await;
}
info!("oauth refresh scheduler: stopped");
diff --git a/crates/screenpipe-connect/src/whatsapp/mod.rs b/crates/screenpipe-connect/src/whatsapp/mod.rs
index a97aa4b11..70d199f51 100644
--- a/crates/screenpipe-connect/src/whatsapp/mod.rs
+++ b/crates/screenpipe-connect/src/whatsapp/mod.rs
@@ -164,6 +164,9 @@ impl WhatsAppGateway {
/// easy (it can just pass `"bun"`) and still works on fresh Macs where bun
/// isn't on the user's PATH.
pub async fn start_pairing(&self, bun_hint: &str) -> Result<()> {
+ if screenpipe_core::background_work::is_suspended() {
+ anyhow::bail!("Open Screenpipe to connect WhatsApp");
+ }
let bun_path = resolve_bun_path(Some(bun_hint))?;
// Bump generation so any existing watchdog exits on its next check
@@ -346,6 +349,15 @@ impl WhatsAppGateway {
return;
}
+ // Preserve the session, but stop connected-service work after Quit.
+ if screenpipe_core::background_work::is_suspended() {
+ if let Some(mut process) = child.lock().await.take() {
+ let _ = process.kill().await;
+ }
+ *http_port.lock().await = None;
+ continue;
+ }
+
// Check if process is still alive
let is_dead = {
let mut lock = child.lock().await;
diff --git a/crates/screenpipe-core/Cargo.toml b/crates/screenpipe-core/Cargo.toml
index c3d44acc1..c6ec69005 100644
--- a/crates/screenpipe-core/Cargo.toml
+++ b/crates/screenpipe-core/Cargo.toml
@@ -33,6 +33,7 @@ regex = { workspace = true, optional = true }
lazy_static = { workspace = true, optional = true }
tracing = { workspace = true }
+screenpipe-resource = { path = "../screenpipe-resource" }
dirs = { workspace = true }
diff --git a/crates/screenpipe-core/src/lib.rs b/crates/screenpipe-core/src/lib.rs
index 85160407f..e4d6e9d2f 100644
--- a/crates/screenpipe-core/src/lib.rs
+++ b/crates/screenpipe-core/src/lib.rs
@@ -28,6 +28,7 @@
//! header before trusting details).
pub mod agents;
+pub use screenpipe_resource::background_work;
pub mod connections;
pub mod display_topology;
// Runtime CPU-feature detection lives in its own leaf crate so that
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index c5ba96572..581796bb4 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -4719,6 +4719,9 @@ impl PipeManager {
// Mark as running
{
let mut running = self.running.lock().await;
+ if crate::background_work::is_suspended() {
+ return Err(anyhow!("Screenpipe is serving saved history after Quit"));
+ }
if running.contains_key(name) {
return Err(anyhow!(
"pipe '{}' is already running — you may already be executing inside this pipe. \
diff --git a/crates/screenpipe-engine/src/calendar_speaker_id.rs b/crates/screenpipe-engine/src/calendar_speaker_id.rs
index 57bd32a12..139c18ee0 100644
--- a/crates/screenpipe-engine/src/calendar_speaker_id.rs
+++ b/crates/screenpipe-engine/src/calendar_speaker_id.rs
@@ -542,6 +542,7 @@ pub fn start_speaker_identification(
{
let db2 = db.clone();
tokio::spawn(async move {
+ screenpipe_core::background_work::wait_until_resumed().await;
deduplicate_existing_speaker_aliases(&db2).await;
});
}
@@ -574,6 +575,10 @@ async fn auto_name_input_speaker(db: Arc<screenpipe_db::DatabaseManager>, user_n
loop {
interval.tick().await;
+ if screenpipe_core::background_work::is_suspended() {
+ continue;
+ }
+
match db
.get_dominant_unnamed_input_speaker(min_transcriptions)
.await
@@ -665,6 +670,9 @@ async fn run_speaker_identification_loop(
break;
}
_ = interval.tick() => {
+ if screenpipe_core::background_work::is_suspended() {
+ continue;
+ }
match db.get_active_speakers_in_timerange(
meeting.started_at,
Utc::now(),
diff --git a/crates/screenpipe-engine/src/external_memory_sync.rs b/crates/screenpipe-engine/src/external_memory_sync.rs
index 64940d648..fe504f446 100644
--- a/crates/screenpipe-engine/src/external_memory_sync.rs
+++ b/crates/screenpipe-engine/src/external_memory_sync.rs
@@ -144,6 +144,10 @@ impl ExternalMemorySyncScheduler {
);
sleep_cancellable(&running, STARTUP_DELAY).await;
while running.load(Ordering::SeqCst) {
+ if screenpipe_core::background_work::is_suspended() {
+ sleep_cancellable(&running, SCAN_INTERVAL).await;
+ continue;
+ }
let outcomes = run_once(&db_clone, ss_clone.as_deref(), &dir_clone).await;
record_outcomes(&metrics, &outcomes);
metrics.last_tick_unix.store(now_unix(), Ordering::Relaxed);
diff --git a/crates/screenpipe-engine/src/lib.rs b/crates/screenpipe-engine/src/lib.rs
index c367d33af..ec6aa5459 100644
--- a/crates/screenpipe-engine/src/lib.rs
+++ b/crates/screenpipe-engine/src/lib.rs
@@ -128,3 +128,4 @@ pub use sleep_monitor::start_sleep_monitor;
pub use snapshot_compaction::start_snapshot_compaction;
pub use ui_recorder::{start_ui_recording, UiRecorderConfig, UiRecorderHandle};
pub use video::{video_quality_to_crf, video_quality_to_jpeg_q, video_quality_to_preset};
+pub mod search_only;
diff --git a/crates/screenpipe-engine/src/retention.rs b/crates/screenpipe-engine/src/retention.rs
index 684859fb5..c6c79a414 100644
--- a/crates/screenpipe-engine/src/retention.rs
+++ b/crates/screenpipe-engine/src/retention.rs
@@ -348,6 +348,9 @@ fn spawn_retention_loop(
}
let (retention_days, mode) = {
+ if screenpipe_core::background_work::is_suspended() {
+ continue;
+ }
let guard = state.read().await;
match guard.as_ref() {
Some(rt) if rt.config.enabled => (rt.config.retention_days, rt.config.mode),
@@ -471,6 +474,9 @@ async fn do_local_cleanup(
let mut any_deleted = false;
while batch_start < cutoff {
+ if screenpipe_core::background_work::is_suspended() {
+ break;
+ }
let batch_end = (batch_start + batch_size).min(cutoff);
// Set on any per-batch DB error below. Before the watermark-resume
// fix, a failed batch was retried "for free" on the very next cycle
diff --git a/crates/screenpipe-engine/src/search_only.rs b/crates/screenpipe-engine/src/search_only.rs
new file mode 100644
index 000000000..8a7ead7be
--- /dev/null
+++ b/crates/screenpipe-engine/src/search_only.rs
@@ -0,0 +1,190 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+//! Preserve the existing history API while the desktop has been quit.
+
+use axum::{
+ extract::Request,
+ http::Method,
+ middleware::Next,
+ response::{IntoResponse, Response},
+};
+
+static MUTATIONS: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
+
+/// Called after suspending work, before stopping capture. The middleware holds
+/// a reader until each admitted mutation has finished dispatching.
+pub async fn finish_in_flight_mutations() {
+ let _drained = MUTATIONS.write().await;
+}
+
+fn history_request(method: &Method, path: &str) -> bool {
+ if method == Method::OPTIONS {
+ return true;
+ }
+ if method == Method::POST {
+ // raw_sql already enforces read-only SQL and the history access policy.
+ return matches!(
+ path,
+ "/raw_sql" | "/tags/vision/batch" | "/export" | "/vault/lock" | "/vault/unlock"
+ );
+ }
+ if method != Method::GET && method != Method::HEAD {
+ return false;
+ }
+ matches!(
+ path,
+ "/search"
+ | "/search/keyword"
+ | "/semantic/actors/search"
+ | "/health"
+ | "/elements"
+ | "/activity-summary"
+ | "/activity-ledger"
+ | "/artifacts"
+ | "/tags/autocomplete"
+ | "/openapi.json"
+ | "/openapi.yaml"
+ | "/vault/status"
+ | "/audio/device/status"
+ | "/vision/device/status"
+ | "/vision/status"
+ | "/vision/metrics"
+ | "/audio/metrics"
+ | "/capture/hd"
+ ) || ["/frames", "/speakers", "/meetings", "/memories"]
+ .iter()
+ .any(|prefix| {
+ path == *prefix
+ || path
+ .strip_prefix(prefix)
+ .is_some_and(|tail| tail.starts_with('/'))
+ })
+}
+
+pub async fn history_only(req: Request, next: Next) -> Response {
+ let _mutation = if history_request(req.method(), req.uri().path()) {
+ None
+ } else {
+ Some(MUTATIONS.read().await)
+ };
+ enforce(screenpipe_core::background_work::is_suspended(), req, next).await
+}
+
+async fn enforce(active: bool, req: Request, next: Next) -> Response {
+ if active && !history_request(req.method(), req.uri().path()) {
+ return (axum::http::StatusCode::CONFLICT, axum::Json(serde_json::json!({
+ "error": "search_only",
+ "message": "Screenpipe was quit and is serving saved history. Open Screenpipe to use this feature."
+ }))).into_response();
+ }
+ next.run(req).await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::{body::Body, routing::any, Router};
+ use std::sync::Arc;
+ use tower::ServiceExt;
+
+ #[tokio::test]
+ async fn quit_drains_admitted_mutations_and_rejects_late_starts() {
+ struct Reset;
+ impl Drop for Reset {
+ fn drop(&mut self) {
+ screenpipe_core::background_work::set_suspended(false);
+ }
+ }
+ let _reset = Reset;
+ let started = Arc::new(tokio::sync::Notify::new());
+ let finish = Arc::new(tokio::sync::Notify::new());
+ let router = Router::new()
+ .route(
+ "/audio/start",
+ any({
+ let started = started.clone();
+ let finish = finish.clone();
+ move || {
+ let started = started.clone();
+ let finish = finish.clone();
+ async move {
+ started.notify_one();
+ finish.notified().await;
+ "started"
+ }
+ }
+ }),
+ )
+ .layer(axum::middleware::from_fn(history_only));
+ let request = || {
+ Request::builder()
+ .method(Method::POST)
+ .uri("/audio/start")
+ .body(Body::empty())
+ .unwrap()
+ };
+ let admitted = tokio::spawn(router.clone().oneshot(request()));
+ started.notified().await;
+ screenpipe_core::background_work::set_suspended(true);
+ let mut drain = tokio::spawn(finish_in_flight_mutations());
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(20), &mut drain)
+ .await
+ .is_err()
+ );
+ finish.notify_one();
+ assert!(admitted.await.unwrap().unwrap().status().is_success());
+ tokio::time::timeout(std::time::Duration::from_secs(1), drain)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ router.oneshot(request()).await.unwrap().status(),
+ axum::http::StatusCode::CONFLICT
+ );
+ }
+
+ #[tokio::test]
+ async fn quit_serves_history_but_never_dispatches_capture_or_jobs() {
+ let router = Router::new()
+ .fallback(any(|| async { "history handler reached" }))
+ .layer(axum::middleware::from_fn(|req, next| {
+ enforce(true, req, next)
+ }));
+ for (method, path, permitted) in [
+ (Method::GET, "/search?q=saved", true),
+ (Method::GET, "/frames/42/thumbnail", true),
+ (Method::GET, "/meetings/1/transcript", true),
+ (Method::POST, "/raw_sql", true),
+ (Method::POST, "/audio/start", false),
+ (Method::POST, "/vision/device/start", false),
+ (Method::POST, "/capture/hd/start", false),
+ (Method::POST, "/frames/42/ocr", false),
+ (Method::POST, "/pipes/example/run", false),
+ (Method::POST, "/connections/browser/eval", false),
+ (Method::GET, "/browser/ws", false),
+ (Method::GET, "/cloud-agents/cursor-agents", false),
+ (Method::POST, "/vault/lock", true),
+ ] {
+ let response = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method(method)
+ .uri(path)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status().is_success(), permitted, "{path}");
+ if !permitted {
+ let bytes = axum::body::to_bytes(response.into_body(), 1024)
+ .await
+ .unwrap();
+ assert!(std::str::from_utf8(&bytes).unwrap().contains("search_only"));
+ }
+ }
+ }
+}
diff --git a/crates/screenpipe-engine/src/server.rs b/crates/screenpipe-engine/src/server.rs
index 09748b637..a96128add 100644
--- a/crates/screenpipe-engine/src/server.rs
+++ b/crates/screenpipe-engine/src/server.rs
@@ -1433,7 +1433,7 @@ impl SCServer {
// (bundled sidecar → install dirs → PATH).
{
let wa_lock = wa.lock().await;
- if wa_lock.has_session() {
+ if wa_lock.has_session() && !screenpipe_core::background_work::is_suspended() {
tracing::info!("whatsapp: found existing session, auto-reconnecting...");
if let Err(e) = wa_lock.start_pairing("").await {
tracing::warn!("whatsapp: auto-reconnect failed: {:?}", e);
@@ -1531,6 +1531,7 @@ impl SCServer {
)
.layer(Extension(crate::routes::workflows::WorkflowCatalogSource(self.workflow_catalog_dir.clone())))
.with_state(app_state.clone())
+ .layer(axum::middleware::from_fn(crate::search_only::history_only))
.layer(axum::middleware::from_fn_with_state(
app_state.clone(),
crate::routes::search::storage_snapshot_middleware,
diff --git a/crates/screenpipe-redact/src/image/worker.rs b/crates/screenpipe-redact/src/image/worker.rs
index 862efe6f0..b52f1c265 100644
--- a/crates/screenpipe-redact/src/image/worker.rs
+++ b/crates/screenpipe-redact/src/image/worker.rs
@@ -188,7 +188,9 @@ impl ImageWorker {
}
loop {
- if self.paused.load(Ordering::SeqCst) {
+ if self.paused.load(Ordering::SeqCst)
+ || screenpipe_resource::background_work::is_suspended()
+ {
self.set_paused(true).await;
if race(time::sleep(self.cfg.poll_interval), shutdown.as_ref())
.await
diff --git a/crates/screenpipe-redact/src/worker/mod.rs b/crates/screenpipe-redact/src/worker/mod.rs
index ba11634d2..b6765cc19 100644
--- a/crates/screenpipe-redact/src/worker/mod.rs
+++ b/crates/screenpipe-redact/src/worker/mod.rs
@@ -296,7 +296,9 @@ impl Worker {
.collect();
loop {
- if self.paused.load(std::sync::atomic::Ordering::SeqCst) {
+ if self.paused.load(std::sync::atomic::Ordering::SeqCst)
+ || screenpipe_resource::background_work::is_suspended()
+ {
self.set_paused(true).await;
if race(time::sleep(self.cfg.poll_interval), shutdown.as_ref())
.await
diff --git a/crates/screenpipe-resource/src/background_work.rs b/crates/screenpipe-resource/src/background_work.rs
new file mode 100644
index 000000000..f3b8a204b
--- /dev/null
+++ b/crates/screenpipe-resource/src/background_work.rs
@@ -0,0 +1,51 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+//! Cooperative suspension of optional work while the desktop serves history only.
+//! Capture admission and database writes never wait on this gate.
+
+use std::sync::LazyLock;
+use tokio::sync::watch;
+
+static SUSPENDED: LazyLock<watch::Sender<bool>> = LazyLock::new(|| watch::channel(false).0);
+
+pub fn is_suspended() -> bool {
+ *SUSPENDED.borrow()
+}
+
+pub fn set_suspended(suspended: bool) {
+ SUSPENDED.send_replace(suspended);
+}
+
+pub async fn wait_until_resumed() {
+ wait_on(&mut SUSPENDED.subscribe()).await;
+}
+
+async fn wait_on(state: &mut watch::Receiver<bool>) {
+ let _ = state.wait_for(|suspended| !*suspended).await;
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::Duration;
+
+ #[tokio::test]
+ async fn suspended_work_waits_without_losing_a_resume() {
+ let (state, mut reader) = watch::channel(true);
+ assert!(
+ tokio::time::timeout(Duration::from_millis(10), wait_on(&mut reader))
+ .await
+ .is_err()
+ );
+ state.send_replace(false);
+ tokio::time::timeout(Duration::from_secs(1), wait_on(&mut reader))
+ .await
+ .unwrap();
+ state.send_replace(true);
+ state.send_replace(false);
+ tokio::time::timeout(Duration::from_secs(1), wait_on(&mut reader))
+ .await
+ .unwrap();
+ }
+}
diff --git a/crates/screenpipe-resource/src/cpu.rs b/crates/screenpipe-resource/src/cpu.rs
index 2bab0e5a9..da31a565c 100644
--- a/crates/screenpipe-resource/src/cpu.rs
+++ b/crates/screenpipe-resource/src/cpu.rs
@@ -147,10 +147,17 @@ impl ResourceGovernor {
/// baseline. Essential capture paths should not use this lane; it is for
/// deferrable work such as redaction, indexing, and maintenance.
pub async fn acquire_background_cpu(self: &Arc<Self>) -> CpuBudgetPermit {
- let lane = Arc::clone(&self.cpu.lane)
- .acquire_owned()
- .await
- .expect("background CPU lane is never closed");
+ let lane = loop {
+ crate::background_work::wait_until_resumed().await;
+ let lane = Arc::clone(&self.cpu.lane)
+ .acquire_owned()
+ .await
+ .expect("background CPU lane is never closed");
+ if !crate::background_work::is_suspended() {
+ break lane;
+ }
+ drop(lane);
+ };
let idle_cpu_percent = self.cpu.sample();
CpuBudgetPermit {
governor: Arc::clone(self),
diff --git a/crates/screenpipe-resource/src/lib.rs b/crates/screenpipe-resource/src/lib.rs
index a339badc1..ed38b965d 100644
--- a/crates/screenpipe-resource/src/lib.rs
+++ b/crates/screenpipe-resource/src/lib.rs
@@ -10,6 +10,7 @@
//! are cooperative: deferrable workloads opt into the shared lane, cooldown,
//! and bounded work-slice feedback without delaying capture or live audio.
+pub mod background_work;
mod cpu;
mod monitor;
diff --git a/docs/TESTING.md b/docs/TESTING.md
index db70d4d07..c8c30a19f 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -298,12 +298,13 @@ commits: `d9d43d31`, `620c89a5`, `14acf6f0`
commits: `94531265`, `d794176a`, `9070639c`, `0378cab1`, `4a3313d3`, `7ffdd4f1`, `1b36f62d`
-- [ ] **clean quit via tray** — right-click tray → Quit. all processes terminate. no orphaned ffmpeg/bun processes.
+- [ ] **Quit keeps search available (default On)** — tray, dock, and Cmd+Q stop screen/audio/UI capture and destroy webviews. A saved-history request still succeeds through the same API; attempts to start capture or workflows fail. Reopen into the same PID with capture paused, then explicitly resume. Repeat after sleep/wake and an update restart. Check idle CPU/memory and that recording devices and child agents are released.
+- [ ] **clean quit via tray (Keep search available after quitting Off)** — right-click tray → Quit. all processes terminate. no orphaned ffmpeg/bun processes. Explicit Off survives restart; OS logout/shutdown exits regardless of the setting.
- [ ] **clean quit via dock** — right-click dock → Quit. same as above.
- [ ] **clean quit via Cmd+Q** — same verification.
- [ ] **force quit recovery** — force quit app. relaunch. database is intact. recording resumes.
- [ ] **sleep/wake** — close laptop lid, wait 10s, open. recording resumes within 5s. no crash (`9070639c`).
-- [ ] **restart app** — quit and relaunch. all settings preserved. recording starts automatically.
+- [ ] **restart app** — settings and recording authorization are preserved. A search-only updater restart restores hidden UI and paused capture; reopening does not authorize recording. Failed shutdown defers the update, and the originating cause survives in the collected/redacted support report. If Quit cannot safely retain search, it falls back to a full exit.
- [ ] **Cross-platform autorelease pool** — Verify that Windows and Linux builds compile and run without issues related to macOS-specific autorelease pool calls. (`851b3037c`)
- [ ] **Main thread safety (macOS)** — Verify that tray icon operations, space monitoring, and frontmost app restoration are dispatched to the main thread to prevent crashes. (`ac46aa437`, `418826dfa`, `274826dfa`)
- [ ] **ObjC memory management (macOS)** — Verify that all ObjC operations are wrapped in scoped autorelease pools and objects are retained in async callbacks to prevent use-after-free or SIGSEGV crashes. (`4cb9850f7`, `c49350df0`, `139500d52`)
@@ -313,7 +314,7 @@ commits: `94531265`, `d794176a`, `9070639c`, `0378cab1`, `4a3313d3`, `7ffdd4f1`,
- [ ] **source build update dialog** — source builds show "source build detected" dialog with link to pre-built version.
- [ ] **owned port release on restart** — restart Screenpipe and verify its internally owned server shuts down gracefully, the shutdown is awaited, and the new server binds port 3030 after the release grace period.
- [ ] **startup port owner arbitration** — after the single-instance focus handoff has had its chance: (a) a healthy Screenpipe owner on 3030 or 11435 remains alive and exactly one native dialog asks the user to quit it; (b) an owner that fails the Screenpipe health probe is terminated gracefully first, forced only after the release grace period, and Screenpipe binds the released port; (c) if reclaim still fails, Screenpipe does not bind through the conflict and shows one native error dialog (`0378cab1`, `4a3313d3`, `8c435a10`).
-- [ ] **no orphaned processes** — after quit, `ps aux | grep screenpipe` shows nothing. `lsof -i :3030` shows nothing.
+- [ ] **no orphaned processes** — after full quit (search setting Off), no Screenpipe process or API listener remains. With the setting On, only the existing search-serving app remains; no second database owner is created.
- [ ] **rollback** — user can rollback to previous version via tray menu (`c7fbc3ea`).
- [ ] **Zombie CPU drain prevention** — Verify that `lsof` calls have a 5-second timeout, preventing zombie CPU drain, especially on quit. Check logs for `lsof` timeouts if applicable.
- [ ] **Tokio shutdown stability** — Verify that the `tokio` shutdown process is stable and doesn't panic in the tree walker, especially during application exit or process restarts.