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

Make chat follow-up and steering flow similar to Codex (#3412)

Harsh Kumarc835db4ad3f9
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index fcbb86637..fdcc7da82 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -4,7 +4,7 @@
"use client";
import * as React from "react";
-import { useState, useRef, useEffect, useCallback } from "react";
+import { useState, useRef, useEffect, useCallback, useMemo } from "react";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import {
mountAgentEventBus,
@@ -76,7 +76,6 @@ import {
isQueuedItemCancelShortcut,
isQueuedItemSteerShortcut,
normalizeQueueEventPayload,
- queuedPreviewMatchesText,
} from "@/lib/chat-queue-controls";
const MermaidDiagram = React.lazy(() =>
@@ -110,6 +109,7 @@ interface MentionSuggestion {
const APP_SUGGESTION_LIMIT = 10;
const STREAM_RENDER_THROTTLE_MS = 80;
+const EMPTY_QUEUED_PROMPTS: PiQueuedPrompt[] = [];
const FOLLOW_UP_GENERATION_DELAY_MS = 10_000;
const POST_STREAM_SIDE_EFFECT_DELAY_MS = 1_500;
const CHAT_RAIL_CLASS = "max-w-4xl mx-auto w-full";
@@ -613,6 +613,15 @@ interface ToolCall {
isRunning: boolean;
}
+function queuedSnapshotsEqual(a: PiQueuedPrompt[], b: PiQueuedPrompt[]): boolean {
+ if (a === b) return true;
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) {
+ if (a[i].id !== b[i].id || a[i].preview !== b[i].preview) return false;
+ }
+ return true;
+}
+
type ContentBlock =
| { type: "text"; text: string }
| { type: "tool"; toolCall: ToolCall }
@@ -623,6 +632,7 @@ interface Message {
role: "user" | "assistant";
content: string; // full text for copy/history
displayContent?: string; // short label shown in chat (e.g. template name)
+ intent?: "steer";
images?: string[]; // base64 data URLs of attached images
timestamp: number;
contentBlocks?: ContentBlock[];
@@ -630,13 +640,16 @@ interface Message {
model?: string;
provider?: string;
retryPrompt?: string; // when set, renders a retry CTA on error messages
- /** True between optimistic enqueue and the moment Pi's drain loop picks
- * the prompt up (`agent_start` for this turn). Drives a lighter visual
- * treatment so the user can tell at-a-glance which messages are still
- * waiting in line vs. already in-flight. Cleared by handleAgentStart. */
- queued?: boolean;
+ interruptedBySteer?: boolean;
+ steeredResponse?: boolean;
}
+type QueuedDisplayPayload = {
+ preview: string;
+ images: string[];
+ displayContent?: string;
+};
+
// Tool icons by name
const TOOL_ICONS: Record<string, string> = {
bash: "⚡",
@@ -2243,6 +2256,19 @@ function MessageContent({
);
}
+function getMessageIntentLabel(message: Message): string | null {
+ if (message.role === "user" && message.intent === "steer") {
+ return "Steered";
+ }
+ if (message.role === "assistant" && message.steeredResponse) {
+ return "Reply redirected";
+ }
+ if (message.role === "assistant" && message.interruptedBySteer) {
+ return "Interrupted by steer";
+ }
+ return null;
+}
+
function CollapsibleUserMessage({ label, fullContent }: { label: string; fullContent: string }) {
const [expanded, setExpanded] = useState(false);
return (
@@ -2622,8 +2648,10 @@ export function StandaloneChat({
// 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 [queuedPromptsBySession, setQueuedPromptsBySession] = useState<Record<string, PiQueuedPrompt[]>>({});
+ const queuedDisplayBySessionRef = useRef<Record<string, Record<string, QueuedDisplayPayload>>>({});
const [queuedActionPromptId, setQueuedActionPromptId] = useState<string | null>(null);
+ const queuedScrollRef = useRef<HTMLDivElement | null>(null);
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
@@ -2724,17 +2752,22 @@ export function StandaloneChat({
const piStreamingTextRef = useRef<string>("");
const piMessageIdRef = useRef<string | null>(null);
const piContentBlocksRef = useRef<ContentBlock[]>([]);
+ const pendingNextPiUserIntentRef = useRef<"steer" | null>(null);
+ const pendingNextPiUserDisplayRef = useRef<QueuedDisplayPayload | null>(null);
const streamRenderTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Last error text observed anywhere in the current Pi stream — used to surface
// quota / credits_exhausted errors when agent_end arrives with no content and
// no explicit stopReason=error on any message (some providers drop that flag).
const piLastErrorRef = useRef<string | null>(null);
const piStartInFlightRef = useRef(false);
+ const sendDispatchInFlightRef = useRef(false);
+ const forceQueueModeRef = useRef(false);
const piFirstCallRetried = useRef(false);
const sessionActivityLastEmitAtRef = useRef<Record<string, number>>({});
const sessionActivityLastSigRef = useRef<Record<string, string>>({});
const piStoppedIntentionallyRef = useRef(false);
const piIntentionallyStoppedPidsRef = useRef<Set<number>>(new Set());
+ const piActiveStopRequestedRef = useRef(false);
const piPresetSwitchPromiseRef = useRef<Promise<void> | null>(null);
const piCrashCountRef = useRef(0);
const piLastCrashRef = useRef(0);
@@ -2797,6 +2830,11 @@ export function StandaloneChat({
const [conversationId, setConversationId] = useState<string | null>(
initialSessionIdRef.current,
);
+ const currentQueueSessionId = conversationId ?? piSessionIdRef.current;
+ const queuedPrompts = useMemo(
+ () => queuedPromptsBySession[currentQueueSessionId] ?? EMPTY_QUEUED_PROMPTS,
+ [queuedPromptsBySession, currentQueueSessionId]
+ );
const cancelStreamingMessageRender = useCallback(() => {
if (streamRenderTimerRef.current) {
@@ -3866,8 +3904,9 @@ export function StandaloneChat({
if (e.key === "Escape" && !showMentionDropdown) {
if (isLoading || isStreaming) {
// Stop the agent
+ piActiveStopRequestedRef.current = true;
try {
- await commands.piAbort(piSessionIdRef.current);
+ await commands.piAbortActive(piSessionIdRef.current);
} catch (err) {
console.warn("[Pi] Failed to abort on Escape:", err);
}
@@ -4173,20 +4212,29 @@ export function StandaloneChat({
const newAssistantId = (Date.now() + 1).toString();
let created = false;
setMessages((prev) => {
- const last = prev[prev.length - 1];
- if (!last || last.role !== "user") return prev;
+ let targetIdx = -1;
+ for (let i = prev.length - 1; i >= 0; i--) {
+ if (prev[i]?.role === "user") {
+ targetIdx = i;
+ break;
+ }
+ }
+ if (targetIdx === -1) return prev;
+
+ const target = prev[targetIdx];
+ if (!target || target.role !== "user") return prev;
created = true;
- return [
- ...prev,
- {
- id: newAssistantId,
- role: "assistant",
- content: "Processing...",
- timestamp: Date.now(),
- model: activePreset?.model,
- provider: activePreset?.provider,
- },
- ];
+
+ const base = [...prev];
+ base.splice(targetIdx + 1, 0, {
+ id: newAssistantId,
+ role: "assistant",
+ content: "Processing...",
+ timestamp: Date.now(),
+ model: activePreset?.model,
+ provider: activePreset?.provider,
+ });
+ return base;
});
if (!created) return false;
piMessageIdRef.current = newAssistantId;
@@ -4477,14 +4525,10 @@ export function StandaloneChat({
}
}
} else if (data.type === "message_start" && data.message?.role === "user") {
- // pi-mono fires `message_start` for a user message at the start of
- // every turn that introduces one — i.e. (a) the original prompt
- // and (b) each queued followUp processed inside the SAME agent run
- // (only one `agent_end` fires for the whole run, after all
- // followUps drain). If we relied on `agent_end` to close out the
- // current assistant message, the followUp's text_delta would land
- // on the previous turn's assistant bubble (the user saw responses
- // mashed together: "...Which?Hey. What do you need?").
+ // Pi fires `message_start` for each user turn. When a queued
+ // follow-up starts, close the previous streaming target here so the
+ // next text_delta creates a fresh assistant bubble instead of
+ // appending to the prior reply.
//
// Clear the streaming refs here so the next text_delta lazily
// creates a fresh assistant placeholder via `ensureAssistantPlaceholder`.
@@ -4504,32 +4548,78 @@ export function StandaloneChat({
// processing the followUp turn.
}
- // The user message tied to this turn just left the queue and is
- // now in-flight — clear the `queued` flag so the bubble drops
- // its muted treatment. We match on content text since pi-mono
- // doesn't echo our optimistic message id back.
- {
- const text = (() => {
- const c = data.message?.content;
- if (typeof c === "string") return c;
- if (Array.isArray(c)) {
- return c
- .filter((p: any) => p?.type === "text" && typeof p.text === "string")
- .map((p: any) => p.text)
- .join("");
- }
- return "";
- })();
- if (text) {
- setMessages((prev) => {
- let cleared = false;
- return prev.map((m) => {
- if (cleared || !m.queued || m.role !== "user" || m.content !== text) {
- return m;
- }
- cleared = true;
- return { ...m, queued: false };
- });
+ const text = (() => {
+ const c = data.message?.content;
+ if (typeof c === "string") return c;
+ if (Array.isArray(c)) {
+ return c
+ .filter((p: any) => p?.type === "text" && typeof p.text === "string")
+ .map((p: any) => p.text)
+ .join("");
+ }
+ return "";
+ })();
+ const eventImages = imageDataUrlsFromPiContent(data.message?.content);
+
+ if (!piMessageIdRef.current) {
+ const sidForStartedUser = piSessionIdRef.current;
+ const pendingDisplay = pendingNextPiUserDisplayRef.current;
+ const queuedDisplay = pendingDisplay ?? consumeQueuedDisplayForStartedMessage(sidForStartedUser, text);
+ const queuedImages = queuedDisplay?.images.length ? queuedDisplay.images : eventImages;
+ if (pendingDisplay) {
+ pendingNextPiUserDisplayRef.current = null;
+ }
+ if (!text && !queuedImages.length && !queuedDisplay?.displayContent) {
+ return;
+ }
+ const nextUserIntent = pendingNextPiUserIntentRef.current;
+ pendingNextPiUserIntentRef.current = null;
+ const queuedTurnUserId = Date.now().toString();
+ const queuedTurnAssistantId = (Date.now() + 1).toString();
+ const startedUser: Message = {
+ id: queuedTurnUserId,
+ role: "user",
+ content: text,
+ ...(queuedDisplay?.displayContent ? { displayContent: queuedDisplay.displayContent } : {}),
+ ...(queuedImages.length ? { images: [...queuedImages] } : {}),
+ ...(nextUserIntent === "steer" ? { intent: "steer" as const } : {}),
+ timestamp: Date.now(),
+ };
+ const assistantPlaceholder: Message = {
+ id: queuedTurnAssistantId,
+ role: "assistant",
+ content: "Processing...",
+ ...(nextUserIntent === "steer" ? { steeredResponse: true } : {}),
+ timestamp: Date.now(),
+ model: activePreset?.model,
+ provider: activePreset?.provider,
+ };
+
+ setMessages((prev) => {
+ const rows = [...prev, startedUser, assistantPlaceholder];
+ void saveConversation(rows, {
+ refreshHistory: false,
+ syncActiveConversation: false,
+ });
+ return rows;
+ });
+
+ piMessageIdRef.current = queuedTurnAssistantId;
+ piStreamingTextRef.current = "";
+ piContentBlocksRef.current = [];
+ setIsLoading(true);
+ setIsStreaming(true);
+
+ if (sidForStartedUser) {
+ const storeState = useChatStore.getState();
+ storeState.actions.appendMessage(sidForStartedUser, startedUser as any);
+ storeState.actions.appendMessage(sidForStartedUser, assistantPlaceholder as any);
+ storeState.actions.setStreaming(sidForStartedUser, {
+ streamingMessageId: queuedTurnAssistantId,
+ streamingText: "",
+ contentBlocks: [],
+ isStreaming: true,
+ isLoading: true,
});
}
}
@@ -4618,6 +4708,7 @@ export function StandaloneChat({
// functional updater until after the refs are cleared below.
const blocksSnapshot = [...piContentBlocksRef.current];
const streamedText = piStreamingTextRef.current;
+ const wasStoppedByUser = piActiveStopRequestedRef.current;
// Check if content was already set by error handlers above
setMessages((prev) => {
@@ -4639,6 +4730,9 @@ export function StandaloneChat({
return prev;
}
const contentBlocks = [...blocksSnapshot];
+ if (wasStoppedByUser && !content && contentBlocks.length === 0) {
+ return prev.filter((m) => m.id !== msgId);
+ }
// If no text content but we have tool/thinking blocks, don't show "no response"
const hasNonTextBlocks = contentBlocks.some((b) => b.type === "tool" || b.type === "thinking");
let emptyResponseRetryPrompt: string | undefined;
@@ -4709,8 +4803,10 @@ export function StandaloneChat({
piMessageIdRef.current = null;
piContentBlocksRef.current = [];
piLastErrorRef.current = null;
+ piActiveStopRequestedRef.current = false;
piThinkingStartRef.current = null;
followUpFiredRef.current = false;
+ forceQueueModeRef.current = false;
setIsLoading(false);
setIsStreaming(false);
emitSessionActivity({ status: "idle" });
@@ -4979,18 +5075,36 @@ export function StandaloneChat({
// 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; session_id?: string; queued?: PiQueuedPrompt[] }>("pi-queue-changed", (event) => {
+ listen<{
+ sessionId?: string;
+ session_id?: string;
+ queued?: PiQueuedPrompt[];
+ }>("pi-queue-changed", (event) => {
if (!mounted) return;
const { sessionId, queued } = normalizeQueueEventPayload(event.payload);
- if (sessionId !== piSessionIdRef.current) return;
- setQueuedPrompts(queued);
+ if (!sessionId) return;
+ setQueuedPromptsBySession((prev) => {
+ const existing = prev[sessionId] ?? [];
+ if (queuedSnapshotsEqual(existing, queued)) return prev;
+ return { ...prev, [sessionId]: queued };
+ });
}).then(fn => { unlistenQueue = fn; });
// Initial fetch — closes the gap between component mount and first event.
(async () => {
+ const sidAtFetch = piSessionIdRef.current;
try {
- const res = await commands.piPending(piSessionIdRef.current);
- if (mounted && res.status === "ok") setQueuedPrompts(res.data);
+ const res = await commands.piPending(sidAtFetch);
+ if (!mounted) return;
+ const nextQueue = res.status === "ok" ? res.data : [];
+ setQueuedPromptsBySession((prev) => {
+ const existing = prev[sidAtFetch] ?? [];
+ if (queuedSnapshotsEqual(existing, nextQueue)) return prev;
+ return {
+ ...prev,
+ [sidAtFetch]: nextQueue,
+ };
+ });
} catch { /* ignore — queue may not be initialized yet */ }
})();
@@ -5294,78 +5408,117 @@ export function StandaloneChat({
return piImages;
}
- 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);
+ function imageDataUrlsFromPiContent(content: unknown) {
+ if (!Array.isArray(content)) return [];
+ const images: string[] = [];
+ for (const part of content) {
+ if (!part || typeof part !== "object") continue;
+ const item = part as { type?: unknown; mimeType?: unknown; mime_type?: unknown; data?: unknown };
+ if (item.type !== "image" || typeof item.data !== "string") continue;
+ if (item.data.startsWith("data:image/")) {
+ images.push(item.data);
+ continue;
+ }
+ const mime = typeof item.mimeType === "string"
+ ? item.mimeType
+ : typeof item.mime_type === "string"
+ ? item.mime_type
+ : "image/png";
+ images.push(`data:${mime};base64,${item.data}`);
}
+ return images;
+ }
- // 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.
- // Mark queued=true so the bubble renders with a muted/lighter treatment
- // until Pi actually starts streaming this turn (cleared in handleAgentStart).
- const newUserMessage: Message = {
- id: Date.now().toString(),
- role: "user",
- content: userMessage,
- ...(displayLabel ? { displayContent: displayLabel } : {}),
- ...(pastedImages.length > 0 ? { images: [...pastedImages] } : {}),
- timestamp: Date.now(),
- queued: true,
+ function queuedPreviewForText(text: string) {
+ return Array.from(text).slice(0, 200).join("");
+ }
+
+ function shouldKeepQueuedDisplay(payload: QueuedDisplayPayload) {
+ return payload.images.length > 0 || !!payload.displayContent;
+ }
+
+ function restoreQueuedDisplay(sessionId: string | null, promptId: string, payload: QueuedDisplayPayload | null) {
+ if (!sessionId || !payload || !shouldKeepQueuedDisplay(payload)) return;
+ queuedDisplayBySessionRef.current = {
+ ...queuedDisplayBySessionRef.current,
+ [sessionId]: {
+ ...(queuedDisplayBySessionRef.current[sessionId] ?? {}),
+ [promptId]: payload,
+ },
};
- setMessages((prev) => {
- const next = [...prev, newUserMessage];
- void saveConversation(next, {
- refreshHistory: false,
- syncActiveConversation: false,
- });
- return next;
- });
- 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() });
- }
+ function takeQueuedDisplayById(sessionId: string | null, promptId: string): QueuedDisplayPayload | null {
+ if (!sessionId) return null;
+ const current = queuedDisplayBySessionRef.current[sessionId];
+ const payload = current?.[promptId] ?? null;
+ if (!payload) return null;
+ const { [promptId]: _removed, ...rest } = current;
+ queuedDisplayBySessionRef.current = {
+ ...queuedDisplayBySessionRef.current,
+ [sessionId]: rest,
+ };
+ return payload;
+ }
- posthog.capture("chat_message_enqueued", {
- provider: activePreset?.provider,
- model: activePreset?.model,
- pending_count: queuedPrompts.length + 1,
- });
+ function payloadMatchesText(payload: QueuedDisplayPayload, text: string) {
+ const preview = queuedPreviewForText(text);
+ if (!payload.preview) return !preview;
+ return preview === payload.preview || text.startsWith(payload.preview);
+ }
+
+ function consumeQueuedDisplayForStartedMessage(sessionId: string | null, text: string): QueuedDisplayPayload | null {
+ if (!sessionId) return null;
+ const queued = queuedDisplayBySessionRef.current[sessionId] ?? {};
+ const match = Object.entries(queued).find(([, payload]) => payloadMatchesText(payload, text));
+ if (!match) return null;
+ return takeQueuedDisplayById(sessionId, match[0]);
+ }
+
+ 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);
+ }
// 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 = imageDataUrlsToPiImages(pastedImages);
- if (pastedImages.length > 0) setPastedImages([]);
+ const queuedImageDataUrls = pastedImages.length > 0 ? [...pastedImages] : [];
+ const prevInput = input;
+ const hadPastedImages = pastedImages.length > 0;
+
+ setInput("");
+ if (inputRef.current) inputRef.current.style.height = "auto";
+ if (hadPastedImages) setPastedImages([]);
try {
- const result = await commands.piPrompt(
+ const result = await commands.piQueuePrompt(
piSessionIdRef.current,
userMessage,
piImages.length > 0 ? piImages : null,
);
if (result.status !== "ok") {
+ setInput(prevInput);
+ if (hadPastedImages) setPastedImages(queuedImageDataUrls);
toast({ title: "failed to queue message", description: result.error, variant: "destructive" });
+ return;
}
+
+ restoreQueuedDisplay(piSessionIdRef.current, result.data, {
+ preview: queuedPreviewForText(userMessage),
+ images: queuedImageDataUrls,
+ ...(displayLabel ? { displayContent: displayLabel } : {}),
+ });
+
+ posthog.capture("chat_message_enqueued", {
+ provider: activePreset?.provider,
+ model: activePreset?.model,
+ pending_count: queuedPrompts.length + 1,
+ });
} catch (e) {
+ setInput(prevInput);
+ if (hadPastedImages) setPastedImages(queuedImageDataUrls);
console.warn("[Pi] failed to enqueue follow-up:", e);
}
}
@@ -5375,6 +5528,7 @@ export function StandaloneChat({
piStreamingTextRef.current = "";
piMessageIdRef.current = null;
piContentBlocksRef.current = [];
+ forceQueueModeRef.current = false;
setIsLoading(false);
setIsStreaming(false);
}
@@ -5463,6 +5617,7 @@ export function StandaloneChat({
}
await interruptActivePiTurn();
+ forceQueueModeRef.current = true;
const outgoingImages = imageDataUrls ?? pastedImages;
const shouldClearPastedImages = imageDataUrls == null && pastedImages.length > 0;
@@ -5714,6 +5869,7 @@ export function StandaloneChat({
: m
)
);
+ forceQueueModeRef.current = false;
setIsLoading(false);
setIsStreaming(false);
}
@@ -5727,6 +5883,7 @@ export function StandaloneChat({
: m
)
);
+ forceQueueModeRef.current = false;
setIsLoading(false);
setIsStreaming(false);
}
@@ -5818,16 +5975,23 @@ export function StandaloneChat({
async function sendMessage(userMessage: string, displayLabel?: string) {
if ((!canChat && !autoSendBypassRef.current) || (!activePreset && !autoSendBypassRef.current)) return;
+ const trimmed = userMessage.trim();
+ if (!trimmed && pastedImages.length === 0) return;
- // If Pi is mid-reply, the default composer action is native steering:
- // the new message should interrupt and redirect the current reply. Queued
- // follow-up is still available through the clock button.
- if (isLoading || isStreaming) {
- return steerMessage(userMessage, displayLabel);
+ // Guard the tiny gap between submit and React's loading state update.
+ // During this window, rapid Enter presses must queue (not start a second
+ // normal turn), otherwise user bubbles can drift.
+ if (forceQueueModeRef.current || sendDispatchInFlightRef.current || piMessageIdRef.current || isLoading || isStreaming) {
+ return enqueuePiMessage(trimmed, displayLabel);
}
- // All providers route through Pi agent
- return sendPiMessage(userMessage, displayLabel);
+ sendDispatchInFlightRef.current = true;
+ try {
+ // All providers route through Pi agent
+ return await sendPiMessage(trimmed, displayLabel);
+ } finally {
+ sendDispatchInFlightRef.current = false;
+ }
}
async function queueFollowUpMessage(userMessage: string, displayLabel?: string) {
@@ -5835,62 +5999,48 @@ export function StandaloneChat({
return enqueuePiMessage(userMessage, displayLabel);
}
- function findLocalQueuedMessage(prompt: PiQueuedPrompt): Message | undefined {
- return messages.find(
- (message) =>
- message.role === "user" &&
- message.queued &&
- queuedPreviewMatchesText(prompt.preview, message.content),
- );
- }
+ // Queue UI is session-scoped. On chat switch, hydrate pending items for the
+ // active session key without mutating other session queues.
+ useEffect(() => {
+ const sid = currentQueueSessionId;
+ if (!sid) {
+ return;
+ }
- function removeLocalQueuedMessage(prompt: PiQueuedPrompt) {
- const matchesPrompt = (message: unknown) => {
- if (!message || typeof message !== "object") return false;
- const candidate = message as { role?: unknown; queued?: unknown; content?: unknown };
- return (
- candidate.role === "user" &&
- candidate.queued === true &&
- typeof candidate.content === "string" &&
- queuedPreviewMatchesText(prompt.preview, candidate.content)
- );
- };
+ let cancelled = false;
+ setQueuedActionPromptId(null);
- setMessages((prev) => {
- let removed = false;
- const next = prev.filter((message) => {
- if (!removed && matchesPrompt(message)) {
- removed = true;
- return false;
+ (async () => {
+ try {
+ const queuedRes = await commands.piPending(sid);
+ if (cancelled) return;
+ const nextQueue = queuedRes.status === "ok" ? queuedRes.data : [];
+ setQueuedPromptsBySession((prev) => {
+ const existing = prev[sid] ?? [];
+ if (queuedSnapshotsEqual(existing, nextQueue)) return prev;
+ return {
+ ...prev,
+ [sid]: nextQueue,
+ };
+ });
+ } catch {
+ if (!cancelled) {
+ setQueuedPromptsBySession((prev) => {
+ const existing = prev[sid] ?? [];
+ if (existing.length === 0) return prev;
+ return {
+ ...prev,
+ [sid]: [],
+ };
+ });
}
- return true;
- });
- if (!removed) return prev;
- void saveConversation(next, {
- refreshHistory: false,
- syncActiveConversation: false,
- });
- return next;
- });
-
- const sid = piSessionIdRef.current;
- if (!sid) return;
- const storeState = useChatStore.getState();
- const sessionMessages = storeState.sessions[sid]?.messages;
- if (!sessionMessages?.length) return;
-
- let removed = false;
- const nextMessages = sessionMessages.filter((message) => {
- if (!removed && matchesPrompt(message)) {
- removed = true;
- return false;
}
- return true;
- });
- if (removed) {
- storeState.actions.setMessages(sid, nextMessages);
- }
- }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ }, [currentQueueSessionId]);
async function cancelQueuedPrompt(prompt: PiQueuedPrompt, options: { silent?: boolean } = {}) {
setQueuedActionPromptId(prompt.id);
@@ -5911,8 +6061,15 @@ export function StandaloneChat({
}
return false;
}
- setQueuedPrompts((prev) => prev.filter((queued) => queued.id !== prompt.id));
- removeLocalQueuedMessage(prompt);
+ if (currentQueueSessionId) {
+ takeQueuedDisplayById(currentQueueSessionId, prompt.id);
+ setQueuedPromptsBySession((prev) => ({
+ ...prev,
+ [currentQueueSessionId]: (prev[currentQueueSessionId] ?? []).filter(
+ (queued) => queued.id !== prompt.id,
+ ),
+ }));
+ }
return true;
} catch (e) {
if (!options.silent) {
@@ -5928,6 +6085,60 @@ export function StandaloneChat({
}
}
+ function markCurrentAssistantInterrupted() {
+ const activeAssistantId = piMessageIdRef.current;
+ if (!activeAssistantId) return;
+
+ setMessages((prev) => {
+ let changed = false;
+ const next = prev.map((message) => {
+ if (message.id !== activeAssistantId || message.role !== "assistant" || message.interruptedBySteer) {
+ return message;
+ }
+ changed = true;
+ return { ...message, interruptedBySteer: true };
+ });
+ if (changed) {
+ void saveConversation(next, {
+ refreshHistory: false,
+ syncActiveConversation: false,
+ });
+ const sidNow = piSessionIdRef.current;
+ if (sidNow) {
+ useChatStore.getState().actions.setMessages(sidNow, next as any);
+ }
+ }
+ return changed ? next : prev;
+ });
+ }
+
+ function clearCurrentAssistantInterrupted() {
+ const activeAssistantId = piMessageIdRef.current;
+ if (!activeAssistantId) return;
+
+ setMessages((prev) => {
+ let changed = false;
+ const next = prev.map((message) => {
+ if (message.id !== activeAssistantId || message.role !== "assistant" || !message.interruptedBySteer) {
+ return message;
+ }
+ changed = true;
+ return { ...message, interruptedBySteer: false };
+ });
+ if (changed) {
+ void saveConversation(next, {
+ refreshHistory: false,
+ syncActiveConversation: false,
+ });
+ const sidNow = piSessionIdRef.current;
+ if (sidNow) {
+ useChatStore.getState().actions.setMessages(sidNow, next as any);
+ }
+ }
+ return changed ? next : prev;
+ });
+ }
+
async function steerMessage(userMessage: string, displayLabel?: string, imageDataUrls?: string[]) {
const hasImages = imageDataUrls ? imageDataUrls.length > 0 : pastedImages.length > 0;
const trimmed = userMessage.trim();
@@ -5948,15 +6159,6 @@ export function StandaloneChat({
const outgoingImages = imageDataUrls ?? pastedImages;
const shouldClearPastedImages = imageDataUrls == null && pastedImages.length > 0;
- const newUserMessage: Message = {
- id: Date.now().toString(),
- role: "user",
- content: trimmed,
- ...(displayLabel ? { displayContent: displayLabel } : {}),
- ...(outgoingImages.length > 0 ? { images: [...outgoingImages] } : {}),
- timestamp: Date.now(),
- };
-
setFollowUpSuggestions([]);
followUpFiredRef.current = false;
if (followUpAbortRef.current) {
@@ -5964,38 +6166,16 @@ export function StandaloneChat({
followUpAbortRef.current = null;
}
lastUserMessageRef.current = trimmed;
-
- setMessages((prev) => {
- const next = [...prev, newUserMessage];
- void saveConversation(next, {
- refreshHistory: false,
- syncActiveConversation: false,
- });
- return next;
- });
+ pendingNextPiUserIntentRef.current = "steer";
+ pendingNextPiUserDisplayRef.current = {
+ preview: queuedPreviewForText(trimmed),
+ images: [...outgoingImages],
+ ...(displayLabel ? { displayContent: displayLabel } : {}),
+ };
+ markCurrentAssistantInterrupted();
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() });
- }
-
const piImages = imageDataUrlsToPiImages(outgoingImages);
if (shouldClearPastedImages) setPastedImages([]);
@@ -6006,9 +6186,15 @@ export function StandaloneChat({
piImages.length > 0 ? piImages : null,
);
if (result.status !== "ok") {
+ pendingNextPiUserIntentRef.current = null;
+ pendingNextPiUserDisplayRef.current = null;
+ clearCurrentAssistantInterrupted();
toast({ title: "failed to steer message", description: result.error, variant: "destructive" });
}
} catch (e) {
+ pendingNextPiUserIntentRef.current = null;
+ pendingNextPiUserDisplayRef.current = null;
+ clearCurrentAssistantInterrupted();
console.warn("[Pi] failed to steer message:", e);
toast({
title: "failed to steer message",
@@ -6019,29 +6205,53 @@ export function StandaloneChat({
}
async function steerQueuedPrompt(prompt: PiQueuedPrompt) {
- const queuedMessage = findLocalQueuedMessage(prompt);
- if (!queuedMessage && (!prompt.preview || prompt.preview.length >= 200)) {
- toast({
- title: "full queued prompt unavailable",
- description: "Cancel it or let it run next; ScreenPipe only has a preview for this item.",
- });
- return;
- }
-
- const cancelled = await cancelQueuedPrompt(prompt, { silent: true });
- if (!cancelled) {
+ setQueuedActionPromptId(prompt.id);
+ const queuedDisplay = takeQueuedDisplayById(currentQueueSessionId, prompt.id);
+ try {
+ pendingNextPiUserIntentRef.current = "steer";
+ pendingNextPiUserDisplayRef.current = queuedDisplay;
+ markCurrentAssistantInterrupted();
+ const result = await commands.piSteerQueued(piSessionIdRef.current, prompt.id);
+ if (result.status !== "ok") {
+ pendingNextPiUserIntentRef.current = null;
+ pendingNextPiUserDisplayRef.current = null;
+ restoreQueuedDisplay(currentQueueSessionId, prompt.id, queuedDisplay);
+ clearCurrentAssistantInterrupted();
+ toast({ title: "failed to steer queued message", description: result.error, variant: "destructive" });
+ return;
+ }
+ if (!result.data) {
+ pendingNextPiUserIntentRef.current = null;
+ pendingNextPiUserDisplayRef.current = null;
+ restoreQueuedDisplay(currentQueueSessionId, prompt.id, queuedDisplay);
+ clearCurrentAssistantInterrupted();
+ toast({
+ title: "message already started",
+ description: "That follow-up has moved out of the queue.",
+ });
+ return;
+ }
+ if (currentQueueSessionId) {
+ setQueuedPromptsBySession((prev) => ({
+ ...prev,
+ [currentQueueSessionId]: (prev[currentQueueSessionId] ?? []).filter(
+ (queued) => queued.id !== prompt.id,
+ ),
+ }));
+ }
+ } catch (e) {
+ pendingNextPiUserIntentRef.current = null;
+ pendingNextPiUserDisplayRef.current = null;
+ restoreQueuedDisplay(currentQueueSessionId, prompt.id, queuedDisplay);
+ clearCurrentAssistantInterrupted();
toast({
- title: "message already started",
- description: "That follow-up has moved out of the queue.",
+ title: "failed to steer queued message",
+ description: e instanceof Error ? e.message : String(e),
+ variant: "destructive",
});
- return;
+ } finally {
+ setQueuedActionPromptId((current) => current === prompt.id ? null : current);
}
-
- await steerMessage(
- queuedMessage?.content ?? prompt.preview,
- queuedMessage?.displayContent,
- queuedMessage?.images ?? [],
- );
}
// Keep ref in sync so useEffect callbacks can call sendMessage
@@ -6116,8 +6326,9 @@ export function StandaloneChat({
};
const handleStop = async () => {
+ piActiveStopRequestedRef.current = true;
try {
- await commands.piAbort(piSessionIdRef.current);
+ await commands.piAbortActive(piSessionIdRef.current);
} catch (e) {
console.warn("[Pi] Failed to abort:", e);
}
@@ -6147,7 +6358,7 @@ export function StandaloneChat({
<div className="p-1 border-b border-border/50">
<button
type="button"
- disabled={isLoading || !canChat}
+ disabled={!canChat}
onClick={async () => {
setAppFilterOpen(false);
await handleFilePicker();
@@ -6739,7 +6950,9 @@ export function StandaloneChat({
if (!m.content && !m.contentBlocks?.length) return false;
return true;
})
- .map((message) => (
+ .map((message) => {
+ const intentLabel = getMessageIntentLabel(message);
+ return (
<motion.div
key={message.id}
initial={{ opacity: 0, y: 10 }}
@@ -6761,6 +6974,16 @@ export function StandaloneChat({
: "items-start w-full"
)}
>
+ {intentLabel ? (
+ <div
+ className={cn(
+ "mb-1 px-1 text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground/80",
+ message.role === "user" ? "text-right" : "text-left"
+ )}
+ >
+ {intentLabel}
+ </div>
+ ) : null}
<div
onMouseDown={(e) => {
if (message.role !== "user" || isLoading || editingMessageId === message.id) return;
@@ -6794,11 +7017,7 @@ export function StandaloneChat({
message.role === "user"
? "bg-muted/60 text-foreground px-4 py-3"
: "bg-background text-foreground py-1",
- message.role === "user" && !isLoading && editingMessageId !== message.id && "cursor-text",
- // Queued user messages — visually de-emphasised so the eye stays on
- // the active turn. Cleared when pi-mono fires message_start for
- // this turn (see handler above).
- message.queued && "bg-muted/35 text-muted-foreground opacity-80"
+ message.role === "user" && !isLoading && editingMessageId !== message.id && "cursor-text"
)}
>
{editingMessageId === message.id ? (
@@ -6941,7 +7160,8 @@ export function StandaloneChat({
</div>
</div>
</motion.div>
- ))}
+ );
+ })}
</AnimatePresence>
<AnimatePresence>
{isLoading && (() => {
@@ -7213,72 +7433,74 @@ export function StandaloneChat({
</AnimatePresence>
)}
- <AnimatePresence>
- {queuedPrompts.length > 0 && (
- <motion.div
- key="composer-queued-rail"
- initial={{ opacity: 0, y: 8 }}
- animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0, y: 6 }}
- transition={{ duration: 0.18 }}
- className="mb-2 rounded-lg border border-border/60 bg-background/95 shadow-sm overflow-hidden"
- >
- <div className="flex items-center justify-between gap-2 px-3 py-1.5 border-b border-border/50">
- <div className="flex items-center gap-1.5 min-w-0">
- <Clock className="h-3 w-3 text-muted-foreground/70 shrink-0" />
- <span className="text-[10px] uppercase tracking-wider text-muted-foreground/70">
- queued
- </span>
- </div>
- <span className="text-[10px] font-mono text-muted-foreground/60">
- {queuedPrompts.length}
+ {queuedPrompts.length > 0 && (
+ <motion.div
+ initial={{ opacity: 0, y: 8 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.18 }}
+ className="mb-2 rounded-lg border border-border/60 bg-background/95 backdrop-blur-sm shadow-sm overflow-hidden"
+ >
+ <div className="flex items-center justify-between gap-2 px-3 py-1.5 border-b border-border/50 bg-background">
+ <div className="flex items-center gap-1.5 min-w-0">
+ <Clock className="h-3 w-3 text-muted-foreground/70 shrink-0" />
+ <span className="text-[10px] uppercase tracking-wide text-muted-foreground font-medium">
+ Queued
</span>
</div>
- <TooltipProvider delayDuration={150}>
- <div className="max-h-[156px] overflow-y-auto scrollbar-minimal">
- {queuedPrompts.map((p, i) => {
- const isBusy = queuedActionPromptId === p.id;
- const label = p.preview || "image follow-up";
- return (
- <motion.div
- key={p.id}
- layout
- initial={{ opacity: 0, y: 4 }}
- animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0, x: 8, scale: 0.98 }}
- transition={{ duration: 0.16 }}
- tabIndex={0}
- role="listitem"
- onKeyDown={(e) => {
- if (isBusy) return;
- if (isQueuedItemSteerShortcut(e, isMac)) {
- e.preventDefault();
- steerQueuedPrompt(p);
- } else if (isQueuedItemCancelShortcut(e)) {
- e.preventDefault();
- cancelQueuedPrompt(p);
- }
- }}
- className="group/qcard flex items-center gap-2 px-3 py-2 border-b border-border/40 last:border-b-0 text-sm text-muted-foreground/90 focus-visible:outline-none focus-visible:bg-muted/40 hover:bg-muted/30 transition-colors"
- title={label.length > 90 ? label : undefined}
- >
- <span className="font-mono text-[10px] text-muted-foreground/50 shrink-0 w-4 text-right">
- {i + 1}
- </span>
- <span className="truncate flex-1 min-w-0">{label}</span>
+ <span className="text-[10px] font-mono text-muted-foreground/60">
+ {queuedPrompts.length}
+ </span>
+ </div>
+ <TooltipProvider delayDuration={150}>
+ <div ref={queuedScrollRef} className="max-h-[112px] overflow-y-auto scrollbar-minimal">
+ {queuedPrompts.map((p, i) => {
+ const isBusy = queuedActionPromptId === p.id;
+ const label = p.preview || "image follow-up";
+ return (
+ <motion.div
+ key={p.id}
+ layout
+ initial={{ opacity: 0, y: 4 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.16 }}
+ tabIndex={0}
+ role="listitem"
+ onKeyDown={(e) => {
+ if (isBusy) return;
+ if (isQueuedItemSteerShortcut(e, isMac)) {
+ e.preventDefault();
+ steerQueuedPrompt(p);
+ } else if (isQueuedItemCancelShortcut(e)) {
+ e.preventDefault();
+ cancelQueuedPrompt(p);
+ }
+ }}
+ className="group/qcard select-none flex min-h-[36px] items-center gap-2 px-2.5 py-1.5 border-b border-border/40 last:border-b-0 text-sm text-foreground/90 focus-visible:outline-none focus-visible:bg-muted/20 hover:bg-muted/15 transition-colors"
+ title={label.length > 90 ? label : undefined}
+ >
+ <span className="w-4 shrink-0 text-right font-mono text-[10px] text-muted-foreground/50">
+ {i + 1}
+ </span>
+ <span className="flex-1 min-w-0 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-[12px]">
+ {label}
+ </span>
+ <div className="flex items-center gap-1 shrink-0">
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
disabled={isBusy}
onClick={() => steerQueuedPrompt(p)}
- className="h-7 w-7 rounded-md inline-flex items-center justify-center text-foreground bg-muted/70 hover:bg-muted disabled:opacity-50 disabled:pointer-events-none transition-colors"
+ className="h-6 px-2 inline-flex items-center gap-1 justify-center text-foreground bg-background hover:bg-muted/20 disabled:opacity-50 disabled:pointer-events-none transition-colors border border-border/50"
aria-label={`steer queued message ${i + 1}`}
>
{isBusy ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
- <CornerDownRight className="h-3 w-3" />
+ <>
+ <CornerDownRight className="h-2.5 w-2.5" />
+ <span className="text-[10px] font-medium">Steer</span>
+ </>
)}
</button>
</TooltipTrigger>
@@ -7292,22 +7514,22 @@ export function StandaloneChat({
type="button"
disabled={isBusy}
onClick={() => cancelQueuedPrompt(p)}
- className="h-7 w-7 rounded-md inline-flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-50 disabled:pointer-events-none transition-colors"
+ className="h-6 w-6 inline-flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted/20 disabled:opacity-50 disabled:pointer-events-none transition-colors border border-transparent hover:border-border/50"
aria-label={`remove queued message ${i + 1}`}
>
- <Trash2 className="h-3.5 w-3.5" />
+ <Trash2 className="h-3 w-3" />
</button>
</TooltipTrigger>
<TooltipContent side="top">Remove queued message</TooltipContent>
</Tooltip>
- </motion.div>
- );
- })}
- </div>
- </TooltipProvider>
- </motion.div>
- )}
- </AnimatePresence>
+ </div>
+ </motion.div>
+ );
+ })}
+ </div>
+ </TooltipProvider>
+ </motion.div>
+ )}
<div
className={cn(
@@ -7329,7 +7551,7 @@ export function StandaloneChat({
disabledReason
? disabledReason
: isLoading || isStreaming
- ? "Steer current reply..."
+ ? "Message will be queued..."
: "Ask about your screen... (type @ for filters, paste images)"
}
disabled={!canChat}
@@ -7458,38 +7680,9 @@ export function StandaloneChat({
{(() => {
const hasInput = input.trim().length > 0 || pastedImages.length > 0;
const primaryAction = getComposerPrimaryAction(isLoading || isStreaming, hasInput);
- const isSteerMode = primaryAction === "steer";
const isStopMode = primaryAction === "stop";
return (
<>
- {isSteerMode && (
- <TooltipProvider delayDuration={150}>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="button"
- size="icon"
- variant="ghost"
- disabled={!canChat}
- onClick={() => queueFollowUpMessage(input.trim())}
- className="h-8 w-8 text-muted-foreground hover:text-foreground hover:bg-muted/60 relative"
- aria-label="queue follow-up after current reply"
- title="queue follow-up after current reply"
- >
- <Clock className="h-3.5 w-3.5" />
- {queuedPrompts.length > 0 && (
- <span className="absolute -top-1.5 -right-1.5 min-w-[16px] h-[16px] px-1 rounded-full bg-muted text-foreground text-[9px] font-mono font-semibold flex items-center justify-center border border-background">
- {queuedPrompts.length}
- </span>
- )}
- </Button>
- </TooltipTrigger>
- <TooltipContent side="top">
- Queue follow-up after current reply
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- )}
<Button
type={isStopMode ? "button" : "submit"}
size="icon"
@@ -7502,22 +7695,16 @@ export function StandaloneChat({
title={
isStopMode
? "stop"
- : isSteerMode
- ? "steer current reply"
- : "send"
+ : "send"
}
aria-label={
isStopMode
? "stop reply"
- : isSteerMode
- ? "steer current reply"
- : "send message"
+ : "send message"
}
>
{isStopMode ? (
<Square className="h-4 w-4" />
- ) : isSteerMode ? (
- <CornerDownRight className="h-4 w-4" />
) : (
<Send className="h-4 w-4" />
)}
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/chat-queue-controls.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/chat-queue-controls.test.ts
index d0344a1d3..cd71d63f6 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/chat-queue-controls.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/chat-queue-controls.test.ts
@@ -10,7 +10,6 @@ import {
isQueuedItemCancelShortcut,
isQueuedItemSteerShortcut,
normalizeQueueEventPayload,
- queuedPreviewMatchesText,
} from "../chat-queue-controls";
describe("chat queue controls", () => {
@@ -61,13 +60,6 @@ describe("chat queue controls", () => {
expect(isQueuedItemCancelShortcut({ key: "Backspace", metaKey: true })).toBe(false);
});
- it("matches queued previews against the local full user prompt", () => {
- expect(queuedPreviewMatchesText("first 200 chars", "first 200 chars plus the rest")).toBe(true);
- expect(queuedPreviewMatchesText("different", "first 200 chars plus the rest")).toBe(false);
- expect(queuedPreviewMatchesText("", "")).toBe(true);
- expect(queuedPreviewMatchesText("", "non-empty text")).toBe(false);
- });
-
it("formats steer shortcuts without platform-specific glyph assumptions", () => {
expect(formatSteerShortcut(true)).toBe("Cmd+Enter");
expect(formatSteerShortcut(false)).toBe("Ctrl+Enter");
diff --git a/apps/screenpipe-app-tauri/lib/chat-queue-controls.ts b/apps/screenpipe-app-tauri/lib/chat-queue-controls.ts
index c7d5ed06b..03969a8ea 100644
--- a/apps/screenpipe-app-tauri/lib/chat-queue-controls.ts
+++ b/apps/screenpipe-app-tauri/lib/chat-queue-controls.ts
@@ -90,8 +90,3 @@ export function getComposerPrimaryAction(
if (!isBusy) return "send";
return hasInput ? "steer" : "stop";
}
-
-export function queuedPreviewMatchesText(preview: string, text: string): boolean {
- if (!preview) return text.length === 0;
- return text.startsWith(preview);
-}
diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
index ff2bb1598..84a822247 100644
--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -913,7 +913,7 @@ async piInstall() : Promise<Result<null, string>> {
* The command is serialized through the queue — it will wait for any prior
* command (new_session, abort) to fully complete before being written to stdin.
*/
-async piPrompt(sessionId: string | null, message: string, images: PiImageContent[] | null) : Promise<Result<null, string>> {
+async piPrompt(sessionId: string | null, message: string, images: PiImageContent[] | null) : Promise<Result<string, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("pi_prompt", { sessionId, message, images }) };
} catch (e) {
@@ -921,6 +921,19 @@ async piPrompt(sessionId: string | null, message: string, images: PiImageContent
else return { status: "error", error: e as any };
}
},
+/**
+ * Queue a follow-up prompt for the current session. Unlike `pi_prompt`, this
+ * returns as soon as Rust owns the queued item; the prompt is written only
+ * after the active turn finishes.
+ */
+async piQueuePrompt(sessionId: string | null, message: string, images: PiImageContent[] | null) : Promise<Result<string, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("pi_queue_prompt", { sessionId, message, images }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
/**
* Steer the active Pi reply using Pi's native steering command.
* Unlike `pi_prompt`, this is intentionally not added to the follow-up queue:
@@ -934,6 +947,19 @@ async piSteer(sessionId: string | null, message: string, images: PiImageContent[
else return { status: "error", error: e as any };
}
},
+/**
+ * Promote a queued follow-up into Pi's native steer path. The prompt is
+ * removed from the Rust queue first, so it cannot later run as a normal
+ * follow-up.
+ */
+async piSteerQueued(sessionId: string | null, promptId: string) : Promise<Result<boolean, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("pi_steer_queued", { sessionId, promptId }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else 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
@@ -972,6 +998,17 @@ async piAbort(sessionId: string | null) : Promise<Result<null, string>> {
else return { status: "error", error: e as any };
}
},
+/**
+ * Abort only the active Pi operation. Pending queued follow-ups remain queued.
+ */
+async piAbortActive(sessionId: string | null) : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("pi_abort_active", { sessionId }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
/**
* Start a new Pi session (clears conversation history).
* Serialized through the queue — waits for any in-flight work to complete,
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 750b1cf61..fb12b60fe 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -811,10 +811,13 @@ async fn main() {
pi::pi_check,
pi::pi_install,
pi::pi_prompt,
+ pi::pi_queue_prompt,
pi::pi_steer,
+ pi::pi_steer_queued,
pi::pi_pending,
pi::pi_cancel_queued,
pi::pi_abort,
+ pi::pi_abort_active,
pi::pi_new_session,
pi::pi_set_model,
pi::pi_update_config,
@@ -1116,10 +1119,13 @@ async fn main() {
pi::pi_check,
pi::pi_install,
pi::pi_prompt,
+ pi::pi_queue_prompt,
pi::pi_steer,
+ pi::pi_steer_queued,
pi::pi_pending,
pi::pi_cancel_queued,
pi::pi_abort,
+ pi::pi_abort_active,
pi::pi_new_session,
pi::pi_set_model,
pi::pi_update_config,
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index 7ff002e4c..a46c3c548 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -1614,42 +1614,15 @@ pub async fn pi_start_inner(
qs.mark_agent_active();
}
Some("agent_end") => {
- // 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("message_start") => {}
Some("response") => {
// 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.
+ // fire agent_start/agent_end. Suppress while a prompt
+ // is mid-stream so the queue never advances on an ACK
+ // while the assistant is still replying.
if !qs.is_agent_active() {
// Note: this runs on a std::thread (not tokio),
// so use std::thread::spawn + std::thread::sleep.
@@ -1842,6 +1815,39 @@ pub struct PiImageContent {
pub data: String, // base64-encoded image data
}
+fn build_prompt_command(
+ message: String,
+ images: Option<Vec<PiImageContent>>,
+) -> Result<Value, String> {
+ let mut cmd = json!({
+ "type": "prompt",
+ "message": message,
+ });
+ if let Some(imgs) = images {
+ if !imgs.is_empty() {
+ cmd["images"] = serde_json::to_value(imgs).map_err(|e| e.to_string())?;
+ }
+ }
+ Ok(cmd)
+}
+
+fn queued_payload_to_steer_command(payload: Value) -> Result<Value, String> {
+ let message = payload
+ .get("message")
+ .and_then(|v| v.as_str())
+ .ok_or("queued prompt is missing message")?
+ .to_string();
+
+ let mut cmd = json!({
+ "type": "steer",
+ "message": message,
+ });
+ if let Some(images) = payload.get("images") {
+ cmd["images"] = images.clone();
+ }
+ Ok(cmd)
+}
+
/// Send a prompt to Pi, optionally with images.
/// The command is serialized through the queue — it will wait for any prior
/// command (new_session, abort) to fully complete before being written to stdin.
@@ -1852,7 +1858,7 @@ pub async fn pi_prompt(
session_id: Option<String>,
message: String,
images: Option<Vec<PiImageContent>>,
-) -> Result<(), String> {
+) -> Result<String, String> {
let sid = session_id.unwrap_or_else(|| "chat".to_string());
let queue = {
let mut pool = state.0.lock().await;
@@ -1866,39 +1872,54 @@ 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,
- "streamingBehavior": "followUp",
- });
- if let Some(imgs) = images {
- if !imgs.is_empty() {
- cmd["images"] = serde_json::to_value(imgs).map_err(|e| e.to_string())?;
- }
- }
-
- // 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
+ let cmd = build_prompt_command(message.clone(), images)?;
+ let (queue_id, rx) = queue
.send_prompt(
cmd,
- crate::pi_command_queue::WaitMode::WriteOnly,
+ crate::pi_command_queue::WaitMode::Prompt,
message.clone(),
+ false,
)
.await?;
rx.await
- .map_err(|_| "Pi command queue dropped".to_string())?
+ .map_err(|_| "Pi command queue dropped".to_string())??;
+ Ok(queue_id)
+}
+
+/// Queue a follow-up prompt for the current session. Unlike `pi_prompt`, this
+/// returns as soon as Rust owns the queued item; the prompt is written only
+/// after the active turn finishes.
+#[tauri::command]
+#[specta::specta]
+pub async fn pi_queue_prompt(
+ state: State<'_, PiState>,
+ session_id: Option<String>,
+ message: String,
+ images: Option<Vec<PiImageContent>>,
+) -> Result<String, String> {
+ let sid = session_id.unwrap_or_else(|| "chat".to_string());
+ let queue = {
+ let mut pool = state.0.lock().await;
+ let m = pool.sessions.get_mut(&sid).ok_or("Pi not initialized")?;
+ if !m.is_running() {
+ return Err("Pi is not running".to_string());
+ }
+ m.last_activity = std::time::Instant::now();
+ m.queue_handle
+ .clone()
+ .ok_or("Pi command queue not initialized")?
+ };
+
+ let cmd = build_prompt_command(message.clone(), images)?;
+ let (queue_id, _rx) = queue
+ .send_prompt(
+ cmd,
+ crate::pi_command_queue::WaitMode::Prompt,
+ message,
+ true,
+ )
+ .await?;
+ Ok(queue_id)
}
/// Steer the active Pi reply using Pi's native steering command.
@@ -1935,11 +1956,38 @@ pub async fn pi_steer(
}
}
- let rx = queue
- .send(cmd, crate::pi_command_queue::WaitMode::WriteOnly)
- .await?;
- rx.await
- .map_err(|_| "Pi command queue dropped".to_string())?
+ queue.send_immediate(cmd).await
+}
+
+/// Promote a queued follow-up into Pi's native steer path. The prompt is
+/// removed from the Rust queue first, so it cannot later run as a normal
+/// follow-up.
+#[tauri::command]
+#[specta::specta]
+pub async fn pi_steer_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 mut pool = state.0.lock().await;
+ let m = pool.sessions.get_mut(&sid).ok_or("Pi not initialized")?;
+ if !m.is_running() {
+ return Err("Pi is not running".to_string());
+ }
+ m.last_activity = std::time::Instant::now();
+ m.queue_handle
+ .clone()
+ .ok_or("Pi command queue not initialized")?
+ };
+
+ let Some(payload) = queue.take_queued_payload(prompt_id).await? else {
+ return Ok(false);
+ };
+ let cmd = queued_payload_to_steer_command(payload)?;
+ queue.send_immediate(cmd).await?;
+ Ok(true)
}
/// Cancel a single queued prompt. Returns true if it was still in the queue
@@ -2008,6 +2056,28 @@ pub async fn pi_abort(state: State<'_, PiState>, session_id: Option<String>) ->
queue.abort().await
}
+/// Abort only the active Pi operation. Pending queued follow-ups remain queued.
+#[tauri::command]
+#[specta::specta]
+pub async fn pi_abort_active(
+ state: State<'_, PiState>,
+ session_id: Option<String>,
+) -> Result<(), String> {
+ let sid = session_id.unwrap_or_else(|| "chat".to_string());
+ let queue = {
+ let mut pool = state.0.lock().await;
+ let m = pool.sessions.get_mut(&sid).ok_or("Pi not initialized")?;
+ if !m.is_running() {
+ return Err("Pi is not running".to_string());
+ }
+ m.last_activity = std::time::Instant::now();
+ m.queue_handle
+ .clone()
+ .ok_or("Pi command queue not initialized")?
+ };
+ queue.abort_active_only().await
+}
+
/// Start a new Pi session (clears conversation history).
/// Serialized through the queue — waits for any in-flight work to complete,
/// then sends new_session and waits for the SDK's done event before returning.
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 811b92b32..ca5f9c4dd 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
@@ -20,6 +20,7 @@
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use specta::Type;
+use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::process::ChildStdin;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -63,15 +64,14 @@ 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 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.
+ /// Write to stdin, reply Ok, advance immediately. Used for commands that
+ /// are allowed to interrupt or redirect the current turn (for example
+ /// native `steer`).
WriteOnly,
+ /// Write a prompt, acknowledge the write, then wait for the agent to
+ /// become idle before the next queued prompt is written. This keeps
+ /// follow-ups in Rust's cancellable queue until their actual turn starts.
+ Prompt,
/// 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,
@@ -81,6 +81,7 @@ pub enum WaitMode {
#[derive(Clone)]
pub struct PiQueueHandle {
tx: mpsc::Sender<QueueMessage>,
+ stdin: Option<Arc<Mutex<ChildStdin>>>,
/// 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.
@@ -117,7 +118,11 @@ pub struct PiQueueState {
/// 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>>,
+ cancelled: std::sync::Mutex<HashSet<String>>,
+ /// Full queued command payloads by queue id. The UI only receives a small
+ /// preview, but backend actions like "Steer this queued row" need the
+ /// exact original prompt/images without trusting frontend shadow state.
+ queued_payloads: std::sync::Mutex<HashMap<String, Value>>,
/// 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
@@ -138,14 +143,15 @@ impl PiQueueState {
terminated_notify: Notify::new(),
alive: alive_tx,
queued: queued_tx,
- cancelled: std::sync::Mutex::new(std::collections::HashSet::new()),
+ cancelled: std::sync::Mutex::new(HashSet::new()),
+ queued_payloads: std::sync::Mutex::new(HashMap::new()),
agent_active: AtomicBool::new(false),
})
}
/// Called by the stdout reader when a `done` event is received.
pub fn signal_done(&self) {
- self.done_notify.notify_one();
+ self.done_notify.notify_waiters();
}
/// Called by the stdout reader on `agent_start` (a prompt has begun streaming).
@@ -172,6 +178,12 @@ 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());
+ if let Ok(mut payloads) = self.queued_payloads.lock() {
+ payloads.clear();
+ }
+ if let Ok(mut cancelled) = self.cancelled.lock() {
+ cancelled.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);
@@ -188,7 +200,10 @@ impl PiQueueState {
self.queued.borrow().clone()
}
- fn enqueue_prompt(&self, prompt: PiQueuedPrompt) {
+ fn enqueue_prompt(&self, prompt: PiQueuedPrompt, payload: Value) {
+ if let Ok(mut payloads) = self.queued_payloads.lock() {
+ payloads.insert(prompt.id.clone(), payload);
+ }
self.queued.send_modify(|v| v.push(prompt));
}
@@ -198,30 +213,9 @@ impl PiQueueState {
v.remove(pos);
}
});
- }
-
- /// 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
+ if let Ok(mut payloads) = self.queued_payloads.lock() {
+ payloads.remove(id);
+ }
}
/// Mark a prompt id as cancelled so the drain loop drops it on dequeue
@@ -239,6 +233,27 @@ impl PiQueueState {
was_present
}
+ fn take_queued_payload(&self, id: &str) -> Option<Value> {
+ let was_visible = self.queued.borrow().iter().any(|p| p.id == id);
+ if !was_visible {
+ return None;
+ }
+ let payload = self
+ .queued_payloads
+ .lock()
+ .ok()
+ .and_then(|mut payloads| payloads.remove(id));
+ if let Ok(mut set) = self.cancelled.lock() {
+ set.insert(id.to_string());
+ }
+ self.queued.send_modify(|v| {
+ if let Some(pos) = v.iter().position(|p| p.id == id) {
+ v.remove(pos);
+ }
+ });
+ payload
+ }
+
fn take_cancelled(&self, id: &str) -> bool {
if let Ok(mut set) = self.cancelled.lock() {
set.remove(id)
@@ -278,6 +293,7 @@ impl PiQueueHandle {
payload: Value,
wait_mode: WaitMode,
preview: String,
+ force_visible_queue: bool,
) -> Result<(String, oneshot::Receiver<Result<(), String>>), String> {
let id = format!("q_{}", uuid::Uuid::new_v4().simple());
let queued_at_ms = std::time::SystemTime::now()
@@ -294,28 +310,99 @@ impl PiQueueHandle {
};
let (tx, rx) = oneshot::channel();
- self.tx
+ let should_show_in_queue = force_visible_queue || self.state.is_agent_active();
+ let tracked_payload = payload.clone();
+
+ if should_show_in_queue {
+ self.state.enqueue_prompt(meta.clone(), tracked_payload);
+ }
+
+ if self
+ .tx
.send(QueueMessage::Command(PiCommand {
payload,
wait_mode,
reply: tx,
- prompt_meta: Some(meta.clone()),
+ prompt_meta: Some(meta),
}))
.await
- .map_err(|_| "Pi command queue closed".to_string())?;
-
- // 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);
+ .is_err()
+ {
+ if should_show_in_queue {
+ self.state.dequeue_prompt(&id);
+ }
+ return Err("Pi command queue closed".to_string());
}
Ok((id, rx))
}
+ /// Remove a queued prompt and return its original command payload. Used
+ /// for queue-row steering: the selected follow-up leaves the queue and is
+ /// sent through Pi's native steer path instead of later running as a
+ /// normal follow-up.
+ pub async fn take_queued_payload(&self, prompt_id: String) -> Result<Option<Value>, String> {
+ Ok(self.state.take_queued_payload(&prompt_id))
+ }
+
+ /// Write a command straight to Pi stdin. This is intentionally reserved
+ /// for native steer, which must redirect the active turn immediately
+ /// instead of waiting behind normal queued follow-ups.
+ pub async fn send_immediate(&self, mut payload: Value) -> Result<(), String> {
+ let stdin = self
+ .stdin
+ .as_ref()
+ .ok_or("Pi stdin is not available".to_string())?;
+ let req_id = format!("req_{}", uuid::Uuid::new_v4().simple());
+ if let Some(obj) = payload.as_object_mut() {
+ obj.insert("id".to_string(), json!(&req_id));
+ }
+ let cmd_type = payload
+ .get("type")
+ .and_then(|t| t.as_str())
+ .unwrap_or("?")
+ .to_string();
+ let cmd_str = serde_json::to_string(&payload).map_err(|e| e.to_string())?;
+ let mut stdin_guard = stdin.lock().await;
+ info!(
+ "pi_command_queue: writing immediate {} ({}), {} bytes",
+ cmd_type,
+ req_id,
+ cmd_str.len()
+ );
+ writeln!(*stdin_guard, "{}", cmd_str)
+ .and_then(|_| stdin_guard.flush())
+ .map_err(|e| format!("stdin write failed: {}", e))
+ }
+
+ /// Abort only the active Pi turn. Unlike `abort`, this does not drain or
+ /// clear queued follow-ups, so the queue can continue after the active
+ /// reply stops.
+ pub async fn abort_active_only(&self) -> Result<(), String> {
+ let stdin = self
+ .stdin
+ .as_ref()
+ .ok_or("Pi stdin is not available".to_string())?;
+ let mut alive_rx = self.state.alive.subscribe();
+ let req_id = format!("req_{}", uuid::Uuid::new_v4().simple());
+ let abort_cmd = json!({"type": "abort", "id": &req_id});
+ let cmd_str = serde_json::to_string(&abort_cmd).map_err(|e| e.to_string())?;
+
+ self.state.mark_agent_idle();
+ {
+ let mut stdin_guard = stdin.lock().await;
+ info!("pi_command_queue: writing active-only abort ({})", req_id);
+ writeln!(*stdin_guard, "{}", cmd_str)
+ .and_then(|_| stdin_guard.flush())
+ .map_err(|e| format!("abort write failed: {}", e))?;
+ }
+
+ if wait_for_done_or_terminated(&self.state, &mut alive_rx, "abort").await {
+ Ok(())
+ } else {
+ Err("Pi process died during abort".to_string())
+ }
+ }
+
/// 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).
@@ -355,6 +442,7 @@ pub fn spawn_queue(
let (tx, mut rx) = mpsc::channel::<QueueMessage>(32);
let handle = PiQueueHandle {
tx,
+ stdin: Some(stdin.clone()),
state: state.clone(),
};
@@ -384,6 +472,7 @@ pub fn spawn_queue(
match msg {
QueueMessage::Command(cmd) => {
let prompt_id = cmd.prompt_meta.as_ref().map(|m| m.id.clone());
+ let is_prompt = prompt_id.is_some();
// Tombstone check — if the user cancelled this prompt
// while it was sitting in the channel, drop it without
@@ -411,6 +500,37 @@ pub fn spawn_queue(
.unwrap_or("?")
.to_string();
+ // Prompt commands must be serialized against the currently
+ // active agent turn. We cannot rely on response ACK order:
+ // ACK can arrive before pi-mono actually starts streaming.
+ if is_prompt && state.is_agent_active() {
+ let ok =
+ wait_for_done_or_terminated(&state, &mut alive_rx, &cmd_type).await;
+ if !ok {
+ if let Some(pid) = &prompt_id {
+ state.dequeue_prompt(pid);
+ }
+ let _ = cmd
+ .reply
+ .send(Err("Pi process died while processing".to_string()));
+ continue;
+ }
+
+ // The first queued prompt can already be popped from
+ // the mpsc channel and parked here waiting for the
+ // current turn to finish. If the user deletes it
+ // during that wait, the original tombstone check above
+ // is now stale. Re-check before writing so "Delete"
+ // really prevents the prompt from ever reaching 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;
+ }
+ }
+ }
+
// Write to stdin
let write_result = {
let mut stdin_guard = stdin.lock().await;
@@ -436,21 +556,35 @@ pub fn spawn_queue(
continue;
}
+ // `agent_start` can arrive a little later than the write.
+ // Mark active optimistically for prompt commands so the
+ // next queued prompt cannot slip through this tiny window.
+ if is_prompt {
+ state.mark_agent_active();
+ }
+
match cmd.wait_mode {
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.
+ if let Some(pid) = &prompt_id {
+ state.dequeue_prompt(pid);
+ }
let _ = cmd.reply.send(Ok(()));
}
+ WaitMode::Prompt => {
+ // The prompt has now left the waiting queue and
+ // entered the transcript as the active turn.
+ if let Some(pid) = &prompt_id {
+ state.dequeue_prompt(pid);
+ }
+ let _ = cmd.reply.send(Ok(()));
+ let _ =
+ 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.
+ // Prompts use Prompt mode and skip this branch.
if let Some(pid) = &prompt_id {
state.dequeue_prompt(pid);
}
@@ -490,6 +624,12 @@ 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());
+ if let Ok(mut payloads) = state.queued_payloads.lock() {
+ payloads.clear();
+ }
+ if let Ok(mut tombstones) = state.cancelled.lock() {
+ tombstones.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
@@ -629,7 +769,11 @@ mod tests {
// Verify the handle API works without a real subprocess
let (tx, mut rx) = mpsc::channel::<QueueMessage>(8);
let state = PiQueueState::new();
- let handle = PiQueueHandle { tx, state };
+ let handle = PiQueueHandle {
+ tx,
+ stdin: None,
+ state,
+ };
// Send a command in the background
let h = tokio::spawn(async move {
@@ -656,7 +800,11 @@ mod tests {
async fn test_abort_cancels_pending() {
let (tx, mut rx) = mpsc::channel::<QueueMessage>(8);
let state = PiQueueState::new();
- let handle = PiQueueHandle { tx, state };
+ let handle = PiQueueHandle {
+ tx,
+ stdin: None,
+ state,
+ };
// Queue two commands
let h1 = {