Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: preserve chat history across desktop downgrades
Josué36a7c7004014
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex ad1629d86..46b72d094 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.330",+ "version": "0.1.331","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.330",+ "version": "0.1.331","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex e7643c29a..b8fd69335 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.330",+ "version": "0.1.331","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.tsindex 21a91732e..4e0192802 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -761,7 +761,7 @@ describe('messages', () => {).toEqual(['turn-1-user', 'local-only', 'turn-2-user', 'turn-2-assistant'])})- it('repairs a missing page from the surviving page files instead of returning an empty chat', async () => {+ it('repairs a missing page from surviving pages and the compatibility snapshot', async () => {const pagedStore = new ChatStore(tempDir, {pageSize: 2,maxLocalSyncedMessages: Number.POSITIVE_INFINITY,@@ -782,11 +782,11 @@ describe('messages', () => {const recovered = await pagedStore.loadMessages('agent-1', 'missing-page')- expect(recovered.map(message => message.id)).toEqual(['m0', 'm1', 'm4', 'm5'])+ expect(recovered.map(message => message.id)).toEqual(['m0', 'm1', 'm2', 'm3', 'm4', 'm5'])const repairedMeta = await readJsonFile<{ localMessageCount: number }>(chatMetaPath('missing-page'))- expect(repairedMeta.localMessageCount).toBe(4)+ expect(repairedMeta.localMessageCount).toBe(6)})it('adopts a fully written orphan page left by an interrupted append', async () => {@@ -833,7 +833,11 @@ describe('messages', () => {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 compatibility = await readJsonFile<{ version: number; messages: ChatMessage[] }>(+ join(tempDir, 'agent-1', 'v2-1.json')+ )+ expect(compatibility.version).toBe(2)+ expect(compatibility.messages[0]!.task_id).toBe('task-abc')const messages = await store.loadMessages('agent-1', 'v2-1')expect(messages[0]!.task_id).toBe('task-abc')@@ -853,7 +857,7 @@ 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(join(agentDir, 'legacy.json'))).resolves.toBeUndefined()await expect(fs.access(chatMetaPath('legacy'))).resolves.toBeUndefined()})@@ -908,7 +912,83 @@ describe('messages', () => {toolCallCount: 1,})const migratedIndex = await readJsonFile<{ version: number }>(agentPath('index.json'))- expect(migratedIndex.version).toBe(3)+ expect(migratedIndex.version).toBe(2)+ })++ it('keeps the downgrade snapshot bounded and current after appends', async () => {+ await store.createChat('agent-1', 'downgrade-window')+ const messages = Array.from({ length: 105 }, (_, index) => ({+ id: `m${index}`,+ role: 'user' as const,+ content: `message-${index}`,+ timestamp: index,+ }))++ await store.saveMessages('agent-1', 'downgrade-window', messages)++ const initial = await readJsonFile<{ version: number; messages: ChatMessage[] }>(+ agentPath('downgrade-window.json')+ )+ expect(initial.version).toBe(2)+ expect(initial.messages).toHaveLength(100)+ expect(initial.messages[0]!.id).toBe('m5')+ expect(initial.messages.at(-1)!.id).toBe('m104')++ await store.appendMessages('agent-1', 'downgrade-window', [+ { id: 'm105', role: 'assistant', content: 'message-105', timestamp: 105 },+ ])++ const appended = await readJsonFile<{ messages: ChatMessage[] }>(+ agentPath('downgrade-window.json')+ )+ expect(appended.messages).toHaveLength(100)+ expect(appended.messages[0]!.id).toBe('m6')+ expect(appended.messages.at(-1)!.id).toBe('m105')+ })++ it('imports local messages written by a downgraded desktop build', async () => {+ await store.createChat('agent-1', 'downgraded-write')+ const original = { id: 'm1', role: 'user' as const, content: 'original', timestamp: 1 }+ await store.saveMessages('agent-1', 'downgraded-write', [original])++ const downgradedMessage = {+ id: 'm2',+ role: 'user' as const,+ content: 'written while downgraded',+ timestamp: 2,+ }+ await fs.writeFile(+ agentPath('downgraded-write.json'),+ JSON.stringify({+ version: 2,+ chatId: 'downgraded-write',+ messages: [original, downgradedMessage],+ })+ )++ const recovered = await store.loadMessages('agent-1', 'downgraded-write')++ expect(recovered.map(message => message.id)).toEqual(['m1', 'm2'])+ const compatibility = await readJsonFile<{ messages: ChatMessage[] }>(+ agentPath('downgraded-write.json')+ )+ expect(compatibility.messages.map(message => message.id)).toEqual(['m1', 'm2'])+ })++ it('repairs a corrupt downgrade snapshot from the valid paged history', async () => {+ await store.createChat('agent-1', 'corrupt-downgrade-snapshot')+ await store.saveMessages('agent-1', 'corrupt-downgrade-snapshot', [+ { id: 'm1', role: 'user', content: 'still durable', timestamp: 1 },+ ])+ await fs.writeFile(agentPath('corrupt-downgrade-snapshot.json'), 'not json{')++ const recovered = await store.loadMessages('agent-1', 'corrupt-downgrade-snapshot')++ expect(recovered.map(message => message.id)).toEqual(['m1'])+ const compatibility = await readJsonFile<{ messages: ChatMessage[] }>(+ agentPath('corrupt-downgrade-snapshot.json')+ )+ expect(compatibility.messages.map(message => message.id)).toEqual(['m1'])})it('does not hide a failed legacy migration as an empty chat', async () => {@@ -982,7 +1062,7 @@ describe('corrupt/missing files', () => {await fs.mkdir(agentDir, { recursive: true })await fs.writeFile(join(agentDir, 'index.json'), 'NOT VALID JSON{{{')const index = await store.getIndex('agent-1')- expect(index.version).toBe(3) // empty index is created at the current schema (D.4)+ expect(index.version).toBe(2) // v2 remains readable by pre-paging desktop buildsexpect(index.chats).toEqual([])})diff --git a/desktop-app/src/__tests__/chatStoreBinding.test.ts b/desktop-app/src/__tests__/chatStoreBinding.test.tsindex 8d510ae55..34472b3af 100644--- a/desktop-app/src/__tests__/chatStoreBinding.test.ts+++ b/desktop-app/src/__tests__/chatStoreBinding.test.ts@@ -154,7 +154,7 @@ describe('chatStoreBinding', () => {expect(await exists(path.join(tmpBase, ENV_A, 'user-broken', 'agent-y'))).toBe(false)})- it('preserves a v2 agent dir and marks it as v3 for downgrade safety', async () => {+ it('preserves the downgrade-compatible v2 agent index', async () => {const v2Index = JSON.stringify({version: 2,chats: [{ id: 'keep', title: 'Keep', createdAt: 'x', updatedAt: 'x', messageCount: 1 }],@@ -171,13 +171,37 @@ describe('chatStoreBinding', () => {expect((await requireChatStore().listChats('agent-x')).find(c => c.id === 'keep')).toBeDefined()- const migrated = JSON.parse(+ const preserved = JSON.parse(await fs.readFile(path.join(tmpBase, ENV_A, 'user-current', 'agent-x', 'index.json'),'utf-8')) as { version: number }- expect(migrated.version).toBe(3)+ expect(preserved.version).toBe(2)+ })++ it('normalizes an earlier paging v3 index back to downgrade-compatible v2', 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', 'agent-x', v3Index, {+ 'keep.json': JSON.stringify({+ version: 2,+ chatId: 'keep',+ messages: [{ id: 'm1', role: 'user', content: 'keep me', timestamp: 1 }],+ }),+ })++ await bindChatStoreForUser('user-v3', ENV_A)++ const normalized = JSON.parse(+ await fs.readFile(path.join(tmpBase, ENV_A, 'user-v3', 'agent-x', 'index.json'), 'utf-8')+ ) as { version: number }+ expect(normalized.version).toBe(2)+ expect(await exists(path.join(tmpBase, ENV_A, 'user-v3', 'agent-x', 'keep.json'))).toBe(true)})it('is a no-op when the user has no cache directory yet', async () => {diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex a19de9b03..0d9cc5630 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -1,12 +1,15 @@-import { randomUUID } from 'node:crypto'+import { createHash, randomUUID } from 'node:crypto'import { promises as fs } from 'node:fs'import { join } from 'node:path'import type { ChatFile, ChatIndex, ChatMessage, ChatMetadata } from './types.js'-const INDEX_VERSION = 3+// Keep the catalog at v2 while paged transcripts are dual-readable by the+// pre-paging desktop build. The page layout has its own versioned metadata.+const INDEX_VERSION = 2const PAGED_CHAT_VERSION = 1const DEFAULT_PAGE_SIZE = 100const DEFAULT_MAX_LOCAL_SYNCED_MESSAGES = 1000+const LEGACY_COMPATIBILITY_MESSAGE_LIMIT = 100const PAGE_FILE_PATTERN = /^\d{6}\.json$/export interface ChatStoreOptions {@@ -32,6 +35,7 @@ interface PagedChatMeta {prunedThroughServerTurnNumber?: numberoldestLocalServerTurnNumber?: numberlatestServerTurnNumber?: number+ legacyCompatibilitySignature?: stringpages: ChatPageEntry[]}@@ -266,6 +270,11 @@ export class ChatStore {return join(this.agentDir(agentRef), `${chatId}.json`)}+ private chatCompatibilitySignaturePath(agentRef: string, chatId: string): string {+ assertSafeSegment('chatId', chatId)+ return join(this.agentDir(agentRef), `${chatId}.compat`)+ }+private chatDirPath(agentRef: string, chatId: string): string {assertSafeSegment('chatId', chatId)return join(this.agentDir(agentRef), 'chats', chatId)@@ -394,6 +403,127 @@ export class ChatStore {}}+ /**+ * Keep a bounded v2 flat-file window for pre-paging desktop builds.+ *+ * Rewriting this fixed-size window preserves downgrade readability without+ * restoring the old unbounded whole-conversation write cost. The server+ * remains the source of truth for older synced turns.+ */+ private legacyCompatibilitySnapshot(+ chatId: string,+ messages: ChatMessage[]+ ): { file: ChatFile; signature: string } {+ const compatibilityMessages = messages.slice(-LEGACY_COMPATIBILITY_MESSAGE_LIMIT)+ const file: ChatFile = {+ version: 2,+ chatId,+ messages: compatibilityMessages,+ }+ const signature = createHash('sha256')+ .update(JSON.stringify([chatId, compatibilityMessages]))+ .digest('hex')+ return { file, signature }+ }++ private async writeLegacyCompatibilitySnapshot(+ agentRef: string,+ chatId: string,+ messages: ChatMessage[]+ ): Promise<string> {+ const { file, signature } = this.legacyCompatibilitySnapshot(chatId, messages)+ await this.writeJsonAtomic(this.chatFilePath(agentRef, chatId), file)+ await this.writeJsonAtomic(this.chatCompatibilitySignaturePath(agentRef, chatId), {+ signature,+ })+ return signature+ }++ private async readLegacyCompatibilitySignature(+ agentRef: string,+ chatId: string+ ): Promise<string | null> {+ try {+ const raw = await fs.readFile(this.chatCompatibilitySignaturePath(agentRef, chatId), 'utf-8')+ const parsed = JSON.parse(raw) as { signature?: unknown }+ return typeof parsed.signature === 'string' ? parsed.signature : null+ } catch {+ return null+ }+ }++ private async refreshLegacyCompatibilitySnapshotUnlocked(+ agentRef: string,+ chatId: string,+ meta: PagedChatMeta+ ): Promise<PagedChatMeta> {+ const compatibilityMessages = await this.readMessagesFromPagedMeta(+ agentRef,+ chatId,+ meta,+ LEGACY_COMPATIBILITY_MESSAGE_LIMIT+ )+ const signature = await this.writeLegacyCompatibilitySnapshot(+ agentRef,+ chatId,+ compatibilityMessages+ )+ const refreshed = { ...meta, legacyCompatibilitySignature: signature }+ await this.writePagedMeta(agentRef, chatId, refreshed)+ return refreshed+ }++ /**+ * A downgraded build may append local messages to the v2 compatibility file.+ * Import only messages missing from the paged snapshot before refreshing the+ * bounded window, so upgrading again cannot discard offline work.+ */+ private async importDowngradedLocalMessagesUnlocked(+ agentRef: string,+ chatId: string,+ meta: PagedChatMeta+ ): Promise<PagedChatMeta> {+ let legacyMessages: ChatMessage[] | null+ try {+ legacyMessages = await this.readLegacyMessages(agentRef, chatId)+ } catch (error) {+ if (isRawFilesystemError(error)) throw error+ return this.refreshLegacyCompatibilitySnapshotUnlocked(agentRef, chatId, meta)+ }+ if (!legacyMessages) {+ return this.refreshLegacyCompatibilitySnapshotUnlocked(agentRef, chatId, meta)+ }++ const legacySignature = this.legacyCompatibilitySnapshot(chatId, legacyMessages).signature+ if (legacySignature === meta.legacyCompatibilitySignature) return meta+ const recordedSignature = await this.readLegacyCompatibilitySignature(agentRef, chatId)+ if (legacySignature === recordedSignature) {+ return this.refreshLegacyCompatibilitySnapshotUnlocked(agentRef, chatId, meta)+ }++ const existing = await this.readMessagesFromPagedMeta(agentRef, chatId, meta)+ const missing = legacyMessages.filter(+ candidate =>+ !existing.some(+ message =>+ sameReconciledMessage(candidate, message) || sameReconciledMessage(message, candidate)+ )+ )+ if (!missing.length) {+ return this.refreshLegacyCompatibilitySnapshotUnlocked(agentRef, chatId, meta)+ }++ const merged = mergeReconciledMessages(existing, missing)+ const indexedCount = await this.indexedMessageCount(agentRef, chatId)+ const imported = await this.writePagedChatUnlocked(agentRef, chatId, merged, {+ messageCount: Math.max(meta.messageCount, merged.length, indexedCount ?? 0),+ })+ await this.updateChatIndexFromMessages(agentRef, chatId, merged, {+ preserveExistingTotals: true,+ })+ return imported+ }+private async readPageMessages(agentRef: string,chatId: string,@@ -632,7 +762,6 @@ export class ChatStore {const recovered = mergeReconciledMessages(surviving, legacy ?? [])if (!recovered.length) return falseawait this.writePagedChatUnlocked(agentRef, chatId, recovered, {- removeLegacy: true,messageCount: recovered.length,})return true@@ -804,7 +933,7 @@ export class ChatStore {agentRef: string,chatId: string,messages: ChatMessage[],- options: { removeLegacy?: boolean; messageCount?: number } = {}+ options: { messageCount?: number } = {}): Promise<PagedChatMeta> {const chatDir = this.chatDirPath(agentRef, chatId)const snapshotToken = randomUUID()@@ -845,6 +974,8 @@ export class ChatStore {pages,}))+ const compatibility = this.legacyCompatibilitySnapshot(chatId, messages)+ pruned.meta.legacyCompatibilitySignature = compatibility.signatureawait this.writePagedMetaToDir(chatId, stagingDir, pruned.meta)await Promise.all(pruned.removedFiles.map(file =>@@ -863,10 +994,7 @@ export class ChatStore {if (movedExistingSnapshot) {await fs.rm(backupDir, { recursive: true, force: true }).catch(() => undefined)}-- if (options.removeLegacy) {- await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })- }+ await this.writeLegacyCompatibilitySnapshot(agentRef, chatId, messages)return pruned.meta} catch (err) {@@ -884,14 +1012,14 @@ export class ChatStore {): Promise<PagedChatMeta | null> {await this.recoverPagedChatUnlocked(agentRef, chatId)const paged = await this.readPagedMeta(agentRef, chatId)- if (paged) return paged+ if (paged) {+ return this.importDowngradedLocalMessagesUnlocked(agentRef, chatId, paged)+ }const legacyMessages = await this.readLegacyMessages(agentRef, chatId)if (!legacyMessages) return null- const migrated = await this.writePagedChatUnlocked(agentRef, chatId, legacyMessages, {- removeLegacy: true,- })+ const migrated = await this.writePagedChatUnlocked(agentRef, chatId, legacyMessages)await this.updateChatIndexFromMessages(agentRef, chatId, legacyMessages)return migrated}@@ -975,13 +1103,21 @@ export class ChatStore {messageCount,pages,})+ const compatibilityMessages = await this.readMessagesFromPagedMeta(+ agentRef,+ chatId,+ pruned.meta,+ LEGACY_COMPATIBILITY_MESSAGE_LIMIT+ )+ const compatibility = this.legacyCompatibilitySnapshot(chatId, compatibilityMessages)+ pruned.meta.legacyCompatibilitySignature = compatibility.signatureawait this.writePagedMeta(agentRef, chatId, pruned.meta)await Promise.all(pruned.removedFiles.map(file =>fs.rm(this.chatPagePath(agentRef, chatId, file), { force: true })))- await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })+ await this.writeLegacyCompatibilitySnapshot(agentRef, chatId, compatibilityMessages)return pruned.meta}@@ -990,8 +1126,8 @@ export class ChatStore {const raw = await fs.readFile(this.indexPath(agentRef), 'utf-8')const parsed = JSON.parse(raw) as ChatIndex// Version-agnostic read: legacy directories are handled at bind time by- // chatStoreBinding, so any index we read here is safe to normalize;- // saveIndex writes the current v3 marker on the next update.+ // chatStoreBinding. saveIndex normalizes v3 indexes produced by earlier+ // paging builds back to the v2 downgrade-compatible catalog schema.if (parsed && Array.isArray(parsed.chats)) {return parsed}@@ -1004,11 +1140,12 @@ export class ChatStore {private async saveIndex(agentRef: string, index: ChatIndex): Promise<void> {const dir = this.agentDir(agentRef)await fs.mkdir(dir, { recursive: true })- // Always persist at the current schema version so a read-back never looks legacy.+ // Keep the index readable by the pre-paging desktop while the transcript+ // files are maintained in both paged and bounded v2-compatible forms.const normalized: ChatIndex = { ...index, version: INDEX_VERSION }// Atomic write (temp + rename): a crash mid-write must never leave a// truncated index.json, because the bootstrap wipe treats an unparseable- // index as legacy and would delete live v3 chats.+ // index as legacy and would delete live paged chats.const target = this.indexPath(agentRef)const tmp = `${target}.tmp`await fs.writeFile(tmp, JSON.stringify(normalized, null, 2), { mode: 0o600 })@@ -1083,6 +1220,7 @@ export class ChatStore {await this.saveIndex(agentRef, index)})await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })+ 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))@@ -1152,7 +1290,6 @@ export class ChatStore {? await this.indexedMessageCount(agentRef, chatId): undefinedawait this.writePagedChatUnlocked(agentRef, chatId, messages, {- removeLegacy: true,messageCount: Math.max(messages.length, indexedCount ?? 0),})@@ -1183,7 +1320,6 @@ export class ChatStore {const merged = mergeReconciledMessages(existingMessages, messages)const indexedCount = await this.indexedMessageCount(agentRef, chatId)await this.writePagedChatUnlocked(agentRef, chatId, merged, {- removeLegacy: true,messageCount: Math.max(merged.length, indexedCount ?? 0),})await this.updateChatIndexFromMessages(agentRef, chatId, merged, {@@ -1200,7 +1336,7 @@ export class ChatStore {return this.serializeChat(agentRef, chatId, async () => {const existing =(await this.readOrMigratePagedChatUnlocked(agentRef, chatId)) ??- (await this.writePagedChatUnlocked(agentRef, chatId, [], { removeLegacy: true }))+ (await this.writePagedChatUnlocked(agentRef, chatId, []))const meta = await this.appendPagedMessagesUnlocked(agentRef, chatId, existing, newMessages)await this.serializeIndex(agentRef, async () => {diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.tsindex 9e0e80a7d..ae3d19d4d 100644--- a/desktop-app/src/chatStoreBinding.ts+++ b/desktop-app/src/chatStoreBinding.ts@@ -3,9 +3,12 @@ import { promises as fs } from 'node:fs'import { join } from 'node:path'import { ChatStore } from './chatStore.js'-/** Current persisted chat schema. Anything older is wiped on bind (§7.1). */-const SCHEMA_VERSION = 3-const PAGED_V2_SCHEMA_VERSION = 2+/**+ * Keep the shared catalog at v2 so pre-paging desktop builds can read the+ * bounded compatibility snapshots. Paged transcripts version their own files.+ */+const SCHEMA_VERSION = 2+const PREVIOUS_PAGED_INDEX_VERSION = 3// Default base dir derived from Electron's userData path. Tests override via// __setChatStoreBaseDirForTests to point at a tmpdir, which means the@@ -178,8 +181,8 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {try {const raw = await fs.readFile(indexPath, 'utf-8')const parsed = JSON.parse(raw) as { version?: number }- if (parsed.version === PAGED_V2_SCHEMA_VERSION) {- const migratedIndexPath = `${indexPath}.v3.tmp`+ if (parsed.version === PREVIOUS_PAGED_INDEX_VERSION) {+ const migratedIndexPath = `${indexPath}.v2.tmp`await fs.writeFile(migratedIndexPath,JSON.stringify({ ...parsed, version: SCHEMA_VERSION }, null, 2),