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-queue): gate queue advance on agent_start, not response ACK

Louis Beaumont2949c81267f5
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index 510e1ecdd..435309729 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -523,6 +523,34 @@ fn find_local_pi_entrypoint() -> Option<String> {
}
}
+/// Extract the plain-text content from a pi-mono `message` JSON value (the
+/// shape that ships in `message_start`/`message_end` events). pi-mono encodes
+/// user messages as either `content: "string"` or
+/// `content: [{type: "text", text: "..."}, ...]`. We concatenate all text
+/// parts in order. Used to match an incoming user message against the queued
+/// prompt rail's preview text.
+fn extract_user_message_text(msg: &serde_json::Value) -> String {
+ let content = match msg.get("content") {
+ Some(c) => c,
+ None => return String::new(),
+ };
+ if let Some(s) = content.as_str() {
+ return s.to_string();
+ }
+ if let Some(arr) = content.as_array() {
+ let mut out = String::new();
+ for part in arr {
+ if part.get("type").and_then(|t| t.as_str()) == Some("text") {
+ if let Some(t) = part.get("text").and_then(|v| v.as_str()) {
+ out.push_str(t);
+ }
+ }
+ }
+ return out;
+ }
+ String::new()
+}
+
fn find_pi_executable() -> Option<String> {
// 1. Check screenpipe-managed local install first (preferred — we control the deps)
if let Some(js) = find_local_pi_entrypoint() {
@@ -1537,21 +1565,59 @@ pub async fn pi_start_inner(
// prompt was sent while the first was still running.
if let Some(ref qs) = queue_state_for_reader {
match event_type.as_deref() {
+ Some("agent_start") => {
+ // A prompt has begun streaming. Suppress the
+ // response→done fallback below so the prompt's
+ // mid-stream `response` ACK doesn't unblock the
+ // queue early.
+ qs.mark_agent_active();
+ }
Some("agent_end") => {
- // Agent fully done — unblock the queue immediately.
+ // Note: pi-mono fires `agent_end` mid-prompt during
+ // its auto-retry path. Only `mark_agent_idle` here —
+ // pi-mono's followUp queue (engaged via
+ // `streamingBehavior: "followUp"` on prompt commands)
+ // is what serializes back-to-back prompts now, so we
+ // don't need `signal_done` to gate the next prompt.
+ // The done_notify is still fired so WaitDone callers
+ // (new_session/abort) advance.
+ qs.mark_agent_idle();
qs.signal_done();
}
+ Some("message_start") => {
+ // Pi-mono just started processing a message. If it's
+ // a user message, find the matching entry in the
+ // queued-prompt rail and remove it — this is the
+ // moment the prompt transitions from "queued in
+ // pi-mono's followUp queue" to in-flight.
+ if let Some(parsed_v) = parsed.as_ref() {
+ if let Some(msg) = parsed_v.get("message") {
+ let role = msg.get("role").and_then(|r| r.as_str());
+ if role == Some("user") {
+ let text = extract_user_message_text(msg);
+ if !text.is_empty() {
+ qs.dequeue_first_matching_text(&text);
+ }
+ }
+ }
+ }
+ }
Some("response") => {
- // Fallback for new_session/abort when no active prompt is
- // running (no agent_end fires in that case). Also covers the
- // prompt ACK path as a safety net.
- // Note: this runs on a std::thread (not tokio), so use
- // std::thread::spawn + std::thread::sleep.
- let qs = qs.clone();
- std::thread::spawn(move || {
- std::thread::sleep(std::time::Duration::from_millis(500));
- qs.signal_done();
- });
+ // Only meaningful for new_session/abort — those don't
+ // fire agent_start/agent_end. For prompts (which use
+ // WriteOnly and rely on pi-mono's internal queue),
+ // firing done here is unnecessary; suppress while a
+ // prompt is mid-stream so we don't race the active
+ // turn for any blocking caller.
+ if !qs.is_agent_active() {
+ // Note: this runs on a std::thread (not tokio),
+ // so use std::thread::spawn + std::thread::sleep.
+ let qs = qs.clone();
+ std::thread::spawn(move || {
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ qs.signal_done();
+ });
+ }
}
_ => {}
}
@@ -1737,9 +1803,16 @@ pub async fn pi_prompt(
.ok_or("Pi command queue not initialized")?
};
+ // `streamingBehavior: "followUp"` tells pi-mono to internally queue this
+ // prompt when its agent is mid-stream (instead of throwing "Agent is
+ // already processing"). pi-mono ignores this option when idle, so it's
+ // safe to set unconditionally. This is the SDK-blessed way to handle
+ // back-to-back prompts and is robust against pi-mono's auto-retry path,
+ // which otherwise fires `agent_end` mid-prompt and would race our queue.
let mut cmd = json!({
"type": "prompt",
- "message": message
+ "message": message,
+ "streamingBehavior": "followUp",
});
if let Some(imgs) = images {
if !imgs.is_empty() {
@@ -1747,12 +1820,17 @@ pub async fn pi_prompt(
}
}
- // Send through the prompt-aware path so the queue UI shows it as queued
- // until the drain loop pulls and writes it to stdin.
+ // Send through the prompt-aware path so the queue UI surfaces this entry
+ // until pi-mono confirms it's started processing (via message_start).
+ // WriteOnly mode: the drain loop writes to stdin and advances immediately
+ // — pi-mono's followUp queue handles serialization with any in-flight
+ // prompt. Combined with `streamingBehavior: "followUp"` on the command,
+ // this avoids the "already processing" race that fires when the agent
+ // momentarily idles between auto-retries.
let (_queue_id, rx) = queue
.send_prompt(
cmd,
- crate::pi_command_queue::WaitMode::StreamThenWaitDone,
+ crate::pi_command_queue::WaitMode::WriteOnly,
message.clone(),
)
.await?;
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rs
index 88ce28abd..e86473d8b 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rs
@@ -22,6 +22,7 @@ use serde_json::{json, Value};
use specta::Type;
use std::io::Write;
use std::process::ChildStdin;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot, watch, Mutex, Notify};
use tracing::{debug, error, info, warn};
@@ -62,10 +63,15 @@ pub struct PiCommand {
/// How the queue waits after writing a command to stdin.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WaitMode {
- /// Write to stdin, reply immediately, but don't dequeue the next command until
- /// the SDK emits `done`. Used for `prompt` — the frontend needs streaming events
- /// to start flowing immediately.
- StreamThenWaitDone,
+ /// Write to stdin, reply Ok, advance immediately. Used for `prompt`
+ /// commands that include `streamingBehavior: "followUp"` — pi-mono owns
+ /// prompt serialization (its internal followUp queue handles back-to-back
+ /// prompts during streaming AND during auto-retry's mid-prompt agent_end
+ /// gap). The Rust queue must NOT block on `agent_end`, because pi-mono
+ /// fires that event mid-prompt during auto-retry and our drain loop would
+ /// race the still-running turn. The "queued" UI rail is cleared by the
+ /// stdout reader when pi-mono fires `message_start` for the user message.
+ WriteOnly,
/// Write to stdin, wait for `done`, then reply and dequeue. Used for `new_session`
/// and `abort` where the caller must know the SDK is fully idle before proceeding.
WaitDone,
@@ -112,6 +118,15 @@ pub struct PiQueueState {
/// can't pluck a specific entry out of it — instead the drain loop
/// checks this set when popping and skips the write.
cancelled: std::sync::Mutex<std::collections::HashSet<String>>,
+ /// True between `agent_start` and `agent_end` — i.e. while the SDK is
+ /// actively processing a `prompt`. Read by the stdout reader to suppress
+ /// the `response → 500ms → signal_done` fallback on prompt ACKs (those
+ /// fire mid-stream and would unblock the drain loop early, causing the
+ /// next queued prompt to race the still-running one and trip the SDK's
+ /// "already processing" error). For prompts, `agent_end` is the
+ /// authoritative done signal; the response-fallback only matters for
+ /// new_session/abort, which never fire agent_start.
+ agent_active: AtomicBool,
}
impl PiQueueState {
@@ -124,6 +139,7 @@ impl PiQueueState {
alive: alive_tx,
queued: queued_tx,
cancelled: std::sync::Mutex::new(std::collections::HashSet::new()),
+ agent_active: AtomicBool::new(false),
})
}
@@ -132,6 +148,22 @@ impl PiQueueState {
self.done_notify.notify_one();
}
+ /// Called by the stdout reader on `agent_start` (a prompt has begun streaming).
+ pub fn mark_agent_active(&self) {
+ self.agent_active.store(true, Ordering::SeqCst);
+ }
+
+ /// Called by the stdout reader on `agent_end` (a prompt has finished).
+ pub fn mark_agent_idle(&self) {
+ self.agent_active.store(false, Ordering::SeqCst);
+ }
+
+ /// Whether a prompt is currently mid-stream. Used by the stdout reader to
+ /// decide whether to fire the `response → 500ms → signal_done` fallback.
+ pub fn is_agent_active(&self) -> bool {
+ self.agent_active.load(Ordering::SeqCst)
+ }
+
/// Called by the stdout reader when the process terminates (EOF).
pub fn signal_terminated(&self) {
let _ = self.alive.send(false);
@@ -140,6 +172,9 @@ impl PiQueueState {
self.done_notify.notify_waiters();
// Drop any queued prompts so subscribers stop showing them — Pi died.
self.queued.send_modify(|v| v.clear());
+ // Clear the agent-active flag so a future restart doesn't start out
+ // in a stuck "active" state if the process died mid-stream.
+ self.agent_active.store(false, Ordering::SeqCst);
}
/// Subscribe to queue-pending changes. Each receive yields the current
@@ -165,6 +200,30 @@ impl PiQueueState {
});
}
+ /// Remove the first queued entry whose preview matches the given user
+ /// message text. Called by the stdout reader when pi-mono fires
+ /// `message_start` with a user message — that's the moment a prompt
+ /// transitions from "waiting in pi-mono's followUp queue" to "in-flight",
+ /// and is the right moment to clear the UI rail entry. Returns whether a
+ /// match was found and removed.
+ ///
+ /// Matching is by preview text (truncated to 200 chars at enqueue time).
+ /// Pi-mono uses the same FIFO match-by-text strategy in its own queue, so
+ /// this stays consistent: if the user enqueues two identical prompts, the
+ /// first message_start dequeues the first entry, the second dequeues the
+ /// second.
+ pub fn dequeue_first_matching_text(&self, text: &str) -> bool {
+ let preview: String = text.chars().take(200).collect();
+ let mut removed = false;
+ self.queued.send_modify(|v| {
+ if let Some(pos) = v.iter().position(|p| p.preview == preview) {
+ v.remove(pos);
+ removed = true;
+ }
+ });
+ removed
+ }
+
/// Mark a prompt id as cancelled so the drain loop drops it on dequeue
/// instead of writing to stdin. Returns whether it was actually in the
/// queued list at the time of the call.
@@ -245,9 +304,15 @@ impl PiQueueHandle {
.await
.map_err(|_| "Pi command queue closed".to_string())?;
- // mpsc accepted the command — make it visible to subscribers. The
- // drain loop will remove this entry the moment it pulls + writes.
- self.state.enqueue_prompt(meta);
+ // Only surface in the "queued · waiting for current reply" UI rail
+ // when the agent is actually mid-stream. For a first prompt to an
+ // idle agent, pi-mono fires `message_start` within milliseconds and
+ // showing it as "queued" briefly is confusing — skip the rail entry.
+ // The stdout reader's `message_start` handler is a no-op when the
+ // entry isn't present (it dequeues by text match).
+ if self.state.is_agent_active() {
+ self.state.enqueue_prompt(meta);
+ }
Ok((id, rx))
}
@@ -371,20 +436,24 @@ pub fn spawn_queue(
continue;
}
- // Successful write — the prompt is now in-flight, no longer
- // "queued" from the UI's perspective.
- if let Some(pid) = &prompt_id {
- state.dequeue_prompt(pid);
- }
-
match cmd.wait_mode {
- WaitMode::StreamThenWaitDone => {
- // Reply immediately so streaming events start flowing to frontend
+ WaitMode::WriteOnly => {
+ // Pi-mono owns serialization for prompts via its
+ // internal followUp queue. We don't wait for done
+ // and we don't dequeue from the UI rail here —
+ // the entry stays visible until pi-mono fires
+ // `message_start` for the user message, at which
+ // point the stdout reader removes it.
let _ = cmd.reply.send(Ok(()));
- // But block the queue until done
- wait_for_done_or_terminated(&state, &mut alive_rx, &cmd_type).await;
}
WaitMode::WaitDone => {
+ // Successful write — for blocking commands the
+ // entry should be removed from the queued rail
+ // immediately (it's now in-flight, not waiting).
+ // Prompts use WriteOnly and skip this branch.
+ if let Some(pid) = &prompt_id {
+ state.dequeue_prompt(pid);
+ }
// Block until done, then reply
let ok =
wait_for_done_or_terminated(&state, &mut alive_rx, &cmd_type).await;
@@ -421,6 +490,11 @@ pub fn spawn_queue(
// queued-prompt list. The drain above should cover them
// but a paranoid clear is cheap and correct.
state.queued.send_modify(|v| v.clear());
+ // Abort halts the agent loop. Clear the active flag so
+ // the abort's `response` ACK is allowed to fire the
+ // done-fallback (otherwise the wait below hangs until
+ // the 300s safety timeout — abort would never reply).
+ state.mark_agent_idle();
if cancelled > 0 {
info!(
"pi_command_queue: abort cancelled {} pending commands",
@@ -553,7 +627,7 @@ mod tests {
// Send a command in the background
let h = tokio::spawn(async move {
let result = handle
- .send(json!({"type": "prompt"}), WaitMode::StreamThenWaitDone)
+ .send(json!({"type": "prompt"}), WaitMode::WriteOnly)
.await;
assert!(result.is_ok());
// The receiver should work
@@ -563,7 +637,7 @@ mod tests {
// Receive from the channel and complete it
if let Some(QueueMessage::Command(cmd)) = rx.recv().await {
- assert_eq!(cmd.wait_mode, WaitMode::StreamThenWaitDone);
+ assert_eq!(cmd.wait_mode, WaitMode::WriteOnly);
let _ = cmd.reply.send(Ok(()));
}
@@ -581,7 +655,7 @@ mod tests {
let h1 = {
let h = handle.clone();
tokio::spawn(async move {
- h.send(json!({"type": "prompt"}), WaitMode::StreamThenWaitDone)
+ h.send(json!({"type": "prompt"}), WaitMode::WriteOnly)
.await
})
};