Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(startup): retry DB init on lock contention + triageable webview errors

Louis Beaumont7801c04dda02
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index 8493e6bcb..dbea3996e 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -9726,7 +9726,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.4.35"
+version = "2.4.40"
dependencies = [
"anyhow",
"arboard",
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
index 438d9a6c0..c947ffe04 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -11,6 +11,35 @@ use crate::{
use tauri::{Emitter, Manager};
use tracing::{debug, error, info, warn};
+/// Log a `WebviewWindowBuilder::build()` failure with structured context.
+///
+/// Why: Sentry events for webview build failures currently say only
+/// "failed to create webview: WebView2 error: …". Without knowing which
+/// window was being built (pipe-store, login, notifications, etc.) we
+/// can't triage.
+///
+/// Tracing's `sentry` layer (see `main.rs`) maps structured fields to
+/// Sentry tags, so `webview_label` and `webview_url` become filterable
+/// tags in the Sentry dashboard.
+///
+/// Call at every `WebviewWindowBuilder::build()` error site instead of
+/// a bare `error!(...)`. Return the error unchanged — this function is
+/// purely observability.
+fn log_webview_build_failure(
+ label: &str,
+ url_hint: &str,
+ err: &(impl std::fmt::Display + ?Sized),
+) {
+ tracing::error!(
+ webview_label = label,
+ webview_url = url_hint,
+ "failed to create webview (label={}, url={}): {}",
+ label,
+ url_hint,
+ err
+ );
+}
+
/// Global app handle stored so the native notification action callback can emit events.
#[cfg(target_os = "macos")]
static GLOBAL_APP_HANDLE: std::sync::OnceLock<tauri::AppHandle> = std::sync::OnceLock::new();
@@ -549,12 +578,13 @@ pub async fn open_pipe_window(
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
}
+ let url = format!("http://localhost:{}", port);
let window = match tauri::WebviewWindowBuilder::new(
&app_handle,
&title,
- tauri::WebviewUrl::External(format!("http://localhost:{}", port).parse().unwrap()),
+ tauri::WebviewUrl::External(url.parse().unwrap()),
)
- .title(title)
+ .title(title.clone())
.inner_size(1200.0, 850.0)
.min_inner_size(600.0, 400.0)
.focused(true)
@@ -564,7 +594,7 @@ pub async fn open_pipe_window(
{
Ok(window) => window,
Err(e) => {
- error!("failed to create window: {}", e);
+ log_webview_build_failure(&title, &url, &e);
return Err(format!("failed to create window: {}", e));
}
};
@@ -670,10 +700,11 @@ pub async fn open_login_window(app_handle: tauri::AppHandle) -> Result<(), Strin
let app_for_nav = app_handle.clone();
+ const LOGIN_URL: &str = "https://screenpi.pe/login";
WebviewWindowBuilder::new(
&app_handle,
label,
- WebviewUrl::External("https://screenpi.pe/login".parse().unwrap()),
+ WebviewUrl::External(LOGIN_URL.parse().unwrap()),
)
.title("sign in to screenpipe")
.inner_size(460.0, 700.0)
@@ -694,7 +725,10 @@ pub async fn open_login_window(app_handle: tauri::AppHandle) -> Result<(), Strin
})
.build()
.map(crate::window::finalize_webview_window)
- .map_err(|e| e.to_string())?;
+ .map_err(|e| {
+ log_webview_build_failure(label, LOGIN_URL, &e);
+ e.to_string()
+ })?;
Ok(())
}
@@ -723,10 +757,13 @@ pub async fn open_google_calendar_auth_window(
let app_for_nav = app_handle.clone();
+ let parsed_url = auth_url
+ .parse()
+ .map_err(|e| format!("invalid url: {e}"))?;
WebviewWindowBuilder::new(
&app_handle,
label,
- WebviewUrl::External(auth_url.parse().map_err(|e| format!("invalid url: {e}"))?),
+ WebviewUrl::External(parsed_url),
)
.title("connect google calendar")
.inner_size(500.0, 700.0)
@@ -745,7 +782,10 @@ pub async fn open_google_calendar_auth_window(
})
.build()
.map(crate::window::finalize_webview_window)
- .map_err(|e| e.to_string())?;
+ .map_err(|e| {
+ log_webview_build_failure(label, &auth_url, &e);
+ e.to_string()
+ })?;
Ok(())
}
@@ -1379,7 +1419,10 @@ pub async fn show_shortcut_reminder(
let window = builder
.build()
.map(crate::window::finalize_webview_window)
- .map_err(|e| format!("Failed to create shortcut reminder window: {}", e))?;
+ .map_err(|e| {
+ log_webview_build_failure(label, "shortcut-reminder", &e);
+ format!("Failed to create shortcut reminder window: {}", e)
+ })?;
info!("shortcut-reminder window created");
@@ -1661,7 +1704,10 @@ pub async fn show_notification_panel(
let window = builder
.build()
.map(crate::window::finalize_webview_window)
- .map_err(|e| format!("Failed to create notification panel window: {}", e))?;
+ .map_err(|e| {
+ log_webview_build_failure(label, "notification-panel", &e);
+ format!("Failed to create notification panel window: {}", e)
+ })?;
info!("notification-panel window created");
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 5e64b7947..d62eb474e 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
@@ -101,15 +101,92 @@ impl ServerCore {
"migrating_database",
Some("updating database — this may take several minutes on large installs"),
);
- let db = Arc::new(
- DatabaseManager::new(&db_path, config.db_config.clone())
- .await
- .map_err(|e| {
- let msg = format!("Failed to initialize database: {}", e);
+
+ // DB init with bounded retry on lock contention.
+ //
+ // Context: user `pmp` on v2.4.37 hit "database is locked" the same
+ // second the server started, before any migration could run. Most
+ // plausible causes are another process briefly touching the file
+ // (Spotlight indexing, Time Machine, antivirus, iCloud/OneDrive
+ // sync, or a stale advisory lock from a crashed prior screenpipe
+ // process). All of those clear within a few seconds.
+ //
+ // A short backoff retry absorbs these without looping through the
+ // outer watchdog, which would otherwise re-run migrations and
+ // other setup. The outer watchdog in recording.rs still covers
+ // the catastrophic case where every inner retry fails.
+ //
+ // Non-lock errors (permissions, corruption, bad path) bail out
+ // immediately — retrying would just delay the user-visible error.
+ const DB_LOCK_RETRY_DELAYS_SECS: &[u64] = &[0, 2, 5];
+ let db = {
+ let mut last_err: Option<String> = None;
+ let mut built = None;
+ for (attempt_idx, delay) in DB_LOCK_RETRY_DELAYS_SECS.iter().enumerate() {
+ if *delay > 0 {
+ info!(
+ "retrying database init after {}s (attempt {}/{})",
+ delay,
+ attempt_idx + 1,
+ DB_LOCK_RETRY_DELAYS_SECS.len()
+ );
+ tokio::time::sleep(std::time::Duration::from_secs(*delay)).await;
+ }
+ match DatabaseManager::new(&db_path, config.db_config.clone()).await {
+ Ok(db) => {
+ built = Some(db);
+ break;
+ }
+ Err(e) => {
+ let s = e.to_string();
+ let is_lock =
+ s.contains("database is locked") || s.contains("database is busy");
+ if is_lock && attempt_idx + 1 < DB_LOCK_RETRY_DELAYS_SECS.len() {
+ // warn, not error — expected transient condition
+ warn!(
+ "database locked on startup (attempt {}/{}): {}",
+ attempt_idx + 1,
+ DB_LOCK_RETRY_DELAYS_SECS.len(),
+ e
+ );
+ last_err = Some(s);
+ continue;
+ }
+ // Final failure — either non-lock error or exhausted retries
+ let msg = if is_lock {
+ format!(
+ "Database is locked by another process (likely Spotlight, \
+ Time Machine, antivirus, or iCloud/OneDrive sync). After \
+ {} attempts the lock did not clear. Close backup/sync tools \
+ and relaunch. Underlying error: {}",
+ DB_LOCK_RETRY_DELAYS_SECS.len(),
+ e
+ )
+ } else {
+ format!("Failed to initialize database: {}", e)
+ };
+ crate::health::set_boot_error(&msg);
+ return Err(msg);
+ }
+ }
+ }
+ match built {
+ Some(db) => Arc::new(db),
+ None => {
+ // All attempts returned lock errors and we exhausted the loop.
+ // The branch above handles the last-attempt case, but defensively
+ // handle the case where the loop exited without a match.
+ let e = last_err.unwrap_or_else(|| "unknown error".to_string());
+ let msg = format!(
+ "Database is locked — exhausted all {} retry attempts. {}",
+ DB_LOCK_RETRY_DELAYS_SECS.len(),
+ e
+ );
crate::health::set_boot_error(&msg);
- msg
- })?,
- );
+ return Err(msg);
+ }
+ }
+ };
info!("Database initialized at {}", db_path);
// --- Audio devices + manager (built but NOT started) ---