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(chat-storage): stop silent history loss

Louis Beaumont71dcbd1cabad
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 6da002d16..fd27613b1 100644
--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
@@ -144,7 +144,12 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
const conversation: ChatConversation = {
id: convId,
title,
- messages: msgs.slice(-100).map(m => {
+ // Persist the full transcript. The previous slice(-100) was silently
+ // dropping the oldest messages on every save, so any chat that grew
+ // past 100 messages walked forward and lost its early history. If
+ // file size becomes a problem for power users we cap at the render
+ // layer, never on disk.
+ messages: msgs.map(m => {
// For tool-only responses, content may be empty but contentBlocks has the data.
let content = m.content;
if (!content && m.contentBlocks?.length) {
diff --git a/apps/screenpipe-app-tauri/lib/chat-storage.ts b/apps/screenpipe-app-tauri/lib/chat-storage.ts
index 50e67f248..6e252c04b 100644
--- a/apps/screenpipe-app-tauri/lib/chat-storage.ts
+++ b/apps/screenpipe-app-tauri/lib/chat-storage.ts
@@ -9,6 +9,7 @@ import {
readDir,
mkdir,
remove,
+ rename,
exists,
} from "@tauri-apps/plugin-fs";
import type {
@@ -46,7 +47,25 @@ export async function saveConversationFile(
): Promise<void> {
const dir = await ensureChatsDir();
const filePath = `${dir}/${conversationFilename(conv.id)}`;
- await writeTextFile(filePath, JSON.stringify(conv, null, 2));
+ // Atomic write: stage to a sibling .tmp, then rename. A crash or quit
+ // mid-write leaves either the previous file intact OR an orphan .tmp
+ // (cleaned up by the next save), never a half-written .json that
+ // loadConversationFile would silently treat as "missing" via its
+ // try/catch → return null path. listConversations would then drop the
+ // row from the sidebar — the user-visible "chat history disappeared"
+ // bug. rename() is atomic on POSIX and same-volume NTFS.
+ const tmpPath = `${filePath}.tmp`;
+ const body = JSON.stringify(conv, null, 2);
+ await writeTextFile(tmpPath, body);
+ try {
+ await rename(tmpPath, filePath);
+ } catch (e) {
+ // Best-effort cleanup so a stale .tmp doesn't accumulate on the rare
+ // path where rename fails (cross-device, permission). Re-throw so
+ // callers don't think the save succeeded.
+ try { await remove(tmpPath); } catch { /* ignore */ }
+ throw e;
+ }
}
export async function loadConversationFile(
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 ed396df1e..e9d40c3ec 100644
--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
@@ -349,6 +349,38 @@ export async function mountPiEventRouter(): Promise<() => void> {
const offTerminated = onTerminated((p) => handleTerminated(p));
const offEvicted = onEvicted((p) => handleSessionEvicted(p));
unregistrations.push(offDefault, offTerminated, offEvicted);
+
+ // Flush pending saves on app quit. Without this, a Cmd+Q during an
+ // active stream — or any time agent_end hasn't fired yet — leaves
+ // the partial transcript only in the in-memory store; the next
+ // launch reads stale disk and the latest exchanges silently
+ // disappear. We prevent the default close, await the flush, then
+ // destroy the window. Foreground sessions whose tokens live only
+ // in the panel's local React state aren't fully covered here —
+ // those rely on the panel's own snapshot-on-switch — but anything
+ // that's reached the store does get persisted.
+ try {
+ const { getCurrentWindow } = await import("@tauri-apps/api/window");
+ const win = getCurrentWindow();
+ const offClose = await win.onCloseRequested(async (event) => {
+ event.preventDefault();
+ try {
+ await flushPendingSaves();
+ } catch (e) {
+ console.warn("[router] flush on close failed:", e);
+ }
+ try {
+ await win.destroy();
+ } catch {
+ /* window already gone */
+ }
+ });
+ unregistrations.push(offClose);
+ } catch (e) {
+ // Non-Tauri context (tests, ssr) — skip silently.
+ console.debug("[router] close-flush hook not available:", e);
+ }
+
mounted = true;
return unmountPiEventRouter;
})();
@@ -565,6 +597,22 @@ function applyEventToSessionContent(sid: string, payload: PiInnerEvent) {
// race on the same file; we chain them through a per-id promise queue.
const saveQueue = new Map<string, Promise<void>>();
+/** Persist every in-store session that has unsaved messages. Awaits the
+ * saveQueue tail for each id so already-running saves finish before
+ * the window closes. Used by the close-on-quit hook in
+ * `mountPiEventRouter`. */
+async function flushPendingSaves(): Promise<void> {
+ const sessions = useChatStore.getState().sessions;
+ const ids = Object.keys(sessions).filter((id) => {
+ const s = sessions[id];
+ return !!s.messages && s.messages.length > 0;
+ });
+ await Promise.all(ids.map((id) => persistBackgroundSession(id)));
+ // Await the entire saveQueue tail so any in-flight save (queued
+ // before flush) also completes. persistBackgroundSession returns the
+ // promise it just appended, so the previous await covers the tail.
+}
+
/**
* Persist a backgrounded session's accumulated state to disk. Called from
* the router when agent_end fires for a session that isn't currently
@@ -620,7 +668,10 @@ async function persistBackgroundSession(sid: string): Promise<void> {
id: sid,
title,
...(lastUserMessageAt ? { lastUserMessageAt } : {}),
- messages: messages.slice(-100).map((m: any) => {
+ // Full transcript — see comment in use-chat-conversations.ts
+ // saveConversation. The slice(-100) here was silently truncating
+ // long backgrounded chats on every agent_end save.
+ messages: messages.map((m: any) => {
let content: string = m.content || "";
if (!content && m.contentBlocks?.length) {
content =