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): stale closure wiped switched-away chats; freeze sidebar order

Louis Beaumont008553efd3c8
diff --git a/apps/screenpipe-app-tauri/app/home/page.tsx b/apps/screenpipe-app-tauri/app/home/page.tsx
index 9a7ce9dd7..698805d2a 100644
--- a/apps/screenpipe-app-tauri/app/home/page.tsx
+++ b/apps/screenpipe-app-tauri/app/home/page.tsx
@@ -528,6 +528,7 @@ function HomeContent() {
preview: "",
status: "idle",
messageCount: 0,
+ createdAt: Date.now(),
updatedAt: Date.now(),
pinned: false,
unread: false,
diff --git a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
index 6e724c1c2..904c09448 100644
--- a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
+++ b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
@@ -104,6 +104,7 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
preview: "",
status: "idle",
messageCount: 0,
+ createdAt: Date.now(),
updatedAt: Date.now(),
pinned: false,
unread: false,
@@ -135,6 +136,7 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
preview: "",
status: "idle",
messageCount: 0,
+ createdAt: Date.now(),
updatedAt: Date.now(),
pinned: false,
unread: false,
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 339e3557c..f5f073368 100644
--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
@@ -379,7 +379,8 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
preview: "",
status: "idle",
messageCount: messagesForPanel.length,
- updatedAt: Date.now(),
+ createdAt: full.createdAt ?? Date.now(),
+ updatedAt: full.updatedAt ?? Date.now(),
pinned: full.pinned === true,
unread: false,
});
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 9cac809ae..d0898a11e 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -1631,6 +1631,20 @@ export function StandaloneChat({
// not, treat it as "start a new chat using THIS id" — the caller (e.g.
// the sidebar's + new chat button) generated the id and wants the chat
// panel to adopt it so both agree on the session id from message 1.
+ // CRITICAL: the listener registers ONCE (deps: []) but the functions
+ // it calls (loadConversation, startNewConversation) close over `messages`
+ // and other state from useChatConversations. If we called the functions
+ // directly here, the listener would forever invoke the FIRST render's
+ // versions — which captured `messages = []` at mount time. Every
+ // snapshot-on-switch would then write empty messages to the store, and
+ // the chat that "should be there when you click back" would actually be
+ // wiped. Route through refs that we update on every render so the
+ // listener always invokes the freshest closure.
+ const loadConversationRef = useRef(loadConversation);
+ const startNewConversationRef = useRef(startNewConversation);
+ loadConversationRef.current = loadConversation;
+ startNewConversationRef.current = startNewConversation;
+
useEffect(() => {
const unlisten = listen<{ conversationId: string }>("chat-load-conversation", async (event) => {
const { conversationId: convId } = event.payload;
@@ -1640,7 +1654,7 @@ export function StandaloneChat({
// 1) Disk first — saved conversations are the canonical source.
const conv = await loadConversationFile(convId);
if (conv) {
- loadConversation(conv);
+ loadConversationRef.current(conv);
return;
}
@@ -1649,16 +1663,13 @@ export function StandaloneChat({
// a turn yet (no agent_end → no save). Without this branch,
// clicking back to a chat that's been streaming in the
// background would fall through to startNewConversation and
- // silently WIPE the in-memory state. That's the "switch to a
- // new chat, switch back, A is empty" repro: A had messages
- // only in the store (mid-stream when the user left), so the
- // disk lookup missed and the panel reset.
+ // silently WIPE the in-memory state.
const session = useChatStore.getState().sessions[convId];
if (session?.messages && session.messages.length > 0) {
// Stub conversation — loadConversation prefers store messages
// over the conv arg whenever the store has them, so the empty
// messages array here is just a satisfaction of the type.
- loadConversation({
+ loadConversationRef.current({
id: convId,
title: session.title || "untitled",
messages: [],
@@ -1671,7 +1682,7 @@ export function StandaloneChat({
// 3) Truly new id (sidebar's "+ new chat" path) — adopt the
// requested id so sidebar + chat (and the chat-store's
// currentId) all agree from message 0.
- await startNewConversation(convId);
+ await startNewConversationRef.current(convId);
// Mirror the new id back to the sidebar so its currentId matches.
emit("chat-current-session", { id: convId });
});
@@ -1699,7 +1710,7 @@ export function StandaloneChat({
const u = await listen<{ session: string }>("pi_session_evicted", async (event) => {
if (cancelled) return;
if (event.payload.session !== piSessionIdRef.current) return;
- await startNewConversation();
+ await startNewConversationRef.current();
emit("chat-current-session", { id: piSessionIdRef.current });
});
unlistenFn = u;
@@ -1721,7 +1732,7 @@ export function StandaloneChat({
const { loadConversationFile } = await import("@/lib/chat-storage");
const conv = await loadConversationFile(pendingId);
if (conv) {
- loadConversation(conv);
+ loadConversationRef.current(conv);
}
})();
}
diff --git a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
index d0c786cc8..905473ac6 100644
--- a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
@@ -53,7 +53,14 @@ export interface SessionRecord {
lastError?: string;
/** Number of messages persisted to disk for this session. */
messageCount: number;
- /** ms since epoch of the most recent activity (for sort + LRU). */
+ /** ms since epoch when the row first appeared in the sidebar. Drives
+ * the sort order — newer rows show at the top of "recents" and stay
+ * put. Set once on creation; never bumped by subsequent activity.
+ * (We tried sorting by updatedAt — every keystroke / pi_event would
+ * reshuffle the list under the user's cursor, which felt broken.) */
+ createdAt: number;
+ /** ms since epoch of the most recent activity. Tracked for telemetry
+ * / "last activity" UI only — DOES NOT affect sort order. */
updatedAt: number;
/** User pinned this conversation to the top of the sidebar. */
pinned: boolean;
@@ -220,7 +227,16 @@ export const useChatStore = create<ChatStore>((set) => ({
}),
upsert: (record) =>
- set((s) => ({ sessions: { ...s.sessions, [record.id]: record } })),
+ set((s) => {
+ const existing = s.sessions[record.id];
+ // Preserve original createdAt when re-upserting an existing row.
+ // Without this, a router lazy-create after a sidebar optimistic
+ // upsert would reset createdAt and visibly reshuffle the row.
+ const merged: SessionRecord = existing
+ ? { ...existing, ...record, createdAt: existing.createdAt }
+ : record;
+ return { sessions: { ...s.sessions, [record.id]: merged } };
+ }),
patch: (id, partial) =>
set((s) => {
@@ -472,10 +488,10 @@ export function selectOrderedSessions(state: ChatStore): SessionRecord[] {
const all = Object.values(state.sessions);
const pinned = all
.filter((s) => s.pinned)
- .sort((a, b) => b.updatedAt - a.updatedAt);
+ .sort((a, b) => b.createdAt - a.createdAt);
const recents = all
.filter((s) => !s.pinned)
- .sort((a, b) => b.updatedAt - a.updatedAt);
+ .sort((a, b) => b.createdAt - a.createdAt);
return [...pinned, ...recents];
}
@@ -492,10 +508,10 @@ export function useOrderedSessions(): SessionRecord[] {
const all = Object.values(sessionsMap);
const pinned = all
.filter((s) => s.pinned)
- .sort((a, b) => b.updatedAt - a.updatedAt);
+ .sort((a, b) => b.createdAt - a.createdAt);
const recents = all
.filter((s) => !s.pinned)
- .sort((a, b) => b.updatedAt - a.updatedAt);
+ .sort((a, b) => b.createdAt - a.createdAt);
return [...pinned, ...recents];
}, [sessionsMap]);
}
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 18af65e11..d1ae7fa9e 100644
--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
@@ -204,6 +204,7 @@ async function handlePiEvent(envelope: PiEventEnvelope) {
status: nextStatus ?? "streaming",
lastError: err ?? undefined,
messageCount: 0,
+ createdAt: Date.now(),
updatedAt: Date.now(),
pinned: false,
// First-touch session is unread unless the user is already viewing
@@ -314,6 +315,7 @@ async function hydrate() {
preview: "",
status: "idle" as const,
messageCount: m.messageCount,
+ createdAt: m.createdAt,
updatedAt: m.updatedAt,
pinned: m.pinned,
// History reload doesn't count as new activity — start clean.
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index 8fe27aad8..6e0f0e25a 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.67"
+version = "2.4.68"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""