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 inconsistent unread indicators across chat switching, pipe runs, and app restart (#3978)

Harsh Kumarde3b75151caa
diff --git a/apps/screenpipe-app-tauri/app/home/page.tsx b/apps/screenpipe-app-tauri/app/home/page.tsx
index 7b1f2c726..200e6f95d 100644
--- a/apps/screenpipe-app-tauri/app/home/page.tsx
+++ b/apps/screenpipe-app-tauri/app/home/page.tsx
@@ -21,6 +21,7 @@ import {
} from "lucide-react";
import { emit } from "@tauri-apps/api/event";
import {
+ isSessionForeground,
sessionRecordFromMeta,
useChatStore,
type SessionStatus,
@@ -257,8 +258,8 @@ function HomeContent() {
updatedAt,
});
}
- if (unreadHint && store.currentId !== id && store.panelSessionId !== id) {
- store.actions.markUnread(id);
+ if (unreadHint && !isSessionForeground(store, id)) {
+ store.actions.patch(id, { lastContentAt: Date.now() });
}
});
unlistenFn = unlisten;
diff --git a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
index f4b94218d..a96544c79 100644
--- a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
+++ b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
@@ -249,12 +249,40 @@ export function ChatSidebar({ className, onViewAll }: ChatSidebarProps) {
const store = useChatStore.getState();
const existing = store.sessions[id];
if (existing) {
+ // The unread watermarks are monotonic: a cross-window mirror must
+ // never rewind them below what this window already knows, or a
+ // slightly-stale disk read (the other window saved first, our own
+ // lastViewedAt patch hasn't flushed yet) would re-light the dot for
+ // a chat we just read. Take the max, same as hydrateFromDisk.
+ const hasContentAt =
+ existing.lastContentAt != null || meta.lastContentAt != null;
+ const hasViewedAt =
+ typeof existing.lastViewedAt === "number" ||
+ typeof meta.lastViewedAt === "number";
store.actions.patch(id, {
title: meta.title || existing.title,
messageCount: meta.messageCount,
pinned: meta.pinned,
hidden: meta.hidden,
- lastUserMessageAt: meta.lastUserMessageAt,
+ ...(meta.lastUserMessageAt
+ ? { lastUserMessageAt: meta.lastUserMessageAt }
+ : {}),
+ ...(hasContentAt
+ ? {
+ lastContentAt: Math.max(
+ existing.lastContentAt ?? 0,
+ meta.lastContentAt ?? 0,
+ ),
+ }
+ : {}),
+ ...(hasViewedAt
+ ? {
+ lastViewedAt: Math.max(
+ existing.lastViewedAt ?? 0,
+ meta.lastViewedAt ?? 0,
+ ),
+ }
+ : {}),
updatedAt: Math.max(existing.updatedAt, meta.updatedAt),
kind: meta.kind,
pipeContext: meta.pipeContext,
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 514269426..77c2aa3db 100644
--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
@@ -38,6 +38,7 @@ import {
migrateFromStoreBin,
CHAT_HISTORY_INITIAL_LIMIT,
conversationDedupKey,
+ updateConversationFlags,
type ConversationMeta,
} from "@/lib/chat-storage";
import type { ContentBlock, Message } from "@/lib/chat/types";
@@ -193,6 +194,8 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
pinned: conversation.pinned === true,
hidden: conversation.hidden === true,
lastUserMessageAt,
+ lastContentAt: conversation.lastContentAt,
+ lastViewedAt: conversation.lastViewedAt,
kind: conversation.kind ?? "chat",
pipeContext: conversation.pipeContext,
titleSource: conversation.titleSource,
@@ -696,12 +699,23 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
...(await (async () => {
const { useChatStore } = await import("@/lib/stores/chat-store");
const sid = piSessionIdRef.current;
- const fromStore = sid
- ? useChatStore.getState().sessions[sid]?.lastUserMessageAt
+ const storeSession = sid
+ ? useChatStore.getState().sessions[sid]
: undefined;
const lastUserMessageAt =
- computedLastUserMessageAt ?? fromStore ?? existing?.lastUserMessageAt;
- return lastUserMessageAt ? { lastUserMessageAt } : {};
+ computedLastUserMessageAt ??
+ storeSession?.lastUserMessageAt ??
+ existing?.lastUserMessageAt;
+ const lastContentAt = storeSession?.lastContentAt ?? existing?.lastContentAt;
+ const lastViewedAt =
+ storeSession?.lastViewedAt ??
+ existing?.lastViewedAt ??
+ (lastContentAt ? 0 : undefined);
+ return {
+ ...(lastUserMessageAt ? { lastUserMessageAt } : {}),
+ ...(lastContentAt ? { lastContentAt } : {}),
+ ...(typeof lastViewedAt === "number" ? { lastViewedAt } : {}),
+ };
})()),
// Persist the preset ID so the model selection survives app restart
// and is restored when switching between chats.
@@ -970,6 +984,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
const { useChatStore } = await import("@/lib/stores/chat-store");
const store = useChatStore.getState();
const outgoingSid = piSessionIdRef.current;
+ const viewedAt = Date.now();
// (1) Snapshot OUTGOING session — atomic so router writes that
// race against this update can't land between the messages
@@ -1076,6 +1091,10 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
...(persisted.hidden === true ? { hidden: true } : {}),
...(persisted.kind ? { kind: persisted.kind } : {}),
...(persisted.pipeContext ? { pipeContext: persisted.pipeContext } : {}),
+ ...(persisted.lastContentAt ? { lastContentAt: persisted.lastContentAt } : {}),
+ ...(typeof persisted.lastViewedAt === "number"
+ ? { lastViewedAt: persisted.lastViewedAt }
+ : {}),
});
} else {
store.actions.patch(conv.id, {
@@ -1086,6 +1105,9 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
updatedAt: Math.max(existing?.updatedAt ?? 0, persisted.updatedAt ?? 0),
...(persisted.kind ? { kind: persisted.kind } : {}),
...(persisted.pipeContext ? { pipeContext: persisted.pipeContext } : {}),
+ ...(typeof persisted.lastViewedAt === "number"
+ ? { lastViewedAt: persisted.lastViewedAt }
+ : {}),
});
}
}
@@ -1171,6 +1193,10 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
// foreground/background swaps.
...(conv.kind ? { kind: conv.kind } : full.kind ? { kind: full.kind } : {}),
...(conv.pipeContext ? { pipeContext: conv.pipeContext } : full.pipeContext ? { pipeContext: full.pipeContext } : {}),
+ ...(full.lastContentAt ? { lastContentAt: full.lastContentAt } : {}),
+ ...(typeof full.lastViewedAt === "number"
+ ? { lastViewedAt: full.lastViewedAt }
+ : {}),
});
} else if (conv.kind || conv.pipeContext) {
store.actions.patch(conv.id, {
@@ -1186,6 +1212,13 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
store.actions.setMessages(conv.id, messagesForPanel as any);
store.actions.markHydrated(conv.id);
}
+ store.actions.patch(conv.id, { lastViewedAt: viewedAt });
+ try {
+ await updateConversationFlags(conv.id, { lastViewedAt: viewedAt });
+ } catch {
+ // Best-effort: unread clears live immediately; the next full save can
+ // still persist the watermark if this patch fails.
+ }
setMessages(messagesForPanel);
setConversationId(conv.id);
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 8193a000d..6c883d7ae 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -48,7 +48,7 @@ import { emit } from "@tauri-apps/api/event";
import { useChatConversations } from "@/components/hooks/use-chat-conversations";
import { useChatStore } from "@/lib/stores/chat-store";
import { useFeedbackStore } from "@/lib/stores/feedback-store";
-import { statusForEvent } from "@/lib/stores/pi-event-router";
+import { handlePiEvent, statusForEvent } from "@/lib/stores/pi-event-router";
import { deriveFallbackConversationTitle } from "@/lib/utils/chat-title";
import { buildChipModelContent, buildChipDisplayContent, parseConnectionChip } from "@/lib/utils/connection-chip";
import { getCurrentWindow } from "@tauri-apps/api/window";
@@ -1734,6 +1734,13 @@ export function StandaloneChat({
await mountAgentEventBus();
if (cancelled) return;
off = registerForeground(conversationId, (envelope) => {
+ if (envelope.sessionId !== piSessionIdRef.current) {
+ // The user switched chats, but the old foreground registration
+ // has not cleaned up yet. Hand the event to the background
+ // router so the old session can accrue unread state normally.
+ void handlePiEvent(envelope);
+ return;
+ }
if (!mountedRef.current) return;
handleAgentEventDataRef.current?.(envelope.event);
});
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts
index eb52630b2..ef441dc6f 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts
@@ -31,9 +31,18 @@ vi.mock("@tauri-apps/plugin-fs", () => ({
if (!file) throw new Error(`missing ${path}`);
return file.text;
}),
- writeTextFile: vi.fn(async () => undefined),
- remove: vi.fn(async () => undefined),
- rename: vi.fn(async () => undefined),
+ writeTextFile: vi.fn(async (path: string, text: string) => {
+ fsMock.files.set(path, { text, mtime: Date.now() });
+ }),
+ remove: vi.fn(async (path: string) => {
+ fsMock.files.delete(path);
+ }),
+ rename: vi.fn(async (from: string, to: string) => {
+ const file = fsMock.files.get(from);
+ if (!file) throw new Error(`missing ${from}`);
+ fsMock.files.set(to, file);
+ fsMock.files.delete(from);
+ }),
stat: vi.fn(async (path: string) => {
fsMock.stats.push(path);
return {
@@ -50,6 +59,8 @@ import {
conversationMetaFromJson,
dedupeConversationMetas,
listConversations,
+ loadConversationFile,
+ saveConversationFile,
searchConversations,
type ConversationDedupCandidate,
type ConversationMeta,
@@ -69,6 +80,8 @@ function putConversation(
titleSource?: "fallback" | "ai" | "user";
/** When set, append an assistant message with this content. */
assistantContent?: string;
+ lastContentAt?: number;
+ lastViewedAt?: number;
}
) {
const messages: Array<Record<string, unknown>> = [
@@ -96,6 +109,8 @@ function putConversation(
updatedAt: opts.updatedAt,
hidden: opts.hidden,
kind: opts.kind,
+ lastContentAt: opts.lastContentAt,
+ lastViewedAt: opts.lastViewedAt,
};
fsMock.files.set(`${CHATS_DIR}/${id}.json`, {
text: JSON.stringify(conv),
@@ -212,6 +227,43 @@ describe("chat-storage bounded history", () => {
expect(meta?.lastUserMessageAt).toBe(4_500);
});
+
+ it("round-trips lastViewedAt through save/load and derived metadata", async () => {
+ await saveConversationFile({
+ id: "roundtrip",
+ title: "roundtrip",
+ messages: [
+ { id: "u1", role: "user", content: "hi", timestamp: 100 },
+ { id: "a1", role: "assistant", content: "hello", timestamp: 200 },
+ ],
+ createdAt: 100,
+ updatedAt: 200,
+ lastContentAt: 200,
+ lastViewedAt: 150,
+ });
+
+ const conv = await loadConversationFile("roundtrip");
+ const meta = conversationMetaFromJson(conv);
+
+ expect(conv?.lastViewedAt).toBe(150);
+ expect(meta?.lastViewedAt).toBe(150);
+ expect(meta?.lastContentAt).toBe(200);
+ });
+
+ it("leaves lastViewedAt undefined for legacy files that predate unread persistence", () => {
+ const meta = conversationMetaFromJson({
+ id: "legacy",
+ title: "legacy",
+ createdAt: 100,
+ updatedAt: 200,
+ lastContentAt: 200,
+ messages: [
+ { id: "u1", role: "user", content: "hello", timestamp: 100 },
+ ],
+ });
+
+ expect(meta?.lastViewedAt).toBeUndefined();
+ });
});
function meta(
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts
index 748cbeec8..eb908b9e7 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts
@@ -15,11 +15,12 @@ import {
selectRecentSwitcherSessions,
getOrCreateEmptyChatId,
dedupeSessionRecords,
+ sessionRecordFromMeta,
type SessionRecord,
} from "../stores/chat-store";
function reset() {
- useChatStore.setState({ sessions: {}, currentId: null });
+ useChatStore.setState({ sessions: {}, currentId: null, panelSessionId: null });
}
function baseRecord(overrides: Partial<SessionRecord> = {}): SessionRecord {
@@ -261,12 +262,14 @@ describe("chat-store: setCurrent clears unread atomically", () => {
beforeEach(reset);
it("flips currentId AND clears unread on the new current in one set", () => {
- useChatStore.getState().actions.upsert(baseRecord({ id: "A", unread: true }));
+ useChatStore.getState().actions.upsert(baseRecord({ id: "A", lastContentAt: 100 }));
useChatStore.getState().actions.setCurrent("A");
const state = useChatStore.getState();
expect(state.currentId).toBe("A");
+ expect(state.panelSessionId).toBe("A");
expect(state.sessions.A.unread).toBe(false);
expect(typeof state.sessions.A.lastViewedAt).toBe("number");
+ expect(state.sessions.A.lastViewedAt).toBeGreaterThanOrEqual(100);
});
});
@@ -323,35 +326,171 @@ describe("chat-store: recent switcher ordering", () => {
});
});
-describe("chat-store: markUnread guards", () => {
+describe("chat-store: unread is computed from timestamps", () => {
beforeEach(reset);
- it("no-ops when the session is the current one", () => {
- useChatStore.getState().actions.upsert(baseRecord({ id: "A", unread: false }));
- useChatStore.getState().actions.setCurrent("A");
- useChatStore.getState().actions.markUnread("A");
+ it("session with lastContentAt > lastViewedAt is unread", () => {
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", lastContentAt: 200, lastViewedAt: 100 }),
+ );
+ expect(useChatStore.getState().sessions.A.unread).toBe(true);
+ });
+
+ it("session with lastContentAt < lastViewedAt is not unread", () => {
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", lastContentAt: 100, lastViewedAt: 200 }),
+ );
expect(useChatStore.getState().sessions.A.unread).toBe(false);
});
- it("no-ops when the session is loaded in the panel even if currentId was cleared", () => {
- // Bug: navigating away from /home reset currentId to null. Late deltas
- // for the still-loaded panel chat then re-marked it unread, even though
- // the user had read everything on screen. Guard on panelSessionId fixes
- // that — the panel keeps the chat visible-on-return, so deltas there
- // don't count as "new since last seen".
- useChatStore.getState().actions.upsert(baseRecord({ id: "A", unread: false }));
- useChatStore.setState({ currentId: null, panelSessionId: "A" });
- useChatStore.getState().actions.markUnread("A");
+ it("appendMessage bumps lastContentAt and recomputes unread", () => {
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", lastViewedAt: 50 }),
+ );
expect(useChatStore.getState().sessions.A.unread).toBe(false);
+ useChatStore.getState().actions.appendMessage(
+ "A",
+ { id: "m1", role: "assistant", content: "hello", timestamp: Date.now() },
+ );
+ const session = useChatStore.getState().sessions.A;
+ expect(session.lastContentAt).toBeGreaterThan(50);
+ expect(session.unread).toBe(true);
+ });
+
+ it("appendMessage keeps the current session read while it stays open", () => {
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", lastViewedAt: 50 }),
+ );
+ useChatStore.getState().actions.setCurrent("A");
+ useChatStore.getState().actions.appendMessage(
+ "A",
+ { id: "m1", role: "assistant", content: "hello", timestamp: Date.now() },
+ );
+ const session = useChatStore.getState().sessions.A;
+ expect(session.lastContentAt).toBeDefined();
+ expect(session.lastViewedAt).toBe(session.lastContentAt);
+ expect(session.unread).toBe(false);
});
- it("DOES mark a different session unread when nav'd away", () => {
- useChatStore.getState().actions.upsert(baseRecord({ id: "A", unread: false }));
- useChatStore.getState().actions.upsert(baseRecord({ id: "B", unread: false }));
+ it("appendMessage keeps the mounted panel session read when home is hidden", () => {
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", lastViewedAt: 50 }),
+ );
useChatStore.setState({ currentId: null, panelSessionId: "A" });
- useChatStore.getState().actions.markUnread("B");
+ useChatStore.getState().actions.appendMessage(
+ "A",
+ { id: "m1", role: "assistant", content: "hello", timestamp: Date.now() },
+ );
+ const session = useChatStore.getState().sessions.A;
+ expect(session.lastViewedAt).toBe(session.lastContentAt);
+ expect(session.unread).toBe(false);
+ });
+
+ it("patch with only updatedAt does NOT flip unread", () => {
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", lastContentAt: 100, lastViewedAt: 200 }),
+ );
expect(useChatStore.getState().sessions.A.unread).toBe(false);
- expect(useChatStore.getState().sessions.B.unread).toBe(true);
+ // Status/preview patches bump updatedAt but should not affect unread.
+ useChatStore.getState().actions.patch("A", { updatedAt: 9_999 });
+ expect(useChatStore.getState().sessions.A.unread).toBe(false);
+ });
+
+ it("setCurrent sets lastViewedAt and clears unread", () => {
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", lastContentAt: 200 }),
+ );
+ expect(useChatStore.getState().sessions.A.unread).toBe(true);
+ useChatStore.getState().actions.setCurrent("A");
+ expect(useChatStore.getState().sessions.A.unread).toBe(false);
+ expect(useChatStore.getState().sessions.A.lastViewedAt).toBeGreaterThanOrEqual(200);
+ });
+
+ it("hydrateFromDisk restores unread when persisted lastViewedAt lags content", () => {
+ useChatStore.getState().actions.hydrateFromDisk([
+ sessionRecordFromMeta({
+ id: "A",
+ title: "A",
+ createdAt: 100,
+ updatedAt: 200,
+ messageCount: 2,
+ pinned: false,
+ hidden: false,
+ lastContentAt: 200,
+ lastViewedAt: 150,
+ kind: "chat",
+ }),
+ ]);
+
+ expect(useChatStore.getState().sessions.A.unread).toBe(true);
+ });
+
+ it("hydrateFromDisk restores read when persisted lastViewedAt catches up", () => {
+ useChatStore.getState().actions.hydrateFromDisk([
+ sessionRecordFromMeta({
+ id: "A",
+ title: "A",
+ createdAt: 100,
+ updatedAt: 200,
+ messageCount: 2,
+ pinned: false,
+ hidden: false,
+ lastContentAt: 200,
+ lastViewedAt: 200,
+ kind: "chat",
+ }),
+ ]);
+
+ expect(useChatStore.getState().sessions.A.unread).toBe(false);
+ });
+
+ it("hydrateFromDisk keeps legacy rows read when lastViewedAt was never persisted", () => {
+ useChatStore.getState().actions.hydrateFromDisk([
+ sessionRecordFromMeta({
+ id: "legacy",
+ title: "legacy",
+ createdAt: 100,
+ updatedAt: 200,
+ messageCount: 1,
+ pinned: false,
+ hidden: false,
+ lastContentAt: 200,
+ kind: "chat",
+ }),
+ ]);
+
+ expect(useChatStore.getState().sessions.legacy.unread).toBe(false);
+ });
+
+ it("hydrateFromDisk merge preserves the never-viewed (0) watermark", () => {
+ // A row already in memory (e.g. a just-finished pipe run) that has
+ // never been viewed: lastViewedAt is the 0 sentinel, so it's unread.
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", lastContentAt: 200, lastViewedAt: 0 }),
+ );
+ expect(useChatStore.getState().sessions.A.unread).toBe(true);
+
+ // A disk record for the same id arrives via a later hydrate pass. The
+ // merge must keep lastViewedAt as 0 (not collapse it to undefined) so
+ // unread stays computed rather than falling back to the stale flag.
+ useChatStore.getState().actions.hydrateFromDisk([
+ sessionRecordFromMeta({
+ id: "A",
+ title: "A",
+ createdAt: 100,
+ updatedAt: 200,
+ messageCount: 2,
+ pinned: false,
+ hidden: false,
+ lastContentAt: 200,
+ lastViewedAt: 0,
+ kind: "chat",
+ }),
+ ]);
+
+ const session = useChatStore.getState().sessions.A;
+ expect(session.lastViewedAt).toBe(0);
+ expect(session.unread).toBe(true);
});
});
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/parallel-chat.integration.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/parallel-chat.integration.test.ts
index 5262f34f1..2b88366e5 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/parallel-chat.integration.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/parallel-chat.integration.test.ts
@@ -74,7 +74,7 @@ function seed(id: string) {
}
beforeEach(() => {
- useChatStore.setState({ sessions: {}, currentId: null });
+ useChatStore.setState({ sessions: {}, currentId: null, panelSessionId: null });
});
describe("parallel chat: Louis's repro at the data layer", () => {
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts
index 75f1cd0c5..b324462eb 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
@@ -132,6 +132,37 @@ describe("pi-event-router: status mirroring for backgrounded sessions", () => {
expect(useChatStore.getState().sessions.fresh).toBeDefined();
expect(useChatStore.getState().sessions.fresh.status).toBe("streaming");
});
+
+ it("marks a switched-away session unread when new assistant text arrives", async () => {
+ seed("A", {
+ lastViewedAt: 100,
+ streamingMessageId: "msg-1",
+ streamingText: "",
+ contentBlocks: [],
+ messages: [
+ {
+ id: "msg-1",
+ role: "assistant",
+ content: "",
+ contentBlocks: [],
+ timestamp: 100,
+ },
+ ],
+ messageCount: 1,
+ });
+ useChatStore.setState({ currentId: "B" });
+
+ await handlePiEvent(
+ piEvt("A", {
+ type: "message_update",
+ assistantMessageEvent: { type: "text_delta", delta: "hello" },
+ }),
+ );
+
+ const session = useChatStore.getState().sessions.A;
+ expect(session.lastContentAt).toBeGreaterThan(100);
+ expect(session.unread).toBe(true);
+ });
});
describe("pi-event-router: browser state preservation", () => {
@@ -172,6 +203,35 @@ describe("pi-event-router: browser state preservation", () => {
}),
);
});
+
+ it("persists never-viewed background chats with a zero lastViewedAt watermark", async () => {
+ seed("A", {
+ messages: [
+ {
+ id: "u1",
+ role: "user",
+ content: "hello",
+ timestamp: 1,
+ },
+ ],
+ messageCount: 1,
+ isLoading: true,
+ isStreaming: true,
+ lastContentAt: 2_000,
+ });
+ useChatStore.setState({ currentId: "B" });
+
+ handleTerminated({ sessionId: "A", exitCode: 0 } as any);
+ await flushPendingSaves();
+
+ expect(saveConversationFile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "A",
+ lastContentAt: 2_000,
+ lastViewedAt: 0,
+ }),
+ );
+ });
});
describe("pi-event-router: background content accumulation (the parallel-chat repro)", () => {
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/save-conversation-race.test.tsx b/apps/screenpipe-app-tauri/lib/__tests__/save-conversation-race.test.tsx
index eddaf5c4f..c7a769623 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/save-conversation-race.test.tsx
+++ b/apps/screenpipe-app-tauri/lib/__tests__/save-conversation-race.test.tsx
@@ -55,6 +55,7 @@ const saveCalls: Array<{
messages: any[];
browserState?: any;
lastUserMessageAt?: number;
+ lastViewedAt?: number;
}> = [];
vi.mock("@/lib/chat-storage", () => ({
@@ -64,6 +65,7 @@ vi.mock("@/lib/chat-storage", () => ({
messages: conv.messages,
browserState: conv.browserState,
lastUserMessageAt: conv.lastUserMessageAt,
+ lastViewedAt: conv.lastViewedAt,
});
}),
loadConversationFile: vi.fn(async () => null),
@@ -97,6 +99,7 @@ vi.mock("@/lib/hooks/use-settings", () => ({
// ── Import under test (after mocks) ───────────────────────────────────
import { useChatConversations } from "../../components/hooks/use-chat-conversations";
import { loadConversationFile } from "@/lib/chat-storage";
+import { useChatStore } from "../stores/chat-store";
// Test harness: thin component that wires up the refs/state the hook
// needs, then exposes `saveConversation` for the test to call. Mirrors
@@ -148,6 +151,7 @@ beforeEach(() => {
saveCalls.length = 0;
deleteCachedBrowserState("chat-A");
deleteCachedBrowserState("fresh-sid");
+ useChatStore.setState({ sessions: {}, currentId: null, panelSessionId: null });
});
afterEach(() => {
@@ -277,4 +281,40 @@ describe("saveConversation race (PR #3600 / issue #3636 candidate)", () => {
expect(saveCalls).toHaveLength(1);
expect(saveCalls[0].lastUserMessageAt).toBe(9_000);
});
+
+ it("persists the store's lastViewedAt watermark on save", async () => {
+ useChatStore.getState().actions.upsert({
+ id: "chat-A",
+ title: "chat-A",
+ preview: "",
+ status: "idle",
+ messageCount: 1,
+ createdAt: 1,
+ updatedAt: 2,
+ pinned: false,
+ unread: false,
+ lastContentAt: 9_000,
+ lastViewedAt: 8_500,
+ });
+
+ const messages = [
+ { id: "u1", role: "user" as const, content: "hello", timestamp: 1_000 },
+ { id: "a1", role: "assistant" as const, content: "reply", timestamp: 2_000 },
+ ];
+
+ const { result } = renderHook(() =>
+ useHarness({
+ initialMessages: messages,
+ initialConversationId: "chat-A",
+ initialPiSessionId: "chat-A",
+ }),
+ );
+
+ await act(async () => {
+ await result.current.hook.saveConversation(messages);
+ });
+
+ expect(saveCalls).toHaveLength(1);
+ expect(saveCalls[0].lastViewedAt).toBe(8_500);
+ });
});
diff --git a/apps/screenpipe-app-tauri/lib/chat-storage.ts b/apps/screenpipe-app-tauri/lib/chat-storage.ts
index eef93e4dd..6b1f58fcd 100644
--- a/apps/screenpipe-app-tauri/lib/chat-storage.ts
+++ b/apps/screenpipe-app-tauri/lib/chat-storage.ts
@@ -179,6 +179,12 @@ export interface ConversationMeta {
* sidebar sort order. Falls back to derive-from-messages on legacy
* files that pre-date the field. */
lastUserMessageAt?: number;
+ /** ms since epoch of the most recent actual message append (user or
+ * assistant). Drives unread detection — immune to non-content writes. */
+ lastContentAt?: number;
+ /** ms since epoch of the most recent time this chat was actually opened.
+ * A value of `0` means "never viewed" for persisted unread restore. */
+ lastViewedAt?: number;
/** Conversation kind — `chat` for chats, `pipe-watch` / `pipe-run` for
* pipe sessions. Sidebar uses this to split rows into separate
* sections. Older files default to `chat`. */
@@ -297,6 +303,15 @@ export function conversationMetaFromJson(conv: any): ConversationMeta | null {
? persistedLastUserMessageAt
: Math.max(persistedLastUserMessageAt ?? 0, newestUserMessageAt);
+ // lastContentAt: prefer the persisted field; fall back to
+ // lastUserMessageAt for older on-disk files that predate it.
+ const lastContentAt =
+ typeof conv.lastContentAt === "number"
+ ? conv.lastContentAt
+ : lastUserMessageAt ?? undefined;
+ const lastViewedAt =
+ typeof conv.lastViewedAt === "number" ? conv.lastViewedAt : undefined;
+
return {
id: conv.id,
title: typeof conv.title === "string" ? conv.title : "untitled",
@@ -306,6 +321,8 @@ export function conversationMetaFromJson(conv: any): ConversationMeta | null {
pinned: conv.pinned === true,
hidden: conv.hidden === true,
lastUserMessageAt,
+ lastContentAt,
+ lastViewedAt,
kind: conv.kind ?? "chat",
pipeContext: conv.pipeContext,
titleSource: conv.titleSource,
@@ -533,7 +550,7 @@ export async function searchConversations(
*/
export async function updateConversationFlags(
id: string,
- patch: Partial<Pick<ChatConversation, "pinned" | "hidden" | "title" | "titleSource" | "browserState">>
+ patch: Partial<Pick<ChatConversation, "pinned" | "hidden" | "title" | "titleSource" | "browserState" | "lastViewedAt">>
): Promise<void> {
const conv = await loadConversationFile(id);
if (!conv) return;
diff --git a/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-run-recorder.test.ts b/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-run-recorder.test.ts
index 0f9e2cd76..61a7747aa 100644
--- a/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-run-recorder.test.ts
+++ b/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-run-recorder.test.ts
@@ -86,6 +86,8 @@ describe("pipe-run-recorder: finalize on terminal event", () => {
expect.objectContaining({ pipeName: "my-pipe", executionId: 42 }),
);
expect(arg.title).toBe("my-pipe #42");
+ expect(arg.lastContentAt).toBe(arg.updatedAt);
+ expect(arg.lastViewedAt).toBe(0);
expect(arg.messages.some((m: any) => m.role === "assistant" && m.content?.includes("result"))).toBe(true);
});
diff --git a/apps/screenpipe-app-tauri/lib/events/pipe-run-recorder.ts b/apps/screenpipe-app-tauri/lib/events/pipe-run-recorder.ts
index 9c7ece1cb..98bdc9028 100644
--- a/apps/screenpipe-app-tauri/lib/events/pipe-run-recorder.ts
+++ b/apps/screenpipe-app-tauri/lib/events/pipe-run-recorder.ts
@@ -208,6 +208,9 @@ async function finalizeBuffer(sid: string, buf: PipeRunBuffer): Promise<void> {
messages,
createdAt: buf.firstEventAt,
updatedAt: buf.lastEventAt,
+ // Unwatched completed pipe runs should surface as unread until opened.
+ lastContentAt: buf.lastEventAt,
+ lastViewedAt: 0,
kind: "pipe-run",
pipeContext: {
pipeName: buf.pipeName,
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 4aad55610..fa9b95919 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -159,6 +159,12 @@ export interface ChatConversation {
* sidebar sort order. Persisted so that order survives app restart;
* derived from messages on first hydration if not set on disk yet. */
lastUserMessageAt?: number;
+ /** ms since epoch of the most recent actual message append (user or
+ * assistant). Drives unread detection — immune to non-content writes. */
+ lastContentAt?: number;
+ /** ms since epoch of the most recent time this chat was actually opened.
+ * A value of `0` means "never viewed" for persisted unread restore. */
+ lastViewedAt?: number;
/** Conversation type — defaults to "chat" when missing (back-compat
* with older on-disk files). See `ConversationKind`. */
kind?: ConversationKind;
diff --git a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
index 372a049f8..2e1e98b40 100644
--- a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
@@ -101,6 +101,10 @@ export interface SessionRecord {
* This matches how email clients show inboxes — bumped on action,
* stable while you're reading. */
lastUserMessageAt?: number;
+ /** ms since epoch of the most recent actual message append (user or
+ * assistant). Drives unread detection — immune to non-content writes
+ * like browser state, status patches, or process-exit saves. */
+ lastContentAt?: number;
/** User pinned this conversation to the top of the sidebar. */
pinned: boolean;
/** Archived conversation hidden from recents. */
@@ -214,11 +218,6 @@ interface ChatStoreActions {
setPanelSession: (id: string | null) => void;
/** Toggle the pinned state. */
togglePinned: (id: string) => void;
- /** Mark a session as having new unseen assistant activity. The router
- * calls this when content lands for a session other than the current
- * 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` /
@@ -293,6 +292,39 @@ interface ChatStoreActions {
export type ChatStore = ChatStoreState & { actions: ChatStoreActions };
type ChatSessionsState = Pick<ChatStoreState, "sessions">;
+export function isSessionForeground(
+ state: Pick<ChatStoreState, "currentId" | "panelSessionId">,
+ id: string,
+): boolean {
+ return state.currentId === id || state.panelSessionId === id;
+}
+
+/** Compute unread from timestamps — immune to non-content writes.
+ * A session is unread when its most recent real message append happened
+ * AFTER the last time the user viewed it. Falls back to
+ * lastUserMessageAt for rows hydrated from older on-disk files that
+ * predate the lastContentAt field. */
+function isUnread(s: SessionRecord): boolean {
+ const content = s.lastContentAt ?? s.lastUserMessageAt ?? 0;
+ return content > (s.lastViewedAt ?? 0);
+}
+
+function restoreUnread(
+ existing: SessionRecord | undefined,
+ merged: SessionRecord,
+): boolean {
+ if (typeof merged.lastViewedAt === "number") return isUnread(merged);
+ return existing?.unread ?? false;
+}
+
+export function getPersistedViewedAt(
+ session: Pick<SessionRecord, "lastViewedAt" | "lastContentAt"> | undefined,
+): number | undefined {
+ if (!session) return undefined;
+ if (typeof session.lastViewedAt === "number") return session.lastViewedAt;
+ return typeof session.lastContentAt === "number" ? 0 : undefined;
+}
+
export const useChatStore = create<ChatStore>((set) => ({
sessions: {},
diskHydrated: false,
@@ -308,19 +340,42 @@ export const useChatStore = create<ChatStore>((set) => ({
const next: Record<string, SessionRecord> = { ...s.sessions };
for (const r of records) {
const existing = next[r.id];
- next[r.id] = existing
- ? {
- ...existing,
- title: r.title,
- titleSource: r.titleSource ?? existing.titleSource,
- preview: r.preview,
- messageCount: r.messageCount,
- pinned: existing.pinned || r.pinned,
- hidden: existing.hidden ?? r.hidden ?? false,
- // updatedAt: take the larger so memory doesn't get clobbered
- updatedAt: Math.max(existing.updatedAt, r.updatedAt),
- }
- : r;
+ if (!existing) {
+ next[r.id] = r;
+ continue;
+ }
+ const merged: SessionRecord = {
+ ...existing,
+ title: r.title,
+ titleSource: r.titleSource ?? existing.titleSource,
+ preview: r.preview,
+ messageCount: r.messageCount,
+ pinned: existing.pinned || r.pinned,
+ hidden: existing.hidden ?? r.hidden ?? false,
+ // updatedAt: take the larger so memory doesn't get clobbered
+ updatedAt: Math.max(existing.updatedAt, r.updatedAt),
+ lastUserMessageAt: Math.max(
+ existing.lastUserMessageAt ?? 0,
+ r.lastUserMessageAt ?? 0,
+ ) || undefined,
+ lastContentAt: Math.max(
+ existing.lastContentAt ?? 0,
+ r.lastContentAt ?? 0,
+ ) || undefined,
+ // lastViewedAt: 0 is the "never viewed" sentinel, so it must NOT
+ // be collapsed to undefined — that would force restoreUnread onto
+ // its fallback instead of computing the real (unread) state.
+ lastViewedAt:
+ typeof existing.lastViewedAt === "number" ||
+ typeof r.lastViewedAt === "number"
+ ? Math.max(existing.lastViewedAt ?? 0, r.lastViewedAt ?? 0)
+ : undefined,
+ kind: existing.kind ?? r.kind,
+ pipeContext: existing.pipeContext ?? r.pipeContext,
+ dedupKey: existing.dedupKey ?? r.dedupKey,
+ };
+ merged.unread = restoreUnread(existing, merged);
+ next[r.id] = merged;
}
return { sessions: next, diskHydrated: true };
}),
@@ -337,6 +392,8 @@ export const useChatStore = create<ChatStore>((set) => ({
const merged: SessionRecord = existing
? { ...existing, ...record, createdAt: existing.createdAt }
: record;
+ // Recompute unread from timestamps so it stays consistent.
+ merged.unread = isUnread(merged);
return { sessions: { ...s.sessions, [record.id]: merged } };
}),
@@ -344,8 +401,13 @@ export const useChatStore = create<ChatStore>((set) => ({
set((s) => {
const existing = s.sessions[id];
if (!existing) return {};
+ const patched = { ...existing, ...partial };
+ // Recompute unread when any timestamp that drives it changed.
+ if ("lastContentAt" in partial || "lastViewedAt" in partial) {
+ patched.unread = isUnread(patched);
+ }
return {
- sessions: { ...s.sessions, [id]: { ...existing, ...partial } },
+ sessions: { ...s.sessions, [id]: patched },
};
}),
@@ -363,13 +425,13 @@ export const useChatStore = create<ChatStore>((set) => ({
setCurrent: (id) =>
set((s) => {
const viewedAt = Date.now();
- // Viewing a session counts as reading it — clear the unread flag
- // for the new current. Same atomic update so the row's unread
- // state can't transiently flicker between the setCurrent call and
- // a follow-up markRead call.
+ // Viewing a session counts as reading it — lastViewedAt >= any
+ // lastContentAt means isUnread() returns false. Same atomic update
+ // so the row's unread state can't transiently flicker.
if (id && s.sessions[id]) {
return {
currentId: id,
+ panelSessionId: id,
sessions: {
...s.sessions,
[id]: { ...s.sessions[id], unread: false, lastViewedAt: viewedAt },
@@ -393,24 +455,6 @@ export const useChatStore = create<ChatStore>((set) => ({
};
}),
- markUnread: (id) =>
- set((s) => {
- const existing = s.sessions[id];
- if (!existing) return {};
- // Can't be unread for the chat the user is actively looking at.
- if (s.currentId === id) return {};
- // Also a no-op when the chat is still loaded in the (display:none)
- // panel — the user already read what's there; trailing deltas that
- // arrive after they navigate to Settings/Pipes/Memories/Timeline
- // shouldn't re-light the unread dot. The panel keeps streaming in
- // the background and panelSessionId tracks its current conversation.
- if (s.panelSessionId === id) return {};
- if (existing.unread) return {}; // already unread, avoid re-render churn
- return {
- sessions: { ...s.sessions, [id]: { ...existing, unread: true } },
- };
- }),
-
setMessages: (id, messages) =>
set((s) => {
const existing = s.sessions[id];
@@ -439,16 +483,24 @@ export const useChatStore = create<ChatStore>((set) => ({
const existing = s.sessions[id];
if (!existing) return {};
const messages = [...(existing.messages ?? []), message];
+ const now = Date.now();
+ const patched = {
+ ...existing,
+ messages,
+ messageCount: messages.length,
+ preview: preview ?? existing.preview,
+ updatedAt: now,
+ lastContentAt: now,
+ // Foreground ownership includes the mounted panel session even
+ // when the home section is hidden, so trailing content there
+ // should stay read.
+ ...(isSessionForeground(s, id) ? { lastViewedAt: now } : {}),
+ };
+ patched.unread = isUnread(patched);
return {
sessions: {
...s.sessions,
- [id]: {
- ...existing,
- messages,
- messageCount: messages.length,
- preview: preview ?? existing.preview,
- updatedAt: Date.now(),
- },
+ [id]: patched,
},
};
}),
@@ -627,10 +679,10 @@ export const useChatActions = () => useChatStore((s) => s.actions);
/** Build a fresh SessionRecord from on-disk metadata. Used by both the
* boot-time hydrate path and the pipe-run recorder so the sidebar sees
* identically-shaped rows whether they were loaded at startup or upserted
- * the moment a pipe finishes. unread is false: persisted-from-disk rows
- * aren't user-actionable in the inbox sense. */
+ * the moment a pipe finishes. Legacy rows that predate `lastViewedAt`
+ * restore as read because they have no persisted unread watermark. */
export function sessionRecordFromMeta(m: ConversationMeta): SessionRecord {
- return {
+ const record: SessionRecord = {
id: m.id,
title: m.title || "untitled",
titleSource: m.titleSource,
@@ -642,11 +694,17 @@ export function sessionRecordFromMeta(m: ConversationMeta): SessionRecord {
pinned: m.pinned,
unread: false,
lastUserMessageAt: m.lastUserMessageAt,
+ lastContentAt: m.lastContentAt,
+ lastViewedAt: m.lastViewedAt,
kind: m.kind,
pipeContext: m.pipeContext,
dedupKey: m.dedupKey,
presetId: m.presetId,
};
+ if (typeof m.lastViewedAt === "number") {
+ record.unread = isUnread(record);
+ }
+ return record;
}
/**
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 4b5152484..2bec221fc 100644
--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
@@ -71,7 +71,9 @@ import {
import { deriveFallbackConversationTitle } from "@/lib/utils/chat-title";
import { isInternalTitleSession } from "@/lib/utils/internal-session";
import {
+ getPersistedViewedAt,
useChatStore,
+ isSessionForeground,
sessionRecordFromMeta,
type SessionStatus,
type SessionRecord,
@@ -216,6 +218,7 @@ export async function handlePiEvent(envelope: AgentEventEnvelope) {
// Handles the case where Pi was started outside the chat-storage flow
// (e.g. resumed from disk before we hydrated).
if (!existing) {
+ const now = Date.now();
store.actions.upsert({
id: sid,
title: "untitled",
@@ -223,13 +226,13 @@ export async function handlePiEvent(envelope: AgentEventEnvelope) {
status: nextStatus ?? "streaming",
lastError: err ?? undefined,
messageCount: 0,
- createdAt: Date.now(),
- updatedAt: Date.now(),
+ createdAt: now,
+ updatedAt: now,
pinned: false,
- // First-touch session is unread unless the user is already viewing
- // it (this is also how external triggers — chat-prefill, pipe
- // events — surface in the sidebar).
- unread: store.currentId !== sid,
+ unread: false,
+ // Set lastContentAt on first touch only when there's actual content.
+ // isUnread() in the store will compute the correct unread boolean.
+ ...(snippet ? { lastContentAt: now } : {}),
});
if (snippet) previewLastEmittedAt.set(sid, Date.now());
return;
@@ -250,6 +253,9 @@ export async function handlePiEvent(envelope: AgentEventEnvelope) {
const patch: Partial<SessionRecord> = { updatedAt: Date.now() };
if (nextStatus) patch.status = nextStatus;
if (writePreview) patch.preview = snippet!;
+ // Background assistant text should mark the session as having new
+ // unseen content once the user has switched away.
+ if (snippet && !isSessionForeground(store, sid)) patch.lastContentAt = Date.now();
if (nextStatus === "error" && err) patch.lastError = err;
if (nextStatus && nextStatus !== "error") patch.lastError = undefined;
@@ -269,12 +275,6 @@ export async function handlePiEvent(envelope: AgentEventEnvelope) {
}
store.actions.patch(sid, patch);
-
- // Mark as unread if real assistant content arrived for a session that
- // is NOT the currently-viewed one. The store's markUnread is a no-op
- // when sid === currentId, so this is safe to call unconditionally on
- // any event that produced a snippet.
- if (snippet) store.actions.markUnread(sid);
}
function handleSessionEvicted(payload: AgentSessionEvictedPayload) {
@@ -752,6 +752,7 @@ async function persistBackgroundSession(sid: string): Promise<void> {
// Background saves use fallback titles; AI titles generated in foreground
const title = existing?.title || derivedTitle;
+ const storeSession = useChatStore.getState().sessions[sid];
let computedLastUserMessageAt: number | undefined;
for (const message of messages as any[]) {
if (message?.role !== "user" || typeof message.timestamp !== "number") continue;
@@ -762,14 +763,27 @@ async function persistBackgroundSession(sid: string): Promise<void> {
const lastUserMessageAt =
computedLastUserMessageAt ??
- useChatStore.getState().sessions[sid]?.lastUserMessageAt ??
+ storeSession?.lastUserMessageAt ??
existing?.lastUserMessageAt;
+ const lastContentAt =
+ storeSession?.lastContentAt ??
+ existing?.lastContentAt;
+ const lastViewedAt =
+ getPersistedViewedAt(storeSession) ??
+ (typeof existing?.lastViewedAt === "number"
+ ? existing.lastViewedAt
+ : lastContentAt
+ ? 0
+ : undefined);
+
const conv: ChatConversation = {
id: sid,
title,
...(existing?.titleSource ? { titleSource: existing.titleSource } : {}),
...(lastUserMessageAt ? { lastUserMessageAt } : {}),
+ ...(lastContentAt ? { lastContentAt } : {}),
+ ...(typeof lastViewedAt === "number" ? { lastViewedAt } : {}),
// 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.