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 multi-session, agent_end queue sync, and error UX (#2598)

Divanshu9866ab44d1c2
diff --git a/apps/screenpipe-app-tauri/components/deeplink-handler.tsx b/apps/screenpipe-app-tauri/components/deeplink-handler.tsx
index 2c891a0a8..ceb9e3460 100644
--- a/apps/screenpipe-app-tauri/components/deeplink-handler.tsx
+++ b/apps/screenpipe-app-tauri/components/deeplink-handler.tsx
@@ -13,7 +13,6 @@ import { listen, emit } from "@tauri-apps/api/event";
import { onOpenUrl } from "@tauri-apps/plugin-deep-link";
import { openSettingsWindow } from "@/lib/utils/window";
import { useTimelineStore } from "@/lib/hooks/use-timeline-store";
-import { homeDir, join } from "@tauri-apps/api/path";
export function DeeplinkHandler() {
const { toast } = useToast();
@@ -38,18 +37,14 @@ export function DeeplinkHandler() {
title: "logged in!",
description: "you have been logged in",
});
- // Force-restart Pi with the new token so it picks up the new
- // account immediately. Without this, Pi keeps running with the
- // old/null token and the user hits the free-tier rate limit.
+ // Notify the chat UI to restart Pi with the new token so it
+ // picks up the new account immediately. The chat component knows
+ // the active session ID; we just pass the key.
try {
- const home = await homeDir();
- const dir = await join(home, ".screenpipe", "pi-chat");
- await commands.piStart("chat", dir, apiKey, null);
- console.log("[deeplink] restarted Pi with new auth token");
+ await emit("pi-reauth", { apiKey });
+ console.log("[deeplink] emitted pi-reauth with new auth token");
} catch (e) {
- // Pi may not be running yet — that's fine, it'll start
- // with the correct token on first message
- console.log("[deeplink] Pi restart after login skipped:", e);
+ console.log("[deeplink] pi-reauth emit skipped:", e);
}
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
diff --git a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
index c8d6ea7c7..42241172d 100644
--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
@@ -21,7 +21,6 @@ import {
migrateFromStoreBin,
} from "@/lib/chat-storage";
-const PI_CHAT_SESSION = "chat";
// --- Types (mirrored from standalone-chat.tsx) ---
@@ -67,6 +66,7 @@ interface UseChatConversationsOpts {
piMessageIdRef: MutableRefObject<string | null>;
piContentBlocksRef: MutableRefObject<ContentBlock[]>;
piSessionSyncedRef: MutableRefObject<boolean>;
+ piSessionIdRef: MutableRefObject<string>;
setIsLoading: Dispatch<SetStateAction<boolean>>;
setIsStreaming: Dispatch<SetStateAction<boolean>>;
setPastedImages: Dispatch<SetStateAction<string[]>>;
@@ -88,6 +88,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
piMessageIdRef,
piContentBlocksRef,
piSessionSyncedRef,
+ piSessionIdRef,
setIsLoading,
setIsStreaming,
setPastedImages,
@@ -251,10 +252,10 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
// ---- loadConversation ----
const loadConversation = async (conv: ChatConversation) => {
- // Abort any ongoing Pi processing before switching
+ // Abort any ongoing Pi processing on the current session before switching
if (isLoading || isStreaming) {
try {
- await commands.piAbort(PI_CHAT_SESSION);
+ await commands.piAbort(piSessionIdRef.current);
} catch (e) {
console.warn("[Pi] Failed to abort:", e);
}
@@ -265,6 +266,9 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
setIsStreaming(false);
}
+ // Switch to this conversation's session — each conversation is its own Pi process
+ piSessionIdRef.current = conv.id;
+
// Load full conversation from file (conv from list may be metadata-only)
const { loadConversationFile } = await import("@/lib/chat-storage");
const full = await loadConversationFile(conv.id) || conv;
@@ -304,11 +308,12 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
};
// ---- startNewConversation ----
- // Always kills and restarts Pi to guarantee a clean session.
- // piNewSession() has a race condition: if a prompt is sent before it
- // completes, the old context leaks through. Kill+restart is safe.
+ // Assigns a fresh session ID so the next message starts a brand-new Pi
+ // process. The old session stays alive (backend evicts LRU when > 4).
+ // No kill/restart needed — true multi-session means each conversation
+ // has its own process that persists across conversation switches.
const startNewConversation = async () => {
- // Clear frontend state first
+ // Clear frontend state
piStreamingTextRef.current = "";
piMessageIdRef.current = null;
piContentBlocksRef.current = [];
@@ -321,12 +326,8 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
setShowHistory(false);
setPastedImages([]);
- // Kill Pi and restart fresh — the only reliable way to clear context
- if (piInfo?.running) {
- try {
- await commands.piStop(PI_CHAT_SESSION);
- } catch {}
- }
+ // New session ID — Pi will be started fresh when the first message is sent
+ piSessionIdRef.current = crypto.randomUUID();
piSessionSyncedRef.current = true;
};
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 4d1c9f082..1e353442b 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -10,7 +10,7 @@ import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { useSettings, ChatMessage, ChatConversation } from "@/lib/hooks/use-settings";
import { cn } from "@/lib/utils";
-import { Loader2, Send, Square, User, Settings, ExternalLink, X, ImageIcon, History, Search, Trash2, ChevronLeft, ChevronRight, ChevronDown, ChevronUp, Plus, Copy, Check, Clock, Paperclip, Filter } from "lucide-react";
+import { Loader2, Send, Square, User, Settings, ExternalLink, X, ImageIcon, History, Search, Trash2, ChevronLeft, ChevronRight, ChevronDown, ChevronUp, Plus, Copy, Check, Clock, Paperclip, Filter, RefreshCw } from "lucide-react";
import { SchedulePromptDialog } from "@/components/chat/schedule-prompt-dialog";
import { toast } from "@/components/ui/use-toast";
import { motion, AnimatePresence } from "framer-motion";
@@ -49,7 +49,8 @@ import { type CustomTemplate } from "@/lib/summary-templates";
import { usePipes } from "@/lib/hooks/use-pipes";
const SCREENPIPE_API = "http://localhost:3030";
-const PI_CHAT_SESSION = "chat";
+// Session ID is per-conversation — set on mount (new conv) and updated on load/new.
+// Stored as a ref so event listeners always see the current value without stale closures.
interface MentionSuggestion {
tag: string;
@@ -221,6 +222,7 @@ interface Message {
contentBlocks?: ContentBlock[];
model?: string;
provider?: string;
+ retryPrompt?: string; // when set, renders a retry CTA on error messages
}
// Tool icons by name
@@ -758,9 +760,24 @@ function ToolCallGroup({ toolCalls }: { toolCalls: ToolCall[] }) {
}
// Renders message content with interleaved text and tool call blocks
-function MessageContent({ message, onImageClick }: { message: Message; onImageClick?: (images: string[], index: number) => void }) {
+function MessageContent({ message, onImageClick, onRetry }: { message: Message; onImageClick?: (images: string[], index: number) => void; onRetry?: (prompt: string) => void }) {
const isUser = message.role === "user";
+ // Retry CTA — shown at the bottom of error messages that have a retryPrompt
+ const retryCta = !isUser && message.retryPrompt ? (
+ <div className="mt-3 pt-3 border-t border-border/40 flex items-center gap-3">
+ <button
+ type="button"
+ onClick={() => onRetry?.(message.retryPrompt!)}
+ className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-lg bg-foreground text-background hover:bg-foreground/80 transition-colors"
+ >
+ <RefreshCw className="h-3 w-3" />
+ Try again
+ </button>
+ <span className="text-xs text-muted-foreground">or edit your message above</span>
+ </div>
+ ) : null;
+
// If we have content blocks (Pi messages with tool calls), render them in order
// Group consecutive tool blocks into collapsible containers
if (message.contentBlocks && message.contentBlocks.length > 0) {
@@ -779,6 +796,7 @@ function MessageContent({ message, onImageClick }: { message: Message; onImageCl
}
return null;
})}
+ {retryCta}
</div>
);
}
@@ -814,6 +832,7 @@ function MessageContent({ message, onImageClick }: { message: Message; onImageCl
<div className="space-y-2">
{imageThumbs}
<MarkdownBlock text={message.content} isUser={isUser} />
+ {retryCta}
</div>
);
}
@@ -919,6 +938,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const piLastCrashRef = useRef(0);
const piThinkingStartRef = useRef<number | null>(null);
const piSessionSyncedRef = useRef(false);
+ const piSessionIdRef = useRef<string>(crypto.randomUUID());
const piRunningConfigRef = useRef<{ provider: string; model: string; token: string | null } | null>(null);
// Active pipe execution (when watching a running pipe)
@@ -1003,6 +1023,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
piMessageIdRef,
piContentBlocksRef,
piSessionSyncedRef,
+ piSessionIdRef,
setIsLoading,
setIsStreaming,
setPastedImages,
@@ -1158,58 +1179,37 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const fullMessage = `${context}\n\n${prompt}`;
// Start a new conversation then send
(async () => {
- // Clear all streaming state so sendPiMessage doesn't think a message is in-flight
- piStreamingTextRef.current = "";
- piMessageIdRef.current = null;
- piContentBlocksRef.current = [];
- setIsLoading(false);
- setIsStreaming(false);
- setMessages([]);
- setConversationId(null);
- setPrefillContext(null);
- setPrefillFrameId(null);
- // Set input as fallback in case auto-send fails (pi not ready)
- setInput(fullMessage);
- // Wait for Pi to be ready before sending (poll up to 10s)
- const waitForPi = async (maxMs: number): Promise<boolean> => {
- const start = Date.now();
- while (Date.now() - start < maxMs) {
- try {
- const info = await commands.piInfo(PI_CHAT_SESSION);
- if (info.status === "ok" && info.data.running) {
- setPiInfo(info.data);
- return true;
- }
- } catch {}
- await new Promise(r => setTimeout(r, 500));
- }
- return false;
- };
- const ready = piInfo?.running || await waitForPi(10000);
- if (ready) {
- // Reset Pi session AFTER confirming it's running to clear any
- // stale isStreaming state from a previous conversation.
- // This must happen here, not earlier — on fresh page loads
- // (e.g. navigateHomeAndPrefill), piInfo is null at mount time
- // so gating on piInfo?.running would skip this entirely.
- try {
- await commands.piNewSession(PI_CHAT_SESSION);
- } catch (e) {
- console.warn("[Pi] Failed to reset session before auto-send:", e);
- }
- // Signal that the next sendPiMessage call should bypass the piInfo guard
- // (we just confirmed Pi is running via waitForPi but React state may be stale)
+ try {
+ // Clear all streaming state so sendPiMessage doesn't think a message is in-flight
+ piStreamingTextRef.current = "";
+ piMessageIdRef.current = null;
+ piContentBlocksRef.current = [];
+ setIsLoading(false);
+ setIsStreaming(false);
+ setMessages([]);
+ setConversationId(null);
+ setPrefillContext(null);
+ setPrefillFrameId(null);
+ // Set input as fallback in case auto-send fails
+ setInput(fullMessage);
+ // Assign a fresh session ID — this is a brand-new conversation.
+ // Without this, the prefill would send to the previous conversation's
+ // Pi process which still has old context baked in.
+ piSessionIdRef.current = crypto.randomUUID();
+ piSessionSyncedRef.current = true; // fresh session, no history to inject
+ // With multi-session, Pi starts fresh per conversation — sendPiMessage
+ // handles auto-starting it. Just bypass the canChat guard and send.
autoSendBypassRef.current = true;
- // Give React a tick to re-render with updated piInfo
await new Promise(r => setTimeout(r, 200));
if (sendMessageRef.current) {
await sendMessageRef.current(fullMessage);
setInput("");
if (inputRef.current) inputRef.current.style.height = "auto";
}
+ } finally {
autoSendBypassRef.current = false;
+ prefillInFlightRef.current = false;
}
- prefillInFlightRef.current = false;
})();
return;
}
@@ -1511,7 +1511,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
if (isLoading || isStreaming) {
// Stop the agent
try {
- await commands.piAbort(PI_CHAT_SESSION);
+ await commands.piAbort(piSessionIdRef.current);
} catch (err) {
console.warn("[Pi] Failed to abort on Escape:", err);
}
@@ -1598,7 +1598,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
useEffect(() => {
const checkPi = async () => {
try {
- const result = await commands.piInfo(PI_CHAT_SESSION);
+ const result = await commands.piInfo(piSessionIdRef.current);
if (result.status === "ok") {
setPiInfo(result.data);
}
@@ -1610,7 +1610,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
// Keep polling Pi status — recovers from stale termination events and transient failures
const interval = setInterval(async () => {
try {
- const result = await commands.piInfo(PI_CHAT_SESSION);
+ const result = await commands.piInfo(piSessionIdRef.current);
if (result.status === "ok") {
setPiInfo(result.data);
}
@@ -1637,6 +1637,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
let unlistenPipeEvent: UnlistenFn | null = null;
let unlistenTerminated: UnlistenFn | null = null;
let unlistenLog: UnlistenFn | null = null;
+ let unlistenReauth: UnlistenFn | null = null;
let mounted = true;
// Shared handler for Pi event data — used by both pi_event and pipe_event
@@ -1992,7 +1993,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
// Re-send the last prompt
const lastUserMsg = messages.findLast(m => m.role === "user");
if (lastUserMsg?.content) {
- commands.piPrompt(PI_CHAT_SESSION, lastUserMsg.content, null).catch(() => {});
+ commands.piPrompt(piSessionIdRef.current, lastUserMsg.content, null).catch(() => {});
}
}
return;
@@ -2024,6 +2025,24 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
setMessages((prev) =>
prev.map((m) => m.id === msgId ? { ...m, content: "This model requires an upgrade." } : m)
);
+ } else if (errorStr.includes("already processing")) {
+ console.warn("[Pi] already-processing race in response event:", errorStr);
+ setMessages((prev) =>
+ prev.map((m) => m.id === msgId ? {
+ ...m,
+ content: "The AI was mid-response when your message arrived.",
+ retryPrompt: lastUserMessageRef.current || undefined,
+ } : m)
+ );
+ } else if (errorStr.includes("api_error") || errorStr.includes("Internal server error") || /\b5\d\d\b/.test(errorStr)) {
+ // Upstream API 5xx — SDK already exhausted its auto-retry attempts
+ setMessages((prev) =>
+ prev.map((m) => m.id === msgId ? {
+ ...m,
+ content: "Something went wrong on the server.",
+ retryPrompt: lastUserMessageRef.current || undefined,
+ } : m)
+ );
} else {
setMessages((prev) =>
prev.map((m) => m.id === msgId ? { ...m, content: `Error: ${errorStr}` } : m)
@@ -2069,7 +2088,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
unlistenEvent = await listen<any>("pi_event", (event) => {
if (!mounted) return;
const { sessionId, event: piEvent } = event.payload;
- if (sessionId !== PI_CHAT_SESSION) return;
+ if (sessionId !== piSessionIdRef.current) return;
handlePiEventData(piEvent);
});
@@ -2088,7 +2107,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
unlistenTerminated = await listen<any>("pi_terminated", (event) => {
if (!mounted) return;
const { sessionId, pid: terminatedPid } = event.payload;
- if (sessionId !== PI_CHAT_SESSION) return;
+ if (sessionId !== piSessionIdRef.current) return;
if (piStoppedIntentionallyRef.current) {
piStoppedIntentionallyRef.current = false;
return;
@@ -2140,7 +2159,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
if (!mounted) return;
// Check if a newer Pi process is already running (race: stop → start → terminated)
try {
- const result = await commands.piInfo(PI_CHAT_SESSION);
+ const result = await commands.piInfo(piSessionIdRef.current);
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);
@@ -2154,7 +2173,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const providerConfig = buildProviderConfig();
const home = await homeDir();
const dir = await join(home, ".screenpipe", "pi-chat");
- const result = await commands.piStart(PI_CHAT_SESSION, dir, settings.user?.token ?? null, providerConfig);
+ const result = await commands.piStart(piSessionIdRef.current, dir, settings.user?.token ?? null, providerConfig);
if (result.status === "ok") {
setPiInfo(result.data);
piSessionSyncedRef.current = false;
@@ -2214,16 +2233,33 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
setup();
+ // Restart the current session when a new auth token arrives (deeplink login).
+ listen<{ apiKey: string }>("pi-reauth", async (event) => {
+ if (!mounted) return;
+ try {
+ const home = await homeDir();
+ const dir = await join(home, ".screenpipe", "pi-chat");
+ const result = await commands.piStart(piSessionIdRef.current, dir, event.payload.apiKey, buildProviderConfig());
+ if (result.status === "ok") {
+ setPiInfo(result.data);
+ piSessionSyncedRef.current = false;
+ }
+ } catch (e) {
+ console.warn("[Pi] reauth restart skipped:", e);
+ }
+ }).then(fn => { unlistenReauth = fn; });
+
return () => {
mounted = false;
unlistenEvent?.();
unlistenPipeEvent?.();
unlistenTerminated?.();
unlistenLog?.();
+ unlistenReauth?.();
// Abort any in-flight Pi request when navigating away from chat.
// Without this, Pi keeps streaming in the background and rejects
// new messages with "already processing" when the user returns.
- commands.piAbort(PI_CHAT_SESSION).catch(() => {});
+ commands.piAbort(piSessionIdRef.current).catch(() => {});
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
@@ -2451,38 +2487,47 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
// Send message using Pi agent
async function sendPiMessage(userMessage: string, displayLabel?: string) {
- // Auto-start Pi if it's dead (singleton recovery)
- if (!piInfo?.running && !autoSendBypassRef.current) {
+ // Auto-start Pi if it's not running yet (new session or crash recovery)
+ if (!piInfo?.running) {
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(PI_CHAT_SESSION, dir, settings.user?.token ?? null, providerConfig);
- if (result.status === "ok" && result.data.running) {
- setPiInfo(result.data);
- piSessionSyncedRef.current = false;
- piCrashCountRef.current = 0; // reset crash loop counter on manual start
- // Keep running-config ref in sync so preset watcher doesn't re-trigger
- if (providerConfig) {
- piRunningConfigRef.current = { provider: providerConfig.provider, model: providerConfig.model, token: settings.user?.token ?? null };
+ if (!autoSendBypassRef.current) {
+ toast({ title: "Pi starting", description: "Please wait a moment", variant: "destructive" });
+ return;
+ }
+ // Prefill auto-send: wait for in-flight start to complete
+ const startWait = Date.now();
+ while (piStartInFlightRef.current && Date.now() - startWait < 10000) {
+ await new Promise(r => setTimeout(r, 300));
+ }
+ if (piStartInFlightRef.current) return; // timed out
+ } else {
+ 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(piSessionIdRef.current, dir, settings.user?.token ?? null, providerConfig);
+ if (result.status === "ok" && result.data.running) {
+ setPiInfo(result.data);
+ piSessionSyncedRef.current = false;
+ piCrashCountRef.current = 0; // reset crash loop counter on manual start
+ // Keep running-config ref in sync so preset watcher doesn't re-trigger
+ if (providerConfig) {
+ piRunningConfigRef.current = { provider: providerConfig.provider, model: providerConfig.model, token: settings.user?.token ?? null };
+ }
+ } else {
+ toast({ title: "Failed to start Screenpipe Cloud", description: result.status === "error" ? result.error : "Unknown error", variant: "destructive" });
+ return;
}
- } else {
- toast({ title: "Failed to start Screenpipe Cloud", description: result.status === "error" ? result.error : "Unknown error", variant: "destructive" });
+ } catch (e) {
+ toast({ title: "Failed to start Screenpipe Cloud", description: String(e), variant: "destructive" });
return;
+ } finally {
+ setPiStarting(false);
+ piStartInFlightRef.current = false;
}
- } catch (e) {
- toast({ title: "Failed to start Screenpipe Cloud", description: String(e), variant: "destructive" });
- return;
- } finally {
- setPiStarting(false);
- piStartInFlightRef.current = false;
}
}
@@ -2491,7 +2536,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
if (piMessageIdRef.current) {
console.warn("[Pi] Aborting previous message before sending new one");
try {
- await commands.piAbort(PI_CHAT_SESSION);
+ await commands.piAbort(piSessionIdRef.current);
} catch (e) {
console.warn("[Pi] Failed to abort previous:", e);
}
@@ -2630,7 +2675,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
// Send prompt — abort/new_session now await completion, so no retry needed
const result = await commands.piPrompt(
- PI_CHAT_SESSION,
+ piSessionIdRef.current,
promptMessage,
piImages.length > 0 ? piImages : null,
);
@@ -2639,23 +2684,28 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
if (timeoutId) clearTimeout(timeoutId);
piMessageIdRef.current = null;
// Provide helpful error messages for common failures
- let errorMsg = result.error;
- if (errorMsg.includes("already processing")) {
- errorMsg = "AI is busy — please wait a moment and try again.";
- } else if (errorMsg.includes("Broken pipe") || errorMsg.includes("not running") || errorMsg.includes("has died")) {
+ const rawError = result.error;
+ let errorMsg: string;
+ let retryPrompt: string | undefined;
+
+ if (rawError.includes("already processing")) {
+ errorMsg = "The AI was mid-response when your message arrived.";
+ retryPrompt = userMessage;
+ } else if (rawError.includes("Broken pipe") || rawError.includes("not running") || rawError.includes("has died")) {
const provider = activePreset?.provider;
- if (provider === "native-ollama") {
- errorMsg = "Ollama is not running. Start it with: `ollama serve`";
- } else {
- errorMsg = "AI agent crashed — restarting automatically...";
- }
- } else if (errorMsg.includes("not found")) {
+ errorMsg = provider === "native-ollama"
+ ? "Ollama is not running. Start it with: `ollama serve`"
+ : "AI agent crashed — restarting automatically...";
+ } else if (rawError.includes("not found")) {
errorMsg = `Model "${activePreset?.model}" not found. Check your AI preset in settings.`;
+ } else {
+ errorMsg = rawError;
+ retryPrompt = userMessage;
}
setMessages((prev) =>
prev.map((m) =>
m.id === assistantMessageId
- ? { ...m, content: `Error: ${errorMsg}` }
+ ? { ...m, content: errorMsg, ...(retryPrompt ? { retryPrompt } : {}) }
: m
)
);
@@ -2816,7 +2866,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const handleStop = async () => {
try {
- await commands.piAbort(PI_CHAT_SESSION);
+ await commands.piAbort(piSessionIdRef.current);
} catch (e) {
console.warn("[Pi] Failed to abort:", e);
}
@@ -3131,7 +3181,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
: "bg-muted/30 border-border/50"
)}
>
- <MessageContent message={message} onImageClick={(images, index) => setImageViewer({ images, index })} />
+ <MessageContent message={message} onImageClick={(images, index) => setImageViewer({ images, index })} onRetry={(prompt) => sendMessage(prompt)} />
</div>
{/* Action buttons - appear on hover, outside the message box */}
<div className="flex items-center gap-0.5 self-end mt-1 opacity-0 group-hover/message:opacity-100 transition-all duration-200">
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index 9c8ec92ff..82121d944 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -1366,20 +1366,30 @@ pub async fn pi_start_inner(
}
// Signal the command queue when the SDK's agent loop finishes.
- // "done" = agent turn complete (prompt finished).
- // "response" = command ACK (new_session/abort acknowledged).
- // For "response", the SDK's internal agent state machine may still be
- // transitioning — a small delay prevents the next queued command from
- // hitting "Agent is already processing".
+ //
+ // pi-mono SDK event types that matter for queue synchronization:
+ // "agent_end" = agent turn fully complete (prompt finished streaming).
+ // This is the authoritative "done" signal for prompts.
+ // "response" = command ACK (new_session/abort/prompt acknowledged).
+ // Fires immediately when the SDK receives the command,
+ // NOT when it finishes processing it.
+ //
+ // The "done" type was the original intent but pi-mono never emits it —
+ // it emits "agent_end" instead. Without "agent_end" handling, the queue
+ // was only ever unblocked by the "response" + 500ms path, which fires
+ // ~500ms after command ACK regardless of whether the agent is still
+ // streaming. This caused "Agent is already processing" when a second
+ // prompt was sent while the first was still running.
if let Some(ref qs) = queue_state_for_reader {
match event_type.as_deref() {
- Some("done") => {
+ Some("agent_end") => {
+ // Agent fully done — unblock the queue immediately.
qs.signal_done();
}
Some("response") => {
- // The SDK ACKed a non-prompt command (new_session/abort)
- // but its agent loop may not be fully idle yet. Wait a
- // beat before unblocking the queue.
+ // 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();