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(startup): boot-phase-aware watchdog — no retry during migration
Louis Beaumont259b05b41428
diff --git a/apps/screenpipe-app-tauri/components/onboarding/engine-startup.tsx b/apps/screenpipe-app-tauri/components/onboarding/engine-startup.tsxindex 770bbabc3..92c53f5c6 100644--- a/apps/screenpipe-app-tauri/components/onboarding/engine-startup.tsx+++ b/apps/screenpipe-app-tauri/components/onboarding/engine-startup.tsx@@ -42,6 +42,26 @@ const STUCK_TIMEOUT_MS = 15000;const LIVE_FEED_MIN_MS = 8000; // minimum time to show live feed before enabling continueconst LIVE_FEED_POLL_MS = 3000; // poll search every 3s+// Boot phases emitted by the Rust backend — see src-tauri/src/health.rs.+// We use these to show actionable copy during long migrations (Mike Cloke+// 2026-04-22 had a 31.5GB db, migration took 13.2s, old UI flipped to+// "stuck" after 15s and told user to send logs instead of waiting).+type BootPhaseSnapshot = {+ phase:+ | "idle"+ | "starting"+ | "migrating_database"+ | "building_audio"+ | "starting_pipes"+ | "ready"+ | "error";+ message: string | null;+ error: string | null;+ sinceEpochSecs: number;+};++const BOOT_PHASE_POLL_MS = 500;+export default function EngineStartup({handleNextSlide,}: EngineStartupProps) {@@ -60,6 +80,9 @@ export default function EngineStartup({const [canContinue, setCanContinue] = useState(false);const [showSkip, setShowSkip] = useState(false);+ // Boot phase — polled via Tauri IPC, available before HTTP server binds+ const [bootPhase, setBootPhase] = useState<BootPhaseSnapshot | null>(null);+const hasAdvancedRef = useRef(false);const mountTimeRef = useRef(Date.now());const feedStartRef = useRef(0);@@ -142,6 +165,29 @@ export default function EngineStartup({return () => clearInterval(interval);}, [state]);+ // Poll boot phase via Tauri IPC — available before HTTP server binds.+ // Crucial on large-db migrations where /health is unreachable for minutes.+ useEffect(() => {+ if (state === "running" || state === "live-feed") return;++ let cancelled = false;+ const poll = async () => {+ try {+ const phase = await invoke<BootPhaseSnapshot>("get_boot_phase");+ if (!cancelled) setBootPhase(phase);+ } catch {+ // command not available (shouldn't happen in a shipped build) — ignore+ }+ };++ poll();+ const interval = setInterval(poll, BOOT_PHASE_POLL_MS);+ return () => {+ cancelled = true;+ clearInterval(interval);+ };+ }, [state]);+// Transition from "running" to "live-feed" instead of auto-advancinguseEffect(() => {if (state !== "running") return;@@ -266,30 +312,58 @@ export default function EngineStartup({return () => clearTimeout(timer);}, [state]);- // Timers for taking-longer and stuck+ // Timers for taking-longer and stuck.+ //+ // The stuck timer used to fire unconditionally after 15s. That was wrong+ // for users with large databases: their migration takes 13-60+ seconds+ // (Mike Cloke had a 31.5GB db), and the UI flipped to "stuck" telling+ // them to send logs while the migration was still running fine.+ //+ // We now re-arm the stuck timer every time a genuine progress signal+ // arrives (new boot phase), so it only fires when nothing has changed+ // for STUCK_TIMEOUT_MS.useEffect(() => {const longerTimer = setTimeout(() => setIsTakingLonger(true),TAKING_LONGER_MS);+ return () => clearTimeout(longerTimer);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ if (state === "running" || state === "live-feed" || state === "stuck") return;+ // If backend is actively progressing (or reports error explicitly) we+ // don't want to fire the generic "stuck" path on a timer. The backend's+ // own error path will set phase=error, which we handle separately.+ if (bootPhase?.phase === "error") return;const stuckTimer = setTimeout(() => {- if (state !== "running" && state !== "live-feed") {- setState("stuck");+ // Re-check at fire time — state or phase may have advanced.+ setState((current) => {+ if (current === "running" || current === "live-feed") return current;+ const activePhases: BootPhaseSnapshot["phase"][] = [+ "migrating_database",+ "building_audio",+ "starting_pipes",+ ];+ if (bootPhase && activePhases.includes(bootPhase.phase)) {+ // Progress is happening — don't flip to stuck. Timer will re-arm+ // when bootPhase updates.+ return current;+ }posthog.capture("onboarding_engine_stuck", {time_spent_ms: Date.now() - mountTimeRef.current,serverStarted,audioReady,visionReady,+ boot_phase: bootPhase?.phase ?? "unknown",});- }+ return "stuck";+ });}, STUCK_TIMEOUT_MS);-- return () => {- clearTimeout(longerTimer);- clearTimeout(stuckTimer);- };+ return () => clearTimeout(stuckTimer);// eslint-disable-next-line react-hooks/exhaustive-deps- }, []);+ }, [state, bootPhase?.phase]);const ensureDefaultPreset = useCallback(async () => {if (settings.aiPresets.length === 0) {@@ -593,18 +667,22 @@ export default function EngineStartup({<ProgressSteps steps={progressSteps} className="mt-3" />- {/* Taking longer hint */}+ {/* Phase-aware status line — prefer backend-provided message when+ present (e.g. "updating database — may take several minutes on+ large installs"), else the generic "starting engine..." hint. */}<AnimatePresence>- {isTakingLonger && state === "starting" && (- <motion.p- className="font-mono text-[10px] text-muted-foreground/60 mt-3"- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- exit={{ opacity: 0 }}- >- starting engine...- </motion.p>- )}+ {state === "starting" &&+ (bootPhase?.message || isTakingLonger) && (+ <motion.p+ key={bootPhase?.phase ?? "taking-longer"}+ className="font-mono text-[10px] text-muted-foreground/60 mt-3 max-w-[360px] text-center"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ >+ {bootPhase?.message ?? "starting engine..."}+ </motion.p>+ )}</AnimatePresence>{/* Stuck UI */}diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lockindex 87483992d..8493e6bcb 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.34"+version = "2.4.35"dependencies = ["anyhow","arboard",diff --git a/apps/screenpipe-app-tauri/src-tauri/src/health.rs b/apps/screenpipe-app-tauri/src-tauri/src/health.rsindex f624f2576..bc621a31a 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/health.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/health.rs@@ -27,6 +27,87 @@ const CONSECUTIVE_FAILURES_THRESHOLD: u32 = 30;/// actively confirming the problem, but still debounced to survive brief spikes.const CONSECUTIVE_UNHEALTHY_THRESHOLD: u32 = 10;+// ─────────────────────────────────────────────────────────────────────────+// Boot phase — tracks where we are inside ServerCore::start.+//+// The HTTP server only binds near the *end* of startup (after DB migration+// and audio-manager build). That means /health is unreachable for the entire+// window we care most about (e.g. 13.2s for Mike's 31.5GB DB migration). The+// frontend and the spawn watchdog can't distinguish "server is migrating" from+// "server is dead" via HTTP alone — so they both time out and retry, and the+// retry races the still-running migration on the SQLite lock (see the Mike+// Cloke incident 2026-04-22).+//+// Rather than refactor the HTTP server to bind early and serve /health while+// the DB is offline, we expose boot phase via a process-local atomic and a+// Tauri command. The watchdog polls the atomic; the UI polls the command.+// Both become the source of truth during startup.+// ─────────────────────────────────────────────────────────────────────────++#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]+#[serde(rename_all = "camelCase")]+pub struct BootPhaseSnapshot {+ /// One of: idle | starting | migrating_database | building_audio |+ /// starting_pipes | ready | error+ pub phase: String,+ /// Human-readable detail to show the user (may be long-running hint)+ pub message: Option<String>,+ /// Present only when phase == "error"+ pub error: Option<String>,+ /// Unix epoch seconds when the current phase was entered. Lets the UI+ /// show "X minutes" on slow migrations.+ pub since_epoch_secs: u64,+}++impl BootPhaseSnapshot {+ pub fn idle() -> Self {+ Self {+ phase: "idle".to_string(),+ message: None,+ error: None,+ since_epoch_secs: 0,+ }+ }+}++static BOOT_PHASE: Lazy<RwLock<BootPhaseSnapshot>> =+ Lazy::new(|| RwLock::new(BootPhaseSnapshot::idle()));++fn now_epoch() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0)+}++pub fn set_boot_phase(phase: &str, message: Option<&str>) {+ let mut guard = BOOT_PHASE.write().unwrap_or_else(|e| e.into_inner());+ // Don't reset since_epoch if the phase is unchanged (no-op writes)+ if guard.phase != phase {+ guard.since_epoch_secs = now_epoch();+ }+ guard.phase = phase.to_string();+ guard.message = message.map(String::from);+ guard.error = None;+ info!("boot phase → {}{}", phase,+ message.map(|m| format!(" ({})", m)).unwrap_or_default());+}++pub fn set_boot_error(err: &str) {+ let mut guard = BOOT_PHASE.write().unwrap_or_else(|e| e.into_inner());+ guard.phase = "error".to_string();+ guard.error = Some(err.to_string());+ guard.since_epoch_secs = now_epoch();+ tracing::error!("boot phase → error: {}", err);+}++pub fn get_boot_phase_snapshot() -> BootPhaseSnapshot {+ BOOT_PHASE+ .read()+ .unwrap_or_else(|e| e.into_inner())+ .clone()+}+// Shared recording status that can be read by the tray menu#[derive(Clone, Copy, PartialEq, Debug)]pub enum RecordingStatus {diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex 3f799016f..7077b5a34 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -598,6 +598,7 @@ async fn main() {recording::stop_capture,recording::get_monitors,recording::get_audio_devices,+ recording::get_boot_phase,// Commands from commands.rscommands::is_enterprise_build_cmd,commands::get_enterprise_license_key,@@ -859,6 +860,7 @@ async fn main() {recording::stop_capture,recording::get_monitors,recording::get_audio_devices,+ recording::get_boot_phase,permissions::open_permission_settings,permissions::request_permission,permissions::do_permissions_check,diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rsindex 3097567b2..d31b3636c 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs@@ -166,6 +166,16 @@ pub async fn get_audio_devices() -> Result<Vec<AudioDeviceInfo>, String> {get_available_audio_devices().await}+/// Read the current boot phase of the server. Used by the onboarding UI to+/// show progress ("updating database", "loading pipes", ...) while the HTTP+/// server is not yet listening — in particular during long DB migrations+/// where /health is unreachable.+#[tauri::command]+#[specta::specta]+pub async fn get_boot_phase() -> crate::health::BootPhaseSnapshot {+ crate::health::get_boot_phase_snapshot()+}+pub async fn get_available_monitors() -> Result<Vec<MonitorDevice>, String> {debug!("Getting available monitors");let monitors = screenpipe_screen::monitor::list_monitors().await;@@ -348,9 +358,28 @@ pub async fn spawn_screenpipe(let health_url = format!("http://localhost:{}/health", port);// --- Race prevention ---+ //+ // If a start is already in progress, wait on it rather than racing. This+ // used to time out after 15s and retry — which was fine for small+ // databases but catastrophic for large ones (Mike Cloke 2026-04-22: 31.5GB+ // db, migration took 13.2s, watchdog fired a retry, both migrations+ // raced on the SQLite lock, both failed, app stuck forever).+ //+ // Now we use boot-phase state as the source of truth:+ // - "ready" → server is up, we're done+ // - "error" → initial start failed, safe to take over and retry+ // - "migrating_database" / "building_audio" / "starting_pipes" / "starting"+ // → another thread is making progress, keep waiting no matter how long+ //+ // A 30-minute safety ceiling prevents a wedged start from hanging the app+ // forever; for context, even a 100GB migration finishes in ~1 minute.if state.is_starting.swap(true, Ordering::SeqCst) {- info!("Server start already in progress, waiting for health...");- for _ in 0..30 {+ info!("Server start already in progress, waiting for boot phase...");+ const MAX_WAIT_SECS: u64 = 1800; // 30 minutes+ const POLL_MS: u64 = 500;+ let start_wait = std::time::Instant::now();+ loop {+ // Fast path: HTTP health up → done.if let Ok(resp) = reqwest::Client::new().get(&health_url).timeout(std::time::Duration::from_secs(1))@@ -362,20 +391,60 @@ pub async fn spawn_screenpipe(return Ok(());}}- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- }- warn!("In-flight server start didn't produce healthy server after 15s");- {- let server_guard = state.server.lock().await;- if server_guard.is_some() {- info!("Server exists after timeout — not starting duplicate");- return Ok(());+ let phase = crate::health::get_boot_phase_snapshot();+ match phase.phase.as_str() {+ "ready" => {+ // Phase says ready — HTTP may be binding right now. Loop+ // once more without extra wait; it'll resolve on next poll.+ tokio::time::sleep(std::time::Duration::from_millis(POLL_MS)).await;+ continue;+ }+ "error" => {+ warn!(+ "In-flight server start reported error: {}",+ phase.error.as_deref().unwrap_or("<no detail>")+ );+ // Take over: clear is_starting so the full-start path below+ // can run. Another concurrent caller may beat us; the+ // swap(true) below detects that.+ state.is_starting.store(false, Ordering::SeqCst);+ if state.is_starting.swap(true, Ordering::SeqCst) {+ // Someone else is already retrying. Bail out cleanly.+ return Ok(());+ }+ break;+ }+ "idle" => {+ // is_starting was true but phase never updated — the+ // spawning thread likely died before setting phase. Treat+ // like error and take over.+ if start_wait.elapsed() > std::time::Duration::from_secs(30) {+ warn!("is_starting set but boot phase still idle after 30s — taking over");+ state.is_starting.store(false, Ordering::SeqCst);+ if state.is_starting.swap(true, Ordering::SeqCst) {+ return Ok(());+ }+ break;+ }+ }+ _ => {+ // starting | migrating_database | building_audio | starting_pipes+ // — keep waiting, progress is being made.+ }}- }- info!("No server after 15s — previous start likely failed, retrying");- state.is_starting.store(false, Ordering::SeqCst);- if state.is_starting.swap(true, Ordering::SeqCst) {- return Ok(());+ if start_wait.elapsed() > std::time::Duration::from_secs(MAX_WAIT_SECS) {+ warn!(+ "In-flight server start did not complete after {}s (phase={})",+ MAX_WAIT_SECS, phase.phase+ );+ state.is_starting.store(false, Ordering::SeqCst);+ return Err(format!(+ "Server start timed out after {} minutes. Current phase: {}",+ MAX_WAIT_SECS / 60,+ phase.phase+ ));+ }+ tokio::time::sleep(std::time::Duration::from_millis(POLL_MS)).await;}}@@ -547,7 +616,9 @@ pub async fn spawn_screenpipe({Ok(rt) => rt,Err(e) => {- let _ = result_tx.send(Err(format!("Failed to create server runtime: {}", e)));+ let msg = format!("Failed to create server runtime: {}", e);+ crate::health::set_boot_error(&msg);+ let _ = result_tx.send(Err(msg));return;}};diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rsindex 318282755..5e64b7947 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs@@ -57,6 +57,7 @@ impl ServerCore {on_pipe_output: Option<screenpipe_core::pipes::OnPipeOutputLine>,) -> Result<Self, String> {info!("Starting server core on port {}", config.port);+ crate::health::set_boot_phase("starting", Some("starting server"));// --- Environment setup ---std::env::set_var("SCREENPIPE_FD_LIMIT", "8192");@@ -96,10 +97,18 @@ impl ServerCore {.map_err(|e| format!("Failed to create data dir: {}", e))?;let db_path = format!("{}/db.sqlite", local_data_dir.to_string_lossy());+ crate::health::set_boot_phase(+ "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| format!("Failed to initialize database: {}", e))?,+ .map_err(|e| {+ let msg = format!("Failed to initialize database: {}", e);+ crate::health::set_boot_error(&msg);+ msg+ })?,);info!("Database initialized at {}", db_path);@@ -162,10 +171,15 @@ impl ServerCore {audio_manager_builder = audio_manager_builder.meeting_detector(detector.clone());}+ crate::health::set_boot_phase("building_audio", Some("starting audio pipeline"));let mut audio_manager = audio_manager_builder.build(db.clone()).await- .map_err(|e| format!("Failed to build audio manager: {}", e))?;+ .map_err(|e| {+ let msg = format!("Failed to build audio manager: {}", e);+ crate::health::set_boot_error(&msg);+ msg+ })?;// Wire audio → hot cache{@@ -273,6 +287,7 @@ impl ServerCore {}// --- Pipe manager ---+ crate::health::set_boot_phase("starting_pipes", Some("loading pipes"));let pipes_dir = config.data_dir.join("pipes");std::fs::create_dir_all(&pipes_dir).ok();@@ -342,7 +357,11 @@ impl ServerCore {config.port,)).await- .map_err(|e| format!("Failed to bind port {}: {}", config.port, e))?;+ .map_err(|e| {+ let msg = format!("Failed to bind port {}: {}", config.port, e);+ crate::health::set_boot_error(&msg);+ msg+ })?;info!("HTTP server bound to port {}", config.port);@@ -354,6 +373,7 @@ impl ServerCore {});info!("Server core started successfully");+ crate::health::set_boot_phase("ready", None);// mDNSif let Err(e) = screenpipe_connect::mdns::advertise(config.port) {