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
refactor: install Pi at app startup in Rust background thread
Louis Beaumontf31dfaa4da5c
diff --git a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsxindex ca7d794ed..9055abda4 100644--- a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx@@ -54,7 +54,6 @@ import {import { Textarea } from "./ui/textarea";import { Slider } from "./ui/slider";import { AIPreset, commands } from "@/lib/utils/tauri";-import { listen } from "@tauri-apps/api/event";// Helper to detect UUID-like strings and format preset names nicelyconst formatPresetName = (name: string): string => {@@ -134,7 +133,7 @@ export function AIProviderConfig({const [showApiKey, setShowApiKey] = useState(false);const [piAvailable, setPiAvailable] = useState(false);- // Check Pi availability+ // Check Pi availability (installed at app startup by Rust background thread)useEffect(() => {const checkPi = async () => {try {@@ -147,16 +146,9 @@ export function AIProviderConfig({}};checkPi();-- const unlisten = listen<boolean>("pi_installed", (event) => {- if (event.payload) {- setPiAvailable(true);- }- });-- return () => {- unlisten.then((fn) => fn());- };+ // Re-check periodically in case background install finishes+ const interval = setInterval(checkPi, 5000);+ return () => clearInterval(interval);}, []);const [formData, setFormData] = useState<AIPreset>({provider: defaultPreset?.provider || "openai",diff --git a/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx b/apps/screenpipe-app-tauri/components/settings/ai-presets.tsxindex 68851e694..8bce6f58a 100644--- a/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx+++ b/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx@@ -56,7 +56,6 @@ import {} from "@/components/ui/alert-dialog";import { cn } from "@/lib/utils";import { AIPreset, commands } from "@/lib/utils/tauri";-import { listen } from "@tauri-apps/api/event";import {validatePresetName,validateUrl,@@ -816,34 +815,19 @@ export const AIPresets = () => {);const [isDuplicating, setIsDuplicating] = useState(false);const [piAvailable, setPiAvailable] = useState(false);- const [piInstalling, setPiInstalling] = useState(false);- // Check Pi availability and install if needed (background)+ // Check Pi availability (installed at app startup by Rust background thread)useEffect(() => {- const checkAndInstallPi = async () => {+ const checkPi = async () => {const result = await commands.piCheck();if (result.status === "ok" && result.data.available) {setPiAvailable(true);- } else {- // Try to install in background- setPiInstalling(true);- await commands.piInstall();- }- };-- checkAndInstallPi();-- // Listen for install completion- const unlisten = listen<boolean>("pi_installed", (event) => {- setPiInstalling(false);- if (event.payload) {- setPiAvailable(true);}- });-- return () => {- unlisten.then((fn) => fn());};+ checkPi();+ // Re-check periodically in case background install finishes+ const interval = setInterval(checkPi, 5000);+ return () => clearInterval(interval);}, []);useEffect(() => {diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex e786dc264..76e910bab 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -965,36 +965,9 @@ export function StandaloneChat() {}}, [isPi, piProjectDir]);- // Auto-install Pi if not available- const [piInstalling, setPiInstalling] = useState(false);+ // Start Pi when needed (Pi is installed at app startup by Rust background thread)useEffect(() => {- if (!isPi) return;- const checkAndInstall = async () => {- const result = await commands.piCheck();- if (result.status === "ok" && result.data.available) return;- console.log("[Pi] Not found, installing in background...");- setPiInstalling(true);- await commands.piInstall();- };- checkAndInstall();-- const unlisten = listen<boolean>("pi_installed", (event) => {- setPiInstalling(false);- if (event.payload) {- console.log("[Pi] Installed successfully, will auto-start");- piRestartCountRef.current = 0; // reset so auto-start kicks in- } else {- console.error("[Pi] Installation failed");- toast({ title: "Failed to install Pi", description: "Install manually: bun add -g @mariozechner/pi-coding-agent", variant: "destructive" });- }- });-- return () => { unlisten.then((fn_) => fn_()); };- }, [isPi]);-- // Start Pi when needed- useEffect(() => {- const shouldStart = isPi && !needsLogin && piProjectDir && !piStarting && !piInfo?.running && !piInstalling;+ const shouldStart = isPi && !needsLogin && piProjectDir && !piStarting && !piInfo?.running;if (!shouldStart) return;if (piStartInFlightRef.current) return;@@ -1032,7 +1005,7 @@ export function StandaloneChat() {}};startPi();- }, [isPi, needsLogin, piProjectDir, piStarting, piInfo?.running, piInstalling, settings.user?.token]);+ }, [isPi, needsLogin, piProjectDir, piStarting, piInfo?.running, settings.user?.token]);// Listen for Pi eventsuseEffect(() => {diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex 952eeb30b..7b3d86a19 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -1327,6 +1327,9 @@ async fn main() {// Autostart setuplet autostart_manager = app.autolaunch();+ // Install Pi coding agent in background (fire-and-forget, never crashes)+ crate::pi::ensure_pi_installed_background();+info!("Local data directory: {}", base_dir.display());// PostHog analytics setupdiff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rsindex e7f56160d..671e1956e 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs@@ -631,28 +631,8 @@ pub async fn pi_check() -> Result<PiCheckResult, String> {pub async fn pi_install(app: AppHandle) -> Result<(), String> {info!("Installing pi via bun...");- let home = dirs::home_dir()- .map(|h| h.to_string_lossy().to_string())- .unwrap_or_default();-- #[cfg(unix)]- let bun_paths = vec![- format!("{}/.bun/bin/bun", home),- "/opt/homebrew/bin/bun".to_string(),- "/usr/local/bin/bun".to_string(),- ];-- #[cfg(windows)]- let bun_paths = vec![- format!("{}\\.bun\\bin\\bun.exe", home),- format!("{}\\AppData\\Local\\bun\\bin\\bun.exe", home),- ];-- let bun = bun_paths- .iter()- .find(|p| std::path::Path::new(p).exists())- .ok_or("Could not find bun. Install from https://bun.sh")?- .clone();+ let bun = find_bun_executable()+ .ok_or("Could not find bun. Install from https://bun.sh")?;let app_handle = app.clone();std::thread::spawn(move || {@@ -778,6 +758,89 @@ pub fn kill(pid: u32) -> Result<(), String> {Ok(())}+/// Find bun executable (shared by pi_install and ensure_pi_installed_background)+fn find_bun_executable() -> Option<String> {+ let home = dirs::home_dir()+ .map(|h| h.to_string_lossy().to_string())+ .unwrap_or_default();++ #[cfg(unix)]+ let paths = vec![+ format!("{}/.bun/bin/bun", home),+ "/opt/homebrew/bin/bun".to_string(),+ "/usr/local/bin/bun".to_string(),+ ];++ #[cfg(windows)]+ let paths = vec![+ format!("{}\\.bun\\bin\\bun.exe", home),+ format!("{}\\AppData\\Local\\bun\\bin\\bun.exe", home),+ ];++ paths.into_iter().find(|p| std::path::Path::new(p).exists())+}++/// Background Pi installation — call once from app setup.+/// Runs on a dedicated thread, never panics, never blocks the caller.+pub fn ensure_pi_installed_background() {+ match std::thread::Builder::new()+ .name("pi-install".to_string())+ .spawn(move || {+ // Catch any unexpected panic so it can never crash the app+ let result = std::panic::catch_unwind(|| {+ // Already installed? Nothing to do.+ if find_pi_executable().is_some() {+ debug!("Pi already installed, skipping background install");+ return;+ }++ let bun = match find_bun_executable() {+ Some(b) => b,+ None => {+ info!("Bun not found, skipping Pi background install");+ return;+ }+ };++ info!("Pi not found — installing via bun in background");++ let mut cmd = std::process::Command::new(&bun);+ cmd.args(["add", "-g", PI_PACKAGE]);++ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ const CREATE_NO_WINDOW: u32 = 0x08000000;+ cmd.creation_flags(CREATE_NO_WINDOW);+ }++ match cmd.output() {+ Ok(output) if output.status.success() => {+ info!("Pi installed successfully in background");+ }+ Ok(output) => {+ let stderr = String::from_utf8_lossy(&output.stderr);+ warn!("Pi background install failed (non-fatal): {}", stderr);+ }+ Err(e) => {+ warn!("Pi background install error (non-fatal): {}", e);+ }+ }+ });++ if let Err(e) = result {+ // Panic was caught — log and move on+ error!("Pi background install panicked (non-fatal): {:?}", e);+ }+ })+ {+ Ok(_) => { /* thread running */ }+ Err(e) => {+ error!("Failed to spawn pi-install thread (non-fatal): {}", e);+ }+ }+}+#[cfg(test)]mod tests {#[cfg(windows)]