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): repair recents age from latest user message timestamp (#3994)

Harsh Kumarfa7c1db8d6d9
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 a3598e708..f4291c584 100644
--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
@@ -124,6 +124,15 @@ interface SaveConversationOptions {
syncActiveConversation?: boolean;
}
+function newestUserMessageTimestamp(messages: Message[]): number | undefined {
+ let latest: number | undefined;
+ for (const message of messages) {
+ if (message.role !== "user" || typeof message.timestamp !== "number") continue;
+ if (latest == null || message.timestamp > latest) latest = message.timestamp;
+ }
+ return latest;
+}
+
/** Module-scope guard for AI title generation — survives component remounts
* and is shared across all hook instances so two StandaloneChat mounts
* (chat window + home page) never both fire for the same conversation.
@@ -200,16 +209,11 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
if (historySearch.trim()) return;
const msgs = Array.isArray(conversation.messages) ? conversation.messages : [];
- let lastUserMessageAt = conversation.lastUserMessageAt;
- if (lastUserMessageAt == null) {
- for (const m of msgs) {
- if (m?.role === "user" && typeof m.timestamp === "number") {
- if (lastUserMessageAt == null || m.timestamp > lastUserMessageAt) {
- lastUserMessageAt = m.timestamp;
- }
- }
- }
- }
+ const computedLastUserMessageAt = newestUserMessageTimestamp(msgs);
+ const lastUserMessageAt =
+ computedLastUserMessageAt == null
+ ? conversation.lastUserMessageAt
+ : Math.max(conversation.lastUserMessageAt ?? 0, computedLastUserMessageAt);
const meta: ConversationMeta = {
id: conversation.id,
@@ -512,6 +516,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
));
const fallbackTitle = deriveFallbackConversationTitle(firstUserMsg);
const existingTitle = existing?.title?.trim() || null;
+ const computedLastUserMessageAt = newestUserMessageTimestamp(msgs);
const hasValidPreset =
selectedPreset &&
@@ -715,15 +720,18 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
...(browserState ? { browserState } : {}),
...(existing?.pinned ? { pinned: existing.pinned } : {}),
...(existing?.hidden ? { hidden: existing.hidden } : {}),
- // Preserve sort key across reloads. Source of truth: the in-memory
- // chat-store, which is bumped exactly once per user-send.
+ // Preserve sort key across reloads. Source of truth: the transcript
+ // being saved, then the in-memory chat-store, then older disk state.
+ // This prevents a stale persisted/store value from keeping an old
+ // sidebar age after a fresh user message is already in `msgs`.
...(await (async () => {
const { useChatStore } = await import("@/lib/stores/chat-store");
const sid = piSessionIdRef.current;
const fromStore = sid
? useChatStore.getState().sessions[sid]?.lastUserMessageAt
: undefined;
- const lastUserMessageAt = fromStore ?? existing?.lastUserMessageAt;
+ const lastUserMessageAt =
+ computedLastUserMessageAt ?? fromStore ?? existing?.lastUserMessageAt;
return lastUserMessageAt ? { lastUserMessageAt } : {};
})()),
};
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 8d130eefd..eb52630b2 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts
@@ -47,6 +47,7 @@ import {
CONVERSATION_DEDUP_WINDOW_MS,
__resetChatStorageCachesForTests,
conversationDedupKey,
+ conversationMetaFromJson,
dedupeConversationMetas,
listConversations,
searchConversations,
@@ -179,6 +180,38 @@ describe("chat-storage bounded history", () => {
expect(rows.map((row) => row.id)).toEqual(["visible-old"]);
});
+
+ it("repairs stale persisted lastUserMessageAt from newer user-message timestamps", () => {
+ const meta = conversationMetaFromJson({
+ id: "stale-last-user",
+ title: "stale-last-user",
+ createdAt: 100,
+ updatedAt: 5_000,
+ lastUserMessageAt: 1_000,
+ messages: [
+ {
+ id: "u1",
+ role: "user",
+ content: "first",
+ timestamp: 1_000,
+ },
+ {
+ id: "a1",
+ role: "assistant",
+ content: "reply",
+ timestamp: 1_500,
+ },
+ {
+ id: "u2",
+ role: "user",
+ content: "latest",
+ timestamp: 4_500,
+ },
+ ],
+ });
+
+ expect(meta?.lastUserMessageAt).toBe(4_500);
+ });
});
function meta(
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 04d9bf299..eddaf5c4f 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
@@ -50,11 +50,21 @@ import {
// ── Mocks ──────────────────────────────────────────────────────────────
// Capture every disk write so the test can assert (id, messages) pairs.
-const saveCalls: Array<{ id: string; messages: any[]; browserState?: any }> = [];
+const saveCalls: Array<{
+ id: string;
+ messages: any[];
+ browserState?: any;
+ lastUserMessageAt?: number;
+}> = [];
vi.mock("@/lib/chat-storage", () => ({
saveConversationFile: vi.fn(async (conv: any) => {
- saveCalls.push({ id: conv.id, messages: conv.messages, browserState: conv.browserState });
+ saveCalls.push({
+ id: conv.id,
+ messages: conv.messages,
+ browserState: conv.browserState,
+ lastUserMessageAt: conv.lastUserMessageAt,
+ });
}),
loadConversationFile: vi.fn(async () => null),
deleteConversationFile: vi.fn(async () => undefined),
@@ -86,6 +96,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";
// Test harness: thin component that wires up the refs/state the hook
// needs, then exposes `saveConversation` for the test to call. Mirrors
@@ -234,4 +245,36 @@ describe("saveConversation race (PR #3600 / issue #3636 candidate)", () => {
collapsed: true,
});
});
+
+ it("recomputes lastUserMessageAt from the outgoing transcript instead of preserving a stale saved value", async () => {
+ vi.mocked(loadConversationFile).mockResolvedValueOnce({
+ id: "chat-A",
+ title: "chat-A",
+ createdAt: 1,
+ updatedAt: 2,
+ lastUserMessageAt: 1_000,
+ messages: [],
+ } as any);
+
+ const messages = [
+ { id: "u1", role: "user" as const, content: "old", timestamp: 1_000 },
+ { id: "a1", role: "assistant" as const, content: "reply", timestamp: 1_200 },
+ { id: "u2", role: "user" as const, content: "new", timestamp: 9_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].lastUserMessageAt).toBe(9_000);
+ });
});
diff --git a/apps/screenpipe-app-tauri/lib/chat-storage.ts b/apps/screenpipe-app-tauri/lib/chat-storage.ts
index 19fba25b1..8aec9d6fb 100644
--- a/apps/screenpipe-app-tauri/lib/chat-storage.ts
+++ b/apps/screenpipe-app-tauri/lib/chat-storage.ts
@@ -279,16 +279,20 @@ export function conversationMetaFromJson(conv: any): ConversationMeta | null {
if (!conv || typeof conv.id !== "string") return null;
const messages = Array.isArray(conv.messages) ? conv.messages : [];
- let lastUserMessageAt = conv.lastUserMessageAt;
- if (lastUserMessageAt == null) {
- for (const m of messages) {
- if (m?.role === "user" && typeof m.timestamp === "number") {
- if (lastUserMessageAt == null || m.timestamp > lastUserMessageAt) {
- lastUserMessageAt = m.timestamp;
- }
+ let newestUserMessageAt: number | undefined;
+ for (const m of messages) {
+ if (m?.role === "user" && typeof m.timestamp === "number") {
+ if (newestUserMessageAt == null || m.timestamp > newestUserMessageAt) {
+ newestUserMessageAt = m.timestamp;
}
}
}
+ const persistedLastUserMessageAt =
+ typeof conv.lastUserMessageAt === "number" ? conv.lastUserMessageAt : undefined;
+ const lastUserMessageAt =
+ newestUserMessageAt == null
+ ? persistedLastUserMessageAt
+ : Math.max(persistedLastUserMessageAt ?? 0, newestUserMessageAt);
return {
id: conv.id,
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 d706a436f..7c6577be6 100644
--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
@@ -748,7 +748,16 @@ async function persistBackgroundSession(sid: string): Promise<void> {
// Background saves use fallback titles; AI titles generated in foreground
const title = existing?.title || derivedTitle;
+ let computedLastUserMessageAt: number | undefined;
+ for (const message of messages as any[]) {
+ if (message?.role !== "user" || typeof message.timestamp !== "number") continue;
+ if (computedLastUserMessageAt == null || message.timestamp > computedLastUserMessageAt) {
+ computedLastUserMessageAt = message.timestamp;
+ }
+ }
+
const lastUserMessageAt =
+ computedLastUserMessageAt ??
useChatStore.getState().sessions[sid]?.lastUserMessageAt ??
existing?.lastUserMessageAt;