YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(chat): persist & resume backgrounded chats reliably
Louis Beaumont0060ae9e5b5b
diff --git a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.tsindex eb7fa3239..339e3557c 100644--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts@@ -297,16 +297,19 @@ export function useChatConversations(opts: UseChatConversationsOpts) {const store = useChatStore.getState();const outgoingSid = piSessionIdRef.current;- // (1) Snapshot OUTGOING session.+ // (1) Snapshot OUTGOING session — atomic so router writes that+ // race against this update can't land between the messages+ // write and the streaming-refs write (which would point the+ // router at a streamingMessageId not yet present in messages).if (outgoingSid && store.sessions[outgoingSid]) {- store.actions.setStreaming(outgoingSid, {+ store.actions.snapshotSession(outgoingSid, {+ messages: messages as any,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.@@ -316,13 +319,29 @@ export function useChatConversations(opts: UseChatConversationsOpts) {setIsLoading(false);setIsStreaming(false);- // Switch to this conversation's session.+ // Switch to this conversation's session. Pair the panel's ref+ // switch with `setCurrent` on the store so the router's+ // foreground/background skip logic flips at the same instant the+ // panel's filter does. Without this pairing, callers that reach+ // loadConversation from a path other than the sidebar (deep-link+ // from another window, settings-driven activeConversationId, etc.)+ // would temporarily have the panel and the router disagree on+ // which session is foreground — producing duplicated writes for+ // the new session and silently dropped writes for the old one.piSessionIdRef.current = conv.id;-- // (3) Prefer the store if it already has live state for this id.+ store.actions.setCurrent(conv.id);++ // (3) Prefer the store whenever it has messages for this id. Two+ // ways messages get there: (a) `markHydrated` was called on a+ // prior view (`hydratedAt` set), or (b) the router accumulated+ // them while the session was streaming in the background. Case+ // (b) is the up-to-the-millisecond truth — the disk file may+ // be one save behind the in-memory state, so falling through to+ // disk would silently drop tokens that arrived since the last+ // persisted agent_end.const existing = store.sessions[conv.id];let messagesForPanel: any[];- if (existing?.hydratedAt && existing.messages?.length) {+ if (existing?.messages && existing.messages.length > 0) {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@@ -333,6 +352,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {piContentBlocksRef.current = (existing.contentBlocks as any[]) ?? [];if (existing.isLoading) setIsLoading(true);if (existing.isStreaming) setIsStreaming(true);+ store.actions.markHydrated(conv.id);} else {// Cold session — load from disk and seed the store.const { loadConversationFile } = await import("@/lib/chat-storage");@@ -473,7 +493,13 @@ export function useChatConversations(opts: UseChatConversationsOpts) {// process. The old session stays alive (backend evicts LRU when > 4).// No kill/restart needed — true multi-session means each conversation// has its own process that persists across conversation switches.- const startNewConversation = async () => {+ // Optional `explicitId` — when the caller has a specific session id it+ // wants the panel to adopt (e.g. sidebar's "+ new chat" generates the+ // id locally and emits chat-load-conversation with it so the row + the+ // chat agree from message 0). Passing one avoids the+ // generate-then-overwrite dance which left store.currentId pointing+ // at the throwaway uuid.+ const startNewConversation = async (explicitId?: string) => {// 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@@ -483,14 +509,14 @@ export function useChatConversations(opts: UseChatConversationsOpts) {const store = useChatStore.getState();const outgoingSid = piSessionIdRef.current;if (outgoingSid && store.sessions[outgoingSid]) {- store.actions.setStreaming(outgoingSid, {+ store.actions.snapshotSession(outgoingSid, {+ messages: messages as any,streamingText: piStreamingTextRef.current,streamingMessageId: piMessageIdRef.current,contentBlocks: [...piContentBlocksRef.current],isStreaming,isLoading,});- store.actions.setMessages(outgoingSid, messages as any);}// Clear panel state@@ -506,9 +532,14 @@ export function useChatConversations(opts: UseChatConversationsOpts) {setShowHistory(false);setPastedImages([]);- // New session ID — Pi will be started fresh when the first message is sent- piSessionIdRef.current = crypto.randomUUID();+ // New session ID — Pi will be started fresh when the first message is sent.+ // Pair with setCurrent so the router immediately knows the new id is+ // foreground (and won't accumulate writes for it). See the matching+ // pairing in loadConversation for the same reasoning.+ const newSid = explicitId ?? crypto.randomUUID();+ piSessionIdRef.current = newSid;piSessionSyncedRef.current = true;+ store.actions.setCurrent(newSid);};// ---- filteredConversations ----diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex 935f9dbb9..1f22db65e 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -1640,11 +1640,14 @@ export function StandaloneChat({loadConversation(conv);} else {// Unknown id → start a new chat that adopts the requested id so- // sidebar + chat agree. startNewConversation generates its own- // uuid; we override piSessionIdRef immediately after to honor the- // caller's id.- await startNewConversation();- piSessionIdRef.current = convId;+ // sidebar + chat (and the chat-store's currentId) all agree from+ // message 0. Pass the id directly into startNewConversation+ // instead of overriding piSessionIdRef after the fact — the+ // override pattern left store.currentId stuck on the throwaway+ // uuid that startNewConversation had generated, which made the+ // router treat the new id as a background session and the+ // sidebar lose its highlight until the user typed.+ await startNewConversation(convId);// Mirror the new id back to the sidebar so its currentId matches.emit("chat-current-session", { id: convId });}diff --git a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts b/apps/screenpipe-app-tauri/lib/stores/chat-store.tsindex 8c8d9a15b..d0c786cc8 100644--- a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts+++ b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts@@ -167,6 +167,26 @@ interface ChatStoreActions {/** 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;+ /** Atomically replace ALL panel-local state for a session (messages ++ * streaming refs) in one update. Used by `loadConversation` /+ * `startNewConversation` to publish the foreground panel's state to+ * the store at the moment of session switch. Doing it in one set call+ * prevents interleaving with router writes that target the same id —+ * separate `setMessages` then `setStreaming` calls would let a router+ * delta land between them and produce a half-snapshot half-router+ * state where the streamingMessageId points to a message that no+ * longer exists in the messages array. */+ snapshotSession: (+ id: string,+ snapshot: {+ messages: StoredMessage[];+ streamingText: string;+ streamingMessageId: string | null;+ contentBlocks: StoredContentBlock[];+ isStreaming: boolean;+ isLoading: boolean;+ }+ ) => void;}export type ChatStore = ChatStoreState & { actions: ChatStoreActions };@@ -397,6 +417,29 @@ export const useChatStore = create<ChatStore>((set) => ({},};}),++ snapshotSession: (id, snapshot) =>+ set((s) => {+ const existing = s.sessions[id];+ if (!existing) return {};+ return {+ sessions: {+ ...s.sessions,+ [id]: {+ ...existing,+ messages: snapshot.messages,+ messageCount: snapshot.messages.length,+ streamingText: snapshot.streamingText,+ streamingMessageId: snapshot.streamingMessageId,+ contentBlocks: snapshot.contentBlocks,+ isStreaming: snapshot.isStreaming,+ isLoading: snapshot.isLoading,+ hydratedAt: existing.hydratedAt ?? Date.now(),+ // No updatedAt bump — snapshot is plumbing, not user activity.+ },+ },+ };+ }),},}));diff --git a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.tsindex 05f3e3f7b..7f9274589 100644--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts@@ -26,7 +26,12 @@*/import { listen, type UnlistenFn } from "@tauri-apps/api/event";-import { listConversations } from "@/lib/chat-storage";+import {+ listConversations,+ loadConversationFile,+ saveConversationFile,+} from "@/lib/chat-storage";+import type { ChatConversation } from "@/lib/hooks/use-settings";import {useChatStore,type SessionStatus,@@ -257,7 +262,16 @@ function handleTerminated(payload: PiTerminatedPayload) {: `pi process exited (code ${payload.exitCode}${payload.reason ? `: ${payload.reason}` : ""})`,updatedAt: Date.now(),});+ store.actions.endTurn(payload.session);previewLastEmittedAt.delete(payload.session);++ // Persist the partial transcript for backgrounded sessions whose Pi+ // crashed mid-stream — without this the user loses everything that+ // was generated after the moment they navigated away. Foreground+ // session has its own pi_terminated handler in standalone-chat.+ if (store.currentId !== payload.session) {+ void persistBackgroundSession(payload.session);+ }}/** Hydrate the store from on-disk chat history once at boot. The router@@ -495,12 +509,128 @@ function applyEventToSessionContent(sid: string, payload: PiEventPayload) {}// 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.+ // in-flight markers. We're in the BACKGROUND-only branch (the early+ // `currentId === sid` return above gates this), so the panel won't+ // run its own save useEffect for this session. Persist directly so+ // a chat that completes while the user is looking elsewhere still+ // ends up on disk and survives a restart.if (t === "agent_end" || t === "turn_end") {store.actions.endTurn(sid);+ void persistBackgroundSession(sid);return;}}++// Per-session save serialization. agent_end can race with subsequent+// background activity (rare but possible — chained turns from a tool+// follow-up). A second save kicked off before the first finishes would+// race on the same file; we chain them through a per-id promise queue.+const saveQueue = new Map<string, Promise<void>>();++/**+ * Persist a backgrounded session's accumulated state to disk. Called from+ * the router when agent_end fires for a session that isn't currently+ * foregrounded — the panel's normal `useEffect[isLoading, messages]` save+ * only runs for the foregrounded chat, so without this function a chat+ * that completes while you're looking at a different tab silently loses+ * everything generated after the moment you switched away.+ *+ * Mirrors the shape and edge-case handling of `saveConversation` in+ * `use-chat-conversations.ts` so foreground/background saves produce+ * byte-identical files. Diverging would mean the panel sees different+ * data depending on where the save came from — confusing and a vector+ * for hard-to-reproduce bugs.+ */+async function persistBackgroundSession(sid: string): Promise<void> {+ const prev = saveQueue.get(sid) ?? Promise.resolve();+ const next = prev+ .catch(() => undefined)+ .then(async () => {+ const session = useChatStore.getState().sessions[sid];+ if (!session) return;+ const messages = (session.messages as MutableMessage[] | undefined) ?? [];+ if (messages.length === 0) return;++ // Skip pure pipe-watch sessions (transient, rendered live from+ // pipe_event — never the user's "real" chat history).+ const allPipe = messages.every((m: any) => m?.id?.startsWith("pipe-"));+ if (allPipe) return;++ // Respect the user's "history disabled" toggle.+ try {+ const { getStore } = await import("@/lib/hooks/use-settings");+ const store = await getStore();+ const settings = await store.get<any>("settings");+ if (settings?.chatHistory?.historyEnabled === false) return;+ } catch {+ // settings store not ready — fall through and save anyway+ }++ const existing = await loadConversationFile(sid);+ const firstUserMsg = messages.find((m: any) => m.role === "user") as any;+ const derivedTitle: string =+ firstUserMsg?.content?.slice(0, 50) || "New Chat";+ // Prefer a previously-persisted title (user may have renamed it),+ // but only if that title isn't itself a stale derivation.+ const title = existing?.title || derivedTitle;++ const conv: ChatConversation = {+ id: sid,+ title,+ messages: messages.slice(-100).map((m: any) => {+ let content: string = m.content || "";+ if (!content && m.contentBlocks?.length) {+ content =+ m.contentBlocks+ .filter((b: any) => b.type === "text")+ .map((b: any) => b.text)+ .join("\n") || "(tool result)";+ }+ const blocks = m.contentBlocks?.map((b: any) => {+ if (b.type === "tool") {+ const { isRunning: _isRunning, ...rest } = b.toolCall ?? {};+ return {+ type: "tool",+ toolCall: {+ ...rest,+ isRunning: false,+ result: rest.result?.slice?.(0, 4000),+ },+ };+ }+ if (b.type === "thinking") {+ return { ...b, isThinking: false };+ }+ return b;+ });+ return {+ id: m.id,+ role: m.role,+ content,+ timestamp: m.timestamp,+ ...(blocks?.length ? { contentBlocks: blocks } : {}),+ ...(m.images?.length ? { images: m.images } : {}),+ ...(m.model ? { model: m.model } : {}),+ ...(m.provider ? { provider: m.provider } : {}),+ };+ }),+ createdAt: existing?.createdAt ?? Date.now(),+ updatedAt: Date.now(),+ pinned: existing?.pinned ?? session.pinned,+ hidden: existing?.hidden ?? false,+ };++ try {+ await saveConversationFile(conv);+ } catch (e) {+ console.warn("[router] background save failed for", sid, e);+ }+ })+ .finally(() => {+ // Drop the entry once we're the tail — keeps the map from growing+ // unbounded over a long session lifetime.+ if (saveQueue.get(sid) === next) saveQueue.delete(sid);+ });+ saveQueue.set(sid, next);+ return next;+}diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.tomlindex b81ffd81c..74d7ec208 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.63"+version = "2.4.64"description = "24/7 memory for your desktop. 100% local."authors = ["you"]license = ""