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

feat(chat): phase 3 — true parallel chats, background streams visible on switch

Louis Beaumontc9d64ce23128
diff --git a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
index c61f169c0..eb7fa3239 100644
--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
@@ -272,45 +272,104 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
};
// ---- loadConversation ----
- // Switching conversations does NOT abort the previous session's Pi
- // process — parallel chats are the entire point of the multi-tab
- // sidebar, and aborting on switch would kill any chat the user
- // navigated away from. The previous Pi process keeps running in the
- // pool (capped at MAX_PI_SESSIONS=20) and continues writing to its
- // own on-disk session log; the user can come back later and reload
- // from disk to see what was produced while they were away.
+ // Phase 3 — true parallel chats. Switching does NOT abort the previous
+ // session's Pi (each chat owns its own subprocess in the pool, capped
+ // at MAX_PI_SESSIONS=20). Three steps on switch:
//
- // Panel-level streaming state IS reset though — the previous session's
- // streaming text/refs/loading flags belong to the panel, not the Pi
- // process, and rendering them on a different conversation would show
- // a misleading "loading…" indicator on a paused chat (the user-
- // reported "loading thing at the bottom despite the chat being
- // paused" symptom from 2026-04-25).
+ // 1. Snapshot the local state for the OUTGOING session into the
+ // chat-store, keyed by piSessionIdRef.current. This captures any
+ // in-flight tokens / streaming cursor / contentBlocks that the
+ // user accumulated locally — without this snapshot, the moment
+ // they switch away their session loses everything that wasn't
+ // yet on disk.
+ //
+ // 2. Reset the panel's streaming flags so the loading indicator
+ // doesn't bleed across to the new conversation (the
+ // "loading…-on-a-paused-chat" symptom Louis hit on 2026-04-25).
+ //
+ // 3. Hydrate from the store if the INCOMING session has live state
+ // already (because it was viewed earlier this session OR because
+ // the pi-event router has been accumulating its background
+ // tokens). Fall back to disk only when the store is cold for
+ // this id.
const loadConversation = async (conv: ChatConversation) => {
+ const { useChatStore } = await import("@/lib/stores/chat-store");
+ const store = useChatStore.getState();
+ const outgoingSid = piSessionIdRef.current;
+
+ // (1) Snapshot OUTGOING session.
+ if (outgoingSid && store.sessions[outgoingSid]) {
+ store.actions.setStreaming(outgoingSid, {
+ streamingText: piStreamingTextRef.current,
+ streamingMessageId: piMessageIdRef.current,
+ contentBlocks: [...piContentBlocksRef.current],
+ isStreaming,
+ isLoading,
+ });
+ store.actions.setMessages(outgoingSid, messages as any);
+ }
+
+ // (2) Reset panel flags — these are panel-local, not session-local.
piStreamingTextRef.current = "";
piMessageIdRef.current = null;
piContentBlocksRef.current = [];
setIsLoading(false);
setIsStreaming(false);
- // Switch to this conversation's session — each conversation is its own Pi process
+ // Switch to this conversation's session.
piSessionIdRef.current = conv.id;
- // Load full conversation from file (conv from list may be metadata-only)
- const { loadConversationFile } = await import("@/lib/chat-storage");
- const full = await loadConversationFile(conv.id) || conv;
-
- setMessages(full.messages.map(m => ({
- id: m.id,
- role: m.role,
- content: m.content,
- timestamp: m.timestamp,
- ...(m.contentBlocks?.length ? { contentBlocks: m.contentBlocks } : {}),
- ...((m as any).images?.length ? { images: (m as any).images } : (m as any).image ? { images: [(m as any).image] } : {}),
- ...((m as any).model ? { model: (m as any).model } : {}),
- ...((m as any).provider ? { provider: (m as any).provider } : {}),
- })));
- setConversationId(full.id);
+ // (3) Prefer the store if it already has live state for this id.
+ const existing = store.sessions[conv.id];
+ let messagesForPanel: any[];
+ if (existing?.hydratedAt && existing.messages?.length) {
+ messagesForPanel = existing.messages as any[];
+ // Restore in-flight streaming markers so the panel resumes
+ // exactly where the user left it. The router has been keeping
+ // these up-to-date for any tokens that arrived while the user
+ // was elsewhere.
+ piStreamingTextRef.current = existing.streamingText ?? "";
+ piMessageIdRef.current = existing.streamingMessageId ?? null;
+ piContentBlocksRef.current = (existing.contentBlocks as any[]) ?? [];
+ if (existing.isLoading) setIsLoading(true);
+ if (existing.isStreaming) setIsStreaming(true);
+ } else {
+ // Cold session — load from disk and seed the store.
+ const { loadConversationFile } = await import("@/lib/chat-storage");
+ const full = (await loadConversationFile(conv.id)) || conv;
+ messagesForPanel = full.messages.map((m) => ({
+ id: m.id,
+ role: m.role,
+ content: m.content,
+ timestamp: m.timestamp,
+ ...(m.contentBlocks?.length ? { contentBlocks: m.contentBlocks } : {}),
+ ...((m as any).images?.length
+ ? { images: (m as any).images }
+ : (m as any).image
+ ? { images: [(m as any).image] }
+ : {}),
+ ...((m as any).model ? { model: (m as any).model } : {}),
+ ...((m as any).provider ? { provider: (m as any).provider } : {}),
+ }));
+ // Make sure a record exists, then seed messages and mark hydrated.
+ if (!store.sessions[conv.id]) {
+ store.actions.upsert({
+ id: conv.id,
+ title: full.title || "untitled",
+ preview: "",
+ status: "idle",
+ messageCount: messagesForPanel.length,
+ updatedAt: Date.now(),
+ pinned: full.pinned === true,
+ unread: false,
+ });
+ }
+ store.actions.setMessages(conv.id, messagesForPanel as any);
+ store.actions.markHydrated(conv.id);
+ }
+
+ setMessages(messagesForPanel);
+ setConversationId(conv.id);
setShowHistory(false);
piSessionSyncedRef.current = false;
@@ -324,7 +383,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
...freshSettings,
chatHistory: {
...freshSettings.chatHistory,
- activeConversationId: full.id,
+ activeConversationId: conv.id,
}
});
await store.save();
@@ -415,7 +474,26 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
// No kill/restart needed — true multi-session means each conversation
// has its own process that persists across conversation switches.
const startNewConversation = async () => {
- // Clear frontend state
+ // Snapshot OUTGOING session into the store so the previous chat's
+ // in-flight state survives the switch to "new chat". Without this,
+ // hitting "+ new chat" in the middle of a stream would silently
+ // discard everything the user couldn't yet see, even though the
+ // Pi process keeps running. Mirrors the snapshot in loadConversation.
+ const { useChatStore } = await import("@/lib/stores/chat-store");
+ const store = useChatStore.getState();
+ const outgoingSid = piSessionIdRef.current;
+ if (outgoingSid && store.sessions[outgoingSid]) {
+ store.actions.setStreaming(outgoingSid, {
+ streamingText: piStreamingTextRef.current,
+ streamingMessageId: piMessageIdRef.current,
+ contentBlocks: [...piContentBlocksRef.current],
+ isStreaming,
+ isLoading,
+ });
+ store.actions.setMessages(outgoingSid, messages as any);
+ }
+
+ // Clear panel state
piStreamingTextRef.current = "";
piMessageIdRef.current = null;
piContentBlocksRef.current = [];
diff --git a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
index 36e75fe38..659d184a5 100644
--- a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
@@ -29,6 +29,17 @@ export type SessionStatus =
| "tool" // executing a tool call
| "error"; // last turn ended in an error
+/**
+ * Streaming state captured per session — opaque blobs from the chat
+ * panel's perspective. Stored as `unknown[]` / `unknown` so the store
+ * stays free of UI-component types; the chat panel narrows them at the
+ * read site (see `useSessionView` in standalone-chat). This isolation is
+ * deliberate — the store is shared by the sidebar (which doesn't care
+ * about message internals) and the panel (which does).
+ */
+export type StoredMessage = unknown;
+export type StoredContentBlock = unknown;
+
export interface SessionRecord {
/** Pi `session_id` — also the uuid used by `commands.piStart`. */
id: string;
@@ -52,6 +63,35 @@ export interface SessionRecord {
* instant the user makes that session current. Sidebar renders unread
* rows in bold, like an email inbox. */
unread: boolean;
+
+ // ── Live session content (Phase 3) ─────────────────────────────────
+ // The chat panel reads these instead of holding its own per-render
+ // state, so background sessions accumulate messages as their Pi
+ // streams. Switching to a previously-backgrounded session shows the
+ // up-to-the-millisecond live state — no disk reload required.
+ // Hydrated on first view (from disk if not already in store) and
+ // mutated by the chat panel + the pi-event-router both keying by
+ // session id.
+ /** Full chronological message list for the session. */
+ messages?: StoredMessage[];
+ /** Content blocks of the in-flight assistant message (text / tool /
+ * thinking) — flattened into the message at completion. */
+ contentBlocks?: StoredContentBlock[];
+ /** Streaming text accumulated so far for the in-flight message. */
+ streamingText?: string;
+ /** Id of the currently-streaming assistant message in `messages`. */
+ streamingMessageId?: string | null;
+ /** True while a Pi response is in-flight for this session. Drives the
+ * loading indicator at the bottom of the chat panel. */
+ isStreaming?: boolean;
+ /** True between user-send and the first assistant token (no UI
+ * content yet, but a request is in-flight). */
+ isLoading?: boolean;
+ /** True once we've populated messages/etc from disk for this session.
+ * Prevents re-loading on every switch and lets the chat panel skip
+ * the disk round-trip when the user comes back to a session that's
+ * been live in the store. */
+ hydratedAt?: number;
}
interface ChatStoreState {
@@ -81,6 +121,52 @@ interface ChatStoreActions {
* one. No-op if the session id is the current one (you can't be
* unread for the chat you're looking at). */
markUnread: (id: string) => void;
+
+ // ── Per-session live content ops ─────────────────────────────────────
+ // These mutate the in-flight `messages` / `contentBlocks` /
+ // `streamingText` / `streamingMessageId` fields of a SessionRecord.
+ // The chat panel calls them on every keystroke / pi_event / save; the
+ // pi-event router calls them for background sessions so their state
+ // accumulates while the user is looking at a different chat.
+
+ /** Replace the full message list for a session. Used by hydration from
+ * disk and by user-side mutations (delete message, branch, etc.). */
+ setMessages: (id: string, messages: StoredMessage[]) => void;
+ /** Append a single message (user or assistant). Bumps updatedAt and
+ * messageCount; preview is updated to the new message's prefix. */
+ appendMessage: (id: string, message: StoredMessage, preview?: string) => void;
+ /** Patch a single message in-place by message-id. No-op if either the
+ * session or the message is unknown. Used to grow the in-flight
+ * assistant message as deltas arrive. */
+ patchMessage: (
+ id: string,
+ messageId: string,
+ patcher: (m: StoredMessage) => StoredMessage
+ ) => void;
+ /** Replace the streaming-state triplet (text / message id / blocks).
+ * Pass undefined for any field you don't want to overwrite. */
+ setStreaming: (
+ id: string,
+ state: Partial<{
+ streamingText: string;
+ streamingMessageId: string | null;
+ contentBlocks: StoredContentBlock[];
+ isLoading: boolean;
+ isStreaming: boolean;
+ }>
+ ) => void;
+ /** Atomic "begin a new turn" — clears streamingText / contentBlocks /
+ * streamingMessageId and flips isLoading + isStreaming to true. The
+ * user-message append and assistant-shell setup happen separately.
+ * Used from sendPiMessage at the start of a turn. */
+ beginTurn: (id: string) => void;
+ /** Atomic "turn complete" — flips isLoading + isStreaming to false
+ * and clears streamingMessageId. Caller is responsible for any final
+ * message patch (e.g. setting `content` on the assistant message). */
+ endTurn: (id: string) => void;
+ /** Mark this session as fully hydrated from disk. Subsequent switches
+ * to it can skip the disk round-trip and read from the store. */
+ markHydrated: (id: string) => void;
}
export type ChatStore = ChatStoreState & { actions: ChatStoreActions };
@@ -176,6 +262,131 @@ export const useChatStore = create<ChatStore>((set) => ({
sessions: { ...s.sessions, [id]: { ...existing, unread: true } },
};
}),
+
+ setMessages: (id, messages) =>
+ set((s) => {
+ const existing = s.sessions[id];
+ if (!existing) return {};
+ return {
+ sessions: {
+ ...s.sessions,
+ [id]: {
+ ...existing,
+ messages,
+ messageCount: messages.length,
+ updatedAt: Date.now(),
+ },
+ },
+ };
+ }),
+
+ appendMessage: (id, message, preview) =>
+ set((s) => {
+ const existing = s.sessions[id];
+ if (!existing) return {};
+ const messages = [...(existing.messages ?? []), message];
+ return {
+ sessions: {
+ ...s.sessions,
+ [id]: {
+ ...existing,
+ messages,
+ messageCount: messages.length,
+ preview: preview ?? existing.preview,
+ updatedAt: Date.now(),
+ },
+ },
+ };
+ }),
+
+ patchMessage: (id, messageId, patcher) =>
+ set((s) => {
+ const existing = s.sessions[id];
+ if (!existing?.messages?.length) return {};
+ let touched = false;
+ const messages = existing.messages.map((m: any) => {
+ if (m?.id === messageId) {
+ touched = true;
+ return patcher(m);
+ }
+ return m;
+ });
+ if (!touched) return {};
+ return {
+ sessions: {
+ ...s.sessions,
+ [id]: { ...existing, messages, updatedAt: Date.now() },
+ },
+ };
+ }),
+
+ setStreaming: (id, state) =>
+ set((s) => {
+ const existing = s.sessions[id];
+ if (!existing) return {};
+ return {
+ sessions: {
+ ...s.sessions,
+ [id]: { ...existing, ...state, updatedAt: Date.now() },
+ },
+ };
+ }),
+
+ beginTurn: (id) =>
+ set((s) => {
+ const existing = s.sessions[id];
+ if (!existing) return {};
+ return {
+ sessions: {
+ ...s.sessions,
+ [id]: {
+ ...existing,
+ streamingText: "",
+ contentBlocks: [],
+ streamingMessageId: null,
+ isLoading: true,
+ isStreaming: true,
+ status: "streaming",
+ lastError: undefined,
+ updatedAt: Date.now(),
+ },
+ },
+ };
+ }),
+
+ endTurn: (id) =>
+ set((s) => {
+ const existing = s.sessions[id];
+ if (!existing) return {};
+ return {
+ sessions: {
+ ...s.sessions,
+ [id]: {
+ ...existing,
+ isLoading: false,
+ isStreaming: false,
+ streamingMessageId: null,
+ streamingText: "",
+ contentBlocks: [],
+ status: existing.status === "error" ? "error" : "idle",
+ updatedAt: Date.now(),
+ },
+ },
+ };
+ }),
+
+ markHydrated: (id) =>
+ set((s) => {
+ const existing = s.sessions[id];
+ if (!existing) return {};
+ if (existing.hydratedAt) return {};
+ return {
+ sessions: {
+ ...s.sessions,
+ [id]: { ...existing, hydratedAt: Date.now() },
+ },
+ };
+ }),
},
}));
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 713337483..55d7c419c 100644
--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
@@ -157,6 +157,15 @@ async function handlePiEvent(payload: PiEventPayload) {
const snippet = previewSnippet(payload);
const err = errorMessage(payload);
+ // Phase 3: accumulate full message-content state in the store for
+ // EVERY session (current + background). This is what makes it possible
+ // for the chat panel to switch back to a previously-backgrounded
+ // session and see live tokens that arrived while it was away — the
+ // router has been writing them to the store the whole time. The chat
+ // panel either reads the store directly or syncs its local state from
+ // the store on session switch.
+ applyEventToSessionContent(sid, payload);
+
// Lazy-create on first event from a previously-unknown session id.
// Handles the case where Pi was started outside the chat-storage flow
// (e.g. resumed from disk before we hydrated).
@@ -326,3 +335,159 @@ function unmountPiEventRouter(): void {
mounted = false;
mountPromise = null;
}
+
+// ---------------------------------------------------------------------------
+// Per-session content accumulation
+//
+// The router doesn't try to fully reconstruct the chat panel's state
+// machine — that lives in `standalone-chat.tsx` for the active session.
+// What it DOES do here is keep the store's `messages` / `streamingText` /
+// `contentBlocks` / `streamingMessageId` fields up-to-date for every
+// session whose Pi process emits events. When the user switches to a
+// previously-backgrounded session, the chat panel can rehydrate its
+// local state from the store and see all the tokens that arrived while
+// it was looking at a different chat.
+//
+// We only handle the small set of event types that materially change
+// message content: text_delta (and its 0.70 wrapper message_update),
+// thinking_delta, tool_execution_start/end, message_start/end for
+// assistant messages, and agent_end for completion. Other events are
+// status-only and already handled by the main `handlePiEvent` block.
+// ---------------------------------------------------------------------------
+
+interface MutableMessage {
+ id: string;
+ role: "user" | "assistant";
+ content: string;
+ contentBlocks?: any[];
+ timestamp: number;
+ [k: string]: unknown;
+}
+
+function applyEventToSessionContent(sid: string, payload: PiEventPayload) {
+ const store = useChatStore.getState();
+ const existing = store.sessions[sid];
+ if (!existing) return; // upsert will fire on the next call
+
+ const t = payload.type;
+
+ // Assistant message starts — create a new in-flight message shell
+ // and remember its id as the streaming target.
+ if (t === "message_start" && payload.message?.role === "assistant") {
+ const newId = `pi-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ const newMsg: MutableMessage = {
+ id: newId,
+ role: "assistant",
+ content: "",
+ contentBlocks: [],
+ timestamp: Date.now(),
+ };
+ store.actions.appendMessage(sid, newMsg);
+ store.actions.setStreaming(sid, {
+ streamingMessageId: newId,
+ streamingText: "",
+ contentBlocks: [],
+ isStreaming: true,
+ isLoading: true,
+ });
+ return;
+ }
+
+ // Per-token text delta — append to streamingText and to the in-flight
+ // message's content + last text content-block.
+ const inner = payload.assistantMessageEvent;
+ const isTextDelta =
+ (t === "text_delta" || (t === "message_update" && inner?.type === "text_delta")) &&
+ typeof (payload.delta ?? inner?.delta) === "string";
+ if (isTextDelta) {
+ const delta = (payload.delta ?? inner?.delta) as string;
+ const cur = store.sessions[sid];
+ if (!cur?.streamingMessageId) return;
+ const msgId = cur.streamingMessageId;
+ const newText = (cur.streamingText ?? "") + delta;
+ const blocks = [...((cur.contentBlocks as any[]) ?? [])];
+ const last = blocks[blocks.length - 1];
+ if (last && last.type === "text") {
+ last.text = (last.text ?? "") + delta;
+ } else {
+ blocks.push({ type: "text", text: delta });
+ }
+ store.actions.setStreaming(sid, {
+ streamingText: newText,
+ contentBlocks: blocks,
+ });
+ store.actions.patchMessage(sid, msgId, (m: any) => ({
+ ...m,
+ content: newText,
+ contentBlocks: blocks,
+ }));
+ return;
+ }
+
+ // Tool execution lifecycle — append a tool block while running, mutate
+ // it in place when the result lands. Matches standalone-chat's local
+ // logic so the rendered shape is the same whether the panel reads from
+ // store (via rehydrate) or from local state.
+ if (t === "tool_execution_start") {
+ const cur = store.sessions[sid];
+ if (!cur?.streamingMessageId) return;
+ const msgId = cur.streamingMessageId;
+ const tool = {
+ id: (payload as any).toolCallId || `${Date.now()}`,
+ toolName: (payload as any).toolName || "unknown",
+ args: (payload as any).args || {},
+ isRunning: true,
+ };
+ const blocks = [...((cur.contentBlocks as any[]) ?? []), { type: "tool", toolCall: tool }];
+ store.actions.setStreaming(sid, { contentBlocks: blocks });
+ store.actions.patchMessage(sid, msgId, (m: any) => ({
+ ...m,
+ contentBlocks: blocks,
+ }));
+ return;
+ }
+
+ if (t === "tool_execution_end") {
+ const cur = store.sessions[sid];
+ if (!cur?.streamingMessageId) return;
+ const msgId = cur.streamingMessageId;
+ const toolCallId = (payload as any).toolCallId;
+ const resultText: string =
+ (payload as any).result?.content
+ ?.map((c: any) => c.text || "")
+ .join("\n") || "";
+ const truncated =
+ resultText.length > 2000
+ ? `${resultText.slice(0, 2000)}\n... (truncated)`
+ : resultText;
+ const blocks = ((cur.contentBlocks as any[]) ?? []).map((b: any) =>
+ b.type === "tool" && b.toolCall?.id === toolCallId
+ ? {
+ ...b,
+ toolCall: {
+ ...b.toolCall,
+ isRunning: false,
+ result: truncated,
+ isError: (payload as any).isError,
+ },
+ }
+ : b
+ );
+ store.actions.setStreaming(sid, { contentBlocks: blocks });
+ store.actions.patchMessage(sid, msgId, (m: any) => ({
+ ...m,
+ contentBlocks: blocks,
+ }));
+ return;
+ }
+
+ // End of turn — flush streaming state to "settled" message + clear
+ // in-flight markers. Disk save happens in standalone-chat for the
+ // current session; for backgrounded sessions the store carries the
+ // settled message until the user comes back and the panel persists
+ // it via its existing save flow.
+ if (t === "agent_end" || t === "turn_end") {
+ store.actions.endTurn(sid);
+ return;
+ }
+}
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index e6d81ac2a..c6f45ad95 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.58"
+version = "2.4.59"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""