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): stop empty "untitled" chats appearing in recents (#6667)
Louis Beaumontb5cc23e0af20
diff --git a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx b/apps/screenpipe-app-tauri/components/chat-sidebar.tsxindex 2bd0995b2..91c45b099 100644--- a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx+++ b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx@@ -58,6 +58,7 @@ import {useChatStore,useChatActions,useOrderedSessions,+ isEmptyChatShell,selectDisplayedChatId,sessionRecordFromMeta,type SessionRecord,@@ -347,8 +348,11 @@ function useVisibleChatSections(): {const archived: SessionRecord[] = [];for (const s of sessions) {// Hide drafts (no user message sent yet)- // Once a message is sent, draft is cleared and the chat becomes visible- if (s.draft) continue;+ // Once a message is sent, draft is cleared and the chat becomes visible.+ // `isEmptyChatShell` is the derived backstop for rows whose creator+ // never set the flag (prewarmed / auto-restarted Pi sessions used to+ // land here as empty "untitled" rows).+ if (s.draft || isEmptyChatShell(s)) continue;if (s.hidden) {archived.push(s);continue;diff --git a/apps/screenpipe-app-tauri/components/chat/recent-chat-switcher-controller.test.tsx b/apps/screenpipe-app-tauri/components/chat/recent-chat-switcher-controller.test.tsxindex cfccb0e10..cb9182046 100644--- a/apps/screenpipe-app-tauri/components/chat/recent-chat-switcher-controller.test.tsx+++ b/apps/screenpipe-app-tauri/components/chat/recent-chat-switcher-controller.test.tsx@@ -62,7 +62,10 @@ function seed(record: Partial<SessionRecord> & Pick<SessionRecord, "id">) {title: record.title ?? record.id,preview: "",status: "idle",- messageCount: 0,+ // Seeded rows stand in for real conversations. The switcher only lists+ // chats that exist (isEmptyChatShell), so they need a message count —+ // a zero-message row is an empty shell and is filtered out.+ messageCount: 2,createdAt: record.createdAt ?? 1_000,updatedAt: record.updatedAt ?? record.createdAt ?? 1_000,pinned: record.pinned ?? false,diff --git a/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.tsindex 96e40b8e3..42b7f4859 100644--- a/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts+++ b/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts@@ -15,6 +15,7 @@ import {selectRecentSwitcherSessions,getOrCreateEmptyChatId,isReusableBlankChatSession,+ isEmptyChatShell,dedupeSessionRecords,sessionRecordFromMeta,selectDisplayedChatId,@@ -454,10 +455,12 @@ describe("chat-store: visible selection follows the rendered panel", () => {describe("chat-store: recent switcher ordering", () => {beforeEach(reset);+ // Fixtures carry `messageCount` because the switcher only lists real chats:+ // an empty shell is filtered by isEmptyChatShell, flag or no flag.it("returns only chats viewed this session ordered by most recent view", () => {- useChatStore.getState().actions.upsert(baseRecord({ id: "older-viewed", createdAt: 100 }));- useChatStore.getState().actions.upsert(baseRecord({ id: "sidebar-top", createdAt: 300 }));- useChatStore.getState().actions.upsert(baseRecord({ id: "newer-viewed", createdAt: 200 }));+ useChatStore.getState().actions.upsert(baseRecord({ id: "older-viewed", createdAt: 100, messageCount: 2 }));+ useChatStore.getState().actions.upsert(baseRecord({ id: "sidebar-top", createdAt: 300, messageCount: 2 }));+ useChatStore.getState().actions.upsert(baseRecord({ id: "newer-viewed", createdAt: 200, messageCount: 2 }));useChatStore.getState().actions.setCurrent("older-viewed");useChatStore.getState().actions.setCurrent("newer-viewed");@@ -478,8 +481,8 @@ describe("chat-store: recent switcher ordering", () => {});it("excludes hidden and draft chats from the switcher", () => {- useChatStore.getState().actions.upsert(baseRecord({ id: "visible", createdAt: 300 }));- useChatStore.getState().actions.upsert(baseRecord({ id: "hidden", createdAt: 200, hidden: true }));+ useChatStore.getState().actions.upsert(baseRecord({ id: "visible", createdAt: 300, messageCount: 2 }));+ useChatStore.getState().actions.upsert(baseRecord({ id: "hidden", createdAt: 200, hidden: true, messageCount: 2 }));useChatStore.getState().actions.upsert(baseRecord({ id: "draft", createdAt: 100, draft: true }));useChatStore.getState().actions.setCurrent("visible");@@ -489,7 +492,7 @@ describe("chat-store: recent switcher ordering", () => {});it("excludes pipe-run and pipe-watch sessions from the switcher", () => {- useChatStore.getState().actions.upsert(baseRecord({ id: "visible", createdAt: 300 }));+ useChatStore.getState().actions.upsert(baseRecord({ id: "visible", createdAt: 300, messageCount: 2 }));useChatStore.getState().actions.upsert(baseRecord({ id: "pipe-run", kind: "pipe-run", createdAt: 200, lastViewedAt: 500 }));@@ -689,6 +692,33 @@ describe("chat-store: persisted empty chat cleanup", () => {expect(isReusableBlankChatSession(record)).toBe(false);});+ it("un-drafts a hydrated conversation that a router row had marked empty", () => {+ // The event router lazy-creates rows for Pi processes it has no+ // conversation for yet, and those rows are born `draft: true`. When disk+ // hydration then proves the id has messages, the stale flag must not keep+ // the real conversation out of RECENTS.+ useChatStore.getState().actions.upsert(+ baseRecord({ id: "A", title: "untitled", draft: true, messageCount: 0 }),+ );++ useChatStore.getState().actions.hydrateFromDisk([+ sessionRecordFromMeta({+ id: "A",+ title: "real conversation",+ createdAt: 100,+ updatedAt: 200,+ messageCount: 4,+ pinned: false,+ hidden: false,+ kind: "chat",+ }),+ ]);++ const session = useChatStore.getState().sessions.A;+ expect(session.draft).toBeUndefined();+ expect(session.title).toBe("real conversation");+ });+it("does not hide an empty scheduled run as a chat draft", () => {const record = sessionRecordFromMeta({id: "pipe-run-1",@@ -705,6 +735,57 @@ describe("chat-store: persisted empty chat cleanup", () => {});});+describe("chat-store: isEmptyChatShell (derived backstop for missing draft flags)", () => {+ // The bug this guards: an empty "untitled" row showing up in RECENTS every+ // time a chat was opened. Its creator (the event router's lazy-create for+ // prewarmed / auto-restarted Pi processes) simply never set `draft`. Rather+ // than trust every creator to remember the flag, emptiness is derived.+ it("treats a row with no messages, no count and no user turn as empty", () => {+ expect(isEmptyChatShell(baseRecord({ id: "A", title: "untitled" }))).toBe(true);+ });++ it("does not call a row empty once it holds in-memory messages", () => {+ const record = baseRecord({+ id: "A",+ messages: [{ id: "u1", role: "user", content: "hi", timestamp: 1 }] as never,+ });+ expect(isEmptyChatShell(record)).toBe(false);+ });++ it("does not call a persisted conversation empty", () => {+ expect(isEmptyChatShell(baseRecord({ id: "A", messageCount: 4 }))).toBe(false);+ });++ it("does not call a chat empty once a user turn was sent", () => {+ expect(isEmptyChatShell(baseRecord({ id: "A", lastUserMessageAt: 5_000 }))).toBe(false);+ });++ it("exempts pipe rows — a finished run is history even with no messages", () => {+ expect(isEmptyChatShell(baseRecord({ id: "A", kind: "pipe-run" }))).toBe(false);+ expect(isEmptyChatShell(baseRecord({ id: "B", kind: "pipe-watch" }))).toBe(false);+ });++ it("keeps an empty shell out of the recent-chat switcher", () => {+ // A blank chat the user merely looked at gets a lastViewedAt, which is all+ // the switcher used to require.+ useChatStore.getState().actions.upsert(+ baseRecord({ id: "ghost", title: "untitled", lastViewedAt: 9_000 }),+ );+ useChatStore.getState().actions.upsert(+ baseRecord({+ id: "real",+ title: "real chat",+ messageCount: 2,+ lastUserMessageAt: 8_000,+ lastViewedAt: 8_500,+ }),+ );++ const ids = selectRecentSwitcherSessions(useChatStore.getState()).map((s) => s.id);+ expect(ids).toEqual(["real"]);+ });+});+describe("chat-store: cross-window duplicate row collapsing", () => {// Bug: one logical conversation persisted under two ids (home + chat-overlay// cross-window save race) showed as two sidebar rows. listConversationsdiff --git a/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.tsindex 9590804db..f9c12c244 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@@ -1217,3 +1217,58 @@ describe("pi-event-router: user echo does not duplicate the optimistic bubble",expect(session.messages?.filter((m) => m.role === "user")).toHaveLength(2);});});++describe("pi-event-router: lazy-created rows stay hidden until they are real", () => {+ beforeEach(reset);++ /**+ * A Pi process exists for plenty of session ids that are not conversations:+ * the chat panel spawns one for its mount-time uuid, home and the+ * pre-created chat window each prewarm their own, and a crash auto-restarts+ * them. Those processes emit lifecycle / state events, and the router used+ * to lazy-create a *visible* row for them — which is how an empty "untitled"+ * chat kept appearing in RECENTS beside the real ones.+ */+ it("marks a lazy-created row draft so an orphan Pi session never shows up", async () => {+ await handlePiEvent(piEvt("orphan", { type: "agent_start" }));++ const session = useChatStore.getState().sessions.orphan;+ expect(session).toBeDefined();+ expect(session.draft).toBe(true);+ expect(session.messageCount).toBe(0);+ });++ it("keeps the row hidden across a whole content-free lifecycle", async () => {+ await handlePiEvent(piEvt("orphan", { type: "agent_start" }));+ await handlePiEvent(piEvt("orphan", { type: "agent_end" } as AgentInnerEvent));++ expect(useChatStore.getState().sessions.orphan.draft).toBe(true);+ });++ it("reveals the row as soon as a user turn lands on it", async () => {+ await handlePiEvent(piEvt("orphan", { type: "agent_start" }));+ await handlePiEvent(+ piEvt("orphan", {+ type: "message_start",+ message: { role: "user", content: "hello from a queued follow-up" },+ } as AgentInnerEvent),+ );++ const session = useChatStore.getState().sessions.orphan;+ expect(session.draft).toBe(false);+ expect(session.messages?.some((m: any) => m.role === "user")).toBe(true);+ });++ it("reveals the row while a backgrounded assistant reply is still streaming", async () => {+ await handlePiEvent(+ piEvt("orphan", {+ type: "message_start",+ message: { role: "assistant" },+ } as AgentInnerEvent),+ );++ const session = useChatStore.getState().sessions.orphan;+ expect(session.draft).toBe(false);+ expect(session.messages?.length).toBeGreaterThan(0);+ });+});diff --git a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts b/apps/screenpipe-app-tauri/lib/stores/chat-store.tsindex 65f643794..150c4e650 100644--- a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts+++ b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts@@ -436,6 +436,11 @@ export const useChatStore = create<ChatStore>((set) => ({messageCount: r.messageCount,pinned: existing.pinned || r.pinned,hidden: existing.hidden ?? r.hidden ?? false,+ // Disk decides emptiness. A router row lazy-created before+ // hydration is born `draft: true` (it has no proof of content+ // yet); once the file says otherwise, the flag must not keep a+ // real conversation out of RECENTS.+ draft: r.messageCount > 0 ? undefined : (r.draft ?? existing.draft),// updatedAt: take the larger so memory doesn't get clobberedupdatedAt: Math.max(existing.updatedAt, r.updatedAt),lastUserMessageAt: Math.max(@@ -1034,6 +1039,24 @@ export function dedupeSessionRecords(records: SessionRecord[]): SessionRecord[]return kept;}+/**+ * True when a chat row has nothing a user could open: no messages in memory,+ * none persisted, and no user turn ever sent.+ *+ * The `draft` boolean is bookkeeping — every creator of a blank session has to+ * remember to set it, and any path that forgets (the event router's+ * lazy-create did, for prewarmed / auto-restarted Pi processes) leaks an empty+ * "untitled" row into RECENTS. This predicate is the derived backstop: the+ * sidebar renders a chat only when a chat exists. Pipe rows are exempt — a+ * finished run is history even with an empty in-memory message array.+ */+export function isEmptyChatShell(s: SessionRecord): boolean {+ if (s.kind === "pipe-run" || s.kind === "pipe-watch") return false;+ if (s.messageCount > 0) return false;+ if ((s.messages?.length ?? 0) > 0) return false;+ return !s.lastUserMessageAt;+}+export function selectOrderedSessions(state: ChatSessionsState): SessionRecord[] {const all = dedupeSessionRecords(Object.values(state.sessions));const pinned = all.filter((s) => s.pinned).sort(compareForSidebar);@@ -1046,6 +1069,7 @@ export function selectRecentSwitcherSessions(state: ChatSessionsState): SessionRconst isEligibleSwitcherSession = (session: SessionRecord) =>!session.hidden &&!session.draft &&+ !isEmptyChatShell(session) &&session.kind !== "pipe-watch" &&session.kind !== "pipe-run";return ordereddiff --git a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.tsindex 8f1e7a037..af9451496 100644--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts@@ -263,6 +263,17 @@ export async function handlePiEvent(envelope: AgentEventEnvelope) {updatedAt: now,pinned: false,unread: false,+ // Born hidden, exactly like the "+ new chat" row. A Pi process exists+ // for plenty of session ids that are not a conversation yet: the chat+ // panel spawns one for its mount-time uuid, each window (home + the+ // pre-created chat panel) prewarms its own, and crashes auto-restart+ // them. Those processes emit startup/state/lifecycle events, and+ // lazy-creating a *visible* row for them is what put an empty+ // "untitled" chat in RECENTS every time the user opened a new chat.+ // The row is revealed by the paths that prove real content exists:+ // `applyEventToSessionContent` on a user `message_start`, and+ // `persistBackgroundSession` after the first save.+ draft: true,// Set lastContentAt on first touch only when there's actual content.// isUnread() in the store will compute the correct unread boolean....(snippet ? { lastContentAt: now } : {}),@@ -286,6 +297,13 @@ export async function handlePiEvent(envelope: AgentEventEnvelope) {// Status mirroring below still runs for both Pi and Pipe sessions.if (envelope.source === "pi") {applyEventToSessionContent(sid, inner);+ // Content is the proof a draft row was waiting for. Reveal it as soon as+ // the session actually holds a message — a backgrounded reply must show+ // up in RECENTS while it streams, not only after the agent_end save.+ const afterContent = useChatStore.getState().sessions[sid];+ if (afterContent?.draft && (afterContent.messages?.length ?? 0) > 0) {+ store.actions.patch(sid, { draft: false });+ }}// Decide whether to write a preview update — throttled per session.