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
feat(chat): queue follow-up prompts while pi is streaming
Louis Beaumonte1f55023d50a
diff --git a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx b/apps/screenpipe-app-tauri/components/chat-sidebar.tsxindex f322a9dcf..8c950eb01 100644--- a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx+++ b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx@@ -52,6 +52,44 @@ interface ChatSidebarProps {className?: string;}+/**+ * Tracks queued-prompt depth per session, sourced from the rust-side queue+ * (`pi_command_queue.rs`). Single sidebar-wide subscription — re-rendering+ * happens at this level, then each ChatRow reads its own depth from the map.+ *+ * The rust queue is the authoritative source: TS never adds entries here,+ * only mirrors the snapshot rust pushes via `pi-queue-changed`.+ */+function useQueueDepths(): Map<string, number> {+ const [depths, setDepths] = useState<Map<string, number>>(() => new Map());+ useEffect(() => {+ let unlisten: (() => void) | undefined;+ let cancelled = false;+ (async () => {+ const u = await listen<{ sessionId: string; queued: { id: string }[] }>(+ "pi-queue-changed",+ (e) => {+ if (cancelled) return;+ const { sessionId, queued } = e.payload;+ setDepths((prev) => {+ const next = new Map(prev);+ const count = queued?.length ?? 0;+ if (count === 0) next.delete(sessionId);+ else next.set(sessionId, count);+ return next;+ });+ }+ );+ unlisten = u;+ })();+ return () => {+ cancelled = true;+ unlisten?.();+ };+ }, []);+ return depths;+}+/*** Embeddable. Designed to live INSIDE the main app sidebar, sandwiched* between the navigation items and the bottom action bar (Team / Settings@@ -67,6 +105,7 @@ export function ChatSidebar({ className }: ChatSidebarProps) {const sessions = useOrderedSessions();const currentId = useChatStore((s) => s.currentId);const actions = useChatActions();+ const queueDepths = useQueueDepths();// Sync currentId from standalone-chat. Whenever the chat panel switches// its piSessionIdRef (new chat, prefill auto-send, history click in the@@ -242,6 +281,7 @@ export function ChatSidebar({ className }: ChatSidebarProps) {key={s.id}session={s}isCurrent={s.id === currentId}+ queuedCount={queueDepths.get(s.id) ?? 0}onSelect={handleSelect}onClose={handleClose}onTogglePin={handleTogglePin}@@ -263,6 +303,7 @@ export function ChatSidebar({ className }: ChatSidebarProps) {key={s.id}session={s}isCurrent={s.id === currentId}+ queuedCount={queueDepths.get(s.id) ?? 0}onSelect={handleSelect}onClose={handleClose}onTogglePin={handleTogglePin}@@ -663,6 +704,10 @@ function Section({interface ChatRowProps {session: SessionRecord;isCurrent: boolean;+ /** Number of follow-up prompts queued for this session at the rust level.+ * > 0 → render an unobtrusive `↑N` badge so the user can spot pending+ * work in chats they've navigated away from. */+ queuedCount: number;onSelect: (id: string) => void;onClose: (e: React.MouseEvent, id: string) => Promise<void> | void;onTogglePin: (e: React.MouseEvent, id: string) => Promise<void> | void;@@ -693,6 +738,7 @@ interface ChatRowProps {function ChatRow({session,isCurrent,+ queuedCount,onSelect,onClose,onTogglePin,@@ -743,6 +789,17 @@ function ChatRow({>{session.title || "untitled"}</span>+ {/* Queued-prompts badge — only visible when this session has rust-side+ queued items waiting. Hidden on hover so it doesn't fight the+ pin/close buttons for the same slot. */}+ {queuedCount > 0 && (+ <span+ className="group-hover:hidden inline-flex items-center gap-0.5 px-1 text-[10px] font-mono text-muted-foreground/80 shrink-0"+ title={`${queuedCount} queued`}+ >+ ↑{queuedCount}+ </span>+ )}{/* hover-only actions — REAL <button>s now (was <span role=button>inside the outer <button>, which is invalid nested-button HTMLand made the X click silently no-op on close). */}diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex 63a66d308..a48874181 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -31,7 +31,7 @@ import { VideoComponent } from "@/components/rewind/video";import { MermaidDiagram } from "@/components/rewind/mermaid-diagram";import { convertFileSrc } from "@tauri-apps/api/core";import { AIPresetsSelector } from "@/components/rewind/ai-presets-selector";-import { AIPreset } from "@/lib/utils/tauri";+import { AIPreset, PiQueuedPrompt } from "@/lib/utils/tauri";import remarkGfm from "remark-gfm";import rehypeRaw from "rehype-raw";// OpenAI SDK no longer used directly — all providers route through Pi agent@@ -1330,6 +1330,11 @@ export function StandaloneChat({const [isLoading, setIsLoading] = useState(false);const [isStreaming, setIsStreaming] = useState(false);const [streamedCharCount, setStreamedCharCount] = useState(0);+ // Prompts the user has queued while a previous one is still streaming.+ // Sourced from rust via the `pi-queue-changed` event — single source of+ // truth lives in `pi_command_queue.rs`. Cleared as soon as the drain loop+ // pulls a queued item and writes it to stdin (it's then in-flight).+ const [queuedPrompts, setQueuedPrompts] = useState<PiQueuedPrompt[]>([]);const [copiedMessageId, setCopiedMessageId] = useState<string | null>(null);const [openMessageMenuId, setOpenMessageMenuId] = useState<string | null>(null);// Cursor-style inline edit: click a sent user message to tweak and resend@@ -2281,10 +2286,13 @@ export function StandaloneChat({return;}- // Enter without shift submits the form+ // Enter without shift submits the form. We intentionally don't gate on+ // isLoading anymore — if a previous prompt is still streaming, the new+ // one is enqueued at the rust level (see `pi_command_queue.rs`) and+ // shown in the queued-cards rail under the transcript.if (e.key === "Enter" && !e.shiftKey && !showMentionDropdown) {e.preventDefault();- if ((input.trim() || pastedImages.length > 0) && !isLoading) {+ if (input.trim() || pastedImages.length > 0) {sendMessage(input.trim());}return;@@ -2562,12 +2570,71 @@ export function StandaloneChat({// uniformly.const busUnregistrations: Array<() => void> = [];- // Shared handler for Pi event data — used by both pi_event and pipe_event+ // Shared handler for Pi event data — used by both pi_event and pipe_event.+ //+ // When the rust queue drains a queued prompt, Pi emits text_delta /+ // thinking_start / tool_execution_start for a NEW turn — but the previous+ // turn's `agent_end` cleared `piMessageIdRef`, so deltas have no target.+ // `ensureAssistantPlaceholder` lazily creates one when the trailing message+ // is a user prompt waiting for a reply (the shape `enqueuePiMessage`+ // leaves the array in). Idempotent — does nothing when a placeholder+ // already exists.+ const ensureAssistantPlaceholder = (): boolean => {+ if (piMessageIdRef.current) return true;+ const newAssistantId = (Date.now() + 1).toString();+ let created = false;+ setMessages((prev) => {+ const last = prev[prev.length - 1];+ if (!last || last.role !== "user") return prev;+ created = true;+ return [+ ...prev,+ {+ id: newAssistantId,+ role: "assistant",+ content: "Processing...",+ timestamp: Date.now(),+ model: activePreset?.model,+ provider: activePreset?.provider,+ },+ ];+ });+ if (!created) return false;+ piMessageIdRef.current = newAssistantId;+ piStreamingTextRef.current = "";+ piContentBlocksRef.current = [];+ setStreamedCharCount(0);+ setIsLoading(true);+ setIsStreaming(true);+ const sidNow = piSessionIdRef.current;+ if (sidNow) {+ const storeState = useChatStore.getState();+ storeState.actions.appendMessage(sidNow, {+ id: newAssistantId,+ role: "assistant",+ content: "Processing...",+ timestamp: Date.now(),+ model: activePreset?.model,+ provider: activePreset?.provider,+ } as any);+ storeState.actions.setStreaming(sidNow, {+ streamingMessageId: newAssistantId,+ streamingText: "",+ contentBlocks: [],+ isStreaming: true,+ isLoading: true,+ });+ }+ return true;+ };+const handlePiEventData = (data: any) => {if (data.type === "message_update" && data.assistantMessageEvent) {const evt = data.assistantMessageEvent;if (evt.type === "text_delta" && evt.delta) {+ // First delta of a queued turn → create the placeholder lazily.+ if (!ensureAssistantPlaceholder()) return;piStreamingTextRef.current += evt.delta;setStreamedCharCount(piStreamingTextRef.current.length);@@ -2601,6 +2668,7 @@ export function StandaloneChat({);}} else if (evt.type === "thinking_start") {+ if (!ensureAssistantPlaceholder()) return;piThinkingStartRef.current = Date.now();const blocks = piContentBlocksRef.current;blocks.push({ type: "thinking", text: "", isThinking: true });@@ -2642,6 +2710,7 @@ export function StandaloneChat({}}} else if (data.type === "tool_execution_start") {+ if (!ensureAssistantPlaceholder()) return;if (piMessageIdRef.current) {const msgId = piMessageIdRef.current;const toolCall: ToolCall = {@@ -3167,6 +3236,25 @@ export function StandaloneChat({setup();+ // Subscribe to queue-pending updates emitted by the rust queue. Each+ // event carries the full snapshot for ONE session — we filter to the+ // session this panel is bound to. Single source of truth lives in+ // `pi_command_queue.rs`; this listener just mirrors it into local state.+ let unlistenQueue: UnlistenFn | undefined;+ listen<{ sessionId: string; queued: PiQueuedPrompt[] }>("pi-queue-changed", (event) => {+ if (!mounted) return;+ if (event.payload.sessionId !== piSessionIdRef.current) return;+ setQueuedPrompts(event.payload.queued ?? []);+ }).then(fn => { unlistenQueue = fn; });++ // Initial fetch — closes the gap between component mount and first event.+ (async () => {+ try {+ const res = await commands.piPending(piSessionIdRef.current);+ if (mounted && res.status === "ok") setQueuedPrompts(res.data);+ } catch { /* ignore — queue may not be initialized yet */ }+ })();+// Restart the current session when a new auth token arrives (deeplink login).listen<{ apiKey: string }>("pi-reauth", async (event) => {if (!mounted) return;@@ -3190,6 +3278,7 @@ export function StandaloneChat({}unlistenLog?.();unlistenReauth?.();+ unlistenQueue?.();// 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.@@ -3440,6 +3529,96 @@ export function StandaloneChat({}// Send message using Pi agent+ /**+ * Enqueue a follow-up while another prompt is still streaming.+ *+ * Distinct from `sendPiMessage` because we explicitly want to NOT:+ * - abort the in-flight turn,+ * - clobber `piMessageIdRef` / streaming refs,+ * - flip `isLoading`/`isStreaming`.+ *+ * The rust queue (`pi_command_queue.rs`) holds the prompt until the current+ * turn's `agent_end` fires, then writes it to stdin. The pi-event-router+ * downstream picks up the new turn and appends user/assistant content to+ * the chat-store — same path used for any other message, just kicked off+ * after the queue drains.+ */+ async function enqueuePiMessage(userMessage: string, displayLabel?: string) {+ if (!piInfo?.running) {+ // No Pi running → fall back to the normal start-and-send path.+ return sendPiMessage(userMessage, displayLabel);+ }++ // Local optimistic message + chat-store mirror. Skips assistant placeholder+ // entirely; the new turn's `agent_start` (downstream from the rust queue+ // dequeue) will create one through the existing event flow.+ const newUserMessage: Message = {+ id: Date.now().toString(),+ role: "user",+ content: userMessage,+ ...(displayLabel ? { displayContent: displayLabel } : {}),+ ...(pastedImages.length > 0 ? { images: [...pastedImages] } : {}),+ timestamp: Date.now(),+ };+ setMessages((prev) => [...prev, newUserMessage]);+ setInput("");+ if (inputRef.current) inputRef.current.style.height = "auto";++ const sidNow = piSessionIdRef.current;+ if (sidNow) {+ const storeState = useChatStore.getState();+ if (!storeState.sessions[sidNow]) {+ storeState.actions.upsert({+ id: sidNow,+ title: "new chat",+ preview: "",+ status: "streaming",+ messageCount: 0,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ pinned: false,+ unread: false,+ });+ }+ storeState.actions.appendMessage(sidNow, newUserMessage as any);+ storeState.actions.patch(sidNow, { lastUserMessageAt: Date.now() });+ }++ // Persist immediately — covers the edge case where Pi crashes between+ // enqueue and dequeue, leaving the user's message stranded otherwise.+ void saveConversation([...messages, newUserMessage]);++ posthog.capture("chat_message_enqueued", {+ provider: activePreset?.provider,+ model: activePreset?.model,+ pending_count: queuedPrompts.length + 1,+ });++ // Convert any data-URL pastes to the Pi image-content shape (same format+ // used by the normal send path further down in this file).+ const piImages: Array<{ type: string; mimeType: string; data: string }> = [];+ for (const img of pastedImages) {+ const match = img.match(/^data:(image\/[^;]+);base64,(.+)$/);+ if (match) {+ piImages.push({ type: "image", mimeType: match[1], data: match[2] });+ }+ }+ if (pastedImages.length > 0) setPastedImages([]);++ try {+ const result = await commands.piPrompt(+ piSessionIdRef.current,+ userMessage,+ piImages.length > 0 ? piImages : null,+ );+ if (result.status !== "ok") {+ toast({ title: "failed to queue message", description: result.error, variant: "destructive" });+ }+ } catch (e) {+ console.warn("[Pi] failed to enqueue follow-up:", e);+ }+ }+async function sendPiMessage(userMessage: string, displayLabel?: string) {// Auto-start Pi if it's not running yet (new session or crash recovery)if (!piInfo?.running) {@@ -3867,6 +4046,16 @@ export function StandaloneChat({async function sendMessage(userMessage: string, displayLabel?: string) {if ((!canChat && !autoSendBypassRef.current) || (!activePreset && !autoSendBypassRef.current)) return;+ // If a previous prompt is still streaming, enqueue this one at the rust+ // level instead of going through sendPiMessage (which aborts the previous+ // turn — exactly what we DON'T want when the user is queueing follow-ups).+ // The rust queue's drain loop will pull this prompt and write it to stdin+ // as soon as the in-flight prompt's `agent_end` arrives. The pi-event-router+ // will append the new turn's user + assistant messages to the chat-store.+ if (isLoading || isStreaming) {+ return enqueuePiMessage(userMessage, displayLabel);+ }+// All providers route through Pi agentreturn sendPiMessage(userMessage, displayLabel);}@@ -3931,7 +4120,7 @@ export function StandaloneChat({const handleSubmit = (e: React.FormEvent) => {e.preventDefault();- if ((!input.trim() && pastedImages.length === 0) || isLoading) return;+ if (!input.trim() && pastedImages.length === 0) return;sendMessage(input.trim());};@@ -4516,6 +4705,61 @@ export function StandaloneChat({);})()}</AnimatePresence>++ {/* Queued follow-ups — rendered between the streaming message and the+ scroll anchor so they sit visually in the "what's next" gap. The+ list comes from rust via `pi-queue-changed`; entries disappear as+ the drain loop pulls each prompt and starts streaming it. */}+ <AnimatePresence>+ {queuedPrompts.length > 0 && (+ <motion.div+ key="queued-rail"+ initial={{ opacity: 0, y: 8 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -4 }}+ transition={{ duration: 0.2 }}+ className="px-4 py-2 space-y-1.5"+ >+ <div className="text-[10px] uppercase tracking-wider text-muted-foreground/60 px-1">+ queued · waiting for current reply+ </div>+ {queuedPrompts.map((p, i) => (+ <motion.div+ key={p.id}+ layout+ initial={{ opacity: 0, x: -6 }}+ animate={{ opacity: 0.85, x: 0 }}+ exit={{ opacity: 0, x: 6, scale: 0.96 }}+ transition={{ duration: 0.18 }}+ className="group/qcard flex items-center gap-2 px-3 py-2 rounded-md border border-dashed border-border/60 bg-muted/30 text-sm text-muted-foreground hover:border-border hover:bg-muted/50 transition-colors"+ title={p.preview.length > 80 ? p.preview : undefined}+ >+ <span className="font-mono text-[10px] text-muted-foreground/50 shrink-0 w-4 text-right">+ {i + 1}+ </span>+ <Clock className="h-3 w-3 flex-shrink-0 opacity-50" />+ <span className="truncate flex-1">{p.preview}</span>+ <button+ type="button"+ onClick={async () => {+ try {+ await commands.piCancelQueued(piSessionIdRef.current, p.id);+ } catch (e) {+ console.warn("[Pi] cancel queued failed:", e);+ }+ }}+ className="opacity-0 group-hover/qcard:opacity-100 transition-opacity p-0.5 hover:bg-muted rounded shrink-0"+ aria-label="cancel queued message"+ title="cancel"+ >+ <X className="h-3 w-3 text-muted-foreground" />+ </button>+ </motion.div>+ ))}+ </motion.div>+ )}+ </AnimatePresence>+<div ref={messagesEndRef} /></div> {/* End of max-w-4xl wrapper */}@@ -4963,7 +5207,9 @@ export function StandaloneChat({placeholder={disabledReason? disabledReason- : "Ask about your screen... (type @ for filters, paste images)"+ : isLoading || isStreaming+ ? "type to queue next message..."+ : "Ask about your screen... (type @ for filters, paste images)"}disabled={!canChat}spellCheck={false}@@ -5112,24 +5358,47 @@ export function StandaloneChat({><Paperclip className="h-4 w-4" /></Button>- <Button- type={isStreaming ? "button" : "submit"}- size="icon"- disabled={(!input.trim() && !isStreaming && pastedImages.length === 0) || !canChat}- onClick={isStreaming ? handleStop : undefined}- className={cn(- "h-8 w-8 transition-all duration-200",- isStreaming- ? "bg-foreground text-background hover:bg-foreground/80"- : "bg-foreground text-background hover:bg-background hover:text-foreground"- )}- >- {isStreaming ? (- <Square className="h-4 w-4" />- ) : (- <Send className="h-4 w-4" />- )}- </Button>+ {(() => {+ // Three button modes:+ // 1. streaming + input empty → stop (square)+ // 2. streaming + input has text → queue (chevron-up, submits, enqueues)+ // 3. not streaming → send (paper plane)+ const hasInput = input.trim().length > 0 || pastedImages.length > 0;+ const isQueueMode = (isLoading || isStreaming) && hasInput;+ const isStopMode = (isLoading || isStreaming) && !hasInput;+ return (+ <Button+ type={isStopMode ? "button" : "submit"}+ size="icon"+ disabled={(!hasInput && !isStopMode) || !canChat}+ onClick={isStopMode ? handleStop : undefined}+ className={cn(+ "h-8 w-8 transition-all duration-200 relative",+ "bg-foreground text-background hover:bg-foreground/80"+ )}+ title={+ isStopMode+ ? "stop"+ : isQueueMode+ ? `queue (${queuedPrompts.length + 1} pending)`+ : "send"+ }+ >+ {isStopMode ? (+ <Square className="h-4 w-4" />+ ) : isQueueMode ? (+ <ChevronUp className="h-4 w-4" />+ ) : (+ <Send className="h-4 w-4" />+ )}+ {isQueueMode && queuedPrompts.length > 0 && (+ <span className="absolute -top-1.5 -right-1.5 min-w-[16px] h-[16px] px-1 rounded-full bg-foreground text-background text-[9px] font-mono font-semibold flex items-center justify-center border border-background">+ {queuedPrompts.length + 1}+ </span>+ )}+ </Button>+ );+ })()}</div></div></form>diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.tsindex 11cbafc4c..e8cce5053 100644--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts@@ -815,6 +815,32 @@ async piPrompt(sessionId: string | null, message: string, images: PiImageContentelse return { status: "error", error: e as any };}},+/**+ * Read the current queued-prompt list for a session. Useful for an initial+ * render before the first `pi-queue-changed` event arrives, and for new+ * chat windows opening on top of an in-progress queue.+ */+async piPending(sessionId: string | null) : Promise<Result<PiQueuedPrompt[], string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("pi_pending", { sessionId }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},+/**+ * Cancel a single queued prompt. Returns true if it was still in the queue+ * (and is now removed), false if it had already been pulled into the+ * in-flight slot — at that point `pi_abort` is the right tool.+ */+async piCancelQueued(sessionId: string | null, promptId: string) : Promise<Result<boolean, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("pi_cancel_queued", { sessionId, promptId }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},/*** Abort current Pi operation. Priority command — cancels all pending commands* in the queue and sends abort directly. Waits for the SDK's done event.@@ -1279,6 +1305,7 @@ export type PiCheckResult = { available: boolean; path: string | null }*/export type PiImageContent = { type: string; mimeType: string; data: string }export type PiInfo = { running: boolean; projectDir: string | null; pid: number | null; sessionId: string | null }+export type PiQueuedPrompt = { id: string; preview: string; queuedAtMs: number }/*** Configuration for which AI provider Pi should use*/diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 496f05508..b5253eb1c 100644--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "screenpipe-app"-version = "2.4.105"+version = "2.4.106"description = "24/7 memory for your desktop. 100% local."authors = ["you"]license = ""diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex c12e13831..47942ff97 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -770,6 +770,8 @@ async fn main() {pi::pi_check,pi::pi_install,pi::pi_prompt,+ pi::pi_pending,+ pi::pi_cancel_queued,pi::pi_abort,pi::pi_new_session,pi::pi_set_model,@@ -1057,6 +1059,8 @@ async fn main() {pi::pi_check,pi::pi_install,pi::pi_prompt,+ pi::pi_pending,+ pi::pi_cancel_queued,pi::pi_abort,pi::pi_new_session,pi::pi_set_model,diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rsindex 67d881227..510e1ecdd 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs@@ -1438,6 +1438,38 @@ pub async fn pi_start_inner(// Grab queue_state for the stdout reader before dropping the locklet queue_state_for_reader = pool.sessions.get(&sid).and_then(|m| m.queue_state.clone());+ // Spawn a watcher that mirrors queue-pending changes out as Tauri events.+ // The frontend uses these to render "queued" cards under the in-flight+ // streaming message and badges in the sidebar — without this, the UI has+ // no visibility into the rust-side mpsc state.+ if let Some(qs) = queue_state_for_reader.clone() {+ let app_handle_for_queue = app.clone();+ let sid_for_queue = sid.clone();+ tokio::spawn(async move {+ let mut rx = qs.subscribe_queued();+ // Emit current state immediately so any UI that subscribes after+ // the watcher boot still gets a fresh value without polling.+ let snap = rx.borrow().clone();+ let _ = app_handle_for_queue.emit(+ "pi-queue-changed",+ serde_json::json!({+ "sessionId": sid_for_queue,+ "queued": snap,+ }),+ );+ while rx.changed().await.is_ok() {+ let snap = rx.borrow().clone();+ let _ = app_handle_for_queue.emit(+ "pi-queue-changed",+ serde_json::json!({+ "session_id": sid_for_queue,+ "queued": snap,+ }),+ );+ }+ });+ }+// Snapshot the state BEFORE dropping the lock, so we don't hold it during I/Olet snapshot = match pool.sessions.get_mut(&sid) {Some(m) => m.snapshot(&sid),@@ -1715,13 +1747,65 @@ pub async fn pi_prompt(}}- let rx = queue- .send(cmd, crate::pi_command_queue::WaitMode::StreamThenWaitDone)+ // Send through the prompt-aware path so the queue UI shows it as queued+ // until the drain loop pulls and writes it to stdin.+ let (_queue_id, rx) = queue+ .send_prompt(+ cmd,+ crate::pi_command_queue::WaitMode::StreamThenWaitDone,+ message.clone(),+ ).await?;rx.await.map_err(|_| "Pi command queue dropped".to_string())?}+/// Cancel a single queued prompt. Returns true if it was still in the queue+/// (and is now removed), false if it had already been pulled into the+/// in-flight slot — at that point `pi_abort` is the right tool.+#[tauri::command]+#[specta::specta]+pub async fn pi_cancel_queued(+ state: State<'_, PiState>,+ session_id: Option<String>,+ prompt_id: String,+) -> Result<bool, String> {+ let sid = session_id.unwrap_or_else(|| "chat".to_string());+ let queue = {+ let pool = state.0.lock().await;+ let m = pool+ .sessions+ .get(&sid)+ .ok_or("session not found".to_string())?;+ m.queue_handle+ .clone()+ .ok_or("queue not initialized".to_string())?+ };+ queue.cancel_one(prompt_id).await+}++/// Read the current queued-prompt list for a session. Useful for an initial+/// render before the first `pi-queue-changed` event arrives, and for new+/// chat windows opening on top of an in-progress queue.+#[tauri::command]+#[specta::specta]+pub async fn pi_pending(+ state: State<'_, PiState>,+ session_id: Option<String>,+) -> Result<Vec<crate::pi_command_queue::PiQueuedPrompt>, String> {+ let sid = session_id.unwrap_or_else(|| "chat".to_string());+ let pool = state.0.lock().await;+ let m = match pool.sessions.get(&sid) {+ Some(m) => m,+ None => return Ok(Vec::new()),+ };+ let qs = match m.queue_state.as_ref() {+ Some(qs) => qs,+ None => return Ok(Vec::new()),+ };+ Ok(qs.queued_snapshot())+}+/// Abort current Pi operation. Priority command — cancels all pending commands/// in the queue and sends abort directly. Waits for the SDK's done event.#[tauri::command]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.rsindex 325a6ca6e..88ce28abd 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@@ -17,13 +17,33 @@//! processing the next command//! 4. Handling abort as a priority command that cancels pending work+use serde::{Deserialize, Serialize};use serde_json::{json, Value};+use specta::Type;use std::io::Write;use std::process::ChildStdin;use std::sync::Arc;use tokio::sync::{mpsc, oneshot, watch, Mutex, Notify};use tracing::{debug, error, info, warn};+/// A user prompt that's been enqueued but not yet written to Pi's stdin.+/// Surfaced to the UI so the chat can render "queued" cards while a prior+/// prompt is still streaming. Once the queue's drain loop pulls a prompt and+/// writes it to stdin, the entry is removed (it's now in-flight, not queued).+#[derive(Clone, Debug, Serialize, Deserialize, Type)]+#[serde(rename_all = "camelCase")]+pub struct PiQueuedPrompt {+ /// Stable id assigned at enqueue time. Used to remove the entry on+ /// dequeue / abort / write-failure.+ pub id: String,+ /// First ~200 chars of the user message — enough for the UI to show a+ /// readable preview without round-tripping the full prompt over IPC.+ pub preview: String,+ /// Unix epoch milliseconds for "queued at" — drives the relative-time+ /// label in the UI ("queued 4s ago").+ pub queued_at_ms: u64,+}+/// A command to be sent to the Pi SDK.#[derive(Debug)]pub struct PiCommand {@@ -34,6 +54,9 @@ pub struct PiCommand {/// Channel to notify the caller when the command has been written to stdin/// (for fire-and-forget prompts) or when `done` is received (for blocking commands).pub reply: oneshot::Sender<Result<(), String>>,+ /// Set on user-prompt commands so the queue can publish "what's pending"+ /// to subscribers. None for new_session / abort / internal commands.+ pub prompt_meta: Option<PiQueuedPrompt>,}/// How the queue waits after writing a command to stdin.@@ -52,6 +75,10 @@ pub enum WaitMode {#[derive(Clone)]pub struct PiQueueHandle {tx: mpsc::Sender<QueueMessage>,+ /// Shared with the drain loop and the stdout reader. We keep a reference+ /// here so `send_prompt` can publish the new entry to subscribers BEFORE+ /// awaiting the drain loop, giving the UI an instant "queued" hint.+ state: Arc<PiQueueState>,}/// Messages the queue accepts.@@ -64,6 +91,10 @@ enum QueueMessage {},}+// Note: cancel-one is implemented as a pure tombstone in `PiQueueState` and+// does NOT travel through the mpsc — see `cancel_one()` on the handle. That+// way it takes effect even while the drain loop is parked.+/// Shared state between the queue drain loop and the stdout reader.pub struct PiQueueState {/// Notified by the stdout reader when a `done` event is received.@@ -72,15 +103,27 @@ pub struct PiQueueState {terminated_notify: Notify,/// Whether the process is still alive.alive: watch::Sender<bool>,+ /// Canonical list of user prompts that are enqueued but not yet written+ /// to stdin. Subscribed to by pi.rs to emit `pi-queue-changed` events to+ /// the frontend.+ queued: watch::Sender<Vec<PiQueuedPrompt>>,+ /// Tombstones for prompts the user cancelled before the drain loop+ /// pulled them. The mpsc channel is FIFO and not introspectable, so we+ /// 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>>,}impl PiQueueState {pub fn new() -> Arc<Self> {let (alive_tx, _) = watch::channel(true);+ let (queued_tx, _) = watch::channel(Vec::new());Arc::new(Self {done_notify: Notify::new(),terminated_notify: Notify::new(),alive: alive_tx,+ queued: queued_tx,+ cancelled: std::sync::Mutex::new(std::collections::HashSet::new()),})}@@ -95,11 +138,60 @@ impl PiQueueState {self.terminated_notify.notify_one();// Also wake anyone waiting for done — they'll see terminatedself.done_notify.notify_waiters();+ // Drop any queued prompts so subscribers stop showing them — Pi died.+ self.queued.send_modify(|v| v.clear());+ }++ /// Subscribe to queue-pending changes. Each receive yields the current+ /// snapshot of queued prompts (everything still waiting, head-first).+ pub fn subscribe_queued(&self) -> watch::Receiver<Vec<PiQueuedPrompt>> {+ self.queued.subscribe()+ }++ /// One-shot read of currently-queued prompts.+ pub fn queued_snapshot(&self) -> Vec<PiQueuedPrompt> {+ self.queued.borrow().clone()+ }++ fn enqueue_prompt(&self, prompt: PiQueuedPrompt) {+ self.queued.send_modify(|v| v.push(prompt));+ }++ fn dequeue_prompt(&self, id: &str) {+ self.queued.send_modify(|v| {+ if let Some(pos) = v.iter().position(|p| p.id == id) {+ v.remove(pos);+ }+ });+ }++ /// 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.+ fn mark_cancelled(&self, id: &str) -> bool {+ let was_present = self.queued.borrow().iter().any(|p| p.id == id);+ // Always tombstone — even if the watch list says "not present", the+ // mpsc channel may still have it queued (the watch updates on+ // enqueue, the channel receives slightly later).+ if let Ok(mut set) = self.cancelled.lock() {+ set.insert(id.to_string());+ }+ self.dequeue_prompt(id);+ was_present+ }++ fn take_cancelled(&self, id: &str) -> bool {+ if let Ok(mut set) = self.cancelled.lock() {+ set.remove(id)+ } else {+ false+ }}}impl PiQueueHandle {- /// Send a command and get back a reply channel.+ /// Send a non-prompt command (new_session / abort wrapper / internal).+ /// These don't appear in the queued-prompts UI.pub async fn send(&self,payload: Value,@@ -111,12 +203,65 @@ impl PiQueueHandle {payload,wait_mode,reply: tx,+ prompt_meta: None,})).await.map_err(|_| "Pi command queue closed".to_string())?;Ok(rx)}+ /// Send a user prompt. Identical to `send` except the queue tracks the+ /// prompt and exposes it to the UI as a "queued" item until it's pulled+ /// by the drain loop. Returns the queue id alongside the reply receiver+ /// so callers can correlate later (e.g. for individual cancellation).+ pub async fn send_prompt(+ &self,+ payload: Value,+ wait_mode: WaitMode,+ preview: String,+ ) -> Result<(String, oneshot::Receiver<Result<(), String>>), String> {+ let id = format!("q_{}", uuid::Uuid::new_v4().simple());+ let queued_at_ms = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0);+ // Trim preview defensively. UI can do its own ellipsis but we don't+ // want to ship a 100kb payload over Tauri IPC for every keystroke.+ let preview_trimmed: String = preview.chars().take(200).collect();+ let meta = PiQueuedPrompt {+ id: id.clone(),+ preview: preview_trimmed,+ queued_at_ms,+ };++ let (tx, rx) = oneshot::channel();+ self.tx+ .send(QueueMessage::Command(PiCommand {+ payload,+ wait_mode,+ reply: tx,+ prompt_meta: Some(meta.clone()),+ }))+ .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);+ Ok((id, rx))+ }++ /// Cancel a single queued prompt by its id. Returns `true` if the prompt+ /// was still in the queued list at cancel time, `false` if it was+ /// already in-flight (in that case, use `abort` to stop the active turn).+ ///+ /// This is a pure state mutation — no mpsc round-trip — so it takes+ /// effect even when the drain loop is parked waiting for `agent_end`+ /// on the in-flight prompt.+ pub async fn cancel_one(&self, prompt_id: String) -> Result<bool, String> {+ Ok(self.state.mark_cancelled(&prompt_id))+ }+/// Priority abort — cancels all pending commands and sends abort to Pi./// Returns when the SDK confirms the abort is complete (done event).pub async fn abort(&self) -> Result<(), String> {@@ -143,7 +288,10 @@ pub fn spawn_queue(request_id_start: u64,) -> (PiQueueHandle, tokio::task::JoinHandle<()>) {let (tx, mut rx) = mpsc::channel::<QueueMessage>(32);- let handle = PiQueueHandle { tx };+ let handle = PiQueueHandle {+ tx,+ state: state.clone(),+ };let join = tokio::spawn(async move {let mut request_id = request_id_start;@@ -156,6 +304,9 @@ pub fn spawn_queue(if !*alive_rx.borrow() {match msg {QueueMessage::Command(cmd) => {+ if let Some(meta) = &cmd.prompt_meta {+ state.dequeue_prompt(&meta.id);+ }let _ = cmd.reply.send(Err("Pi process has died".to_string()));}QueueMessage::Abort { reply } => {@@ -167,6 +318,19 @@ pub fn spawn_queue(match msg {QueueMessage::Command(cmd) => {+ let prompt_id = cmd.prompt_meta.as_ref().map(|m| m.id.clone());++ // Tombstone check — if the user cancelled this prompt+ // while it was sitting in the channel, drop it without+ // ever writing to Pi.+ if let Some(pid) = &prompt_id {+ if state.take_cancelled(pid) {+ state.dequeue_prompt(pid);+ let _ = cmd.reply.send(Err("cancelled".to_string()));+ continue;+ }+ }+request_id += 1;let req_id = format!("req_{}", request_id);@@ -200,10 +364,19 @@ pub fn spawn_queue(if let Err(e) = write_result {error!("pi_command_queue: stdin write failed: {}", e);+ if let Some(pid) = &prompt_id {+ state.dequeue_prompt(pid);+ }let _ = cmd.reply.send(Err(format!("stdin write failed: {}", e)));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@@ -232,6 +405,9 @@ pub fn spawn_queue(while let Ok(queued) = rx.try_recv() {match queued {QueueMessage::Command(cmd) => {+ if let Some(meta) = &cmd.prompt_meta {+ state.dequeue_prompt(&meta.id);+ }let _ = cmd.reply.send(Err("aborted".to_string()));cancelled += 1;}@@ -241,6 +417,10 @@ pub fn spawn_queue(}}}+ // Defensive: also clear any orphaned entries in the+ // queued-prompt list. The drain above should cover them+ // but a paranoid clear is cheap and correct.+ state.queued.send_modify(|v| v.clear());if cancelled > 0 {info!("pi_command_queue: abort cancelled {} pending commands",@@ -367,7 +547,8 @@ mod tests {async fn test_queue_handle_send_returns_receiver() {// Verify the handle API works without a real subprocesslet (tx, mut rx) = mpsc::channel::<QueueMessage>(8);- let handle = PiQueueHandle { tx };+ let state = PiQueueState::new();+ let handle = PiQueueHandle { tx, state };// Send a command in the backgroundlet h = tokio::spawn(async move {@@ -393,7 +574,8 @@ mod tests {#[tokio::test]async fn test_abort_cancels_pending() {let (tx, mut rx) = mpsc::channel::<QueueMessage>(8);- let handle = PiQueueHandle { tx };+ let state = PiQueueState::new();+ let handle = PiQueueHandle { tx, state };// Queue two commandslet h1 = {