Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

perf(desktop): page and cache remote session catalogs

Josuéf74815a43cf9
diff --git a/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx
new file mode 100644
index 000000000..0550ec247
--- /dev/null
+++ b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx
@@ -0,0 +1,30 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { renderHook } from '@testing-library/react'
+import { useChatStore } from '../useChatStore'
+
+describe('useChatStore remote request cache', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ delete (window as { clerum?: unknown }).clerum
+ })
+
+ it('shares an in-flight session page and clears it at an identity boundary', async () => {
+ const listSessions = vi.fn(async () => ({ items: [] }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { rpc: { listSessions } },
+ })
+ const { result } = renderHook(() => useChatStore())
+
+ await Promise.all([
+ result.current.listSessions('cache-test-host', { limit: 50 }),
+ result.current.listSessions('cache-test-host', { limit: 50 }),
+ ])
+ expect(listSessions).toHaveBeenCalledTimes(1)
+
+ result.current.clearCachedRemoteData()
+ await result.current.listSessions('cache-test-host', { limit: 50 })
+ expect(listSessions).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index f9cf379d6..d0bc6deed 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -1,9 +1,20 @@
import { type MutableRefObject, useCallback, useEffect, useRef, useState } from 'react'
import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'
-import type { ChatIndex, ChatMetadata } from '../../../../src/types'
+import type { ChatIndex, ChatMetadata, SessionsListResult } from '../../../../src/types'
import type { useChatStore } from '../useChatStore'
import { type SessionFsmEvent, type SessionFsmStore, seedSessionSnapshots } from './sessionFsm'
+function scheduleAfterFirstPaint(task: () => Promise<unknown>): void {
+ const run = () => {
+ void task().catch(() => undefined)
+ }
+ if (typeof requestAnimationFrame === 'function') {
+ requestAnimationFrame(() => requestAnimationFrame(run))
+ return
+ }
+ setTimeout(run, 0)
+}
+
/**
* useChatListController (spec-v2 §4.4) — owns the whole sidebar chat-list
* subsystem extracted from the god-hook:
@@ -93,8 +104,32 @@ export function useChatListController({
const selectedAgentRef = useRef(selectedAgent)
useEffect(() => {
selectedAgentRef.current = selectedAgent
+ return () => {
+ if (selectedAgentRef.current === selectedAgent) {
+ selectedAgentRef.current = null
+ }
+ }
}, [selectedAgent])
+ const loadRemainingServerSessions = useCallback(
+ async (
+ agentRef: string,
+ initialCursor: string | undefined
+ ): Promise<Awaited<ReturnType<typeof chatStore.listSessions>>['items']> => {
+ const items: Awaited<ReturnType<typeof chatStore.listSessions>>['items'] = []
+ const seenCursors = new Set<string>()
+ let cursor = initialCursor
+ while (cursor && !seenCursors.has(cursor)) {
+ seenCursors.add(cursor)
+ const page = await chatStore.listSessions(agentRef, { limit: 50, cursor })
+ items.push(...page.items)
+ cursor = page.nextCursor
+ }
+ return items
+ },
+ [chatStore.listSessions]
+ )
+
// ─── Cross-agent latest-sessions mutators ───
const upsertLatestChatSession = useCallback((agentRef: string, chat: SidebarChatEntry) => {
@@ -117,9 +152,9 @@ export function useChatListController({
const loadChatListOnce = useCallback(
async (agentRef: string): Promise<{ index: ChatIndex; merged: SidebarChatEntry[] }> => {
- const [index, serverResult] = await Promise.all([
+ const [index, serverResult]: [ChatIndex, SessionsListResult] = await Promise.all([
chatStore.getIndex(agentRef),
- chatStore.listSessions(agentRef).catch(() => ({ items: [] })),
+ chatStore.listSessions(agentRef, { limit: 50 }).catch(() => ({ items: [] })),
])
const localChats: SidebarChatEntry[] = index.chats
@@ -140,12 +175,41 @@ export function useChatListController({
title: `Chat ${s.chatId.slice(0, 8)}`,
createdAt: s.lastActivityAt,
updatedAt: s.lastActivityAt,
- messageCount: 0,
+ messageCount: s.turnCount * 2,
+ turnCount: s.turnCount,
}))
const merged = [...localChats, ...fromServerOnly].sort(byUpdatedDesc)
setChatList(merged)
+ if (serverResult.nextCursor) {
+ scheduleAfterFirstPaint(async () => {
+ if (selectedAgentRef.current !== agentRef) return
+ const additionalItems = await loadRemainingServerSessions(
+ agentRef,
+ serverResult.nextCursor
+ )
+ const additionalSessions = additionalItems.filter(session => session.agent === agentRef)
+ if (!additionalSessions.length) return
+ seedSessionSnapshots(fsm, agentRef, additionalSessions)
+ if (selectedAgentRef.current !== agentRef) return
+ setChatList(previous => {
+ const knownIds = new Set(previous.map(chat => chat.id))
+ const additionalChats: SidebarChatEntry[] = additionalSessions
+ .filter(session => !knownIds.has(session.chatId))
+ .map(session => ({
+ id: session.chatId,
+ title: `Chat ${session.chatId.slice(0, 8)}`,
+ createdAt: session.lastActivityAt,
+ updatedAt: session.lastActivityAt,
+ messageCount: session.turnCount * 2,
+ turnCount: session.turnCount,
+ }))
+ return [...previous, ...additionalChats].sort(byUpdatedDesc)
+ })
+ })
+ }
+
// Persist server freshness into the local index (spec §5.3): keeps the
// durable sidebar order aligned with the source of truth. A pure tail
// effect that does NOT affect this render — the merge above sorts local
@@ -166,7 +230,13 @@ export function useChatListController({
return { index, merged }
},
- [chatStore.getIndex, chatStore.listSessions, chatStore.reconcileServerSessions, fsm]
+ [
+ chatStore.getIndex,
+ chatStore.listSessions,
+ chatStore.reconcileServerSessions,
+ fsm,
+ loadRemainingServerSessions,
+ ]
)
const loadChatList = useCallback(
@@ -423,9 +493,9 @@ export function useChatListController({
const sessionGroups = await Promise.all(
agentNames.map(async agentRef => {
try {
- const [index, serverResult] = await Promise.all([
+ const [index, serverResult]: [ChatIndex, SessionsListResult] = await Promise.all([
chatStore.getIndex(agentRef),
- chatStore.listSessions(agentRef).catch(() => ({ items: [] })),
+ chatStore.listSessions(agentRef, { limit: 50 }).catch(() => ({ items: [] })),
])
const localChats: LatestSidebarChatEntry[] = index.chats.map(chat => ({
...chat,
@@ -439,7 +509,7 @@ export function useChatListController({
title: `Remote · ${session.chatId.slice(0, 8)}`,
createdAt: session.lastActivityAt,
updatedAt: session.lastActivityAt,
- messageCount: 0,
+ messageCount: session.turnCount * 2,
remote: true,
turnCount: session.turnCount,
agentRef,
@@ -450,12 +520,18 @@ export function useChatListController({
// D4 (§4.1 R2): the "snapshot never degrades a live task" rule that
// used to live in `mergeSeededSessionStates` is now the reducer's.
const sessions = serverResult.items.filter(session => session.agent === agentRef)
- return { agentRef, entries: [...localChats, ...remoteOnly], sessions }
+ return {
+ agentRef,
+ entries: [...localChats, ...remoteOnly],
+ sessions,
+ nextCursor: serverResult.nextCursor,
+ }
} catch {
return {
agentRef,
entries: [] as LatestSidebarChatEntry[],
sessions: [] as Awaited<ReturnType<typeof chatStore.listSessions>>['items'],
+ nextCursor: undefined,
}
}
})
@@ -465,6 +541,40 @@ export function useChatListController({
for (const group of sessionGroups) {
seedSessionSnapshots(fsm, group.agentRef, group.sessions)
}
+ void Promise.all(
+ sessionGroups.map(async group => ({
+ agentRef: group.agentRef,
+ sessions: await loadRemainingServerSessions(group.agentRef, group.nextCursor),
+ }))
+ )
+ .then(remainingGroups => {
+ if (cancelled) return
+ setLatestChatSessions(previous => {
+ const knownKeys = new Set(previous.map(item => `${item.agentRef}:${item.id}`))
+ const additional: LatestSidebarChatEntry[] = []
+ for (const group of remainingGroups) {
+ const sessions = group.sessions.filter(session => session.agent === group.agentRef)
+ seedSessionSnapshots(fsm, group.agentRef, sessions)
+ for (const session of sessions) {
+ const key = `${group.agentRef}:${session.chatId}`
+ if (knownKeys.has(key)) continue
+ knownKeys.add(key)
+ additional.push({
+ id: session.chatId,
+ title: `Chat ${session.chatId.slice(0, 8)}`,
+ createdAt: session.lastActivityAt,
+ updatedAt: session.lastActivityAt,
+ messageCount: session.turnCount * 2,
+ turnCount: session.turnCount,
+ remote: true,
+ agentRef: group.agentRef,
+ })
+ }
+ }
+ return [...previous, ...additional].sort(byUpdatedDesc)
+ })
+ })
+ .catch(() => undefined)
} finally {
if (!cancelled) {
setLatestChatSessionsLoading(false)
@@ -475,7 +585,14 @@ export function useChatListController({
return () => {
cancelled = true
}
- }, [agentNames, chatStore.getIndex, chatStore.listSessions, isAuthenticated, fsm])
+ }, [
+ agentNames,
+ chatStore.getIndex,
+ chatStore.listSessions,
+ isAuthenticated,
+ fsm,
+ loadRemainingServerSessions,
+ ])
return {
// State (public contract, re-exported unchanged by the parent).
diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.ts
index 95e593c77..6583f5439 100644
--- a/desktop-app/ui/src/hooks/useChatStore.ts
+++ b/desktop-app/ui/src/hooks/useChatStore.ts
@@ -1,5 +1,11 @@
import { useCallback } from 'react'
-import type { ChatMessage } from '../../../src/types'
+import type {
+ ChatMessage,
+ HostModelsResult,
+ SessionMessagesQuery,
+ SessionsListQuery,
+ SessionsListResult,
+} from '../../../src/types'
// The session lifecycle types live in the shared `src/types` (they cross the
// IPC bridge from the server). Re-exported here so existing UI imports from
@@ -44,6 +50,18 @@ const pendingModelByChat: Record<string, string> = {}
* `pendingModelByChat`.
*/
const preChatModelByAgent: Record<string, string> = {}
+const SESSION_CATALOG_TTL_MS = 5_000
+const HOST_MODELS_TTL_MS = 30_000
+
+type CachedRequest<T> = {
+ expiresAt: number
+ promise: Promise<T>
+}
+
+const sessionCatalogRequests = new Map<string, CachedRequest<SessionsListResult>>()
+const hostModelRequests = new Map<string, CachedRequest<HostModelsResult | null>>()
+let sessionCatalogSource: typeof window.clerum.rpc.listSessions | null = null
+let hostModelsSource: typeof window.clerum.rpc.getHostModels | null = null
/** Composite key mirroring the session `chatKey` convention (`agentRef::chatId`). */
function pendingModelKey(agentRef: string, chatId: string): string {
@@ -111,10 +129,36 @@ export function useChatStore() {
[]
)
- const listSessions = useCallback((hostRef: string) => window.clerum.rpc.listSessions(hostRef), [])
+ const listSessions = useCallback(
+ (
+ hostRef: string,
+ query: SessionsListQuery = { limit: 50 },
+ options: { force?: boolean } = {}
+ ) => {
+ const source = window.clerum.rpc.listSessions
+ if (sessionCatalogSource !== source) {
+ sessionCatalogRequests.clear()
+ sessionCatalogSource = source
+ }
+ const key = `${hostRef}:${query.limit ?? 'all'}:${query.cursor ?? ''}`
+ const cached = sessionCatalogRequests.get(key)
+ if (!options.force && cached && cached.expiresAt > Date.now()) return cached.promise
+
+ const promise = source(hostRef, undefined, query).catch(error => {
+ sessionCatalogRequests.delete(key)
+ throw error
+ })
+ sessionCatalogRequests.set(key, {
+ expiresAt: Date.now() + SESSION_CATALOG_TTL_MS,
+ promise,
+ })
+ return promise
+ },
+ []
+ )
const loadSessionMessages = useCallback(
- (hostRef: string, agent: string, chatId: string) =>
- window.clerum.rpc.loadSessionMessages(hostRef, agent, chatId),
+ (hostRef: string, agent: string, chatId: string, query: SessionMessagesQuery = {}) =>
+ window.clerum.rpc.loadSessionMessages(hostRef, agent, chatId, undefined, query),
[]
)
const getContextBreakdown = useCallback(
@@ -122,15 +166,34 @@ export function useChatStore() {
window.clerum.rpc.getContextBreakdown(hostRef, agent, chatId),
[]
)
- const getHostModels = useCallback(
- (hostRef: string, chatId: string) => window.clerum.rpc.getHostModels(hostRef, chatId),
- []
- )
- const setHostModel = useCallback(
- (hostRef: string, chatId: string, model: string) =>
- window.clerum.rpc.setHostModel(hostRef, chatId, model),
- []
- )
+ const getHostModels = useCallback((hostRef: string, chatId: string) => {
+ const source = window.clerum.rpc.getHostModels
+ if (hostModelsSource !== source) {
+ hostModelRequests.clear()
+ hostModelsSource = source
+ }
+ const key = `${hostRef}:${chatId}`
+ const cached = hostModelRequests.get(key)
+ if (cached && cached.expiresAt > Date.now()) return cached.promise
+
+ const promise = source(hostRef, chatId).catch(error => {
+ hostModelRequests.delete(key)
+ throw error
+ })
+ hostModelRequests.set(key, { expiresAt: Date.now() + HOST_MODELS_TTL_MS, promise })
+ return promise
+ }, [])
+ const setHostModel = useCallback(async (hostRef: string, chatId: string, model: string) => {
+ const result = await window.clerum.rpc.setHostModel(hostRef, chatId, model)
+ hostModelRequests.delete(`${hostRef}:${chatId}`)
+ return result
+ }, [])
+ const clearCachedRemoteData = useCallback(() => {
+ sessionCatalogRequests.clear()
+ hostModelRequests.clear()
+ sessionCatalogSource = null
+ hostModelsSource = null
+ }, [])
// --- Pending (unpersisted) model selections — R2 "Option A" (see the
// `pendingModelByChat` note above). Only UNPERSISTED selections are tracked:
@@ -187,6 +250,7 @@ export function useChatStore() {
getContextBreakdown,
getHostModels,
setHostModel,
+ clearCachedRemoteData,
setPendingModel,
getPendingModel,
clearPendingModel,