Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix queued chat messages disappearing when switching chats (#3897)

Harsh Kumar24b6414e67af
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index ee07f8081..ac6d75391 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -6969,16 +6969,9 @@ export function StandaloneChat({
};
});
} catch {
- if (!cancelled) {
- setQueuedPromptsBySession((prev) => {
- const existing = prev[sid] ?? [];
- if (existing.length === 0) return prev;
- return {
- ...prev,
- [sid]: [],
- };
- });
- }
+ // Transient queue refresh failures should not erase the last known
+ // visible queue. The Rust-side `pi-queue-changed` subscription is the
+ // source of truth and will reconcile once IPC recovers.
}
})();
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts
index f0cb5e3a1..82c9c5141 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts
@@ -174,18 +174,25 @@ describe("pi-event-router: background content accumulation (the parallel-chat re
expect((a3.messages![0] as any).content).toBe("Hello world");
});
- it("SKIPS content writes for the foreground session (panel owns it)", async () => {
- // Foreground writes belong to standalone-chat. If the router also
- // wrote, the same delta would land twice — once in panel state,
- // once in store messages — and on snapshot the panel's view would
- // overwrite the router's, producing flicker / duplicates.
+ it("materializes queued background user turns before the assistant reply", async () => {
seed("A");
- useChatStore.setState({ currentId: "A" }); // A is foreground
+ useChatStore.setState({ currentId: "B" });
await handlePiEvent(
- piEvt("A", { type: "message_start", message: { role: "assistant" } }),
+ piEvt("A", {
+ type: "message_start",
+ message: {
+ role: "user",
+ content:
+ "<conversation_history>\nuser: x\nassistant: y\n</conversation_history>\n\nqueued follow-up",
+ },
+ }),
);
- expect(useChatStore.getState().sessions.A.messages ?? []).toEqual([]);
- expect(useChatStore.getState().sessions.A.streamingMessageId).toBeFalsy();
+ const session = useChatStore.getState().sessions.A;
+ expect(session.messages).toHaveLength(2);
+ expect((session.messages![0] as any).role).toBe("user");
+ expect((session.messages![0] as any).content).toBe("queued follow-up");
+ expect((session.messages![1] as any).role).toBe("assistant");
+ expect(session.streamingMessageId).toBe((session.messages![1] as any).id);
});
it("keeps one assistant message across turn_end + assistant restart after switch-away", async () => {
@@ -252,6 +259,35 @@ describe("pi-event-router: background content accumulation (the parallel-chat re
]);
expect(assistant.contentBlocks[1].toolCall.result).toBe("hi");
});
+
+ it("keeps accumulating during the switch-back gap after currentId flips", async () => {
+ // Regression for the "come back immediately and the queued turn vanishes"
+ // repro. During the handoff window `loadConversation` has already flipped
+ // currentId to A but the new foreground handler is not attached yet, so
+ // the default router must still accept A's events.
+ seed("A");
+ useChatStore.setState({ currentId: "A" });
+
+ await handlePiEvent(
+ piEvt("A", {
+ type: "message_start",
+ message: { role: "user", content: "queued while switching back" },
+ }),
+ );
+ await handlePiEvent(
+ piEvt("A", {
+ type: "message_update",
+ assistantMessageEvent: { type: "text_delta", delta: "still here" },
+ }),
+ );
+
+ const session = useChatStore.getState().sessions.A;
+ expect(session.messages).toHaveLength(2);
+ expect((session.messages![0] as any).role).toBe("user");
+ expect((session.messages![0] as any).content).toBe("queued while switching back");
+ expect((session.messages![1] as any).role).toBe("assistant");
+ expect((session.messages![1] as any).content).toBe("still here");
+ });
});
describe("pi-event-router: agent_terminated", () => {
diff --git a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
index 30b7b78e6..5135e9e32 100644
--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
@@ -60,7 +60,10 @@ import {
saveConversationFile,
} from "@/lib/chat-storage";
import type { ChatConversation } from "@/lib/hooks/use-settings";
-import { isInjectedTitleSourcePrompt } from "@/lib/chat-utils";
+import {
+ extractConversationHistorySyncUserText,
+ isInjectedTitleSourcePrompt,
+} from "@/lib/chat-utils";
import { deriveFallbackConversationTitle } from "@/lib/utils/chat-title";
import { isInternalTitleSession } from "@/lib/utils/internal-session";
import {
@@ -431,26 +434,99 @@ interface MutableMessage {
[k: string]: unknown;
}
+function textFromPiMessageContent(content: unknown): string {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content
+ .filter((part): part is { type?: unknown; text?: unknown } =>
+ !!part && typeof part === "object",
+ )
+ .filter((part) => part.type === "text" && typeof part.text === "string")
+ .map((part) => part.text)
+ .join("");
+}
+
+function imageDataUrlsFromPiContent(content: unknown): string[] {
+ 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;
+}
+
function applyEventToSessionContent(sid: string, payload: PiInnerEvent) {
const store = useChatStore.getState();
const existing = store.sessions[sid];
if (!existing) return; // upsert will fire on the next call
- // CRITICAL: skip content writes for the session the panel is actively
- // rendering. The chat panel's own pi_event handler in standalone-chat
- // owns the message lifecycle for the current session (it creates the
- // assistant placeholder, appends deltas, handles agent_end, persists
- // to disk). If both this router AND the local handler write messages
- // for the same session, you get DOUBLE messages — one from each
- // writer — and the panel renders the same assistant reply twice.
- // The router's job is exclusively to keep BACKGROUND sessions in
- // sync; the panel handles foreground. On switch, loadConversation
- // snapshots the panel's state to the store before the router takes
- // over for what's now a background session.
- if (store.currentId === sid) return;
+ // The agent-event bus already enforces exclusive delivery: a session's
+ // foreground handler receives its events OR the default router does, never
+ // both at once. So we intentionally do not guard on `currentId === sid`
+ // here. That old belt-and-suspenders check created a switch-back gap where
+ // loadConversation flipped `currentId` before the new foreground handler was
+ // attached; any events in that window were dropped by both writers.
const t = payload.type;
+ // Queued follow-ups begin with `message_start(role=user)`. When the user has
+ // switched away, the foreground panel does not see that event, so the
+ // background router must materialize the user bubble and the assistant
+ // placeholder itself. Without this, completed background queues persist only
+ // assistant replies and the user turns appear to vanish from history.
+ if (t === "message_start" && payload.message?.role === "user") {
+ const rawText = textFromPiMessageContent(payload.message?.content);
+ const text = extractConversationHistorySyncUserText(rawText) ?? rawText;
+ const images = imageDataUrlsFromPiContent(payload.message?.content);
+ if (!text && images.length === 0) return;
+
+ const userId = `pi-user-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ const assistantId = `pi-assistant-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ const userMsg: MutableMessage = {
+ id: userId,
+ role: "user",
+ content: text,
+ ...(images.length ? { images } : {}),
+ timestamp: Date.now(),
+ };
+ const assistantShell: MutableMessage = {
+ id: assistantId,
+ role: "assistant",
+ content: "",
+ contentBlocks: [],
+ timestamp: Date.now(),
+ };
+
+ store.actions.appendMessage(sid, userMsg);
+ store.actions.appendMessage(sid, assistantShell);
+ store.actions.setStreaming(sid, {
+ streamingMessageId: assistantId,
+ streamingText: "",
+ contentBlocks: [],
+ isStreaming: true,
+ isLoading: true,
+ });
+ return;
+ }
+
// Assistant message starts. When a session moves to the background in the
// middle of a tool-using reply, Pi may emit another assistant
// `message_start` after an internal `turn_end`. Foreground chat keeps that