Skip to content

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

TypeScript

perf(desktop): page local chat history and stabilize loading

Josué833884bdc082
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 4d8260240..3fbb72e4d 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.316",
+ "version": "0.1.317",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.316",
+ "version": "0.1.317",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index b1139fe31..81ab5c880 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.316",
+ "version": "0.1.317",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.ts
index 32de92eae..3555bcb69 100644
--- a/desktop-app/src/__tests__/chatStore.test.ts
+++ b/desktop-app/src/__tests__/chatStore.test.ts
@@ -3,6 +3,7 @@ import { promises as fs } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { ChatStore } from '../chatStore.js'
+import type { ChatMessage } from '../types.js'
let tempDir: string
let store: ChatStore
@@ -16,6 +17,26 @@ afterEach(async () => {
await fs.rm(tempDir, { recursive: true, force: true })
})
+function agentPath(...segments: string[]): string {
+ return join(tempDir, 'agent-1', ...segments)
+}
+
+function chatCacheDir(chatId: string): string {
+ return agentPath('chats', chatId)
+}
+
+function chatMetaPath(chatId: string): string {
+ return join(chatCacheDir(chatId), 'meta.json')
+}
+
+function chatPagesDir(chatId: string): string {
+ return join(chatCacheDir(chatId), 'pages')
+}
+
+async function readJsonFile<T = Record<string, unknown>>(path: string): Promise<T> {
+ return JSON.parse(await fs.readFile(path, 'utf-8')) as T
+}
+
// ── listChats ────────────────────────────────────────────────────────────────
describe('listChats', () => {
@@ -71,7 +92,7 @@ describe('renameChat', () => {
// ── deleteChat ───────────────────────────────────────────────────────────────
describe('deleteChat', () => {
- it('removes from index and deletes message file', async () => {
+ it('removes from index and deletes message cache', async () => {
await store.createChat('agent-1', 'del-1')
await store.saveMessages('agent-1', 'del-1', [
{ id: 'm1', role: 'user', content: 'hello', timestamp: Date.now() },
@@ -80,9 +101,8 @@ describe('deleteChat', () => {
const chats = await store.listChats('agent-1')
expect(chats).toHaveLength(0)
- // message file should be gone
- const filePath = join(tempDir, 'agent-1', 'del-1.json')
- await expect(fs.access(filePath)).rejects.toThrow()
+ await expect(fs.access(join(tempDir, 'agent-1', 'del-1.json'))).rejects.toThrow()
+ await expect(fs.access(chatCacheDir('del-1'))).rejects.toThrow()
})
it('clears lastActiveChatId when deleting active chat', async () => {
@@ -132,6 +152,132 @@ describe('messages', () => {
expect(offset2[2]!.content).toBe('msg-7')
})
+ it('stores large chats in page files and reads windows across page boundaries', async () => {
+ const pagedStore = new ChatStore(tempDir, {
+ pageSize: 3,
+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,
+ })
+ await pagedStore.createChat('agent-1', 'paged-1')
+ const msgs = Array.from({ length: 10 }, (_, i) => ({
+ id: `m${i}`,
+ role: 'user' as const,
+ content: `msg-${i}`,
+ timestamp: i,
+ }))
+
+ await pagedStore.saveMessages('agent-1', 'paged-1', msgs)
+
+ expect(await fs.readdir(chatPagesDir('paged-1'))).toEqual([
+ '000001.json',
+ '000002.json',
+ '000003.json',
+ '000004.json',
+ ])
+ const meta = await readJsonFile<{ messageCount: number; localMessageCount: number }>(
+ chatMetaPath('paged-1')
+ )
+ expect(meta).toMatchObject({ messageCount: 10, localMessageCount: 10 })
+
+ const window = await pagedStore.loadMessages('agent-1', 'paged-1', 4, 2)
+ expect(window.map(message => message.content)).toEqual(['msg-4', 'msg-5', 'msg-6', 'msg-7'])
+ })
+
+ it('appends into the last page before creating another page', async () => {
+ const pagedStore = new ChatStore(tempDir, {
+ pageSize: 2,
+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,
+ })
+ await pagedStore.createChat('agent-1', 'append-pages')
+ await pagedStore.saveMessages('agent-1', 'append-pages', [
+ { id: 'm0', role: 'user', content: 'msg-0', timestamp: 0 },
+ { id: 'm1', role: 'user', content: 'msg-1', timestamp: 1 },
+ { id: 'm2', role: 'user', content: 'msg-2', timestamp: 2 },
+ ])
+
+ await pagedStore.appendMessages('agent-1', 'append-pages', [
+ { id: 'm3', role: 'user', content: 'msg-3', timestamp: 3 },
+ { id: 'm4', role: 'user', content: 'msg-4', timestamp: 4 },
+ ])
+
+ expect(await fs.readdir(chatPagesDir('append-pages'))).toEqual([
+ '000001.json',
+ '000002.json',
+ '000003.json',
+ ])
+ const secondPage = await readJsonFile<{ messages: ChatMessage[] }>(
+ join(chatPagesDir('append-pages'), '000002.json')
+ )
+ expect(secondPage.messages.map(message => message.id)).toEqual(['m2', 'm3'])
+
+ const messages = await pagedStore.loadMessages('agent-1', 'append-pages')
+ expect(messages.map(message => message.id)).toEqual(['m0', 'm1', 'm2', 'm3', 'm4'])
+ })
+
+ it('prunes only old pages whose messages are known to exist on the server', async () => {
+ const prunedStore = new ChatStore(tempDir, {
+ pageSize: 2,
+ maxLocalSyncedMessages: 4,
+ })
+ await prunedStore.createChat('agent-1', 'pruned')
+ const msgs = Array.from({ length: 6 }, (_, i) => ({
+ id: `m${i}`,
+ role: 'user' as const,
+ content: `msg-${i}`,
+ timestamp: i,
+ serverTurnNumber: i + 1,
+ }))
+
+ await prunedStore.saveMessages('agent-1', 'pruned', msgs)
+
+ expect(await fs.readdir(chatPagesDir('pruned'))).toEqual(['000002.json', '000003.json'])
+ await expect(fs.access(join(chatPagesDir('pruned'), '000001.json'))).rejects.toThrow()
+ const meta = await readJsonFile<{
+ messageCount: number
+ localMessageCount: number
+ prunedBeforeCount: number
+ prunedThroughServerTurnNumber: number
+ }>(chatMetaPath('pruned'))
+ expect(meta).toMatchObject({
+ messageCount: 6,
+ localMessageCount: 4,
+ prunedBeforeCount: 2,
+ prunedThroughServerTurnNumber: 2,
+ })
+
+ const chat = (await prunedStore.listChats('agent-1')).find(item => item.id === 'pruned')
+ expect(chat?.messageCount).toBe(6)
+ const localMessages = await prunedStore.loadMessages('agent-1', 'pruned')
+ expect(localMessages.map(message => message.id)).toEqual(['m2', 'm3', 'm4', 'm5'])
+ })
+
+ it('does not prune pages containing local-only messages', async () => {
+ const prunedStore = new ChatStore(tempDir, {
+ pageSize: 2,
+ maxLocalSyncedMessages: 4,
+ })
+ await prunedStore.createChat('agent-1', 'local-only')
+ const msgs = Array.from({ length: 6 }, (_, i) => ({
+ id: `m${i}`,
+ role: 'user' as const,
+ content: `msg-${i}`,
+ timestamp: i,
+ ...(i >= 2 ? { serverTurnNumber: i + 1 } : {}),
+ }))
+
+ await prunedStore.saveMessages('agent-1', 'local-only', msgs)
+
+ expect(await fs.readdir(chatPagesDir('local-only'))).toEqual([
+ '000001.json',
+ '000002.json',
+ '000003.json',
+ ])
+ const meta = await readJsonFile<{ localMessageCount: number; prunedBeforeCount?: number }>(
+ chatMetaPath('local-only')
+ )
+ expect(meta.localMessageCount).toBe(6)
+ expect(meta.prunedBeforeCount).toBeUndefined()
+ })
+
it('updates messageCount in index after save', async () => {
await store.createChat('agent-1', 'mc-1')
await store.saveMessages('agent-1', 'mc-1', [
@@ -168,14 +314,22 @@ describe('messages', () => {
})
})
- it('persists task_id and writes the v2 chat file (D.3)', async () => {
+ it('persists task_id and writes the paged chat cache', async () => {
await store.createChat('agent-1', 'v2-1')
await store.saveMessages('agent-1', 'v2-1', [
{ id: 'm1', role: 'user', content: 'hi', timestamp: 1, task_id: 'task-abc' },
])
- const raw = await fs.readFile(join(tempDir, 'agent-1', 'v2-1.json'), 'utf-8')
- const parsed = JSON.parse(raw)
- expect(parsed.version).toBe(2)
+ const meta = await readJsonFile<{ version: number; pages: Array<{ file: string }> }>(
+ chatMetaPath('v2-1')
+ )
+ expect(meta.version).toBe(1)
+ expect(meta.pages.map(page => page.file)).toEqual(['000001.json'])
+ const page = await readJsonFile<{ messages: ChatMessage[] }>(
+ join(chatPagesDir('v2-1'), '000001.json')
+ )
+ expect(page.messages[0]!.task_id).toBe('task-abc')
+ await expect(fs.access(join(tempDir, 'agent-1', 'v2-1.json'))).rejects.toThrow()
+
const messages = await store.loadMessages('agent-1', 'v2-1')
expect(messages[0]!.task_id).toBe('task-abc')
})
@@ -194,6 +348,8 @@ describe('messages', () => {
const messages = await store.loadMessages('agent-1', 'legacy')
expect(messages).toHaveLength(1)
expect(messages[0]!.task_id).toBeUndefined()
+ await expect(fs.access(join(agentDir, 'legacy.json'))).rejects.toThrow()
+ await expect(fs.access(chatMetaPath('legacy'))).resolves.toBeUndefined()
})
})
diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.ts
index 00599fc65..944c44681 100644
--- a/desktop-app/src/chatStore.ts
+++ b/desktop-app/src/chatStore.ts
@@ -3,6 +3,92 @@ import { join } from 'node:path'
import type { ChatFile, ChatIndex, ChatMessage, ChatMetadata } from './types.js'
const INDEX_VERSION = 2
+const PAGED_CHAT_VERSION = 1
+const DEFAULT_PAGE_SIZE = 100
+const DEFAULT_MAX_LOCAL_SYNCED_MESSAGES = 1000
+const PAGE_FILE_PATTERN = /^\d{6}\.json$/
+
+export interface ChatStoreOptions {
+ pageSize?: number
+ maxLocalSyncedMessages?: number
+}
+
+interface ChatPageEntry {
+ file: string
+ count: number
+ serverSynced: boolean
+ firstServerTurnNumber?: number
+ lastServerTurnNumber?: number
+}
+
+interface PagedChatMeta {
+ version: typeof PAGED_CHAT_VERSION
+ chatId: string
+ pageSize: number
+ messageCount: number
+ localMessageCount: number
+ prunedBeforeCount?: number
+ prunedThroughServerTurnNumber?: number
+ oldestLocalServerTurnNumber?: number
+ latestServerTurnNumber?: number
+ pages: ChatPageEntry[]
+}
+
+interface ChatPageFile {
+ version: typeof PAGED_CHAT_VERSION
+ chatId: string
+ pageNumber: number
+ messages: ChatMessage[]
+}
+
+function normalizePositiveInteger(value: number | undefined, fallback: number): number {
+ if (value === undefined) return fallback
+ if (!Number.isFinite(value)) return fallback
+ const normalized = Math.floor(value)
+ return normalized > 0 ? normalized : fallback
+}
+
+function normalizeMaxLocalSyncedMessages(value: number | undefined): number {
+ if (value === undefined) return DEFAULT_MAX_LOCAL_SYNCED_MESSAGES
+ if (value === Number.POSITIVE_INFINITY) return Number.POSITIVE_INFINITY
+ if (!Number.isFinite(value)) return DEFAULT_MAX_LOCAL_SYNCED_MESSAGES
+ return Math.max(0, Math.floor(value))
+}
+
+function pageFileName(pageNumber: number): string {
+ return `${pageNumber.toString().padStart(6, '0')}.json`
+}
+
+function pageNumberFromFileName(fileName: string): number {
+ if (!PAGE_FILE_PATTERN.test(fileName)) return 0
+ return Number(fileName.slice(0, 6))
+}
+
+function serverTurnNumber(message: ChatMessage): number | undefined {
+ return Number.isFinite(message.serverTurnNumber) ? message.serverTurnNumber : undefined
+}
+
+function aggregateMessages(
+ messages: ChatMessage[]
+): Pick<ChatMetadata, 'errorCount' | 'toolCallCount'> {
+ return {
+ errorCount: messages.reduce((total, message) => total + (message.isError ? 1 : 0), 0),
+ toolCallCount: messages.reduce((total, message) => total + (message.toolSteps?.length ?? 0), 0),
+ }
+}
+
+function pageEntry(file: string, messages: ChatMessage[]): ChatPageEntry {
+ const serverTurns = messages
+ .map(serverTurnNumber)
+ .filter((turn): turn is number => turn !== undefined)
+ return {
+ file,
+ count: messages.length,
+ serverSynced: messages.length > 0 && serverTurns.length === messages.length,
+ firstServerTurnNumber: serverTurns.length ? Math.min(...serverTurns) : undefined,
+ lastServerTurnNumber: serverTurns.length ? Math.max(...serverTurns) : undefined,
+ }
+}
/**
* Reject any path-component (agentRef / chatId) that could escape the store
@@ -27,7 +113,16 @@ function emptyIndex(): ChatIndex {
}
export class ChatStore {
- constructor(private readonly baseDir: string) {}
+ private readonly pageSize: number
+ private readonly maxLocalSyncedMessages: number
+
+ constructor(
+ private readonly baseDir: string,
+ options: ChatStoreOptions = {}
+ ) {
+ this.pageSize = normalizePositiveInteger(options.pageSize, DEFAULT_PAGE_SIZE)
+ this.maxLocalSyncedMessages = normalizeMaxLocalSyncedMessages(options.maxLocalSyncedMessages)
+ }
/**
* Per-agent serialization of index read-modify-write sequences. The index is
@@ -67,6 +162,329 @@ export class ChatStore {
return join(this.agentDir(agentRef), `${chatId}.json`)
}
+ private chatDirPath(agentRef: string, chatId: string): string {
+ assertSafeSegment('chatId', chatId)
+ return join(this.agentDir(agentRef), 'chats', chatId)
+ }
+
+ private chatPagesDirPath(agentRef: string, chatId: string): string {
+ return join(this.chatDirPath(agentRef, chatId), 'pages')
+ }
+
+ private chatMetaPath(agentRef: string, chatId: string): string {
+ return join(this.chatDirPath(agentRef, chatId), 'meta.json')
+ }
+
+ private chatPagePath(agentRef: string, chatId: string, fileName: string): string {
+ if (!PAGE_FILE_PATTERN.test(fileName)) {
+ throw new Error(`Invalid chat page: unsafe file name`)
+ }
+ return join(this.chatPagesDirPath(agentRef, chatId), fileName)
+ }
+
+ private async writeJsonAtomic(filePath: string, value: unknown): Promise<void> {
+ const tmp = `${filePath}.tmp`
+ await fs.writeFile(tmp, JSON.stringify(value), { mode: 0o600 })
+ await fs.rename(tmp, filePath)
+ }
+
+ private finalizePagedMeta(meta: PagedChatMeta): PagedChatMeta {
+ const localMessageCount = meta.pages.reduce((total, page) => total + page.count, 0)
+ const oldestLocalServerTurnNumber = meta.pages.find(
+ page => page.firstServerTurnNumber !== undefined
+ )?.firstServerTurnNumber
+ const latestServerTurnNumber = [...meta.pages]
+ .reverse()
+ .find(page => page.lastServerTurnNumber !== undefined)?.lastServerTurnNumber
+
+ return {
+ ...meta,
+ pageSize: this.pageSize,
+ localMessageCount,
+ oldestLocalServerTurnNumber,
+ latestServerTurnNumber,
+ }
+ }
+
+ private async readPagedMeta(agentRef: string, chatId: string): Promise<PagedChatMeta | null> {
+ try {
+ const raw = await fs.readFile(this.chatMetaPath(agentRef, chatId), 'utf-8')
+ const parsed = JSON.parse(raw) as PagedChatMeta
+ if (
+ parsed?.version !== PAGED_CHAT_VERSION ||
+ parsed.chatId !== chatId ||
+ !Array.isArray(parsed.pages)
+ ) {
+ return null
+ }
+ if (parsed.pages.some(page => !PAGE_FILE_PATTERN.test(page.file))) return null
+ return this.finalizePagedMeta({
+ ...parsed,
+ pageSize: normalizePositiveInteger(parsed.pageSize, this.pageSize),
+ messageCount: Math.max(0, Math.floor(parsed.messageCount ?? 0)),
+ localMessageCount: Math.max(0, Math.floor(parsed.localMessageCount ?? 0)),
+ })
+ } catch {
+ return null
+ }
+ }
+
+ private async readLegacyMessages(
+ agentRef: string,
+ chatId: string
+ ): Promise<ChatMessage[] | null> {
+ try {
+ const raw = await fs.readFile(this.chatFilePath(agentRef, chatId), 'utf-8')
+ const file = JSON.parse(raw) as ChatFile
+ if (!file || !Array.isArray(file.messages)) return null
+ return file.messages
+ } catch {
+ return null
+ }
+ }
+
+ private async readPageMessages(
+ agentRef: string,
+ chatId: string,
+ page: ChatPageEntry
+ ): Promise<ChatMessage[]> {
+ try {
+ const raw = await fs.readFile(this.chatPagePath(agentRef, chatId, page.file), 'utf-8')
+ const parsed = JSON.parse(raw) as ChatPageFile
+ if (
+ parsed?.version !== PAGED_CHAT_VERSION ||
+ parsed.chatId !== chatId ||
+ !Array.isArray(parsed.messages)
+ ) {
+ return []
+ }
+ return parsed.messages
+ } catch {
+ return []
+ }
+ }
+
+ private async writePageMessages(
+ agentRef: string,
+ chatId: string,
+ pageNumber: number,
+ messages: ChatMessage[]
+ ): Promise<ChatPageEntry> {
+ const file = pageFileName(pageNumber)
+ const page: ChatPageFile = {
+ version: PAGED_CHAT_VERSION,
+ chatId,
+ pageNumber,
+ messages,
+ }
+ await this.writeJsonAtomic(this.chatPagePath(agentRef, chatId, file), page)
+ return pageEntry(file, messages)
+ }
+
+ private async writePagedMeta(
+ agentRef: string,
+ chatId: string,
+ meta: PagedChatMeta
+ ): Promise<void> {
+ await this.writeJsonAtomic(this.chatMetaPath(agentRef, chatId), this.finalizePagedMeta(meta))
+ }
+
+ private async pruneSyncedPages(
+ agentRef: string,
+ chatId: string,
+ meta: PagedChatMeta
+ ): Promise<PagedChatMeta> {
+ if (this.maxLocalSyncedMessages === Number.POSITIVE_INFINITY) {
+ return this.finalizePagedMeta(meta)
+ }
+
+ let localCount = meta.pages.reduce((total, page) => total + page.count, 0)
+ let prunedBeforeCount = meta.prunedBeforeCount ?? 0
+ let prunedThroughServerTurnNumber = meta.prunedThroughServerTurnNumber
+ const retained: ChatPageEntry[] = []
+ let pruning = true
+
+ for (const page of meta.pages) {
+ const canPrunePage =
+ pruning && page.serverSynced && localCount - page.count >= this.maxLocalSyncedMessages
+
+ if (canPrunePage) {
+ await fs.rm(this.chatPagePath(agentRef, chatId, page.file), { force: true })
+ localCount -= page.count
+ prunedBeforeCount += page.count
+ prunedThroughServerTurnNumber = page.lastServerTurnNumber ?? prunedThroughServerTurnNumber
+ continue
+ }
+
+ pruning = false
+ retained.push(page)
+ }
+
+ return this.finalizePagedMeta({
+ ...meta,
+ pages: retained,
+ prunedBeforeCount: prunedBeforeCount > 0 ? prunedBeforeCount : undefined,
+ prunedThroughServerTurnNumber,
+ })
+ }
+
+ private async writePagedChatUnlocked(
+ agentRef: string,
+ chatId: string,
+ messages: ChatMessage[],
+ options: { removeLegacy?: boolean } = {}
+ ): Promise<PagedChatMeta> {
+ const chatDir = this.chatDirPath(agentRef, chatId)
+ const pagesDir = this.chatPagesDirPath(agentRef, chatId)
+ await fs.rm(chatDir, { recursive: true, force: true })
+ await fs.mkdir(pagesDir, { recursive: true })
+
+ const pages: ChatPageEntry[] = []
+ for (
+ let start = 0, pageNumber = 1;
+ start < messages.length;
+ start += this.pageSize, pageNumber += 1
+ ) {
+ pages.push(
+ await this.writePageMessages(
+ agentRef,
+ chatId,
+ pageNumber,
+ messages.slice(start, start + this.pageSize)
+ )
+ )
+ }
+
+ const meta = await this.pruneSyncedPages(
+ agentRef,
+ chatId,
+ this.finalizePagedMeta({
+ version: PAGED_CHAT_VERSION,
+ chatId,
+ pageSize: this.pageSize,
+ messageCount: messages.length,
+ localMessageCount: messages.length,
+ pages,
+ })
+ )
+ await this.writePagedMeta(agentRef, chatId, meta)
+
+ if (options.removeLegacy) {
+ await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })
+ }
+
+ return meta
+ }
+
+ private async readOrMigratePagedChatUnlocked(
+ agentRef: string,
+ chatId: string
+ ): Promise<PagedChatMeta | null> {
+ const paged = await this.readPagedMeta(agentRef, chatId)
+ if (paged) return paged
+
+ const legacyMessages = await this.readLegacyMessages(agentRef, chatId)
+ if (!legacyMessages) return null
+
+ return this.writePagedChatUnlocked(agentRef, chatId, legacyMessages, { removeLegacy: true })
+ }
+
+ private async readOrMigratePagedChat(
+ agentRef: string,
+ chatId: string
+ ): Promise<PagedChatMeta | null> {
+ const paged = await this.readPagedMeta(agentRef, chatId)
+ if (paged) return paged
+
+ return this.serializeIndex(agentRef, async () =>
+ this.readOrMigratePagedChatUnlocked(agentRef, chatId)
+ )
+ }
+
+ private async readMessagesFromPagedMeta(
+ agentRef: string,
+ chatId: string,
+ meta: PagedChatMeta,
+ limit?: number,
+ offset?: number
+ ): Promise<ChatMessage[]> {
+ const localCount = meta.pages.reduce((total, page) => total + page.count, 0)
+ if (localCount === 0) return []
+
+ const effectiveOffset = Math.max(0, Math.floor(offset ?? 0))
+ const end = Math.max(0, localCount - effectiveOffset)
+ if (end === 0) return []
+
+ const effectiveLimit = limit === undefined ? end : Math.max(0, Math.floor(limit))
+ if (effectiveLimit === 0) return []
+
+ const start = Math.max(0, end - effectiveLimit)
+ const result: ChatMessage[] = []
+ let cursor = 0
+
+ for (const page of meta.pages) {
+ const pageStart = cursor
+ const pageEnd = cursor + page.count
+ cursor = pageEnd
+
+ const overlapStart = Math.max(start, pageStart)
+ const overlapEnd = Math.min(end, pageEnd)
+ if (overlapStart >= overlapEnd) continue
+
+ const pageMessages = await this.readPageMessages(agentRef, chatId, page)
+ result.push(...pageMessages.slice(overlapStart - pageStart, overlapEnd - pageStart))
+ }
+
+ return result
+ }
+
+ private async appendPagedMessagesUnlocked(
+ agentRef: string,
+ chatId: string,
+ meta: PagedChatMeta,
+ newMessages: ChatMessage[]
+ ): Promise<PagedChatMeta> {
+ if (!newMessages.length) return meta
+
+ const pages = [...meta.pages]
+ let remaining = [...newMessages]
+
+ const lastPage = pages.at(-1)
+ if (lastPage && lastPage.count < this.pageSize) {
+ const currentMessages = await this.readPageMessages(agentRef, chatId, lastPage)
+ const capacity = Math.max(0, this.pageSize - currentMessages.length)
+ if (capacity > 0) {
+ const added = remaining.slice(0, capacity)
+ remaining = remaining.slice(added.length)
+ pages[pages.length - 1] = await this.writePageMessages(
+ agentRef,
+ chatId,
+ pageNumberFromFileName(lastPage.file),
+ [...currentMessages, ...added]
+ )
+ }
+ }
+
+ let nextPageNumber = pageNumberFromFileName(pages.at(-1)?.file ?? '') + 1
+ while (remaining.length) {
+ const pageMessages = remaining.slice(0, this.pageSize)
+ remaining = remaining.slice(pageMessages.length)
+ pages.push(await this.writePageMessages(agentRef, chatId, nextPageNumber, pageMessages))
+ nextPageNumber += 1
+ }
+
+ const messageCount =
+ Math.max(meta.messageCount, meta.localMessageCount ?? 0) + newMessages.length
+ const pruned = await this.pruneSyncedPages(agentRef, chatId, {
+ ...meta,
+ messageCount,
+ pages,
+ })
+ await this.writePagedMeta(agentRef, chatId, pruned)
+ await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })
+ return pruned
+ }
+
async getIndex(agentRef: string): Promise<ChatIndex> {
try {
const raw = await fs.readFile(this.indexPath(agentRef), 'utf-8')
@@ -162,11 +580,8 @@ export class ChatStore {
index.lastActiveChatId = null
}
await this.saveIndex(agentRef, index)
- try {
- await fs.unlink(this.chatFilePath(agentRef, chatId))
- } catch {
- // file may not exist
- }
+ await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })
+ await fs.rm(this.chatDirPath(agentRef, chatId), { recursive: true, force: true })
})
}
@@ -177,17 +592,9 @@ export class ChatStore {
offset?: number
): Promise<ChatMessage[]> {
try {
- const raw = await fs.readFile(this.chatFilePath(agentRef, chatId), 'utf-8')
- const file = JSON.parse(raw) as ChatFile
- if (!file || !Array.isArray(file.messages)) return []
-
- const messages = file.messages
- if (limit === undefined && offset === undefined) return messages
-
- const effectiveOffset = offset ?? 0
- const start = Math.max(0, messages.length - effectiveOffset - (limit ?? messages.length))
- const end = messages.length - effectiveOffset
- return messages.slice(start, end)
+ const meta = await this.readOrMigratePagedChat(agentRef, chatId)
+ if (!meta) return []
+ return this.readMessagesFromPagedMeta(agentRef, chatId, meta, limit, offset)
} catch {
return []
}
@@ -195,20 +602,13 @@ export class ChatStore {
async saveMessages(agentRef: string, chatId: string, messages: ChatMessage[]): Promise<void> {
return this.serializeIndex(agentRef, async () => {
- const dir = this.agentDir(agentRef)
- await fs.mkdir(dir, { recursive: true })
- const file: ChatFile = { version: 2, chatId, messages }
- await fs.writeFile(this.chatFilePath(agentRef, chatId), JSON.stringify(file), { mode: 0o600 })
+ await this.writePagedChatUnlocked(agentRef, chatId, messages, { removeLegacy: true })
const index = await this.getIndex(agentRef)
const chat = index.chats.find(c => c.id === chatId)
if (chat) {
chat.messageCount = messages.length
- chat.errorCount = messages.reduce((total, message) => total + (message.isError ? 1 : 0), 0)
- chat.toolCallCount = messages.reduce(
- (total, message) => total + (message.toolSteps?.length ?? 0),
- 0
- )
+ Object.assign(chat, aggregateMessages(messages))
chat.updatedAt = new Date().toISOString()
await this.saveIndex(agentRef, index)
}
@@ -220,8 +620,23 @@ export class ChatStore {
chatId: string,
newMessages: ChatMessage[]
): Promise<void> {
- const existing = await this.loadMessages(agentRef, chatId)
- await this.saveMessages(agentRef, chatId, [...existing, ...newMessages])
+ return this.serializeIndex(agentRef, async () => {
+ const existing =
+ (await this.readOrMigratePagedChatUnlocked(agentRef, chatId)) ??
+ (await this.writePagedChatUnlocked(agentRef, chatId, [], { removeLegacy: true }))
+ const meta = await this.appendPagedMessagesUnlocked(agentRef, chatId, existing, newMessages)
+
+ const index = await this.getIndex(agentRef)
+ const chat = index.chats.find(c => c.id === chatId)
+ if (chat) {
+ const delta = aggregateMessages(newMessages)
+ chat.messageCount = meta.messageCount
+ chat.errorCount = (chat.errorCount ?? 0) + (delta.errorCount ?? 0)
+ chat.toolCallCount = (chat.toolCallCount ?? 0) + (delta.toolCallCount ?? 0)
+ chat.updatedAt = new Date().toISOString()
+ await this.saveIndex(agentRef, index)
+ }
+ })
}
/**
diff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsx
index f3d139a72..035cfd256 100644
--- a/desktop-app/ui/src/components/agents/ChatThread.tsx
+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx
@@ -278,26 +278,30 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {
const groupedWithKeys = useMemo(
() =>
- groupedMessages.map((group, groupIndex) => ({
- ...group,
- groupKey: `${group.role}-${groupIndex}`,
- items: group.items.map((message, messageIndex) => ({
- ...message,
- messageKey: `${message.timestamp}-${groupIndex}-${messageIndex}`,
- })),
- })),
+ groupedMessages.map((group, groupIndex) => {
+ const first = group.items[0]
+ const last = group.items.at(-1)
+ const firstKey = first?.id ?? first?.timestamp ?? groupIndex
+ const lastKey = last?.id ?? last?.timestamp ?? groupIndex
+ return {
+ ...group,
+ groupKey: `${group.role}-${firstKey}-${lastKey}-${group.items.length}`,
+ items: group.items.map(message => ({
+ ...message,
+ messageKey: message.id,
+ })),
+ }
+ }),
[groupedMessages]
)
const messageGroupChunks = useMemo(() => {
const indexedGroups = groupedWithKeys.map((group, groupIndex) => ({ group, groupIndex }))
- return Array.from(
- { length: Math.ceil(indexedGroups.length / VIRTUAL_MESSAGE_GROUPS_PER_CHUNK) },
- (_, chunkIndex) =>
- indexedGroups.slice(
- chunkIndex * VIRTUAL_MESSAGE_GROUPS_PER_CHUNK,
- (chunkIndex + 1) * VIRTUAL_MESSAGE_GROUPS_PER_CHUNK
- )
- )
+ const chunks: (typeof indexedGroups)[] = []
+ for (let end = indexedGroups.length; end > 0; end -= VIRTUAL_MESSAGE_GROUPS_PER_CHUNK) {
+ const start = Math.max(0, end - VIRTUAL_MESSAGE_GROUPS_PER_CHUNK)
+ chunks.unshift(indexedGroups.slice(start, end))
+ }
+ return chunks
}, [groupedWithKeys])
const localMessageIds = useMemo(
@@ -543,7 +547,7 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {
{activeChatId &&
messageGroupChunks.map((chunk, chunkIndex) => (
<VirtualizedMessageChunk
- key={chunk[0]?.group.groupKey ?? `chunk-${chunkIndex}`}
+ key={chunk.at(-1)?.group.groupKey ?? `chunk-${chunkIndex}`}
estimatedHeight={Math.max(240, chunk.length * 180)}
initiallyVisible={chunkIndex >= messageGroupChunks.length - 2}
render={() =>
diff --git a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx
index 33ecf171a..f688654df 100644
--- a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx
+++ b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx
@@ -1,9 +1,9 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
+import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'
import {
loadWorkflowRunsWithArtifactsForApprovalRefresh,
loadWorkflowRunsWithArtifactsForWorkflowTarget,
- scheduleAfterFirstPaint,
} from '../useAppController'
function installWorkflowHarness(runsResult: unknown) {
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx
index 5cafe9e99..1535e1eeb 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx
@@ -254,6 +254,42 @@ describe('switchToChat (unified, D.4)', () => {
)
})
+ it('does not show older history for a complete exact-page-size local chat', async () => {
+ const cached = Array.from({ length: 40 }, (_, index) =>
+ turn(index + 1, `q${index + 1}`, `a${index + 1}`)
+ ).flatMap(t => [
+ { id: `turn-${t.number}-user`, role: 'user' as const, content: t.user_input, timestamp: 1 },
+ {
+ id: `turn-${t.number}-assistant`,
+ role: 'assistant' as const,
+ content: t.response!,
+ timestamp: 2,
+ },
+ ])
+ clerum.chat.loadMessages.mockImplementation(
+ async (_agentRef: string, _chatId: string, _limit?: number, offset?: number) =>
+ offset ? [] : cached
+ )
+ clerum.rpc.loadSessionMessages.mockResolvedValue({
+ agent: 'agent-x',
+ chatId: 'exact-page',
+ state: 'idle',
+ turns: [],
+ hasMoreBefore: false,
+ hasMoreAfter: false,
+ })
+ const { result } = renderController()
+ await settleMount()
+
+ await act(async () => {
+ await result.current.switchToChat('agent-x', 'exact-page')
+ })
+
+ expect(clerum.chat.loadMessages).toHaveBeenCalledWith('agent-x', 'exact-page', 1, 80)
+ expect(result.current.chatMessages).toHaveLength(80)
+ expect(result.current.hasOlderMessages).toBe(false)
+ })
+
it('adds a server-only chat to the sidebar when switched to directly (S4)', async () => {
// chatList starts empty (default getIndex → no chats); simulate opening a
// notification for a chat the local list doesn't know about.
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index 0902afd06..e888f2e00 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -107,6 +107,13 @@ function serverTurnNumber(message: AgentChatMessage): number | undefined {
return match ? Number(match[1]) : undefined
}
+function oldestServerTurnNumber(messages: AgentChatMessage[]): number | undefined {
+ return messages.reduce<number | undefined>((oldest, message) => {
+ const current = serverTurnNumber(message)
+ return current === undefined ? oldest : Math.min(oldest ?? current, current)
+ }, undefined)
+}
+
function mergeUniqueMessages(
existing: AgentChatMessage[],
incoming: AgentChatMessage[],
@@ -667,9 +674,18 @@ export function useAgentChatController({
const cached = await chatStore
.loadMessages(agentRef, chatId, MESSAGE_PAGE_SIZE)
.catch(() => [])
+ const oldestCachedTurn = oldestServerTurnNumber(cached as AgentChatMessage[])
+ const hasOlderServerMessages = Boolean(oldestCachedTurn && oldestCachedTurn > 1)
+ const hasOlderLocalMessages =
+ !hasOlderServerMessages &&
+ cached.length === MESSAGE_PAGE_SIZE &&
+ (await chatStore
+ .loadMessages(agentRef, chatId, 1, MESSAGE_PAGE_SIZE)
+ .then(messages => messages.length > 0)
+ .catch(() => false))
if (!isStillActive()) return
loadedLocalMessageCountRef.current = cached.length
- setHasOlderMessages(cached.length === MESSAGE_PAGE_SIZE)
+ setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)
setChatMessages(cached as AgentChatMessage[])
// Phase 1 rendered the cache → clear the blocking spinner. The reconcile
// runs under the `syncing` indicator (RECONCILE_STARTED, dispatched by the
@@ -787,10 +803,7 @@ export function useAgentChatController({
return
}
- const oldestTurn = chatMessages.reduce<number | undefined>((oldest, message) => {
- const current = serverTurnNumber(message)
- return current === undefined ? oldest : Math.min(oldest ?? current, current)
- }, undefined)
+ const oldestTurn = oldestServerTurnNumber(chatMessages)
if (oldestTurn === undefined || oldestTurn <= 1) {
setHasOlderMessages(false)
return
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index 25e448caa..ed374a08a 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -1,20 +1,10 @@
import { type MutableRefObject, useCallback, useEffect, useRef, useState } from 'react'
import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'
import type { ChatIndex, ChatMetadata, SessionsListResult } from '../../../../src/types'
+import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'
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:
diff --git a/desktop-app/ui/src/hooks/scheduleAfterFirstPaint.ts b/desktop-app/ui/src/hooks/scheduleAfterFirstPaint.ts
new file mode 100644
index 000000000..6fae64241
--- /dev/null
+++ b/desktop-app/ui/src/hooks/scheduleAfterFirstPaint.ts
@@ -0,0 +1,10 @@
+export function scheduleAfterFirstPaint(task: () => Promise<unknown>): void {
+ const run = () => {
+ void task().catch(() => undefined)
+ }
+ if (typeof requestAnimationFrame === 'function') {
+ requestAnimationFrame(() => requestAnimationFrame(run))
+ return
+ }
+ setTimeout(run, 0)
+}
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index 213ee5713..e9b53495b 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -46,6 +46,7 @@ import {
type WorkflowSelectionState,
createResetWorkflowSelection,
} from './domain/useWorkflowController.types'
+import { scheduleAfterFirstPaint } from './scheduleAfterFirstPaint'
const DENY_REASON_BY_SOURCE: Record<ApprovalDecisionTarget['source'], string> = {
desktop_notification: 'Denied from desktop notification',
@@ -94,17 +95,6 @@ export async function loadWorkflowRunsWithArtifactsForApprovalRefresh(
})
}
-export function scheduleAfterFirstPaint(task: () => Promise<unknown>): void {
- const run = () => {
- void task().catch(() => undefined)
- }
- if (typeof requestAnimationFrame === 'function') {
- requestAnimationFrame(() => requestAnimationFrame(run))
- return
- }
- setTimeout(run, 0)
-}
-
export function useAppController() {
const queryClient = useQueryClient()