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: pi agent crash loop — concurrent start race condition

Louis Beaumont7a7c04a5064a
diff --git a/Cargo.lock b/Cargo.lock
index eb80cf724..2d6b864ed 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6628,7 +6628,7 @@ dependencies = [
[[package]]
name = "screenpipe-audio"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"anyhow",
"bytemuck",
@@ -6681,7 +6681,7 @@ dependencies = [
[[package]]
name = "screenpipe-core"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -6732,7 +6732,7 @@ dependencies = [
[[package]]
name = "screenpipe-db"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"anyhow",
"chrono",
@@ -6756,7 +6756,7 @@ dependencies = [
[[package]]
name = "screenpipe-events"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"anyhow",
"chrono",
@@ -6774,7 +6774,7 @@ dependencies = [
[[package]]
name = "screenpipe-integrations"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"anyhow",
"image",
@@ -6789,7 +6789,7 @@ dependencies = [
[[package]]
name = "screenpipe-server"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"anyhow",
"async-trait",
@@ -6858,7 +6858,7 @@ dependencies = [
[[package]]
name = "screenpipe-vision"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"accessibility-sys",
"anyhow",
diff --git a/apps/screenpipe-app-tauri/components/global-chat.tsx b/apps/screenpipe-app-tauri/components/global-chat.tsx
index e01f2482c..b54c7d35f 100644
--- a/apps/screenpipe-app-tauri/components/global-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/global-chat.tsx
@@ -570,6 +570,9 @@ export function GlobalChat() {
const [piStarting, setPiStarting] = useState(false);
const piStreamingTextRef = useRef<string>("");
const piMessageIdRef = useRef<string | null>(null);
+ const piStartInFlightRef = useRef(false); // guards against concurrent pi_start calls
+ const piRestartCountRef = useRef(0); // consecutive restarts without a successful prompt
+ const piStoppedIntentionallyRef = useRef(false); // true when we killed Pi on purpose
// Chat history state
const [conversationId, setConversationId] = useState<string | null>(null);
@@ -1081,9 +1084,22 @@ export function GlobalChat() {
return;
}
+ // Prevent concurrent pi_start calls (ref doesn't trigger re-renders)
+ if (piStartInFlightRef.current) {
+ return;
+ }
+
+ // Stop auto-restarting after 3 consecutive failures
+ if (piRestartCountRef.current >= 3) {
+ console.warn("[Pi] Too many restart attempts, giving up");
+ return;
+ }
+
const startPi = async () => {
+ piStartInFlightRef.current = true;
+ piStoppedIntentionallyRef.current = false;
setPiStarting(true);
- console.log("[Pi] Starting with dir:", piProjectDir);
+ console.log("[Pi] Starting with dir:", piProjectDir, "attempt:", piRestartCountRef.current + 1);
try {
const result = await commands.piStart(piProjectDir, settings.user?.token ?? null);
console.log("[Pi] Start result:", result);
@@ -1091,12 +1107,17 @@ export function GlobalChat() {
setPiInfo(result.data);
console.log("[Pi] Started successfully, piInfo:", result.data);
} else {
+ piRestartCountRef.current += 1;
console.error("[Pi] Start failed:", result.error);
- toast({ title: "Failed to start Pi", description: result.error, variant: "destructive" });
+ if (piRestartCountRef.current >= 3) {
+ toast({ title: "Failed to start Pi", description: result.error, variant: "destructive" });
+ }
}
} catch (e) {
+ piRestartCountRef.current += 1;
console.error("[Pi] Start exception:", e);
} finally {
+ piStartInFlightRef.current = false;
setPiStarting(false);
}
};
@@ -1159,6 +1180,7 @@ export function GlobalChat() {
} else if (data.type === "agent_end") {
// Agent finished - final update
console.log("[Pi] Agent ended");
+ piRestartCountRef.current = 0; // successful round-trip, reset restart counter
if (piMessageIdRef.current) {
const msgId = piMessageIdRef.current;
const content = piStreamingTextRef.current || "Done";
@@ -1188,8 +1210,19 @@ export function GlobalChat() {
unlistenTerminated = await listen("pi_terminated", () => {
if (!mounted) return;
- console.log("[Pi] Process terminated");
- setPiInfo(null);
+ // If we intentionally stopped Pi (e.g. to restart), don't auto-restart
+ if (piStoppedIntentionallyRef.current) {
+ console.log("[Pi] Process terminated (intentional)");
+ piStoppedIntentionallyRef.current = false;
+ return;
+ }
+ console.log("[Pi] Process terminated unexpectedly, restart count:", piRestartCountRef.current);
+ piRestartCountRef.current += 1;
+ // Delay before allowing restart to break rapid crash loops
+ setTimeout(() => {
+ if (!mounted) return;
+ setPiInfo(null); // triggers the auto-start useEffect
+ }, Math.min(1000 * piRestartCountRef.current, 5000));
});
// Also listen for raw output for debugging
@@ -1265,6 +1298,7 @@ export function GlobalChat() {
useEffect(() => {
if (open) {
posthog.capture("chat_opened");
+ piRestartCountRef.current = 0; // reset restart counter on manual open
setTimeout(() => inputRef.current?.focus(), 100);
} else {
// Reset chat state when dialog closes
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index 59a6bf51f..d630ebbdf 100755
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -9007,7 +9007,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.0.259"
+version = "2.0.260"
dependencies = [
"anyhow",
"async-stream",
@@ -9089,7 +9089,7 @@ dependencies = [
[[package]]
name = "screenpipe-audio"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"anyhow",
"bytemuck",
@@ -9137,7 +9137,7 @@ dependencies = [
[[package]]
name = "screenpipe-core"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -9188,7 +9188,7 @@ dependencies = [
[[package]]
name = "screenpipe-db"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"anyhow",
"chrono",
@@ -9212,7 +9212,7 @@ dependencies = [
[[package]]
name = "screenpipe-events"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"anyhow",
"chrono",
@@ -9228,7 +9228,7 @@ dependencies = [
[[package]]
name = "screenpipe-integrations"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"anyhow",
"image 0.25.9",
@@ -9243,7 +9243,7 @@ dependencies = [
[[package]]
name = "screenpipe-server"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"anyhow",
"async-trait",
@@ -9307,7 +9307,7 @@ dependencies = [
[[package]]
name = "screenpipe-vision"
-version = "0.3.53"
+version = "0.3.54"
dependencies = [
"accessibility-sys",
"anyhow",
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index 47748a59f..b4c75dc76 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -375,6 +375,16 @@ pub async fn pi_start(
m.project_dir = Some(project_dir.clone());
}
+ // Snapshot the state BEFORE dropping the lock, so we don't hold it during I/O
+ let snapshot = match manager_guard.as_ref() {
+ Some(m) => m.snapshot(),
+ None => PiInfo::default(),
+ };
+
+ // Drop the lock before spawning reader threads — this is critical to prevent
+ // queued pi_start calls from stacking behind a 500ms sleep while holding the lock
+ drop(manager_guard);
+
// Spawn stdout reader thread
let app_handle = app.clone();
std::thread::spawn(move || {
@@ -383,12 +393,9 @@ pub async fn pi_start(
for line in reader.lines() {
match line {
Ok(line) => {
- // Log all output at info level for debugging
- info!("Pi stdout: {}", line);
// Try to parse as JSON and emit event
match serde_json::from_str::<Value>(&line) {
Ok(event) => {
- info!("Pi event type: {:?}", event.get("type"));
if let Err(e) = app_handle.emit("pi_event", &event) {
error!("Failed to emit pi_event: {}", e);
}
@@ -420,7 +427,6 @@ pub async fn pi_start(
for line in reader.lines() {
match line {
Ok(line) => {
- // Log all stderr at info level for debugging
info!("Pi stderr: {}", line);
let _ = app_handle.emit("pi_log", &line);
}
@@ -431,13 +437,32 @@ pub async fn pi_start(
});
}
- // Wait a moment for initialization
- tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
-
- match manager_guard.as_ref() {
- Some(m) => Ok(m.snapshot()),
- None => Ok(PiInfo::default()),
+ // Brief wait then check if process died immediately (e.g. bad config, missing deps)
+ tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;
+ {
+ let mut manager_guard = state.0.lock().await;
+ if let Some(m) = manager_guard.as_mut() {
+ if let Some(ref mut child) = m.child {
+ match child.try_wait() {
+ Ok(Some(status)) => {
+ let code = status.code().unwrap_or(-1);
+ error!("Pi process exited immediately with code {}", code);
+ m.child = None;
+ m.stdin = None;
+ return Err(format!("Pi exited immediately with code {}", code));
+ }
+ Ok(None) => {
+ // Still running — good
+ }
+ Err(e) => {
+ warn!("Failed to check pi process status: {}", e);
+ }
+ }
+ }
+ }
}
+
+ Ok(snapshot)
}
/// Send a prompt to Pi