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(chat): keep loader active across tool boundaries (#6591)

Ezra Ellette82e683cb59c0
diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts
index e8c1766c1..b5c5a8951 100644
--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts
+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts
@@ -988,6 +988,17 @@ export function usePiForegroundEvents({
}
}
+ // Pi also emits agent_end at tool-use boundaries. The native queue
+ // annotates those events from its durable agent/tool/steer state;
+ // keep this assistant row live until the logical turn actually
+ // settles instead of flashing a false "done" receipt after a tool.
+ if (!isPipeWatch && data.turnBusy === true) {
+ setIsLoading(true);
+ setIsStreaming(true);
+ emitSessionActivity({ status: "streaming" });
+ return;
+ }
+
// Always clear loading/streaming state on agent_end, even if piMessageIdRef is null
// This fixes the "stuck loading" bug when the ref was cleared prematurely
if (!isPipeWatch) {
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts
index fea0b0457..1d8a511c1 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts
@@ -205,6 +205,33 @@ describe("pi-event-router: status mirroring for backgrounded sessions", () => {
expect(useChatStore.getState().sessions.A.status).toBe("streaming");
});
+ it("stays streaming across an intermediate tool-boundary agent_end", async () => {
+ seed("A", {
+ status: "tool",
+ streamingMessageId: "assistant-1",
+ streamingText: "",
+ contentBlocks: [],
+ messages: [
+ {
+ id: "assistant-1",
+ role: "assistant",
+ content: "",
+ timestamp: 1_000,
+ },
+ ],
+ messageCount: 1,
+ });
+ useChatStore.setState({ currentId: "B" });
+
+ await handlePiEvent(piEvt("A", { type: "agent_end", turnBusy: true }));
+ await Promise.resolve();
+
+ const session = useChatStore.getState().sessions.A;
+ expect(session.status).toBe("streaming");
+ expect(session.streamingMessageId).toBe("assistant-1");
+ expect(routerCommandMocks.piStopIfIdle).not.toHaveBeenCalled();
+ });
+
it("marks an exhausted automatic retry as an error", async () => {
seed("A", { status: "streaming" });
useChatStore.setState({ currentId: "B" });
diff --git a/apps/screenpipe-app-tauri/lib/events/types.ts b/apps/screenpipe-app-tauri/lib/events/types.ts
index 8113dbcde..dc4241edc 100644
--- a/apps/screenpipe-app-tauri/lib/events/types.ts
+++ b/apps/screenpipe-app-tauri/lib/events/types.ts
@@ -61,6 +61,8 @@ export interface AgentInnerEvent {
isError?: boolean;
/** Pi keeps the logical turn active across provider retry backoff. */
willRetry?: boolean;
+ /** The native queue still owns tool/steer work after an intermediate agent_end. */
+ turnBusy?: boolean;
success?: boolean;
attempt?: number;
maxAttempts?: number;
diff --git a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
index 81d2ce708..e452a09bd 100644
--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
@@ -131,10 +131,10 @@ export function statusForEvent(evt: PiInnerEvent): SessionStatus | null {
case "tool_execution_end":
return "streaming";
case "agent_end":
- // Pi emits agent_end before its retry backoff. `willRetry` means the
- // logical turn is still active; marking it idle here makes foreground
- // and background composers send directly into a busy process.
- if (evt.willRetry === true) return "streaming";
+ // Retry backoff and tool-use boundaries both keep the logical turn
+ // active. The native queue owns this predicate so the sidebar and the
+ // transcript cannot disagree about whether work is still in flight.
+ if (evt.willRetry === true || evt.turnBusy === true) return "streaming";
if (evt.message?.stopReason === "error") return "error";
return "idle";
case "turn_end":
@@ -894,6 +894,7 @@ function applyEventToSessionContent(sid: string, payload: PiInnerEvent) {
// a chat that completes while the user is looking elsewhere still
// ends up on disk and survives a restart.
if (t === "agent_end") {
+ if ((payload as { turnBusy?: boolean }).turnBusy === true) return;
store.actions.endTurn(sid);
const willRetry = (payload as { willRetry?: boolean }).willRetry === true;
void persistBackgroundSession(sid).finally(() => {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index 2668806b2..f3db5a421 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -713,6 +713,21 @@ fn sync_queue_state_from_event(
}
}
+/// Apply an SDK event to the durable queue state, then expose whether an
+/// `agent_end` was only an intermediate tool boundary to the webview. Pi can
+/// end the assistant's tool-request message before the tool result and the
+/// follow-up assistant message exist; the queue already preserves that logical
+/// turn, so the visible loading state must use the same predicate.
+fn sync_and_annotate_queue_state(
+ queue_state: &Arc<crate::pi_command_queue::PiQueueState>,
+ event: &mut Value,
+) {
+ sync_queue_state_from_event(queue_state, event);
+ if event.get("type").and_then(Value::as_str) == Some("agent_end") {
+ event["turnBusy"] = Value::Bool(queue_state.has_active_turn_work());
+ }
+}
+
/// Process-scoped conversation synchronization state.
///
/// Replacing this value when Pi stops gives each subprocess a distinct
@@ -3446,7 +3461,7 @@ pub async fn pi_start_inner(
let mut pending_text_delta: Option<PendingAgentTextDelta> = None;
while let Some(line) = read_lines_lossy(&mut reader) {
line_count += 1;
- let parsed = serde_json::from_str::<Value>(&line).ok();
+ let mut parsed = serde_json::from_str::<Value>(&line).ok();
let is_stdout_text_delta = parsed.as_ref().and_then(assistant_text_delta).is_some();
let event_type = parsed.as_ref().and_then(|v| {
v.get("type")
@@ -3505,8 +3520,10 @@ pub async fn pi_start_inner(
// Drive the command queue's turn/tool/lifecycle state machine from
// this event. Extracted into one helper so the production reader and
// the watchdog e2e test share a single, tested code path.
- if let (Some(qs), Some(event)) = (queue_state_for_reader.as_ref(), parsed.as_ref()) {
- sync_queue_state_from_event(qs, event);
+ if let (Some(qs), Some(event)) =
+ (queue_state_for_reader.as_ref(), parsed.as_mut())
+ {
+ sync_and_annotate_queue_state(qs, event);
}
if let Some(event) = parsed.as_ref() {
@@ -5938,6 +5955,38 @@ mod tests {
);
}
+ #[test]
+ fn agent_end_reports_when_tool_work_still_owns_the_turn() {
+ let state = crate::pi_command_queue::PiQueueState::new();
+ super::sync_queue_state_from_event(&state, &json!({ "type": "agent_start" }));
+ super::sync_queue_state_from_event(
+ &state,
+ &json!({
+ "type": "message_end",
+ "message": {
+ "role": "assistant",
+ "stopReason": "toolUse",
+ "content": [{ "type": "toolCall", "id": "tool-1" }]
+ }
+ }),
+ );
+
+ let mut intermediate_end = json!({ "type": "agent_end" });
+ super::sync_and_annotate_queue_state(&state, &mut intermediate_end);
+ assert_eq!(intermediate_end["turnBusy"], true);
+
+ super::sync_queue_state_from_event(
+ &state,
+ &json!({
+ "type": "message_end",
+ "message": { "role": "toolResult", "toolCallId": "tool-1" }
+ }),
+ );
+ let mut terminal_end = json!({ "type": "agent_end" });
+ super::sync_and_annotate_queue_state(&state, &mut terminal_end);
+ assert_eq!(terminal_end["turnBusy"], false);
+ }
+
#[test]
fn exhausted_provider_retry_releases_queue() {
let state = crate::pi_command_queue::PiQueueState::new();