Skip to content

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

TypeScript

fix: address desktop paging and session review findings

Josuécdd62e16cbfc
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 46b72d094..180fa9f38 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.331",
+ "version": "0.1.332",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.331",
+ "version": "0.1.332",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index b8fd69335..60bbb28e1 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.331",
+ "version": "0.1.332",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/scripts/start-branded-app.mjs b/desktop-app/scripts/start-branded-app.mjs
index f24b3edaa..263b0d3f8 100644
--- a/desktop-app/scripts/start-branded-app.mjs
+++ b/desktop-app/scripts/start-branded-app.mjs
@@ -70,9 +70,9 @@ async function main() {
throw new Error(`The branded ${APP_NAME} executable was not created at ${executable}.`)
}
- const appProcess = spawn(executable, [], {
+ const appProcess = spawn(executable, ['--evenfire-desktop-dev-package'], {
cwd: projectDirectory,
- env: { ...process.env, EVENFIRE_DESKTOP_DEV_PACKAGE: '1' },
+ env: process.env,
stdio: 'inherit',
})
diff --git a/desktop-app/src/__tests__/chatMessageMerge.test.ts b/desktop-app/src/__tests__/chatMessageMerge.test.ts
new file mode 100644
index 000000000..658831275
--- /dev/null
+++ b/desktop-app/src/__tests__/chatMessageMerge.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from 'vitest'
+import { mergeAuthoritativeServerMessages } from '../chatMessageMerge.js'
+import type { ChatMessage } from '../types.js'
+
+describe('mergeAuthoritativeServerMessages', () => {
+ it('replaces an image-only optimistic turn despite content and clock differences', () => {
+ const existing: ChatMessage[] = [
+ {
+ id: 'optimistic-user',
+ role: 'user',
+ content: '',
+ timestamp: 1,
+ attachments: [
+ {
+ id: 'photo',
+ type: 'uploaded_file',
+ label: 'photo.png',
+ mimeType: 'image/png',
+ },
+ ],
+ },
+ {
+ id: 'optimistic-assistant',
+ role: 'assistant',
+ content: 'working',
+ timestamp: 2,
+ },
+ ]
+ const incoming: ChatMessage[] = [
+ {
+ id: 'turn-7-user',
+ role: 'user',
+ content: '[Image attached]',
+ timestamp: 120_001,
+ serverTurnNumber: 7,
+ },
+ {
+ id: 'turn-7-assistant',
+ role: 'assistant',
+ content: 'done',
+ timestamp: 120_002,
+ serverTurnNumber: 7,
+ },
+ ]
+
+ const merged = mergeAuthoritativeServerMessages(existing, incoming)
+
+ expect(merged.map(message => message.id)).toEqual(['turn-7-user', 'turn-7-assistant'])
+ expect(merged[0]?.attachments).toEqual(existing[0]?.attachments)
+ })
+
+ it('preserves a task-backed in-flight message outside the authoritative turn', () => {
+ const pending: ChatMessage = {
+ id: 'pending',
+ role: 'assistant',
+ content: 'still running',
+ timestamp: 2,
+ task_id: 'task-1',
+ }
+ const merged = mergeAuthoritativeServerMessages(
+ [{ id: 'optimistic', role: 'user', content: 'old', timestamp: 1 }, pending],
+ [
+ {
+ id: 'turn-3-user',
+ role: 'user',
+ content: 'server copy',
+ timestamp: 100,
+ serverTurnNumber: 3,
+ },
+ ]
+ )
+
+ expect(merged.map(message => message.id)).toEqual(['turn-3-user', 'pending'])
+ })
+})
diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.ts
index 4e0192802..917d372f5 100644
--- a/desktop-app/src/__tests__/chatStore.test.ts
+++ b/desktop-app/src/__tests__/chatStore.test.ts
@@ -548,7 +548,11 @@ describe('messages', () => {
await fs.mkdir(`${chatCacheDir('stale-snapshots')}.next-stale`, { recursive: true })
await fs.mkdir(`${chatCacheDir('stale-snapshots')}.previous-stale`, { recursive: true })
- const reloaded = await pagedStore.loadMessages('agent-1', 'stale-snapshots')
+ const restartedStore = new ChatStore(tempDir, {
+ pageSize: 2,
+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,
+ })
+ const reloaded = await restartedStore.loadMessages('agent-1', 'stale-snapshots')
expect(reloaded.map(message => message.id)).toEqual(['m0'])
await expect(fs.access(`${chatCacheDir('stale-snapshots')}.next-stale`)).rejects.toThrow()
await expect(fs.access(`${chatCacheDir('stale-snapshots')}.previous-stale`)).rejects.toThrow()
@@ -612,7 +616,7 @@ describe('messages', () => {
expect(localMessages.map(message => message.id)).toEqual(['m2', 'm3', 'm4', 'm5'])
})
- it('does not prune pages containing local-only messages', async () => {
+ it('keeps local-only pages while pruning later fully synced pages', async () => {
const prunedStore = new ChatStore(tempDir, {
pageSize: 2,
maxLocalSyncedMessages: 4,
@@ -628,16 +632,12 @@ describe('messages', () => {
await prunedStore.saveMessages('agent-1', 'local-only', msgs)
- expect(await fs.readdir(chatPagesDir('local-only'))).toEqual([
- '000001.json',
- '000002.json',
- '000003.json',
- ])
+ expect(await fs.readdir(chatPagesDir('local-only'))).toEqual(['000001.json', '000003.json'])
const meta = await readJsonFile<{ localMessageCount: number; prunedBeforeCount?: number }>(
chatMetaPath('local-only')
)
- expect(meta.localMessageCount).toBe(6)
- expect(meta.prunedBeforeCount).toBeUndefined()
+ expect(meta.localMessageCount).toBe(4)
+ expect(meta.prunedBeforeCount).toBe(2)
})
it('updates messageCount in index after save', async () => {
@@ -780,7 +780,11 @@ describe('messages', () => {
)
await fs.rm(join(chatPagesDir('missing-page'), '000002.json'))
- const recovered = await pagedStore.loadMessages('agent-1', 'missing-page')
+ const restartedStore = new ChatStore(tempDir, {
+ pageSize: 2,
+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,
+ })
+ const recovered = await restartedStore.loadMessages('agent-1', 'missing-page')
expect(recovered.map(message => message.id)).toEqual(['m0', 'm1', 'm2', 'm3', 'm4', 'm5'])
const repairedMeta = await readJsonFile<{ localMessageCount: number }>(
@@ -809,7 +813,11 @@ describe('messages', () => {
})
)
- const recovered = await pagedStore.loadMessages('agent-1', 'orphan-append')
+ const restartedStore = new ChatStore(tempDir, {
+ pageSize: 2,
+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,
+ })
+ const recovered = await restartedStore.loadMessages('agent-1', 'orphan-append')
expect(recovered.map(message => message.id)).toEqual(['m0', 'm1', 'm2'])
const repairedMeta = await readJsonFile<{ localMessageCount: number; pages: unknown[] }>(
@@ -817,6 +825,10 @@ describe('messages', () => {
)
expect(repairedMeta).toMatchObject({ localMessageCount: 3 })
expect(repairedMeta.pages).toHaveLength(2)
+ expect(
+ (await restartedStore.listChats('agent-1')).find(chat => chat.id === 'orphan-append')
+ ?.messageCount
+ ).toBe(3)
})
it('persists task_id and writes the paged chat cache', async () => {
@@ -966,7 +978,8 @@ describe('messages', () => {
})
)
- const recovered = await store.loadMessages('agent-1', 'downgraded-write')
+ const restartedStore = new ChatStore(tempDir)
+ const recovered = await restartedStore.loadMessages('agent-1', 'downgraded-write')
expect(recovered.map(message => message.id)).toEqual(['m1', 'm2'])
const compatibility = await readJsonFile<{ messages: ChatMessage[] }>(
@@ -982,7 +995,8 @@ describe('messages', () => {
])
await fs.writeFile(agentPath('corrupt-downgrade-snapshot.json'), 'not json{')
- const recovered = await store.loadMessages('agent-1', 'corrupt-downgrade-snapshot')
+ const restartedStore = new ChatStore(tempDir)
+ const recovered = await restartedStore.loadMessages('agent-1', 'corrupt-downgrade-snapshot')
expect(recovered.map(message => message.id)).toEqual(['m1'])
const compatibility = await readJsonFile<{ messages: ChatMessage[] }>(
diff --git a/desktop-app/src/__tests__/chatStoreBinding.test.ts b/desktop-app/src/__tests__/chatStoreBinding.test.ts
index 34472b3af..a76f87be5 100644
--- a/desktop-app/src/__tests__/chatStoreBinding.test.ts
+++ b/desktop-app/src/__tests__/chatStoreBinding.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 os from 'node:os'
import path from 'node:path'
@@ -204,6 +204,41 @@ describe('chatStoreBinding', () => {
expect(await exists(path.join(tmpBase, ENV_A, 'user-v3', 'agent-x', 'keep.json'))).toBe(true)
})
+ it('preserves a valid v3 cache when its index normalization cannot be renamed', async () => {
+ const v3Index = JSON.stringify({
+ version: 3,
+ chats: [{ id: 'keep', title: 'Keep', createdAt: 'x', updatedAt: 'x', messageCount: 1 }],
+ lastActiveChatId: 'keep',
+ onboardingDismissed: false,
+ })
+ await seedAgentDir(ENV_A, 'user-v3-failure', 'agent-x', v3Index, {
+ 'keep.json': '{"version":2,"chatId":"keep","messages":[]}',
+ })
+ const originalRename = fs.rename.bind(fs)
+ vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => {
+ if (String(from).endsWith('index.json.v2.tmp')) {
+ const error = new Error('read only') as NodeJS.ErrnoException
+ error.code = 'EACCES'
+ throw error
+ }
+ return originalRename(from, to)
+ })
+
+ await bindChatStoreForUser('user-v3-failure', ENV_A)
+
+ expect(
+ await exists(path.join(tmpBase, ENV_A, 'user-v3-failure', 'agent-x', 'keep.json'))
+ ).toBe(true)
+ expect(
+ JSON.parse(
+ await fs.readFile(
+ path.join(tmpBase, ENV_A, 'user-v3-failure', 'agent-x', 'index.json'),
+ 'utf-8'
+ )
+ ).version
+ ).toBe(3)
+ })
+
it('is a no-op when the user has no cache directory yet', async () => {
await expect(bindChatStoreForUser('brand-new-user', ENV_A)).resolves.toBeUndefined()
expect(await requireChatStore().listChats('agent-x')).toEqual([])
diff --git a/desktop-app/src/__tests__/config.runtimeConfig.test.ts b/desktop-app/src/__tests__/config.runtimeConfig.test.ts
index 36fd8ac5e..5c81fd5ca 100644
--- a/desktop-app/src/__tests__/config.runtimeConfig.test.ts
+++ b/desktop-app/src/__tests__/config.runtimeConfig.test.ts
@@ -8,7 +8,7 @@ describe('desktop runtime config', () => {
const originalExternalRestApiBaseUrl = process.env.EXTERNAL_REST_API_BASE_URL
const originalRpcProxyBaseUrl = process.env.RPC_PROXY_BASE_URL
const originalDesktopAppName = process.env.DESKTOP_APP_NAME
- const originalDesktopDevPackage = process.env.EVENFIRE_DESKTOP_DEV_PACKAGE
+ const originalArgv = [...process.argv]
const originalRendererUrl = process.env.EVENFIRE_RENDERER_URL
let tempUserDataDir: string | null = null
@@ -38,11 +38,7 @@ describe('desktop runtime config', () => {
} else {
process.env.DESKTOP_APP_NAME = originalDesktopAppName
}
- if (originalDesktopDevPackage === undefined) {
- delete process.env.EVENFIRE_DESKTOP_DEV_PACKAGE
- } else {
- process.env.EVENFIRE_DESKTOP_DEV_PACKAGE = originalDesktopDevPackage
- }
+ process.argv.splice(0, process.argv.length, ...originalArgv)
if (originalRendererUrl === undefined) {
delete process.env.EVENFIRE_RENDERER_URL
} else {
@@ -135,7 +131,7 @@ describe('desktop runtime config', () => {
process.env.EXTERNAL_REST_API_BASE_URL = 'http://127.0.0.1:8091'
process.env.RPC_PROXY_BASE_URL = 'http://127.0.0.1:8094'
process.env.EVENFIRE_RENDERER_URL = 'http://127.0.0.1:5173'
- process.env.EVENFIRE_DESKTOP_DEV_PACKAGE = '1'
+ process.argv.push('--evenfire-desktop-dev-package')
vi.doMock('electron', () => ({
app: {
@@ -166,7 +162,7 @@ describe('desktop runtime config', () => {
delete process.env.CLERUM_DESKTOP_CONFIG_PATH
process.env.EXTERNAL_REST_API_BASE_URL = 'https://attacker.example.com'
process.env.RPC_PROXY_BASE_URL = 'https://rpc.attacker.example.com'
- process.env.EVENFIRE_DESKTOP_DEV_PACKAGE = '1'
+ process.argv.push('--evenfire-desktop-dev-package')
vi.doMock('electron', () => ({
app: {
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index d4d25f0bb..ea42774a8 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -270,6 +270,7 @@ export class AppService {
private teamDirectoryCache: TeamDirectoryResult | null = null
private teamContextQueue: Promise<void> = Promise.resolve()
private restoreSavedSessionInFlight: Promise<SessionState> | null = null
+ private sessionGeneration = 0
private workflowApprovalTeamById = new Map<string, string>()
private workflowTeamByKey = new Map<string, string>()
private readonly prewarmAttemptAtByHostRef = new Map<string, number>()
@@ -385,6 +386,7 @@ export class AppService {
options: { refreshMe?: boolean } = {}
): Promise<void> {
const tokenChanged = token !== this.sessionToken
+ if (tokenChanged) this.sessionGeneration += 1
this.sessionToken = token
if (tokenChanged) {
this.rpcTokenManager.clear()
@@ -521,6 +523,7 @@ export class AppService {
}
private clearAuthenticatedSessionState(): void {
+ this.sessionGeneration += 1
this.stopAllStreams()
this.sessionToken = null
this.me = null
@@ -548,18 +551,34 @@ export class AppService {
}
private async restoreSavedSessionOnce(options: { runLaunchMaintenance?: boolean } = {}) {
+ const restoreGeneration = this.sessionGeneration
hydrateDesktopRuntimeConfig()
const envKey = getActiveEnvKey()
const token = await this.tokenStore.getSessionToken(envKey)
if (!token) {
- this.clearAuthenticatedSessionState()
+ if (this.sessionGeneration === restoreGeneration) {
+ this.clearAuthenticatedSessionState()
+ }
return { authenticated: false, me: null }
}
+ if (this.sessionGeneration !== restoreGeneration) {
+ return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }
+ }
this.sessionToken = token
try {
- this.me = await this.authClient.getMe(token)
- await bindChatStoreForUser(this.me.id, envKey)
+ const restoredMe = await this.authClient.getMe(token)
+ if (this.sessionGeneration !== restoreGeneration || this.sessionToken !== token) {
+ return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }
+ }
+ this.me = restoredMe
+ await bindChatStoreForUser(restoredMe.id, envKey)
+ if (this.sessionGeneration !== restoreGeneration || this.sessionToken !== token) {
+ if (this.me) {
+ await bindChatStoreForUser(this.me.id, getActiveEnvKey())
+ }
+ return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }
+ }
this.accessCatalog = null
this.teamDirectoryCache = null
this.workflowApprovalTeamById.clear()
@@ -572,6 +591,9 @@ export class AppService {
}
return { authenticated: true, me: this.me }
} catch (error) {
+ if (this.sessionGeneration !== restoreGeneration || this.sessionToken !== token) {
+ return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }
+ }
this.clearAuthenticatedSessionState()
if (AppService.isRejectedStoredSessionError(error)) {
await this.tokenStore.clearSessionToken(envKey)
@@ -608,6 +630,7 @@ export class AppService {
private async completePasswordLogin(email: string, password: string): Promise<SessionState> {
const result = await this.authClient.passwordLogin(email, password)
+ this.sessionGeneration += 1
this.sessionToken = result.token
this.me = result.me
await bindChatStoreForUser(result.me.id, getActiveEnvKey())
@@ -677,6 +700,7 @@ export class AppService {
async googleLogin(idToken: string): Promise<SessionState> {
const result = await this.authClient.googleLogin(idToken)
+ this.sessionGeneration += 1
this.sessionToken = result.token
this.me = result.me
await bindChatStoreForUser(result.me.id, getActiveEnvKey())
diff --git a/desktop-app/src/chatMessageMerge.ts b/desktop-app/src/chatMessageMerge.ts
new file mode 100644
index 000000000..8a4e295bf
--- /dev/null
+++ b/desktop-app/src/chatMessageMerge.ts
@@ -0,0 +1,107 @@
+import type { ChatMessage } from './types.js'
+
+export function messageServerTurnNumber(message: Pick<ChatMessage, 'id' | 'serverTurnNumber'>) {
+ if (message.serverTurnNumber !== undefined) return message.serverTurnNumber
+ const match = /^turn-(\d+)-(?:user|assistant)$/.exec(message.id)
+ return match ? Number(match[1]) : undefined
+}
+
+function roleRank(message: Pick<ChatMessage, 'role'>): number {
+ return message.role === 'user' ? 0 : message.role === 'assistant' ? 1 : 2
+}
+
+function preferredServerMessage(server: ChatMessage, local: ChatMessage | undefined): ChatMessage {
+ if (!local) return server
+ return {
+ ...server,
+ task_id: local.task_id ?? server.task_id,
+ attachments: server.attachments?.length ? server.attachments : local.attachments,
+ }
+}
+
+/**
+ * Replace the authoritative server-turn range as a unit.
+ *
+ * Turnless optimistic messages positioned inside that range are paired by role
+ * and replaced even when content or clocks differ. Unmatched in-flight messages
+ * remain, while orphaned optimistic messages are evicted.
+ */
+export function mergeAuthoritativeServerMessages(
+ existing: ChatMessage[],
+ incoming: ChatMessage[]
+): ChatMessage[] {
+ const authoritative = incoming
+ .filter(message => messageServerTurnNumber(message) !== undefined)
+ .sort((left, right) => {
+ const turnDelta =
+ (messageServerTurnNumber(left) ?? Number.MAX_SAFE_INTEGER) -
+ (messageServerTurnNumber(right) ?? Number.MAX_SAFE_INTEGER)
+ return turnDelta || roleRank(left) - roleRank(right)
+ })
+ if (!authoritative.length) {
+ const incomingIds = new Set(incoming.map(message => message.id))
+ return [...existing.filter(message => !incomingIds.has(message.id)), ...incoming]
+ }
+
+ const firstTurn = messageServerTurnNumber(authoritative[0]!)!
+ const lastTurn = messageServerTurnNumber(authoritative.at(-1)!)!
+ const previousTurns: Array<number | undefined> = []
+ let previousTurn: number | undefined
+ for (const message of existing) {
+ previousTurns.push(previousTurn)
+ previousTurn = messageServerTurnNumber(message) ?? previousTurn
+ }
+ const nextTurns: Array<number | undefined> = new Array(existing.length)
+ let nextTurn: number | undefined
+ for (let index = existing.length - 1; index >= 0; index -= 1) {
+ nextTurns[index] = nextTurn
+ nextTurn = messageServerTurnNumber(existing[index]!) ?? nextTurn
+ }
+
+ const removed: ChatMessage[] = []
+ const kept: ChatMessage[] = []
+ let insertionIndex: number | undefined
+ for (const [index, message] of existing.entries()) {
+ const turn = messageServerTurnNumber(message)
+ const numberedInRange = turn !== undefined && turn >= firstTurn && turn <= lastTurn
+ const turnlessInRange =
+ turn === undefined &&
+ (previousTurns[index] ?? Number.NEGATIVE_INFINITY) < firstTurn &&
+ (nextTurns[index] ?? Number.POSITIVE_INFINITY) >= firstTurn
+ const shouldReplace =
+ numberedInRange || (turnlessInRange && !message.task_id && !message.isError)
+ if (shouldReplace) {
+ insertionIndex ??= kept.length
+ removed.push(message)
+ } else {
+ kept.push(message)
+ }
+ }
+
+ if (insertionIndex === undefined) {
+ const nextNumberedIndex = kept.findIndex(message => {
+ const turn = messageServerTurnNumber(message)
+ return turn !== undefined && turn > lastTurn
+ })
+ insertionIndex = nextNumberedIndex < 0 ? kept.length : nextNumberedIndex
+ }
+
+ const availableByRole = new Map<ChatMessage['role'], ChatMessage[]>()
+ for (const message of removed) {
+ const entries = availableByRole.get(message.role) ?? []
+ entries.push(message)
+ availableByRole.set(message.role, entries)
+ }
+ const replacements = authoritative.map(message => {
+ const sameTurn = removed.find(
+ local =>
+ messageServerTurnNumber(local) === messageServerTurnNumber(message) &&
+ local.role === message.role
+ )
+ const local = sameTurn ?? availableByRole.get(message.role)?.shift()
+ return preferredServerMessage(message, local)
+ })
+
+ kept.splice(insertionIndex, 0, ...replacements)
+ return kept
+}
diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.ts
index 0d9cc5630..7a18e0d59 100644
--- a/desktop-app/src/chatStore.ts
+++ b/desktop-app/src/chatStore.ts
@@ -1,6 +1,7 @@
import { createHash, randomUUID } from 'node:crypto'
import { promises as fs } from 'node:fs'
import { join } from 'node:path'
+import { mergeAuthoritativeServerMessages } from './chatMessageMerge.js'
import type { ChatFile, ChatIndex, ChatMessage, ChatMetadata } from './types.js'
// Keep the catalog at v2 while paged transcripts are dual-readable by the
@@ -225,6 +226,8 @@ export class ChatStore {
private indexChains = new Map<string, Promise<unknown>>()
private chatChains = new Map<string, Promise<unknown>>()
private cleanedSnapshotSiblingKeys = new Set<string>()
+ private compatibilityCheckedKeys = new Set<string>()
+ private compatibilityWindows = new Map<string, ChatMessage[]>()
private serialize<T>(
chains: Map<string, Promise<unknown>>,
@@ -436,6 +439,7 @@ export class ChatStore {
await this.writeJsonAtomic(this.chatCompatibilitySignaturePath(agentRef, chatId), {
signature,
})
+ this.compatibilityWindows.set(this.chatSnapshotCleanupKey(agentRef, chatId), [...file.messages])
return signature
}
@@ -483,22 +487,42 @@ export class ChatStore {
chatId: string,
meta: PagedChatMeta
): Promise<PagedChatMeta> {
+ const compatibilityKey = this.chatSnapshotCleanupKey(agentRef, chatId)
let legacyMessages: ChatMessage[] | null
try {
legacyMessages = await this.readLegacyMessages(agentRef, chatId)
} catch (error) {
- if (isRawFilesystemError(error)) throw error
+ if (isRawFilesystemError(error)) {
+ console.warn(`[chatStore] Downgrade snapshot unavailable for ${chatId}:`, error)
+ return meta
+ }
return this.refreshLegacyCompatibilitySnapshotUnlocked(agentRef, chatId, meta)
}
if (!legacyMessages) {
- return this.refreshLegacyCompatibilitySnapshotUnlocked(agentRef, chatId, meta)
+ const refreshed = await this.refreshLegacyCompatibilitySnapshotUnlocked(
+ agentRef,
+ chatId,
+ meta
+ )
+ this.compatibilityCheckedKeys.add(compatibilityKey)
+ return refreshed
}
+ this.compatibilityWindows.set(compatibilityKey, [...legacyMessages])
const legacySignature = this.legacyCompatibilitySnapshot(chatId, legacyMessages).signature
- if (legacySignature === meta.legacyCompatibilitySignature) return meta
+ if (legacySignature === meta.legacyCompatibilitySignature) {
+ this.compatibilityCheckedKeys.add(compatibilityKey)
+ return meta
+ }
const recordedSignature = await this.readLegacyCompatibilitySignature(agentRef, chatId)
if (legacySignature === recordedSignature) {
- return this.refreshLegacyCompatibilitySnapshotUnlocked(agentRef, chatId, meta)
+ const refreshed = await this.refreshLegacyCompatibilitySnapshotUnlocked(
+ agentRef,
+ chatId,
+ meta
+ )
+ this.compatibilityCheckedKeys.add(compatibilityKey)
+ return refreshed
}
const existing = await this.readMessagesFromPagedMeta(agentRef, chatId, meta)
@@ -510,7 +534,13 @@ export class ChatStore {
)
)
if (!missing.length) {
- return this.refreshLegacyCompatibilitySnapshotUnlocked(agentRef, chatId, meta)
+ const refreshed = await this.refreshLegacyCompatibilitySnapshotUnlocked(
+ agentRef,
+ chatId,
+ meta
+ )
+ this.compatibilityCheckedKeys.add(compatibilityKey)
+ return refreshed
}
const merged = mergeReconciledMessages(existing, missing)
@@ -520,7 +550,9 @@ export class ChatStore {
})
await this.updateChatIndexFromMessages(agentRef, chatId, merged, {
preserveExistingTotals: true,
+ touchUpdatedAt: false,
})
+ this.compatibilityCheckedKeys.add(compatibilityKey)
return imported
}
@@ -626,21 +658,21 @@ export class ChatStore {
let prunedThroughServerTurnNumber = meta.prunedThroughServerTurnNumber
const retained: ChatPageEntry[] = []
const removedFiles: string[] = []
- let pruning = true
-
for (const page of meta.pages) {
const canPrunePage =
- pruning && page.serverSynced && localCount - page.count >= this.maxLocalSyncedMessages
+ page.serverSynced && localCount - page.count >= this.maxLocalSyncedMessages
if (canPrunePage) {
removedFiles.push(page.file)
localCount -= page.count
prunedBeforeCount += page.count
- prunedThroughServerTurnNumber = page.lastServerTurnNumber ?? prunedThroughServerTurnNumber
+ prunedThroughServerTurnNumber = Math.max(
+ prunedThroughServerTurnNumber ?? 0,
+ page.lastServerTurnNumber ?? 0
+ )
continue
}
- pruning = false
retained.push(page)
}
@@ -728,9 +760,24 @@ export class ChatStore {
pages: repairedPages,
})
await this.writePagedMeta(agentRef, chatId, repaired)
+ await this.updateIndexedMessageCount(agentRef, chatId, repaired.messageCount)
return repaired
}
+ private async updateIndexedMessageCount(
+ agentRef: string,
+ chatId: string,
+ messageCount: number
+ ): Promise<void> {
+ await this.serializeIndex(agentRef, async () => {
+ const index = await this.getIndex(agentRef)
+ const chat = index.chats.find(candidate => candidate.id === chatId)
+ if (!chat || chat.messageCount >= messageCount) return
+ chat.messageCount = messageCount
+ await this.saveIndex(agentRef, index)
+ })
+ }
+
private async rebuildPagedChatFromSurvivingFilesUnlocked(
agentRef: string,
chatId: string
@@ -767,7 +814,10 @@ export class ChatStore {
return true
}
- private async recoverPagedChatUnlocked(agentRef: string, chatId: string): Promise<void> {
+ private async recoverPagedChatUnlocked(
+ agentRef: string,
+ chatId: string
+ ): Promise<PagedChatMeta | null> {
const activeDir = this.chatDirPath(agentRef, chatId)
const chatsDir = join(this.agentDir(agentRef), 'chats')
const cleanupKey = this.chatSnapshotCleanupKey(agentRef, chatId)
@@ -782,12 +832,12 @@ export class ChatStore {
}
if (activeMeta) {
+ if (this.cleanedSnapshotSiblingKeys.has(cleanupKey)) return activeMeta
const repaired = await this.adoptDurablePageWritesUnlocked(agentRef, chatId, activeMeta)
if (repaired) {
- if (this.cleanedSnapshotSiblingKeys.has(cleanupKey)) return
await this.removePagedChatSnapshotSiblings(chatsDir, chatId)
this.cleanedSnapshotSiblingKeys.add(cleanupKey)
- return
+ return repaired
}
activeReadError = new Error(`Paged chat snapshot is incomplete for ${chatId}`)
activeMeta = null
@@ -804,7 +854,7 @@ export class ChatStore {
try {
entries = await fs.readdir(chatsDir, { withFileTypes: true })
} catch {
- return
+ return null
}
const snapshots = await Promise.all(
@@ -875,7 +925,7 @@ export class ChatStore {
await fs.rm(corruptDir, { recursive: true, force: true }).catch(() => undefined)
}
this.cleanedSnapshotSiblingKeys.add(cleanupKey)
- return
+ return await this.readPagedMeta(agentRef, chatId)
} catch (err) {
if (corruptDir) {
await fs.rename(corruptDir, activeDir).catch(() => undefined)
@@ -884,8 +934,12 @@ export class ChatStore {
}
}
- if (await this.rebuildPagedChatFromSurvivingFilesUnlocked(agentRef, chatId)) return
+ if (await this.rebuildPagedChatFromSurvivingFilesUnlocked(agentRef, chatId)) {
+ this.cleanedSnapshotSiblingKeys.add(cleanupKey)
+ return await this.readPagedMeta(agentRef, chatId)
+ }
if (activeReadError) throw activeReadError
+ return null
}
private async removePagedChatSnapshotSiblings(chatsDir: string, chatId: string): Promise<void> {
@@ -995,6 +1049,9 @@ export class ChatStore {
await fs.rm(backupDir, { recursive: true, force: true }).catch(() => undefined)
}
await this.writeLegacyCompatibilitySnapshot(agentRef, chatId, messages)
+ const cacheKey = this.chatSnapshotCleanupKey(agentRef, chatId)
+ this.cleanedSnapshotSiblingKeys.add(cacheKey)
+ this.compatibilityCheckedKeys.add(cacheKey)
return pruned.meta
} catch (err) {
@@ -1010,9 +1067,11 @@ export class ChatStore {
agentRef: string,
chatId: string
): Promise<PagedChatMeta | null> {
- await this.recoverPagedChatUnlocked(agentRef, chatId)
- const paged = await this.readPagedMeta(agentRef, chatId)
+ const paged = await this.recoverPagedChatUnlocked(agentRef, chatId)
if (paged) {
+ if (this.compatibilityCheckedKeys.has(this.chatSnapshotCleanupKey(agentRef, chatId))) {
+ return paged
+ }
return this.importDowngradedLocalMessagesUnlocked(agentRef, chatId, paged)
}
@@ -1020,7 +1079,9 @@ export class ChatStore {
if (!legacyMessages) return null
const migrated = await this.writePagedChatUnlocked(agentRef, chatId, legacyMessages)
- await this.updateChatIndexFromMessages(agentRef, chatId, legacyMessages)
+ await this.updateChatIndexFromMessages(agentRef, chatId, legacyMessages, {
+ touchUpdatedAt: false,
+ })
return migrated
}
@@ -1069,6 +1130,8 @@ export class ChatStore {
): Promise<PagedChatMeta> {
if (!newMessages.length) return meta
+ const cacheKey = this.chatSnapshotCleanupKey(agentRef, chatId)
+ this.cleanedSnapshotSiblingKeys.delete(cacheKey)
const pages = [...meta.pages]
let remaining = [...newMessages]
@@ -1103,12 +1166,15 @@ export class ChatStore {
messageCount,
pages,
})
- const compatibilityMessages = await this.readMessagesFromPagedMeta(
- agentRef,
- chatId,
- pruned.meta,
- LEGACY_COMPATIBILITY_MESSAGE_LIMIT
- )
+ const cachedCompatibilityMessages = this.compatibilityWindows.get(cacheKey)
+ const compatibilityMessages = cachedCompatibilityMessages
+ ? [...cachedCompatibilityMessages, ...newMessages].slice(-LEGACY_COMPATIBILITY_MESSAGE_LIMIT)
+ : await this.readMessagesFromPagedMeta(
+ agentRef,
+ chatId,
+ pruned.meta,
+ LEGACY_COMPATIBILITY_MESSAGE_LIMIT
+ )
const compatibility = this.legacyCompatibilitySnapshot(chatId, compatibilityMessages)
pruned.meta.legacyCompatibilitySignature = compatibility.signature
await this.writePagedMeta(agentRef, chatId, pruned.meta)
@@ -1117,7 +1183,11 @@ export class ChatStore {
fs.rm(this.chatPagePath(agentRef, chatId, file), { force: true })
)
)
- await this.writeLegacyCompatibilitySnapshot(agentRef, chatId, compatibilityMessages)
+ if (compatibility.signature !== meta.legacyCompatibilitySignature) {
+ await this.writeLegacyCompatibilitySnapshot(agentRef, chatId, compatibilityMessages)
+ }
+ this.cleanedSnapshotSiblingKeys.add(cacheKey)
+ this.compatibilityCheckedKeys.add(cacheKey)
return pruned.meta
}
@@ -1223,7 +1293,10 @@ export class ChatStore {
await fs.rm(this.chatCompatibilitySignaturePath(agentRef, chatId), { force: true })
await fs.rm(this.chatDirPath(agentRef, chatId), { recursive: true, force: true })
await this.removePagedChatSnapshotSiblings(join(this.agentDir(agentRef), 'chats'), chatId)
- this.cleanedSnapshotSiblingKeys.delete(this.chatSnapshotCleanupKey(agentRef, chatId))
+ const cacheKey = this.chatSnapshotCleanupKey(agentRef, chatId)
+ this.cleanedSnapshotSiblingKeys.delete(cacheKey)
+ this.compatibilityCheckedKeys.delete(cacheKey)
+ this.compatibilityWindows.delete(cacheKey)
})
}
@@ -1249,7 +1322,7 @@ export class ChatStore {
agentRef: string,
chatId: string,
messages: ChatMessage[],
- options: { preserveExistingTotals?: boolean } = {}
+ options: { preserveExistingTotals?: boolean; touchUpdatedAt?: boolean } = {}
): Promise<void> {
await this.serializeIndex(agentRef, async () => {
const index = await this.getIndex(agentRef)
@@ -1265,7 +1338,9 @@ export class ChatStore {
chat.messageCount = messages.length
Object.assign(chat, aggregate)
}
- chat.updatedAt = new Date().toISOString()
+ if (options.touchUpdatedAt !== false) {
+ chat.updatedAt = new Date().toISOString()
+ }
await this.saveIndex(agentRef, index)
})
}
@@ -1317,7 +1392,7 @@ export class ChatStore {
const existingMessages = existingMeta
? await this.readMessagesFromPagedMeta(agentRef, chatId, existingMeta)
: []
- const merged = mergeReconciledMessages(existingMessages, messages)
+ const merged = mergeAuthoritativeServerMessages(existingMessages, messages)
const indexedCount = await this.indexedMessageCount(agentRef, chatId)
await this.writePagedChatUnlocked(agentRef, chatId, merged, {
messageCount: Math.max(merged.length, indexedCount ?? 0),
diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.ts
index ae3d19d4d..6f6f8c356 100644
--- a/desktop-app/src/chatStoreBinding.ts
+++ b/desktop-app/src/chatStoreBinding.ts
@@ -182,14 +182,24 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {
const raw = await fs.readFile(indexPath, 'utf-8')
const parsed = JSON.parse(raw) as { version?: number }
if (parsed.version === PREVIOUS_PAGED_INDEX_VERSION) {
- const migratedIndexPath = `${indexPath}.v2.tmp`
- await fs.writeFile(
- migratedIndexPath,
- JSON.stringify({ ...parsed, version: SCHEMA_VERSION }, null, 2),
- { mode: 0o600 }
- )
- await fs.rename(migratedIndexPath, indexPath)
+ // A parsed v3 catalog is valid even if the compatibility-marker rewrite
+ // fails. Keep the cache and retry the atomic normalization next launch.
isLegacy = false
+ const migratedIndexPath = `${indexPath}.v2.tmp`
+ try {
+ await fs.writeFile(
+ migratedIndexPath,
+ JSON.stringify({ ...parsed, version: SCHEMA_VERSION }, null, 2),
+ { mode: 0o600 }
+ )
+ await fs.rename(migratedIndexPath, indexPath)
+ } catch (error) {
+ await fs.rm(migratedIndexPath, { force: true }).catch(() => undefined)
+ console.warn(
+ `[chatStore] Failed to normalize v3 index for "${entry.name}"; retrying next launch`,
+ error
+ )
+ }
} else {
isLegacy = parsed.version !== SCHEMA_VERSION
}
diff --git a/desktop-app/src/config.ts b/desktop-app/src/config.ts
index 682beb6c2..5efe732ce 100644
--- a/desktop-app/src/config.ts
+++ b/desktop-app/src/config.ts
@@ -482,7 +482,7 @@ const envRuntimeConfig = validateRuntimeConfig({
appName: requiredOrDefault('DESKTOP_APP_NAME', DEFAULT_APP_NAME),
})
const desktopDevPackageRuntimeConfigEnabled =
- process.env.EVENFIRE_DESKTOP_DEV_PACKAGE?.trim() === '1' &&
+ process.argv.includes('--evenfire-desktop-dev-package') &&
isLocalhostRuntimeConfig(envRuntimeConfig)
const canUseEnvRuntimeConfig = !app?.isPackaged || desktopDevPackageRuntimeConfigEnabled
const envRuntimeConfigured = Boolean(
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 4e37b6a75..50ab7da89 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -807,7 +807,7 @@ export interface ChatMetadata {
}
export interface ChatIndex {
- /** v3 marks paged chat caches so older builds wipe rather than mix storage formats. */
+ /** v2 remains readable by pre-paging builds; v3 is accepted and normalized for compatibility. */
version: 1 | 2 | 3
lastActiveChatId: string | null
onboardingDismissed: boolean
diff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsx
index 1d861bf7a..145f64da8 100644
--- a/desktop-app/ui/src/components/agents/ChatThread.tsx
+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx
@@ -72,17 +72,23 @@ export function buildMessageGroupChunks<T extends ChunkableMessageGroup>(
chunkKey: string
groups: Array<{ group: T; groupIndex: number }>
}> = []
+ const occurrencesByBaseKey = new Map<string, number>()
+ let lastBaseKey: string | null = null
for (const [groupIndex, group] of groupedWithKeys.entries()) {
const firstTurn = group.items[0]?.serverTurnNumber
- const chunkKey =
+ const baseKey =
firstTurn !== undefined
? `server-turns-${Math.floor((firstTurn - 1) / (VIRTUAL_MESSAGE_GROUPS_PER_CHUNK / 2))}`
: `local-${group.groupKey}`
const current = chunks.at(-1)
- if (current?.chunkKey === chunkKey) {
+ if (current && lastBaseKey === baseKey) {
current.groups.push({ group, groupIndex })
} else {
+ const occurrence = (occurrencesByBaseKey.get(baseKey) ?? 0) + 1
+ occurrencesByBaseKey.set(baseKey, occurrence)
+ const chunkKey = occurrence === 1 ? baseKey : `${baseKey}#${occurrence}`
chunks.push({ chunkKey, groups: [{ group, groupIndex }] })
+ lastBaseKey = baseKey
}
}
return chunks
diff --git a/desktop-app/ui/src/components/agents/__tests__/chatThread.chunking.test.ts b/desktop-app/ui/src/components/agents/__tests__/chatThread.chunking.test.ts
index 028175449..aca5f5457 100644
--- a/desktop-app/ui/src/components/agents/__tests__/chatThread.chunking.test.ts
+++ b/desktop-app/ui/src/components/agents/__tests__/chatThread.chunking.test.ts
@@ -36,4 +36,15 @@ describe('buildMessageGroupChunks', () => {
before[1]?.groups.map(({ group }) => group.groupKey)
)
})
+
+ it('suffixes repeated server buckets separated by a local-only group', () => {
+ const local = { groupKey: 'local-message', items: [{}] }
+ const chunks = buildMessageGroupChunks([group(1, 'user'), local, group(2, 'assistant')])
+
+ expect(chunks.map(chunk => chunk.chunkKey)).toEqual([
+ 'server-turns-0',
+ 'local-local-message',
+ 'server-turns-0#2',
+ ])
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx
index f9a119b55..70da270b3 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx
@@ -139,6 +139,6 @@ describe('useActivityController', () => {
toolCalls: 1,
})
)
- expect(loadMessages).toHaveBeenCalledWith('agent-a', 'legacy-chat', undefined, undefined)
+ expect(loadMessages).toHaveBeenCalledWith('agent-a', 'legacy-chat', 1000, undefined)
})
})
diff --git a/desktop-app/ui/src/hooks/domain/useActivityController.ts b/desktop-app/ui/src/hooks/domain/useActivityController.ts
index 8fcd5a974..a0da03e68 100644
--- a/desktop-app/ui/src/hooks/domain/useActivityController.ts
+++ b/desktop-app/ui/src/hooks/domain/useActivityController.ts
@@ -12,6 +12,9 @@ interface UseActivityControllerParams {
agentNames: string[]
}
+const ACTIVITY_SUMMARY_CHAT_SCAN_LIMIT = 20
+const ACTIVITY_SUMMARY_MESSAGE_SCAN_LIMIT = 1000
+
function activityCounterKey(agentRef: string, chatId: string): string {
return `${agentRef}\u0000${chatId}`
}
@@ -92,6 +95,8 @@ export function useActivityController({
const missingCounterChatIds = JSON.stringify(
chatList
.filter(chat => chat.errorCount === undefined || chat.toolCallCount === undefined)
+ .sort((left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt))
+ .slice(0, ACTIVITY_SUMMARY_CHAT_SCAN_LIMIT)
.map(chat => chat.id)
)
@@ -106,7 +111,9 @@ export function useActivityController({
let cancelled = false
void Promise.all(
chatIds.map(async chatId => {
- const messages = await chatStore.loadMessages(selectedAgent, chatId).catch(() => [])
+ const messages = await chatStore
+ .loadMessages(selectedAgent, chatId, ACTIVITY_SUMMARY_MESSAGE_SCAN_LIMIT)
+ .catch(() => [])
return [
activityCounterKey(selectedAgent, chatId),
{
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index 86b8d3e52..8198b130b 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -11,6 +11,10 @@ import {
buildResponseFileAttachments,
} from '@lib/chatMessageAttachments'
import { buildComposerRequestContent } from '@lib/composerReferencesPrompt'
+import {
+ mergeAuthoritativeServerMessages,
+ messageServerTurnNumber,
+} from '../../../../src/chatMessageMerge'
import type {
ChatMessageAttachment,
HostActivityEvent,
@@ -103,9 +107,7 @@ const MESSAGE_PAGE_SIZE = 80
const MAX_RECONCILE_DELTA_PAGES = 5
function serverTurnNumber(message: AgentChatMessage): number | undefined {
- if (message.serverTurnNumber !== undefined) return message.serverTurnNumber
- const match = /^turn-(\d+)-(?:user|assistant)$/.exec(message.id)
- return match ? Number(match[1]) : undefined
+ return messageServerTurnNumber(message)
}
function oldestServerTurnNumber(messages: AgentChatMessage[]): number | undefined {
@@ -150,81 +152,11 @@ function mergeUniqueMessages(
})
}
-function sameLocalServerMessage(local: AgentChatMessage, server: AgentChatMessage): boolean {
- const sameTask =
- Boolean(local.task_id) && Boolean(server.task_id) && local.task_id === server.task_id
- const sameNearbyContent =
- local.content.trim() === server.content.trim() &&
- Math.abs(local.timestamp - server.timestamp) <= 60_000
- return (
- serverTurnNumber(local) === undefined &&
- serverTurnNumber(server) !== undefined &&
- local.role === server.role &&
- (sameTask || sameNearbyContent)
- )
-}
-
-function messageRoleRank(message: AgentChatMessage): number {
- return message.role === 'user' ? 0 : message.role === 'assistant' ? 1 : 2
-}
-
function mergeServerMessages(
existing: AgentChatMessage[],
incoming: AgentChatMessage[]
): AgentChatMessage[] {
- const merged = [...existing]
- const replacedIndexes = new Set<number>()
-
- for (const serverMessage of incoming) {
- if (merged.some(message => message.id === serverMessage.id)) continue
-
- const serverTurn = serverTurnNumber(serverMessage)
- const sameTurnIndex =
- serverTurn === undefined
- ? -1
- : merged.findIndex(
- message =>
- serverTurnNumber(message) === serverTurn && message.role === serverMessage.role
- )
- if (sameTurnIndex >= 0) {
- merged[sameTurnIndex] = {
- ...serverMessage,
- task_id: merged[sameTurnIndex]?.task_id ?? serverMessage.task_id,
- }
- replacedIndexes.add(sameTurnIndex)
- continue
- }
-
- const localEchoIndex = merged.findIndex(
- (message, index) =>
- !replacedIndexes.has(index) && sameLocalServerMessage(message, serverMessage)
- )
- if (localEchoIndex >= 0) {
- merged[localEchoIndex] = {
- ...serverMessage,
- task_id: merged[localEchoIndex]?.task_id ?? serverMessage.task_id,
- }
- replacedIndexes.add(localEchoIndex)
- continue
- }
-
- const insertionIndex =
- serverTurn === undefined
- ? -1
- : merged.findIndex(message => {
- const messageTurn = serverTurnNumber(message)
- if (messageTurn === undefined) return false
- return (
- messageTurn > serverTurn ||
- (messageTurn === serverTurn &&
- messageRoleRank(message) > messageRoleRank(serverMessage))
- )
- })
- if (insertionIndex < 0) merged.push(serverMessage)
- else merged.splice(insertionIndex, 0, serverMessage)
- }
-
- return merged
+ return mergeAuthoritativeServerMessages(existing, incoming)
}
function sameMessageSequence(a: AgentChatMessage[], b: AgentChatMessage[]): boolean {
@@ -315,6 +247,7 @@ const EMPTY_PROGRESS_MAP: Record<string, TaskProgress> = Object.freeze({})
interface UseAgentChatControllerParams {
selectedAgent: string | null
agentNames: string[]
+ currentUserId?: string
currentTeamId: string
currentTeamName: string
isAuthenticated: boolean
@@ -338,6 +271,7 @@ interface UseAgentChatControllerParams {
export function useAgentChatController({
selectedAgent,
agentNames,
+ currentUserId,
currentTeamId,
currentTeamName,
isAuthenticated,
@@ -351,10 +285,13 @@ export function useAgentChatController({
decideApprovalFromNotification,
}: UseAgentChatControllerParams) {
const chatStore = useChatStore()
+ const authenticatedScope = `${currentUserId ?? 'unknown-user'}:${currentTeamId}`
useEffect(() => {
- chatStore.setRemoteCacheScope(isAuthenticated ? `authenticated:${currentTeamId}` : 'signed-out')
- }, [chatStore.setRemoteCacheScope, currentTeamId, isAuthenticated])
+ chatStore.setRemoteCacheScope(
+ isAuthenticated ? `authenticated:${authenticatedScope}` : 'signed-out'
+ )
+ }, [authenticatedScope, chatStore.setRemoteCacheScope, isAuthenticated])
const tracker = useAgentTaskTracker()
const [activeChatId, setActiveChatId] = useState<string | null>(null)
@@ -379,6 +316,7 @@ export function useAgentChatController({
selectedAgent,
agentNames,
isAuthenticated,
+ scopeKey: authenticatedScope,
loadMenuData,
chatStore,
fsm,
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index ffc2bd452..7c05b3cd7 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -65,6 +65,7 @@ interface UseChatListControllerParams {
selectedAgent: string | null
agentNames: string[]
isAuthenticated: boolean
+ scopeKey: string
loadMenuData: boolean
chatStore: ReturnType<typeof useChatStore>
fsm: SessionFsmStore
@@ -92,6 +93,7 @@ export function useChatListController({
selectedAgent,
agentNames,
isAuthenticated,
+ scopeKey,
loadMenuData,
chatStore,
fsm,
@@ -111,6 +113,11 @@ export function useChatListController({
const suppressAutoSelectionByAgentRef = useRef<Set<string>>(new Set())
const chatListNextCursorByAgentRef = useRef<Record<string, string | null | undefined>>({})
const chatListLoadingMoreByAgentRef = useRef<Set<string>>(new Set())
+ const requestGenerationRef = useRef(0)
+
+ useEffect(() => {
+ requestGenerationRef.current += 1
+ }, [isAuthenticated, scopeKey])
// Live `selectedAgent` for the stable callbacks below (they gate a chatList
// write on "is this the selected agent"). A ref keeps the callbacks stable
@@ -162,11 +169,17 @@ export function useChatListController({
const merged = [...index.chats].sort(byUpdatedDesc)
setChatList(merged)
+ const requestGeneration = requestGenerationRef.current
scheduleAfterFirstPaint(async () => {
const serverResult = await chatStore
.listSessions(agentRef, { limit: SESSION_CATALOG_PAGE_LIMIT })
.catch((): SessionsListResult => ({ items: [] }))
- if (selectedAgentRef.current !== agentRef) return
+ if (
+ selectedAgentRef.current !== agentRef ||
+ requestGenerationRef.current !== requestGeneration
+ ) {
+ return
+ }
const serverSessions = serverResult.items.filter(s => s.agent === agentRef)
chatListNextCursorByAgentRef.current[agentRef] = serverResult.nextCursor ?? null
@@ -242,12 +255,13 @@ export function useChatListController({
if (chatListLoadingMoreByAgentRef.current.has(agentRef)) return
chatListLoadingMoreByAgentRef.current.add(agentRef)
+ const requestGeneration = requestGenerationRef.current
setChatListMoreLoading(true)
try {
const serverResult = await chatStore
.listSessions(agentRef, { limit: SESSION_CATALOG_PAGE_LIMIT, cursor }, { force: true })
.catch(() => null)
- if (!serverResult) return
+ if (!serverResult || requestGenerationRef.current !== requestGeneration) return
const serverSessions = serverResult.items.filter(s => s.agent === agentRef)
if (selectedAgentRef.current !== agentRef) return
@@ -445,6 +459,7 @@ export function useChatListController({
)
const clearPendingSelection = useCallback((agentName: string) => {
delete pendingChatSelectionByAgentRef.current[agentName]
+ suppressAutoSelectionByAgentRef.current.delete(agentName)
}, [])
// ─── Chat CRUD ───
@@ -625,7 +640,15 @@ export function useChatListController({
return () => {
cancelled = true
}
- }, [agentNames, chatStore.getIndex, chatStore.listSessions, isAuthenticated, loadMenuData, fsm])
+ }, [
+ agentNames,
+ chatStore.getIndex,
+ chatStore.listSessions,
+ isAuthenticated,
+ loadMenuData,
+ scopeKey,
+ fsm,
+ ])
return {
// State (public contract, re-exported unchanged by the parent).
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index f7cffef26..61bf08640 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -246,6 +246,7 @@ export function useAppController() {
const chat = useAgentChatController({
selectedAgent: nav.selectedAgent,
agentNames: agentsData.agentNames,
+ currentUserId: auth.me?.id,
currentTeamId,
currentTeamName,
isAuthenticated: auth.isAuthenticated,
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index a66c660a1..a003ab769 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.214",
+ "version": "0.1.215",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.214",
+ "version": "0.1.215",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index dfb6f2a56..fd8da4977 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.214",
+ "version": "0.1.215",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts b/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
index ad48621b0..a7fed15bc 100644
--- a/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
+++ b/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
@@ -29,6 +29,11 @@ import { ConversationState } from '../../core/types'
import { getDisplayName } from '../../progress/intentExtraction'
import { makeHandlers } from '../../server/__tests__/testHelpers'
import { handleSessionMessagesRoute, handleSessionsListRoute } from '../../server/routes'
+import {
+ decodeSessionsCursor,
+ paginateSessionSummaries,
+ projectMessageWindowBounds,
+} from '../../server/wireProjections'
// D.1 — mirrors main.ts `sessionStateView`: expose state/activeTaskId/pendingApproval.
function stateView(conversation: Conversation) {
@@ -77,8 +82,22 @@ function makeApp(convManager: ConversationManager) {
// Closures mirror main.ts — same prefix filter, same mapping shape.
const handlers = makeHandlers({
sessionsListHandler: (userSub: string, query) => {
- const entries = convManager.listSessionsForUser(`${userSub}:rpc:`)
- const page = query.limit ? entries.slice(0, query.limit) : entries
+ const cursor = decodeSessionsCursor(query.cursor)
+ const entries = convManager
+ .listSessionsForUser(`${userSub}:rpc:`)
+ .map(entry => ({ ...entry, lastActivityAt: entry.conversation.updated_at }))
+ .filter(
+ entry =>
+ !cursor ||
+ entry.lastActivityAt.toISOString() < cursor.updatedAt ||
+ (entry.lastActivityAt.toISOString() === cursor.updatedAt && entry.key > cursor.key)
+ )
+ .sort(
+ (left, right) =>
+ right.lastActivityAt.getTime() - left.lastActivityAt.getTime() ||
+ left.key.localeCompare(right.key)
+ )
+ const { page, nextCursor } = paginateSessionSummaries(entries, query.limit)
return {
items: page.map(({ conversation, agent, chatId }) => ({
agent,
@@ -87,6 +106,7 @@ function makeApp(convManager: ConversationManager) {
lastActivityAt: conversation.updated_at.toISOString(),
...stateView(conversation),
})),
+ ...(nextCursor ? { nextCursor } : {}),
}
},
sessionMessagesHandler: (userSub: string, agentName: string, chatId: string, query) => {
@@ -106,15 +126,20 @@ function makeApp(convManager: ConversationManager) {
: query.afterTurn !== undefined
? eligibleTurns.slice(0, query.limit)
: eligibleTurns.slice(-query.limit)
+ const windowBounds = projectMessageWindowBounds(
+ turns,
+ {
+ firstTurnNumber: conversation.turns[0]?.number,
+ lastTurnNumber: conversation.turns.at(-1)?.number,
+ },
+ query
+ )
return {
agent: agentName,
chatId,
...stateView(conversation),
totalTurns: conversation.turns.length,
- oldestTurnNumber: turns[0]?.number,
- latestTurnNumber: turns.at(-1)?.number,
- hasMoreBefore: Boolean(turns[0] && turns[0].number > 1),
- hasMoreAfter: Boolean(turns.at(-1) && turns.at(-1)!.number < conversation.turns.length),
+ ...windowBounds,
turns: turns.map(t => ({
number: t.number,
user_input: t.user_input,
diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
index 3942be6ff..9d8b7c043 100644
--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
@@ -734,7 +734,6 @@ export class SqliteConversationStore implements ConversationStore {
const state = this.ordinals.get(conv.id) ?? this.initOrdinalState(conv.id)
const ordinal = state.nextOrdinal++
const turnNumber = state.nextTurnNumber
- state.nextTurnNumber += 1
// Stamp the per-turn token total onto the final assistant message (the turn
// accumulated it in RAM via recordSessionUsage). reconstruct sums these back
// onto the Turn on cold-load.
@@ -769,6 +768,7 @@ export class SqliteConversationStore implements ConversationStore {
},
sessionKey
)
+ state.nextTurnNumber += 1
}
async persistTurnCancel(conv: Conversation): Promise<void> {
@@ -778,7 +778,6 @@ export class SqliteConversationStore implements ConversationStore {
const state = this.ordinals.get(conv.id) ?? this.initOrdinalState(conv.id)
const ordinal = state.nextOrdinal++
const turnNumber = state.nextTurnNumber
- state.nextTurnNumber += 1
// Stamp the partial per-turn total accumulated before cancellation.
const turn = conv.turns[conv.turns.length - 1]
// ATOMIC boundary (matches persistTurnComplete): the cancel message insert
@@ -817,6 +816,7 @@ export class SqliteConversationStore implements ConversationStore {
},
sessionKey
)
+ state.nextTurnNumber += 1
}
/**
diff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.ts
index d82d6d45c..e4ca52268 100644
--- a/mcp-host/src/db/statements.ts
+++ b/mcp-host/src/db/statements.ts
@@ -197,7 +197,11 @@ export function prepareStatements(db: Database): PreparedStatements {
s.started_at
) AS last_activity_at,
COALESCE(
- (SELECT MAX(m.turn_number) FROM messages m WHERE m.session_id = s.id),
+ (
+ SELECT COUNT(DISTINCT COALESCE(m.turn_number, 0))
+ FROM messages m
+ WHERE m.session_id = s.id
+ ),
0
) AS turn_count,
(
@@ -230,9 +234,9 @@ export function prepareStatements(db: Database): PreparedStatements {
LIMIT @limit
`),
selectSessionTurnBounds: db.prepare(`
- SELECT MAX(COALESCE(turn_number, 0)) AS total_turns,
- MIN(COALESCE(turn_number, 0)) AS first_turn_number,
- MAX(COALESCE(turn_number, 0)) AS last_turn_number,
+ SELECT COUNT(DISTINCT COALESCE(turn_number, 0)) AS total_turns,
+ MIN(turn_number) AS first_turn_number,
+ MAX(turn_number) AS last_turn_number,
MAX(timestamp) AS last_activity_at
FROM messages
WHERE session_id = ?
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 431b1fdd8..ae67f17d0 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -98,7 +98,10 @@ import {
WorkflowApprovalNotificationTerminal,
} from './server'
import {
+ decodeSessionsCursor,
+ paginateSessionSummaries,
projectContextBreakdown,
+ projectMessageWindowBounds,
projectSessionTokens,
projectTurnTokens,
projectTurnToolSteps,
@@ -2061,26 +2064,6 @@ async function startRPCServer(): Promise<void> {
const redactToolError = (toolName: string, rawError: string): string =>
sanitizeError(toolErrorSafety.sanitizeOutput(toolName, rawError).content)
- const decodeSessionsCursor = (
- cursor: string | undefined
- ): { updatedAt: string; key: string } | null => {
- if (!cursor) return null
- try {
- const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as {
- updatedAt?: unknown
- key?: unknown
- }
- return typeof parsed.updatedAt === 'string' && typeof parsed.key === 'string'
- ? { updatedAt: parsed.updatedAt, key: parsed.key }
- : null
- } catch {
- return null
- }
- }
-
- const encodeSessionsCursor = (updatedAt: string, key: string): string =>
- Buffer.from(JSON.stringify({ updatedAt, key }), 'utf8').toString('base64url')
-
const handleSessionsList = async (
userSub: string,
query: { limit?: number; cursor?: string }
@@ -2092,23 +2075,20 @@ async function startRPCServer(): Promise<void> {
limit: query.limit === undefined ? undefined : query.limit + 1,
cursor: cursor ? { updatedAt: new Date(cursor.updatedAt), key: cursor.key } : undefined,
})
- const page = query.limit ? entries.slice(0, query.limit) : entries
- const hasMore = query.limit !== undefined && entries.length > page.length
- const last = page.at(-1)
+ const { page, nextCursor } = paginateSessionSummaries(entries, query.limit)
return {
items: page.map(summary => ({
agent: summary.agent,
chatId: summary.chatId,
turnCount: summary.turnCount,
- messageCount: summary.messageCount,
+ // A message is one renderable user/assistant part. Derive from logical
+ // turns so in-memory and SQLite stores report the same unit regardless
+ // of persisted tool-call rows.
+ messageCount: summary.turnCount * 2,
lastActivityAt: summary.lastActivityAt.toISOString(),
...sessionStateView(summary),
})),
- ...(hasMore && last
- ? {
- nextCursor: encodeSessionsCursor(last.lastActivityAt.toISOString(), last.key),
- }
- : {}),
+ ...(nextCursor ? { nextCursor } : {}),
}
}
@@ -2125,27 +2105,20 @@ async function startRPCServer(): Promise<void> {
const page = await convManager.getSessionMessagesByKeyAsync(key, keyPrefix, query)
if (!page) return null
const turns = page.turns
- const oldestTurnNumber = turns[0]?.number
- const latestTurnNumber = turns.at(-1)?.number
- const firstConversationTurn = page.firstTurnNumber
- const lastConversationTurn = page.lastTurnNumber
+ const windowBounds = projectMessageWindowBounds(
+ turns,
+ {
+ firstTurnNumber: page.firstTurnNumber,
+ lastTurnNumber: page.lastTurnNumber,
+ },
+ query
+ )
return {
agent: agentName,
chatId,
...sessionStateView(page),
totalTurns: page.totalTurns,
- oldestTurnNumber,
- latestTurnNumber,
- hasMoreBefore:
- firstConversationTurn !== undefined &&
- (oldestTurnNumber !== undefined
- ? oldestTurnNumber > firstConversationTurn
- : query.afterTurn !== undefined),
- hasMoreAfter:
- lastConversationTurn !== undefined &&
- (latestTurnNumber !== undefined
- ? latestTurnNumber < lastConversationTurn
- : query.beforeTurn !== undefined),
+ ...windowBounds,
turns: turns.map(t => ({
number: t.number,
user_input: t.user_input,
diff --git a/mcp-host/src/server/__tests__/wireProjections.test.ts b/mcp-host/src/server/__tests__/wireProjections.test.ts
index 6c81611a5..42206dcc3 100644
--- a/mcp-host/src/server/__tests__/wireProjections.test.ts
+++ b/mcp-host/src/server/__tests__/wireProjections.test.ts
@@ -6,12 +6,54 @@ import {
type Turn,
} from '../../core/types'
import {
+ decodeSessionsCursor,
+ paginateSessionSummaries,
projectContextBreakdown,
+ projectMessageWindowBounds,
projectSessionTokens,
projectTurnTokens,
projectTurnToolSteps,
} from '../wireProjections'
+describe('session pagination projections', () => {
+ it('rejects malformed and invalid-date cursors', () => {
+ expect(decodeSessionsCursor('not-base64-json')).toBeNull()
+ const invalidDate = Buffer.from(
+ JSON.stringify({ updatedAt: 'not-a-date', key: 'session-1' })
+ ).toString('base64url')
+ expect(decodeSessionsCursor(invalidDate)).toBeNull()
+ })
+
+ it('returns a cursor only when another summary page exists', () => {
+ const entries = [
+ { key: 'a', lastActivityAt: new Date('2026-01-03T00:00:00Z') },
+ { key: 'b', lastActivityAt: new Date('2026-01-02T00:00:00Z') },
+ ]
+ const result = paginateSessionSummaries(entries, 1)
+ expect(result.page).toEqual([entries[0]])
+ expect(decodeSessionsCursor(result.nextCursor)).toEqual({
+ updatedAt: '2026-01-03T00:00:00.000Z',
+ key: 'a',
+ })
+ expect(paginateSessionSummaries(entries, 2).nextCursor).toBeUndefined()
+ })
+
+ it('projects bounded message-window navigation consistently', () => {
+ expect(
+ projectMessageWindowBounds(
+ [{ number: 3 }, { number: 4 }],
+ { firstTurnNumber: 1, lastTurnNumber: 6 },
+ {}
+ )
+ ).toEqual({
+ oldestTurnNumber: 3,
+ latestTurnNumber: 4,
+ hasMoreBefore: true,
+ hasMoreAfter: true,
+ })
+ })
+})
+
function makeConversation(overrides: Partial<Conversation> = {}): Conversation {
return {
id: 'conv-1',
diff --git a/mcp-host/src/server/wireProjections.ts b/mcp-host/src/server/wireProjections.ts
index 3126db14a..c8a8d9c11 100644
--- a/mcp-host/src/server/wireProjections.ts
+++ b/mcp-host/src/server/wireProjections.ts
@@ -15,6 +15,73 @@ type SessionTokenSource = Pick<
| 'cacheTokensReported'
>
+export interface SessionsCursor {
+ updatedAt: string
+ key: string
+}
+
+export function decodeSessionsCursor(cursor: string | undefined): SessionsCursor | null {
+ if (!cursor) return null
+ try {
+ const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as {
+ updatedAt?: unknown
+ key?: unknown
+ }
+ if (
+ typeof parsed.updatedAt !== 'string' ||
+ typeof parsed.key !== 'string' ||
+ !Number.isFinite(Date.parse(parsed.updatedAt))
+ ) {
+ return null
+ }
+ return { updatedAt: parsed.updatedAt, key: parsed.key }
+ } catch {
+ return null
+ }
+}
+
+export function encodeSessionsCursor(updatedAt: string, key: string): string {
+ return Buffer.from(JSON.stringify({ updatedAt, key }), 'utf8').toString('base64url')
+}
+
+export function paginateSessionSummaries<T extends { key: string; lastActivityAt: Date }>(
+ entries: T[],
+ limit: number | undefined
+): { page: T[]; nextCursor?: string } {
+ if (limit === undefined) return { page: entries }
+ const page = entries.slice(0, limit)
+ const last = page.at(-1)
+ return {
+ page,
+ ...(entries.length > page.length && last
+ ? { nextCursor: encodeSessionsCursor(last.lastActivityAt.toISOString(), last.key) }
+ : {}),
+ }
+}
+
+export function projectMessageWindowBounds(
+ turns: Array<{ number: number }>,
+ bounds: { firstTurnNumber?: number; lastTurnNumber?: number },
+ query: { beforeTurn?: number; afterTurn?: number }
+) {
+ const oldestTurnNumber = turns[0]?.number
+ const latestTurnNumber = turns.at(-1)?.number
+ return {
+ oldestTurnNumber,
+ latestTurnNumber,
+ hasMoreBefore:
+ bounds.firstTurnNumber !== undefined &&
+ (oldestTurnNumber !== undefined
+ ? oldestTurnNumber > bounds.firstTurnNumber
+ : query.afterTurn !== undefined),
+ hasMoreAfter:
+ bounds.lastTurnNumber !== undefined &&
+ (latestTurnNumber !== undefined
+ ? latestTurnNumber < bounds.lastTurnNumber
+ : query.beforeTurn !== undefined),
+ }
+}
+
/**
* Project a Conversation's lifetime token mirror into the wire shape served by
* `/v1/runtime/sessions` and `/messages`.