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
Optimize chat history refresh
Louis Beaumontddbf0c4ade1e
diff --git a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.tsindex 865bc278c..206b35e10 100644--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts@@ -18,8 +18,11 @@ import { ChatConversation } from "@/lib/hooks/use-settings";import { commands } from "@/lib/utils/tauri";import {saveConversationFile,+ loadConversationFile,deleteConversationFile,+ invalidateConversationListCache,listConversations,+ markConversationFileChanged,searchConversations,migrateFromStoreBin,CHAT_HISTORY_INITIAL_LIMIT,@@ -76,6 +79,7 @@ interface UseChatConversationsOpts {setIsStreaming: Dispatch<SetStateAction<boolean>>;setPastedImages: Dispatch<SetStateAction<string[]>>;settings: any;+ inlineHistoryEnabled?: boolean;}interface SaveConversationOptions {@@ -103,6 +107,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {setIsStreaming,setPastedImages,settings,+ inlineHistoryEnabled = true,} = opts;const [showHistory, setShowHistoryRaw] = useState(() => {@@ -133,8 +138,58 @@ export function useChatConversations(opts: UseChatConversationsOpts) {return q ? searchConversations(q, options) : listConversations(options);}, []);+ const upsertFileConversationMeta = useCallback((conversation: ChatConversation) => {+ 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 meta: ConversationMeta = {+ id: conversation.id,+ title: typeof conversation.title === "string" ? conversation.title : "untitled",+ createdAt: typeof conversation.createdAt === "number" ? conversation.createdAt : 0,+ updatedAt: typeof conversation.updatedAt === "number" ? conversation.updatedAt : 0,+ messageCount: msgs.length,+ pinned: conversation.pinned === true,+ hidden: conversation.hidden === true,+ lastUserMessageAt,+ kind: conversation.kind ?? "chat",+ pipeContext: conversation.pipeContext,+ };++ setFileConversations((prev) => {+ const existing = prev.find((c) => c.id === meta.id);+ const nextMeta = existing+ ? { ...existing, ...meta, pinned: existing.pinned || meta.pinned }+ : meta;+ const without = prev.filter((c) => c.id !== meta.id);+ const next = nextMeta.hidden ? without : [nextMeta, ...without];+ return next+ .sort((a, b) => b.updatedAt - a.updatedAt)+ .slice(0, CHAT_HISTORY_INITIAL_LIMIT);+ });+ lastHistoryQueryRef.current = "";+ }, [historySearch]);+useEffect(() => {- if (migrationDoneRef.current) return;+ if (!inlineHistoryEnabled || !showHistory) {+ setHistoryReady(false);+ return;+ }++ if (migrationDoneRef.current) {+ setHistoryReady(true);+ return;+ }migrationDoneRef.current = true;(async () => {try {@@ -149,9 +204,10 @@ export function useChatConversations(opts: UseChatConversationsOpts) {setHistoryReady(true);}})();- }, [loadConversationMetas]);+ }, [inlineHistoryEnabled, loadConversationMetas, showHistory]);useEffect(() => {+ if (!inlineHistoryEnabled || !showHistory) return;if (!historyReady) return;const q = historySearch.trim();if (lastHistoryQueryRef.current === q) return;@@ -172,14 +228,15 @@ export function useChatConversations(opts: UseChatConversationsOpts) {}, q ? 200 : 0);return () => clearTimeout(timer);- }, [historyReady, historySearch, loadConversationMetas]);+ }, [historyReady, historySearch, inlineHistoryEnabled, loadConversationMetas, showHistory]);const refreshFileConversations = useCallback(async () => {+ if (!inlineHistoryEnabled || !showHistory) return;const q = historySearch.trim();const convs = await loadConversationMetas(q);setFileConversations(convs);lastHistoryQueryRef.current = q;- }, [historySearch, loadConversationMetas]);+ }, [historySearch, inlineHistoryEnabled, loadConversationMetas, showHistory]);const scheduleHistoryRefresh = useCallback((delayMs = 80) => {if (historyRefreshTimerRef.current) {@@ -215,6 +272,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {if (cancelled) return;const id = event.payload?.id;if (!id) return;+ invalidateConversationListCache();setFileConversations((prev) => prev.filter((c) => c.id !== id));if (conversationId === id) {setMessages([]);@@ -231,6 +289,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {if (cancelled) return;const { id, hidden } = event.payload ?? {};if (!id) return;+ invalidateConversationListCache();if (hidden) {setFileConversations((prev) => prev.filter((c) => c.id !== id));}@@ -241,11 +300,20 @@ export function useChatConversations(opts: UseChatConversationsOpts) {const unlistenSaved = await listen<{ id: string; title?: string }>("chat-conversation-saved",- (event) => {+ async (event) => {if (cancelled) return;const { id } = event.payload ?? {};if (!id) return;- scheduleHistoryRefresh();+ if (id === conversationId || id === piSessionIdRef.current) return;+ try {+ await markConversationFileChanged(id);+ const conv = await loadConversationFile(id);+ if (!cancelled && conv) {+ upsertFileConversationMeta(conv);+ }+ } catch {+ // ignore: a later explicit history refresh can repair the list+ }},);unlistenFns.push(unlistenSaved);@@ -257,49 +325,14 @@ export function useChatConversations(opts: UseChatConversationsOpts) {cancelled = true;for (const unlisten of unlistenFns) unlisten();};- }, [conversationId, scheduleHistoryRefresh, setConversationId, setMessages]);-- const upsertFileConversationMeta = (conversation: ChatConversation) => {- 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 meta: ConversationMeta = {- id: conversation.id,- title: typeof conversation.title === "string" ? conversation.title : "untitled",- createdAt: typeof conversation.createdAt === "number" ? conversation.createdAt : 0,- updatedAt: typeof conversation.updatedAt === "number" ? conversation.updatedAt : 0,- messageCount: msgs.length,- pinned: conversation.pinned === true,- hidden: conversation.hidden === true,- lastUserMessageAt,- kind: conversation.kind ?? "chat",- pipeContext: conversation.pipeContext,- };-- setFileConversations((prev) => {- const existing = prev.find((c) => c.id === meta.id);- const nextMeta = existing- ? { ...existing, ...meta, pinned: existing.pinned || meta.pinned }- : meta;- const without = prev.filter((c) => c.id !== meta.id);- const next = nextMeta.hidden ? without : [nextMeta, ...without];- return next- .sort((a, b) => b.updatedAt - a.updatedAt)- .slice(0, CHAT_HISTORY_INITIAL_LIMIT);- });- lastHistoryQueryRef.current = "";- };+ }, [+ conversationId,+ piSessionIdRef,+ scheduleHistoryRefresh,+ setConversationId,+ setMessages,+ upsertFileConversationMeta,+ ]);// ---- saveConversation ----const saveConversation = async (diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex 0fd0ced48..e6313e574 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -2574,6 +2574,7 @@ export function StandaloneChat({setIsStreaming,setPastedImages,settings,+ inlineHistoryEnabled: !hideInlineHistory,});// Read an image file by path and append it to pastedImages (base64 data URL)diff --git a/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.tsindex 79f32338f..4e42cebb9 100644--- a/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts+++ b/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts@@ -7,6 +7,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";const fsMock = vi.hoisted(() => ({files: new Map<string, { text: string; mtime: number }>(),reads: [] as string[],+ stats: [] as string[],}));vi.mock("@tauri-apps/api/path", () => ({@@ -33,13 +34,17 @@ vi.mock("@tauri-apps/plugin-fs", () => ({writeTextFile: vi.fn(async () => undefined),remove: vi.fn(async () => undefined),rename: vi.fn(async () => undefined),- stat: vi.fn(async (path: string) => ({- mtime: new Date(fsMock.files.get(path)?.mtime ?? 0),- })),+ stat: vi.fn(async (path: string) => {+ fsMock.stats.push(path);+ return {+ mtime: new Date(fsMock.files.get(path)?.mtime ?? 0),+ };+ }),}));import {CHAT_HISTORY_INITIAL_LIMIT,+ __resetChatStorageCachesForTests,listConversations,searchConversations,} from "../chat-storage";@@ -82,6 +87,8 @@ describe("chat-storage bounded history", () => {beforeEach(() => {fsMock.files.clear();fsMock.reads.length = 0;+ fsMock.stats.length = 0;+ __resetChatStorageCachesForTests();});it("loads only the newest 50 conversation files for the default history view", async () => {@@ -98,6 +105,24 @@ describe("chat-storage bounded history", () => {expect(fsMock.reads.some((path) => path.endsWith("/chat-0.json"))).toBe(false);});+ it("reuses the ordered file cache for repeated bounded history refreshes", async () => {+ for (let i = 0; i < 60; i += 1) {+ putConversation(`chat-${i}`, { updatedAt: i + 1 });+ }++ await listConversations({ limit: CHAT_HISTORY_INITIAL_LIMIT });+ expect(fsMock.stats).toHaveLength(60);++ fsMock.reads.length = 0;+ fsMock.stats.length = 0;+ const rows = await listConversations({ limit: CHAT_HISTORY_INITIAL_LIMIT });++ expect(rows).toHaveLength(50);+ expect(rows[0].id).toBe("chat-59");+ expect(fsMock.stats).toHaveLength(0);+ expect(fsMock.reads).toHaveLength(50);+ });+it("still searches older chats outside the initial 50", async () => {for (let i = 0; i < 60; i += 1) {putConversation(`chat-${i}`, {diff --git a/apps/screenpipe-app-tauri/lib/chat-storage.ts b/apps/screenpipe-app-tauri/lib/chat-storage.tsindex c7a38afae..e7511b8c8 100644--- a/apps/screenpipe-app-tauri/lib/chat-storage.ts+++ b/apps/screenpipe-app-tauri/lib/chat-storage.ts@@ -20,10 +20,17 @@ import type {} from "@/lib/hooks/use-settings";let _chatsDir: string | null = null;+let _orderedEntriesCacheDir: string | null = null;+let _orderedEntriesCache: ConversationEntry[] | null = null;export const CHAT_HISTORY_INITIAL_LIMIT = 50;export const CHAT_SEARCH_RESULT_LIMIT = 50;+export function __resetChatStorageCachesForTests(): void {+ _chatsDir = null;+ clearConversationEntryCache();+}+export interface ConversationListOptions {/** Max visible rows to return. Undefined preserves the old "all rows" behavior. */limit?: number;@@ -84,6 +91,10 @@ export async function saveConversationFile(await writeTextFile(tmpPath, body);try {await rename(tmpPath, filePath);+ rememberConversationEntry(dir, {+ name: conversationFilename(conv.id),+ path: 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@@ -109,16 +120,31 @@ export async function loadConversationFile(export async function deleteConversationFile(id: string): Promise<void> {const dir = await getChatsDir();- const filePath = `${dir}/${conversationFilename(id)}`;+ const filename = conversationFilename(id);+ const filePath = `${dir}/${filename}`;try {if (await exists(filePath)) {await remove(filePath);+ forgetConversationEntry(dir, filename);}} catch {// ignore}}+export async function markConversationFileChanged(id: string): Promise<void> {+ const dir = await getChatsDir();+ const filename = conversationFilename(id);+ rememberConversationEntry(dir, {+ name: filename,+ path: `${dir}/${filename}`,+ });+}++export function invalidateConversationListCache(): void {+ clearConversationEntryCache();+}+export interface ConversationMeta {id: string;title: string;@@ -158,6 +184,24 @@ async function listConversationEntries(dir: string): Promise<ConversationEntry[]}));}+function clearConversationEntryCache(): void {+ _orderedEntriesCacheDir = null;+ _orderedEntriesCache = null;+}++function rememberConversationEntry(dir: string, entry: ConversationEntry): void {+ if (_orderedEntriesCacheDir !== dir || !_orderedEntriesCache) return;+ _orderedEntriesCache = [+ entry,+ ..._orderedEntriesCache.filter((cached) => cached.name !== entry.name),+ ];+}++function forgetConversationEntry(dir: string, name: string): void {+ if (_orderedEntriesCacheDir !== dir || !_orderedEntriesCache) return;+ _orderedEntriesCache = _orderedEntriesCache.filter((entry) => entry.name !== name);+}+function timeToMs(value: unknown): number {if (value instanceof Date) return value.getTime();if (typeof value === "number") return value;@@ -194,6 +238,17 @@ async function orderEntriesByMtime(.map(({ sortTime: _sortTime, ...entry }) => entry);}+async function orderedConversationEntries(dir: string): Promise<ConversationEntry[]> {+ if (_orderedEntriesCacheDir === dir && _orderedEntriesCache) {+ return _orderedEntriesCache;+ }++ const ordered = await orderEntriesByMtime(await listConversationEntries(dir));+ _orderedEntriesCacheDir = dir;+ _orderedEntriesCache = ordered;+ return ordered;+}+function conversationMetaFromJson(conv: any): ConversationMeta | null {if (!conv || typeof conv.id !== "string") return null;@@ -249,9 +304,10 @@ export async function listConversations(const limit = normalizeLimit(options.limit);const offset = Math.max(0, Math.floor(options.offset ?? 0));if (limit === 0) return [];- const entries = await listConversationEntries(dir);const orderedEntries =- limit == null && offset === 0 ? entries : await orderEntriesByMtime(entries);+ limit == null && offset === 0+ ? await listConversationEntries(dir)+ : await orderedConversationEntries(dir);const metas: ConversationMeta[] = [];let skipped = 0;@@ -298,7 +354,7 @@ export async function searchConversations(const limit = normalizeLimit(options.limit ?? CHAT_SEARCH_RESULT_LIMIT);const offset = Math.max(0, Math.floor(options.offset ?? 0));if (limit === 0) return [];- const entries = await orderEntriesByMtime(await listConversationEntries(dir));+ const entries = await orderedConversationEntries(dir);const metas: ConversationMeta[] = [];let skipped = 0;@@ -354,9 +410,10 @@ export async function loadAllConversations(const limit = normalizeLimit(options.limit);const offset = Math.max(0, Math.floor(options.offset ?? 0));if (limit === 0) return [];- const entries = await listConversationEntries(dir);const orderedEntries =- limit == null && offset === 0 ? entries : await orderEntriesByMtime(entries);+ limit == null && offset === 0+ ? await listConversationEntries(dir)+ : await orderedConversationEntries(dir);const convs: ChatConversation[] = [];let skipped = 0;diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lockindex 8e7c6cc8f..ba6b868bc 100644--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -10580,7 +10580,7 @@ dependencies = [[[package]]name = "screenpipe-app"-version = "2.4.230"+version = "2.4.231"dependencies = ["aes","anyhow",diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 3337c7afb..caff6cb30 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.230"+version = "2.4.231"description = "24/7 memory for your desktop. 100% local."authors = ["you"]license = ""