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
feat: make Pi a stable singleton — no watchdog, readiness handshake, auto-recovery
Louis Beaumontfa88740745a0
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex 10ef197fc..c832a36d3 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -660,7 +660,6 @@ export function StandaloneChat({ className }: { className?: string } = {}) {const piMessageIdRef = useRef<string | null>(null);const piContentBlocksRef = useRef<ContentBlock[]>([]);const piStartInFlightRef = useRef(false);- const piRestartCountRef = useRef(0);const piStoppedIntentionallyRef = useRef(false);const piThinkingStartRef = useRef<number | null>(null);const piSessionSyncedRef = useRef(false);@@ -1333,8 +1332,8 @@ export function StandaloneChat({ className }: { className?: string } = {}) {const isPi = true;const hasValidModel = activePreset?.model && activePreset.model.trim() !== "";const needsLogin = (activePreset?.provider === "screenpipe-cloud" || activePreset?.provider === "pi") && !settings.user?.token;- const piReady = piInfo?.running ?? false;- const canChat = hasPresets && hasValidModel && !needsLogin && piReady;+ // Pi auto-starts on first message, so don't block chat when Pi is not running+ const canChat = hasPresets && hasValidModel && !needsLogin && !piStarting;const getDisabledReason = (): string | null => {if (!hasPresets) return "No AI presets configured";@@ -1342,7 +1341,6 @@ export function StandaloneChat({ className }: { className?: string } = {}) {if (!hasValidModel) return `No model selected in "${activePreset.id}" preset`;if (needsLogin) return "Login required";if (piStarting) return "Starting Pi agent...";- if (!piReady) return "Connecting to Pi agent...";return null;};const disabledReason = getDisabledReason();@@ -1409,7 +1407,8 @@ export function StandaloneChat({ className }: { className?: string } = {}) {// Track previous preset to detect changesconst prevPresetRef = useRef<{ provider?: string; model?: string; token?: string | null }>({});- // Restart Pi when user switches preset (different provider/model) or token changes (login)+ // Update Pi config when user switches preset — no restart, just update config files.+ // Pi picks up the new provider/model on the next prompt.useEffect(() => {if (!activePreset) return;const prev = prevPresetRef.current;@@ -1419,55 +1418,12 @@ export function StandaloneChat({ className }: { className?: string } = {}) {prevPresetRef.current = { provider: activePreset.provider, model: activePreset.model, token: currentToken };if (!presetChanged && !tokenChanged) return;- if (piStartInFlightRef.current) return;- const restartPi = async () => {- // Clear any in-flight streaming state before killing Pi- if (piMessageIdRef.current) {- const msgId = piMessageIdRef.current;- setMessages((prev) =>- prev.map((m) =>- m.id === msgId && (m.content === "Processing..." || !m.content)- ? { ...m, content: "Model changed — restarting AI agent..." }- : m- )- );- piStreamingTextRef.current = "";- piMessageIdRef.current = null;- piContentBlocksRef.current = [];- setIsLoading(false);- setIsStreaming(false);- }- piStartInFlightRef.current = true;- setPiStarting(true);- const providerConfig = buildProviderConfig();- let dir: string;- try {- const home = await homeDir();- dir = await join(home, ".screenpipe", "pi-chat");- } catch {- dir = "/tmp/.screenpipe/pi-chat";- }- console.log("[Pi] Restarting with new preset:", providerConfig?.provider, providerConfig?.model);- try {- const result = await commands.piStart(dir, settings.user?.token ?? null, providerConfig);- if (result.status === "ok") {- setPiInfo(result.data);- piSessionSyncedRef.current = false;- } else {- console.error("[Pi] Restart failed:", result.error);- toast({ title: "Failed to restart Pi", description: result.error, variant: "destructive" });- }- } catch (e) {- console.error("[Pi] Restart exception:", e);- } finally {- setPiStarting(false);- // Keep the guard active for 2s to absorb delayed re-triggers from- // settings/loadUser cascades during boot (prevents double-start race)- setTimeout(() => { piStartInFlightRef.current = false; }, 2000);- }- };- restartPi();+ const providerConfig = buildProviderConfig();+ console.log("[Pi] Config updated (no restart):", providerConfig?.provider, providerConfig?.model);+ commands.piUpdateConfig(settings.user?.token ?? null, providerConfig).catch((e) => {+ console.error("[Pi] Config update failed:", e);+ });// eslint-disable-next-line react-hooks/exhaustive-deps}, [activePreset?.provider, activePreset?.model, settings.user?.token]);@@ -1698,7 +1654,6 @@ export function StandaloneChat({ className }: { className?: string } = {}) {}}} else if (data.type === "agent_end") {- piRestartCountRef.current = 0;if (piMessageIdRef.current) {const msgId = piMessageIdRef.current;// Use streamed text if available, otherwise extract from agent_end messages@@ -1827,8 +1782,6 @@ export function StandaloneChat({ className }: { className?: string } = {}) {const setup = async () => {unlistenEvent = await listen<any>("pi_event", (event) => {if (!mounted) return;- // Pi sent an event — it's running stably, reset restart counter- piRestartCountRef.current = 0;handlePiEventData(event.payload);});@@ -1851,14 +1804,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {return;}const terminatedPid = event.payload;- console.log("[Pi] Process terminated, pid:", terminatedPid, "restart count:", piRestartCountRef.current);-- // pid=0 means the idle watchdog stopped Pi to save resources — don't auto-restart- if (terminatedPid === 0) {- console.log("[Pi] Idle watchdog stopped Pi, skipping auto-restart");- setPiInfo(null);- return;- }+ console.log("[Pi] Process terminated, pid:", terminatedPid);// If a message was in flight, mark it as errored so the UI doesn't stay stuckif (piMessageIdRef.current) {@@ -1877,8 +1823,8 @@ export function StandaloneChat({ className }: { className?: string } = {}) {setIsStreaming(false);}- piRestartCountRef.current += 1;- const delay = Math.min(1000 * piRestartCountRef.current, 5000);+ // Always auto-restart — Pi is a singleton, keep it alive+ const delay = 1500;setTimeout(async () => {if (!mounted) return;// Check if a newer Pi process is already running (race: stop → start → terminated)@@ -1887,14 +1833,12 @@ export function StandaloneChat({ className }: { className?: string } = {}) {if (result.status === "ok" && result.data.running && result.data.pid !== terminatedPid) {console.log("[Pi] Stale termination for pid", terminatedPid, "— newer pid", result.data.pid, "is running");setPiInfo(result.data);- piRestartCountRef.current = 0;return;}} catch {}- // Pi is actually dead — auto-restart (up to 5 attempts)- if (piRestartCountRef.current <= 5 && !piStartInFlightRef.current) {- console.log("[Pi] Auto-restarting (attempt", piRestartCountRef.current, "/ 5)");+ if (!piStartInFlightRef.current) {+ console.log("[Pi] Auto-restarting after crash");try {const providerConfig = buildProviderConfig();const home = await homeDir();@@ -1903,23 +1847,15 @@ export function StandaloneChat({ className }: { className?: string } = {}) {if (result.status === "ok") {setPiInfo(result.data);piSessionSyncedRef.current = false;- if (result.data.running) piRestartCountRef.current = 0;} else {console.error("[Pi] Auto-restart failed:", result.error);- // Show error to user on final attempt so they know what's wrong- if (piRestartCountRef.current >= 5) {- toast({ title: "ai assistant failed to start", description: result.error, variant: "destructive" });- }+ // Don't give up — user can still trigger restart on next messagesetPiInfo(null);}} catch (e) {console.error("[Pi] Auto-restart exception:", e);setPiInfo(null);}- } else {- // All restart attempts exhausted- console.error("[Pi] All restart attempts exhausted");- setPiInfo(null);}}, delay);});@@ -2083,9 +2019,34 @@ export function StandaloneChat({ className }: { className?: string } = {}) {// Send message using Pi agentasync function sendPiMessage(userMessage: string, displayLabel?: string) {+ // Auto-start Pi if it's dead (singleton recovery)if (!piInfo?.running && !autoSendBypassRef.current) {- toast({ title: "Pi not running", description: "Please wait for Pi to start", variant: "destructive" });- return;+ if (piStartInFlightRef.current) {+ toast({ title: "Pi starting", description: "Please wait a moment", variant: "destructive" });+ return;+ }+ console.log("[Pi] Not running, auto-starting before sending message");+ piStartInFlightRef.current = true;+ setPiStarting(true);+ try {+ const providerConfig = buildProviderConfig();+ const home = await homeDir();+ const dir = await join(home, ".screenpipe", "pi-chat");+ const result = await commands.piStart(dir, settings.user?.token ?? null, providerConfig);+ if (result.status === "ok" && result.data.running) {+ setPiInfo(result.data);+ piSessionSyncedRef.current = false;+ } else {+ toast({ title: "Failed to start Pi", description: result.status === "error" ? result.error : "Unknown error", variant: "destructive" });+ return;+ }+ } catch (e) {+ toast({ title: "Failed to start Pi", description: String(e), variant: "destructive" });+ return;+ } finally {+ setPiStarting(false);+ piStartInFlightRef.current = false;+ }}// Prevent sending while a previous message is still being processeddiff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.tsindex 4c0faca47..638b1e246 100644--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts@@ -574,6 +574,17 @@ async piNewSession() : Promise<Result<null, string>> {else return { status: "error", error: e as any };}},+/**+ * Update Pi config files without restarting the process.+ */+async piUpdateConfig(userToken: string | null, providerConfig: PiProviderConfig | null) : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("pi_update_config", { userToken, providerConfig }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},/*** Check Reminders authorization + scheduler status (no popup).*/diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex 339c93929..a64cb3385 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -1224,6 +1224,7 @@ async fn main() {pi::pi_prompt,pi::pi_abort,pi::pi_new_session,+ pi::pi_update_config,// Reminders commandsreminders::reminders_status,reminders::reminders_authorize,@@ -1447,6 +1448,7 @@ async fn main() {pi::pi_prompt,pi::pi_abort,pi::pi_new_session,+ pi::pi_update_config,// Reminders commandsreminders::reminders_status,reminders::reminders_authorize,diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rsindex 551ee1f20..6c59d09c7 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs@@ -111,17 +111,9 @@ pub struct PiManager {project_dir: Option<String>,request_id: u64,app_handle: AppHandle,- /// Tracks last activity (creation or send_command) for idle shutdown+ /// Tracks last activity (creation or send_command)last_activity: std::time::Instant,- /// Handle to the idle watchdog task so stop() can abort it- watchdog_handle: Option<tokio::task::JoinHandle<()>>,- /// Shared flag: set by the idle watchdog before stopping Pi, read by the- /// stdout reader to decide whether to emit `pi_terminated(0)` (idle) or- /// `pi_terminated(pid)` (crash). Each Pi session creates a fresh Arc so- /// old reader threads don't interfere with new sessions.- idle_stopped: Arc<AtomicBool>,/// Guard: ensures only one `pi_terminated` event is emitted per session.- /// Both the reader thread and watchdog check-and-set this before emitting.terminated_emitted: Arc<AtomicBool>,}@@ -134,17 +126,10 @@ impl PiManager {request_id: 0,app_handle,last_activity: std::time::Instant::now(),- watchdog_handle: None,- idle_stopped: Arc::new(AtomicBool::new(false)),terminated_emitted: Arc::new(AtomicBool::new(false)),}}- /// How long since the last send_command() or creation- pub fn idle_duration(&self) -> std::time::Duration {- self.last_activity.elapsed()- }-/// Check if the child process is actually alive via try_wait()./// If the process has exited, cleans up child/stdin and returns false./// NOTE: does NOT emit `pi_terminated` — the stdout reader thread is the@@ -183,11 +168,6 @@ impl PiManager {}pub fn stop(&mut self) {- // Abort the idle watchdog first- if let Some(handle) = self.watchdog_handle.take() {- handle.abort();- }-if let Some(mut child) = self.child.take() {// Send abort command before killingif let Some(ref mut stdin) = self.stdin {@@ -596,10 +576,8 @@ fn kill_orphan_pi_processes(managed_alive: bool) {}}-/// Duration after which an idle Pi process is automatically stopped.-const PI_IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5 * 60);-/// How often the watchdog checks for idle / dead Pi processes.-const PI_WATCHDOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(30);+/// Max time to wait for Pi to emit its first stdout line (readiness handshake).+const PI_READY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);/// Resolve a model name against the screenpipe cloud models list./// Handles mismatches like "claude-haiku-4-5@20251001" when the list only has@@ -854,17 +832,13 @@ pub async fn pi_start_inner(let stderr = child.stderr.take();// Update manager- let idle_stopped = Arc::new(AtomicBool::new(false));let terminated_emitted = Arc::new(AtomicBool::new(false));if let Some(m) = manager_guard.as_mut() {m.child = Some(child);m.stdin = Some(stdin);m.project_dir = Some(project_dir.clone());- // Reset idle timer so the watchdog doesn't use a stale timestamp- // from a previous session and immediately kill this new processm.last_activity = std::time::Instant::now();- // Fresh flags for this session — old reader threads keep their own Arc- m.idle_stopped = idle_stopped.clone();+ // Fresh flag for this session — old reader threads keep their own Arcm.terminated_emitted = terminated_emitted.clone();}@@ -878,17 +852,19 @@ pub async fn pi_start_inner(// queued pi_start calls from stacking behind a 500ms sleep while holding the lockdrop(manager_guard);+ // Readiness signal — stdout reader notifies when first JSON line arrives,+ // so pi_start_inner can return without a blind 1500ms sleep.+ let ready_notify = Arc::new(tokio::sync::Notify::new());+ let ready_notify_reader = ready_notify.clone();+// Spawn stdout reader thread — this is the SOLE emitter of `pi_terminated`.- // Using idle_stopped (shared with the watchdog) to distinguish idle stops- // from crashes: idle → emit pid=0 (frontend skips restart), crash → emit- // real pid (frontend auto-restarts).let app_handle = app.clone();- let idle_stopped_reader = idle_stopped.clone();let terminated_guard = terminated_emitted.clone();std::thread::spawn(move || {let reader = BufReader::new(stdout);info!("Pi stdout reader started (pid: {})", pid);let mut line_count = 0u64;+ let mut ready_signalled = false;for line in reader.lines() {match line {Ok(line) => {@@ -899,6 +875,14 @@ pub async fn pi_start_inner(debug!("Pi stdout #{} (pid {}): type={}", line_count, pid,event_type.as_deref().unwrap_or("non-json"));+ // Signal readiness on first successful JSON line+ if !ready_signalled {+ if serde_json::from_str::<Value>(&line).is_ok() {+ ready_notify_reader.notify_one();+ ready_signalled = true;+ }+ }+// Try to parse as JSON and emit eventmatch serde_json::from_str::<Value>(&line) {Ok(event) => {@@ -923,10 +907,9 @@ pub async fn pi_start_inner(}}info!("Pi stdout reader ended (pid: {}), processed {} lines", pid, line_count);- // Only emit once per session — watchdog or overlapping sessions could race+ // Only emit once per session — overlapping sessions could raceif terminated_guard.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_ok() {- let terminated_pid = if idle_stopped_reader.load(Ordering::Acquire) { 0u32 } else { pid };- let _ = app_handle.emit("pi_terminated", terminated_pid);+ let _ = app_handle.emit("pi_terminated", pid);} else {debug!("Pi stdout reader: pi_terminated already emitted for this session, skipping");}@@ -968,48 +951,16 @@ pub async fn pi_start_inner(});}- // Spawn idle watchdog — auto-stops Pi after PI_IDLE_TIMEOUT of inactivity.- // The watchdog does NOT emit `pi_terminated` directly. Instead, it sets- // `idle_stopped` and calls stop(). The stdout reader thread detects EOF- // from the killed process and emits the single authoritative event.- {- let state_clone = state.0.clone();- let watchdog = tokio::spawn(async move {- loop {- tokio::time::sleep(PI_WATCHDOG_INTERVAL).await;- let mut guard = state_clone.lock().await;- if let Some(m) = guard.as_mut() {- if !m.check_alive() {- // Process already dead — stdout reader will emit pi_terminated- info!("Watchdog: Pi process is dead, reader thread will handle termination");- break;- }- let idle = m.idle_duration();- if idle >= PI_IDLE_TIMEOUT {- info!("Watchdog: Pi idle for {:?}, stopping to save resources", idle);- m.idle_stopped.store(true, Ordering::Release);- m.stop();- // stdout reader will see EOF and emit pi_terminated(0)- break;- }- } else {- // No manager — nothing to watch- break;- }- }- debug!("Watchdog task exiting");- });-- // Store the handle so stop() can abort it- let mut guard = state.0.lock().await;- if let Some(m) = guard.as_mut() {- m.watchdog_handle = Some(watchdog);+ // Wait for Pi to signal readiness (first JSON line on stdout) instead of+ // a blind 1500ms sleep. Falls back to process-alive check on timeout.+ tokio::select! {+ _ = ready_notify.notified() => {+ info!("Pi readiness signal received (pid: {})", pid);+ }+ _ = tokio::time::sleep(PI_READY_TIMEOUT) => {+ warn!("Pi readiness timeout after {:?} (pid: {}), checking if alive", PI_READY_TIMEOUT, pid);}}-- // Wait for Pi to initialize before allowing prompts. Pi v0.51+ needs time- // to set up its RPC listener — sending prompts too early causes them to be lost.- tokio::time::sleep(tokio::time::Duration::from_millis(1500)).await;{let mut manager_guard = state.0.lock().await;if let Some(m) = manager_guard.as_mut() {@@ -1018,10 +969,6 @@ pub async fn pi_start_inner(Ok(Some(status)) => {let code = status.code().unwrap_or(-1);error!("Pi process exited immediately with code {} — check 'Pi stderr:' warnings above for details (bun path: {})", code, bun_path);- // Clean up: abort watchdog so it doesn't emit stale pi_terminated events- if let Some(handle) = m.watchdog_handle.take() {- handle.abort();- }m.child = None;m.stdin = None;return Err(format!("Pi exited immediately with code {} (bun: {}). Check app logs for 'Pi stderr:' lines.", code, bun_path));@@ -1118,6 +1065,23 @@ pub async fn pi_check() -> Result<PiCheckResult, String> {})}+/// Update Pi config files (models.json / auth.json) without restarting the process.+/// Call this when the user changes preset — Pi picks up the new config on next prompt.+#[tauri::command]+#[specta::specta]+pub async fn pi_update_config(+ user_token: Option<String>,+ provider_config: Option<PiProviderConfig>,+) -> Result<(), String> {+ ensure_pi_config(user_token.as_deref(), provider_config.as_ref())?;+ info!(+ "Pi config updated (provider: {:?}, model: {:?})",+ provider_config.as_ref().map(|c| &c.provider),+ provider_config.as_ref().map(|c| &c.model),+ );+ Ok(())+}+/// Install pi via bun#[tauri::command]#[specta::specta]@@ -1615,24 +1579,6 @@ mod tests {assert_eq!(result, Some("C:\\Users\\npm\\pi.cmd".to_string()));}- /// Test that idle_duration tracks time correctly- #[test]- fn test_idle_duration_tracking() {- use std::time::{Duration, Instant};- // Simulate the tracking logic without needing a full PiManager- let start = Instant::now();- std::thread::sleep(Duration::from_millis(50));- let elapsed = start.elapsed();- assert!(elapsed >= Duration::from_millis(50));- assert!(elapsed < Duration::from_secs(2));-- // Simulate activity reset- let reset = Instant::now();- std::thread::sleep(Duration::from_millis(10));- let after_reset = reset.elapsed();- assert!(after_reset < elapsed, "activity reset should reduce idle duration");- }-/// Test that kill_orphan_pi_processes doesn't crash when no processes exist./// Ignored by default because pkill interferes with parallel tests.#[test]@@ -1649,12 +1595,10 @@ mod tests {super::kill_orphan_pi_processes(true);}- /// Test PI_IDLE_TIMEOUT and PI_WATCHDOG_INTERVAL constants are sensible+ /// Test PI_READY_TIMEOUT constant is sensible#[test]- fn test_idle_timeout_constants() {- assert_eq!(super::PI_IDLE_TIMEOUT.as_secs(), 300); // 5 minutes- assert_eq!(super::PI_WATCHDOG_INTERVAL.as_secs(), 30);- assert!(super::PI_IDLE_TIMEOUT > super::PI_WATCHDOG_INTERVAL);+ fn test_ready_timeout_constant() {+ assert_eq!(super::PI_READY_TIMEOUT.as_secs(), 15);}}