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(app): don't give up mic-grant capture restart on a slow-but-succeeding boot (#4992)
Ezra Ellettef56444514488
diff --git a/TESTING.md b/TESTING.mdindex 7b9f099f5..8e26ed58f 100644--- a/TESTING.md+++ b/TESTING.md@@ -249,6 +249,7 @@ commits: `d9d43d31`, `620c89a5`, `14acf6f0`- [ ] **startup permission gate** — on first launch, permissions are requested before recording starts (`d9d43d31`).- [ ] **faster permission polling** — permission status checked every 5-10 seconds, not 30 (`d9d43d31`).- [ ] **No recurring permission modal after close** — Grant macOS permissions, quit the app, and relaunch it multiple times. Verify that the macOS permission modal does NOT reappear every time the app is closed.+- [ ] **mic-grant restart survives a slow boot** — with mic permission already granted from a prior session, relaunch with a slow boot (large DB migration or first-run model download) so the window gains focus before `ServerCore` finishes constructing. Verify capture actually starts once boot completes instead of silently staying off. Check `grep "start_capture after mic grant" ~/.screenpipe/screenpipe-app.*.log` — should show success, not "gave up after N attempts" (previously a fixed ~10s budget that raced boot and gave up permanently — found during the Intel-Mac CI smoke-test investigation, screenpipe#4978). If an attempt does time out, verify a **later window focus retries** rather than being silently disabled for the rest of the session (regression: the old `MIC_FOCUS_CAPTURE_RESTART` latch was set once and never reset).- [ ] **fresh install — all prompts appear** — screen recording, microphone, accessibility prompts all show on first launch.- [ ] **denied permission → opens System Settings** — if user previously denied mic permission, clicking "grant" opens System Settings > Privacy directly (`620c89a5`).diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex f274a781c..6099ae053 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -143,8 +143,6 @@ mod specta_bindings;mod vault;mod viewer;-#[cfg(target_os = "macos")]-static MIC_FOCUS_CAPTURE_RESTART: AtomicBool = AtomicBool::new(false);use base64::Engine;use health::start_health_check;use log_files::{get_log_files, get_screenpipe_data_dir};@@ -833,12 +831,6 @@ async fn main() {if !health::get_audio_device_status().is_empty() {return;}- if MIC_FOCUS_CAPTURE_RESTART- .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)- .is_err()- {- return;- }info!("Microphone permission newly granted (focus return) — restarting capture for audio reinit");diff --git a/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs b/apps/screenpipe-app-tauri/src-tauri/src/permissions.rsindex 41f4861c6..e669767d1 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs@@ -155,19 +155,59 @@ fn request_av_permission(app: tauri::AppHandle, media_type: nokhwa_bindings_maco});}+/// Guards concurrent/duplicate `restart_capture_on_mic_grant` invocations —+/// both the window-focus handler in main.rs and the direct AVCaptureDevice+/// grant callback in `request_av_permission` above can trigger it. Always+/// reset on drop (success, early-return, or a give-up) so a *later* trigger+/// (e.g. the user refocusing the window) can retry. A latch that is set once+/// and never reset would permanently disable mic-grant recovery for the rest+/// of the process the first time an attempt didn't land (found during the+/// Intel-Mac CI smoke-test investigation, screenpipe#4978).+#[cfg(target_os = "macos")]+static MIC_GRANT_RESTART_IN_FLIGHT: std::sync::atomic::AtomicBool =+ std::sync::atomic::AtomicBool::new(false);++#[cfg(target_os = "macos")]+struct ResetGuard<'a>(&'a std::sync::atomic::AtomicBool);+#[cfg(target_os = "macos")]+impl Drop for ResetGuard<'_> {+ fn drop(&mut self) {+ self.0.store(false, Ordering::SeqCst);+ }+}++/// How long to wait for the backend to finish booting before giving up on+/// this mic-grant attempt. Matches `updates.rs::AUTO_UPDATE_GATE_TIMEOUT` —+/// production boot is well under a minute even on cold installs; 5 minutes+/// covers slow first-time model downloads and large DB migrations.+#[cfg(target_os = "macos")]+const BOOT_WAIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);+/// Stop and restart capture so `capture_session::start` re-queries TCC and/// repopulates audio devices. Matches the settings-toggle path.////// When the user grants the mic permission immediately on first launch, the-/// AVCaptureDevice completion callback can fire before the backend-/// `ServerCore` has been constructed — `start_capture` then errors with-/// "Server not running" and capture stays dead until the user manually toggles-/// it. Wait up to ~10s with short backoff so we ride out backend boot before-/// giving up.+/// AVCaptureDevice completion callback (or the window-focus handler) can fire+/// before the backend `ServerCore` has been constructed. Rather than guess a+/// fixed retry budget against the "Server not running" error string — which+/// raced a slow-but-succeeding boot (DB migration, first-launch model+/// download) and gave up before `ServerCore` was even constructed — wait on+/// the boot-phase state machine that `spawn_screenpipe`'s race-prevention+/// path and the auto-update restart gate already use for this exact class of+/// race (found during the Intel-Mac CI smoke-test investigation, screenpipe#4978).#[cfg(target_os = "macos")]pub(crate) async fn restart_capture_on_mic_grant(app: tauri::AppHandle) {use tauri::Manager;+ if MIC_GRANT_RESTART_IN_FLIGHT+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)+ .is_err()+ {+ debug!("start_capture after mic grant: already in flight, skipping duplicate trigger");+ return;+ }+ let _guard = ResetGuard(&MIC_GRANT_RESTART_IN_FLIGHT);+let need_stop = {let state = app.state::<crate::recording::RecordingState>();let is_running = state.capture.lock().await.is_some();@@ -180,11 +220,35 @@ pub(crate) async fn restart_capture_on_mic_grant(app: tauri::AppHandle) {}}- // Retry start_capture with backoff while the backend is still booting.- // "Server not running" / "Server not responding" are the two transient- // errors emitted before `ServerCore` is wired into RecordingState.- const MAX_ATTEMPTS: u32 = 20;- const BACKOFF_MS: u64 = 500;+ match crate::health::wait_for_boot_ready(BOOT_WAIT_TIMEOUT).await {+ crate::health::BootReadiness::Errored => {+ error!(+ "start_capture after mic grant: boot phase errored ({}) — capture cannot start \+ until the app is restarted",+ crate::health::get_boot_phase_snapshot()+ .error+ .unwrap_or_default()+ );+ return;+ }+ crate::health::BootReadiness::Pending => {+ error!(+ "start_capture after mic grant: boot still not ready after {}s (phase={}) — \+ giving up this attempt; a later focus event will retry",+ BOOT_WAIT_TIMEOUT.as_secs(),+ crate::health::get_boot_phase_snapshot().phase+ );+ return;+ }+ crate::health::BootReadiness::Ready => {}+ }++ // Boot is confirmed ready — RecordingState.server is assigned a handful+ // of sync instructions after `set_boot_phase("ready", ...)` in+ // server_core.rs, with no intervening `.await`. A short retry buffer+ // rides out that razor-thin window rather than guessing at boot duration.+ const MAX_ATTEMPTS: u32 = 5;+ const BACKOFF_MS: u64 = 200;let mut last_err: Option<String> = None;for attempt in 1..=MAX_ATTEMPTS {let state = app.state::<crate::recording::RecordingState>();@@ -210,10 +274,10 @@ pub(crate) async fn restart_capture_on_mic_grant(app: tauri::AppHandle) {}}}- warn!(- "start_capture after mic grant: gave up after {} attempts ({}s): {}",+ error!(+ "start_capture after mic grant: gave up after {} attempts post-boot-ready ({}ms): {}",MAX_ATTEMPTS,- (MAX_ATTEMPTS as u64 * BACKOFF_MS) / 1000,+ MAX_ATTEMPTS as u64 * BACKOFF_MS,last_err.unwrap_or_else(|| "unknown error".to_string()));}@@ -1174,3 +1238,54 @@ pub fn request_arc_automation_permission(_app: tauri::AppHandle) -> bool {// subscribes via `crate::engine_events::permission` over /ws/events. This module// keeps the synchronous TCC/AV check helpers used by the onboarding UI// and the preflight startup check.++#[cfg(all(test, target_os = "macos"))]+mod mic_grant_restart_tests {+ use super::*;+ use std::sync::atomic::AtomicBool;++ // Regression for the mic-grant-restart guard: previously it was a+ // fire-once-per-process AtomicBool (`MIC_FOCUS_CAPTURE_RESTART` in+ // main.rs) that was set true and never reset, so if the first attempt+ // didn't land (e.g. the boot-wait timed out), no later window-focus+ // event could ever retry for the rest of the process's life (found during+ // the Intel-Mac CI smoke-test investigation, screenpipe#4978).+ #[test]+ fn guard_resets_after_scope_so_a_later_call_can_retry() {+ let flag = AtomicBool::new(false);++ assert!(+ flag.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)+ .is_ok(),+ "first entry should acquire the guard"+ );+ {+ let _guard = ResetGuard(&flag);+ assert!(flag.load(Ordering::SeqCst));+ } // guard drops here — must release the flag+ assert!(+ !flag.load(Ordering::SeqCst),+ "guard must reset the flag on drop so a later trigger (e.g. the \+ user refocusing the window) can retry"+ );++ // A later trigger can now acquire the guard again.+ assert!(flag+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)+ .is_ok());+ }++ #[test]+ fn concurrent_entry_is_rejected_while_first_is_in_flight() {+ let flag = AtomicBool::new(false);+ flag.store(true, Ordering::SeqCst);+ let _guard = ResetGuard(&flag);++ // A second caller (e.g. the direct AVCaptureDevice grant callback+ // firing at the same time as a window-focus event) must be rejected+ // while the first is still in flight.+ assert!(flag+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)+ .is_err());+ }+}