Skip to content

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

TypeScript

fix(desktop): close paged history review gaps

Josué2905ae270211
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 3fbb72e4d..4fcc2e210 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.317",
+ "version": "0.1.318",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.317",
+ "version": "0.1.318",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index 81ab5c880..6803ebb82 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.317",
+ "version": "0.1.318",
"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 3555bcb69..ed951583b 100644
--- a/desktop-app/src/__tests__/chatStore.test.ts
+++ b/desktop-app/src/__tests__/chatStore.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { promises as fs } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -14,6 +14,7 @@ beforeEach(async () => {
})
afterEach(async () => {
+ vi.restoreAllMocks()
await fs.rm(tempDir, { recursive: true, force: true })
})
@@ -213,6 +214,47 @@ describe('messages', () => {
expect(messages.map(message => message.id)).toEqual(['m0', 'm1', 'm2', 'm3', 'm4'])
})
+ it('serializes paged reads behind concurrent appends', async () => {
+ const pagedStore = new ChatStore(tempDir, {
+ pageSize: 2,
+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,
+ })
+ await pagedStore.createChat('agent-1', 'atomic-read')
+ await pagedStore.saveMessages('agent-1', 'atomic-read', [
+ { id: 'm0', role: 'user', content: 'msg-0', timestamp: 0 },
+ { id: 'm1', role: 'user', content: 'msg-1', timestamp: 1 },
+ ])
+
+ const originalWriteFile = fs.writeFile.bind(fs)
+ let releaseWrite: (() => void) | undefined
+ let delayedWrite = false
+ const appendWriteStarted = new Promise<void>(resolve => {
+ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {
+ const filePath = String(args[0])
+ if (!delayedWrite && filePath.includes('atomic-read') && filePath.endsWith('.tmp')) {
+ delayedWrite = true
+ resolve()
+ await new Promise<void>(release => {
+ releaseWrite = release
+ })
+ }
+ return originalWriteFile(...(args as Parameters<typeof fs.writeFile>))
+ })
+ })
+
+ const append = pagedStore.appendMessages('agent-1', 'atomic-read', [
+ { id: 'm2', role: 'assistant', content: 'msg-2', timestamp: 2 },
+ ])
+ await appendWriteStarted
+
+ const loadedDuringAppend = pagedStore.loadMessages('agent-1', 'atomic-read')
+ await Promise.resolve()
+ releaseWrite?.()
+
+ const [messages] = await Promise.all([loadedDuringAppend, append.then(() => undefined)])
+ expect(messages.map(message => message.id)).toEqual(['m0', 'm1', 'm2'])
+ })
+
it('prunes only old pages whose messages are known to exist on the server', async () => {
const prunedStore = new ChatStore(tempDir, {
pageSize: 2,
diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.ts
index 944c44681..972eb75bf 100644
--- a/desktop-app/src/chatStore.ts
+++ b/desktop-app/src/chatStore.ts
@@ -130,7 +130,9 @@ export class ChatStore {
* agent terminating at once — a first-class case post-D.4 fire-and-forget)
* could interleave getIndex→saveIndex and drop one update (e.g. an
* `unreadTerminal` flag). Chaining per agentRef makes each RMW atomic w.r.t.
- * the others. Reads (getIndex/loadMessages) are not serialized.
+ * the others. Plain index reads are not serialized. `loadMessages` is
+ * serialized because paged chat reads combine meta + page files and must not
+ * observe a partially-applied append/replace.
*/
private indexChains = new Map<string, Promise<unknown>>()
@@ -389,18 +391,6 @@ export class ChatStore {
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,
@@ -592,9 +582,11 @@ export class ChatStore {
offset?: number
): Promise<ChatMessage[]> {
try {
- const meta = await this.readOrMigratePagedChat(agentRef, chatId)
- if (!meta) return []
- return this.readMessagesFromPagedMeta(agentRef, chatId, meta, limit, offset)
+ return await this.serializeIndex(agentRef, async () => {
+ const meta = await this.readOrMigratePagedChatUnlocked(agentRef, chatId)
+ if (!meta) return []
+ return this.readMessagesFromPagedMeta(agentRef, chatId, meta, limit, offset)
+ })
} catch {
return []
}
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 1535e1eeb..4131fe720 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
@@ -290,6 +290,49 @@ describe('switchToChat (unified, D.4)', () => {
expect(result.current.hasOlderMessages).toBe(false)
})
+ it('does not keep older history visible after loading an exact multiple of local pages', async () => {
+ const allMessages = Array.from({ length: 160 }, (_, index) => ({
+ id: `turn-${index + 1}-user`,
+ role: 'user' as const,
+ content: `q${index + 1}`,
+ timestamp: index + 1,
+ }))
+ const firstVisiblePage = allMessages.slice(80)
+ const olderPage = allMessages.slice(0, 80)
+ clerum.chat.loadMessages.mockImplementation(
+ async (_agentRef: string, chatId: string, _limit?: number, offset?: number) => {
+ if (chatId !== 'exact-local-pages') return []
+ if (offset === undefined) return firstVisiblePage
+ if (offset === 80) return olderPage
+ return []
+ }
+ )
+ clerum.rpc.loadSessionMessages.mockResolvedValue({
+ agent: 'agent-x',
+ chatId: 'exact-local-pages',
+ state: 'idle',
+ turns: [],
+ hasMoreBefore: false,
+ hasMoreAfter: false,
+ })
+ const { result } = renderController()
+ await settleMount()
+
+ await act(async () => {
+ await result.current.switchToChat('agent-x', 'exact-local-pages')
+ })
+ expect(result.current.hasOlderMessages).toBe(true)
+
+ await act(async () => {
+ await result.current.handleLoadOlderMessages()
+ })
+
+ expect(clerum.chat.loadMessages).toHaveBeenCalledWith('agent-x', 'exact-local-pages', 1, 160)
+ expect(result.current.chatMessages).toHaveLength(160)
+ expect(result.current.hasOlderMessages).toBe(false)
+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledTimes(1)
+ })
+
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 e888f2e00..bfb3c4da8 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -114,6 +114,20 @@ function oldestServerTurnNumber(messages: AgentChatMessage[]): number | undefine
}, undefined)
}
+type ChatStoreClient = ReturnType<typeof useChatStore>
+
+async function hasLocalMessagesBeyond(
+ chatStore: ChatStoreClient,
+ agentRef: string,
+ chatId: string,
+ offset: number
+): Promise<boolean> {
+ return chatStore
+ .loadMessages(agentRef, chatId, 1, offset)
+ .then(messages => messages.length > 0)
+ .catch(() => false)
+}
+
function mergeUniqueMessages(
existing: AgentChatMessage[],
incoming: AgentChatMessage[],
@@ -679,10 +693,7 @@ export function useAgentChatController({
const hasOlderLocalMessages =
!hasOlderServerMessages &&
cached.length === MESSAGE_PAGE_SIZE &&
- (await chatStore
- .loadMessages(agentRef, chatId, 1, MESSAGE_PAGE_SIZE)
- .then(messages => messages.length > 0)
- .catch(() => false))
+ (await hasLocalMessagesBeyond(chatStore, agentRef, chatId, MESSAGE_PAGE_SIZE))
if (!isStillActive()) return
loadedLocalMessageCountRef.current = cached.length
setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)
@@ -797,9 +808,22 @@ export function useAgentChatController({
.catch(() => [])) as AgentChatMessage[]
const unseenLocal = localPage.filter(message => !visibleIds.has(message.id))
if (unseenLocal.length) {
- loadedLocalMessageCountRef.current += localPage.length
- setChatMessages(previous => mergeUniqueMessages(previous, unseenLocal, 'before'))
- setHasOlderMessages(localPage.length === MESSAGE_PAGE_SIZE)
+ const nextLoadedLocalMessageCount = loadedLocalMessageCountRef.current + localPage.length
+ const merged = mergeUniqueMessages(chatMessages, unseenLocal, 'before')
+ const oldestMergedTurn = oldestServerTurnNumber(merged)
+ const hasOlderServerMessages = Boolean(oldestMergedTurn && oldestMergedTurn > 1)
+ const hasOlderLocalMessages =
+ !hasOlderServerMessages &&
+ localPage.length === MESSAGE_PAGE_SIZE &&
+ (await hasLocalMessagesBeyond(
+ chatStore,
+ selectedAgent,
+ activeChatId,
+ nextLoadedLocalMessageCount
+ ))
+ loadedLocalMessageCountRef.current = nextLoadedLocalMessageCount
+ setChatMessages(merged)
+ setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)
return
}