Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): address PR review findings
Josué3ce7835eb1ea
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex a86de9fcb..f344dc192 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.321",+ "version": "0.1.322","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.321",+ "version": "0.1.322","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex ce2450ae7..19b999f75 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.321",+ "version": "0.1.322","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",diff --git a/desktop-app/src/__tests__/appService.bootstrap.test.ts b/desktop-app/src/__tests__/appService.bootstrap.test.tsindex 8241d6d35..a28d05c51 100644--- a/desktop-app/src/__tests__/appService.bootstrap.test.ts+++ b/desktop-app/src/__tests__/appService.bootstrap.test.ts@@ -16,6 +16,13 @@ describe('AppService invitation configuration lookup', () => {const originalExternalRestApiBaseUrl = process.env.EXTERNAL_REST_API_BASE_URLconst originalRpcProxyBaseUrl = process.env.RPC_PROXY_BASE_URLconst originalProfileUiBaseUrl = process.env.PROFILE_UI_BASE_URL+ const tempDirs = new Set<string>()++ async function createTempConfigPath(prefix: string): Promise<string> {+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), `${prefix}-`))+ tempDirs.add(tempDir)+ return path.join(tempDir, 'config.json')+ }afterEach(async () => {if (originalConfigPath === undefined) {@@ -39,13 +46,14 @@ describe('AppService invitation configuration lookup', () => {process.env.PROFILE_UI_BASE_URL = originalProfileUiBaseUrl}vi.resetModules()+ await Promise.all(+ [...tempDirs].map(tempDir => fs.rm(tempDir, { recursive: true, force: true }))+ )+ tempDirs.clear()})it('persists runtime config when desktop setup is completed', async () => {- const configPath = path.join(- os.tmpdir(),- `clerum-desktop-config-${Date.now()}-${Math.random().toString(16).slice(2)}.json`- )+ const configPath = await createTempConfigPath('clerum-desktop-config')process.env.CLERUM_DESKTOP_CONFIG_PATH = configPathdelete process.env.EXTERNAL_REST_API_BASE_URLdelete process.env.RPC_PROXY_BASE_URL@@ -184,10 +192,7 @@ describe('AppService invitation configuration lookup', () => {})it('keeps a saved token when startup session restore has a transient failure', async () => {- const configPath = path.join(- os.tmpdir(),- `clerum-desktop-restore-local-${Date.now()}-${Math.random().toString(16).slice(2)}.json`- )+ const configPath = await createTempConfigPath('clerum-desktop-restore-local')await fs.writeFile(configPath,JSON.stringify({@@ -262,10 +267,7 @@ describe('AppService invitation configuration lookup', () => {})it('clears a saved token when startup session restore is rejected by the API', async () => {- const configPath = path.join(- os.tmpdir(),- `clerum-desktop-restore-api-${Date.now()}-${Math.random().toString(16).slice(2)}.json`- )+ const configPath = await createTempConfigPath('clerum-desktop-restore-api')await fs.writeFile(configPath,JSON.stringify({@@ -313,10 +315,7 @@ describe('AppService invitation configuration lookup', () => {})it('keeps a saved token when startup session restore is forbidden', async () => {- const configPath = path.join(- os.tmpdir(),- `clerum-desktop-restore-forbidden-${Date.now()}-${Math.random().toString(16).slice(2)}.json`- )+ const configPath = await createTempConfigPath('clerum-desktop-restore-forbidden')await fs.writeFile(configPath,JSON.stringify({@@ -368,10 +367,7 @@ describe('AppService invitation configuration lookup', () => {})it('persists a manually saved runtime environment', async () => {- const configPath = path.join(- os.tmpdir(),- `clerum-desktop-manual-config-${Date.now()}-${Math.random().toString(16).slice(2)}.json`- )+ const configPath = await createTempConfigPath('clerum-desktop-manual-config')process.env.CLERUM_DESKTOP_CONFIG_PATH = configPathdelete process.env.EXTERNAL_REST_API_BASE_URLdelete process.env.RPC_PROXY_BASE_URLdiff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.tsindex ed951583b..7673f9c59 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -255,6 +255,59 @@ describe('messages', () => {expect(messages.map(message => message.id)).toEqual(['m0', 'm1', 'm2'])})+ it('does not block paged reads behind writes to another chat', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'busy-chat')+ await pagedStore.createChat('agent-1', 'readable-chat')+ await pagedStore.saveMessages('agent-1', 'busy-chat', [+ { id: 'busy-0', role: 'user', content: 'busy', timestamp: 0 },+ ])+ await pagedStore.saveMessages('agent-1', 'readable-chat', [+ { id: 'readable-0', role: 'user', content: 'readable', timestamp: 0 },+ ])++ const originalWriteFile = fs.writeFile.bind(fs)+ const originalReadFile = fs.readFile.bind(fs)+ let releaseWrite: (() => void) | undefined+ let delayedWrite = false+ let readableChatReadStarted = false+ const busyWriteStarted = new Promise<void>(resolve => {+ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ if (!delayedWrite && filePath.includes('busy-chat') && filePath.endsWith('.tmp')) {+ delayedWrite = true+ resolve()+ await new Promise<void>(release => {+ releaseWrite = release+ })+ }+ return originalWriteFile(...(args as Parameters<typeof fs.writeFile>))+ })+ })+ vi.spyOn(fs, 'readFile').mockImplementation(async (...args) => {+ if (String(args[0]).includes('readable-chat')) readableChatReadStarted = true+ return originalReadFile(...(args as Parameters<typeof fs.readFile>))+ })++ const append = pagedStore.appendMessages('agent-1', 'busy-chat', [+ { id: 'busy-1', role: 'assistant', content: 'still busy', timestamp: 1 },+ ])+ await busyWriteStarted++ const readableMessages = pagedStore.loadMessages('agent-1', 'readable-chat')+ try {+ await vi.waitFor(() => expect(readableChatReadStarted).toBe(true))+ } finally {+ releaseWrite?.()+ }++ const [messages] = await Promise.all([readableMessages, append.then(() => undefined)])+ expect(messages.map(message => message.id)).toEqual(['readable-0'])+ })+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.tsindex 972eb75bf..cafb8dddb 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -125,31 +125,40 @@ export class ChatStore {}/**- * Per-agent serialization of index read-modify-write sequences. The index is- * a single shared `index.json`, so concurrent mutators (e.g. two chats of one- * 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. 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.+ * Index read-modify-write sequences are serialized per agent because every+ * chat shares one `index.json`. Paged transcript operations use a separate+ * per-chat chain so reads stay atomic with writes for the same chat without+ * queuing behind unrelated chat activity.*/private indexChains = new Map<string, Promise<unknown>>()-- private serializeIndex<T>(agentRef: string, fn: () => Promise<T>): Promise<T> {- const prev = this.indexChains.get(agentRef) ?? Promise.resolve()+ private chatChains = new Map<string, Promise<unknown>>()++ private serialize<T>(+ chains: Map<string, Promise<unknown>>,+ key: string,+ fn: () => Promise<T>+ ): Promise<T> {+ const prev = chains.get(key) ?? Promise.resolve()const run = prev.then(fn, fn)- // Keep the chain alive regardless of individual outcomes.- this.indexChains.set(- agentRef,- run.then(- () => undefined,- () => undefined- )+ const settled = run.then(+ () => undefined,+ () => undefined)+ chains.set(key, settled)+ void settled.then(() => {+ if (chains.get(key) === settled) chains.delete(key)+ })return run}+ private serializeIndex<T>(agentRef: string, fn: () => Promise<T>): Promise<T> {+ return this.serialize(this.indexChains, agentRef, fn)+ }++ private serializeChat<T>(agentRef: string, chatId: string, fn: () => Promise<T>): Promise<T> {+ return this.serialize(this.chatChains, JSON.stringify([agentRef, chatId]), fn)+ }+private agentDir(agentRef: string): string {assertSafeSegment('agentRef', agentRef)return join(this.baseDir, agentRef)@@ -563,13 +572,15 @@ export class ChatStore {}async deleteChat(agentRef: string, chatId: string): Promise<void> {- return this.serializeIndex(agentRef, async () => {- const index = await this.getIndex(agentRef)- index.chats = index.chats.filter(c => c.id !== chatId)- if (index.lastActiveChatId === chatId) {- index.lastActiveChatId = null- }- await this.saveIndex(agentRef, index)+ return this.serializeChat(agentRef, chatId, async () => {+ await this.serializeIndex(agentRef, async () => {+ const index = await this.getIndex(agentRef)+ index.chats = index.chats.filter(c => c.id !== chatId)+ if (index.lastActiveChatId === chatId) {+ index.lastActiveChatId = null+ }+ await this.saveIndex(agentRef, index)+ })await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })await fs.rm(this.chatDirPath(agentRef, chatId), { recursive: true, force: true })})@@ -582,7 +593,7 @@ export class ChatStore {offset?: number): Promise<ChatMessage[]> {try {- return await this.serializeIndex(agentRef, async () => {+ return await this.serializeChat(agentRef, chatId, async () => {const meta = await this.readOrMigratePagedChatUnlocked(agentRef, chatId)if (!meta) return []return this.readMessagesFromPagedMeta(agentRef, chatId, meta, limit, offset)@@ -593,17 +604,19 @@ export class ChatStore {}async saveMessages(agentRef: string, chatId: string, messages: ChatMessage[]): Promise<void> {- return this.serializeIndex(agentRef, async () => {+ return this.serializeChat(agentRef, chatId, async () => {await this.writePagedChatUnlocked(agentRef, chatId, messages, { removeLegacy: true })- const index = await this.getIndex(agentRef)- const chat = index.chats.find(c => c.id === chatId)- if (chat) {- chat.messageCount = messages.length- Object.assign(chat, aggregateMessages(messages))- chat.updatedAt = new Date().toISOString()- await this.saveIndex(agentRef, index)- }+ await this.serializeIndex(agentRef, async () => {+ const index = await this.getIndex(agentRef)+ const chat = index.chats.find(c => c.id === chatId)+ if (chat) {+ chat.messageCount = messages.length+ Object.assign(chat, aggregateMessages(messages))+ chat.updatedAt = new Date().toISOString()+ await this.saveIndex(agentRef, index)+ }+ })})}@@ -612,22 +625,24 @@ export class ChatStore {chatId: string,newMessages: ChatMessage[]): Promise<void> {- return this.serializeIndex(agentRef, async () => {+ return this.serializeChat(agentRef, chatId, async () => {const existing =(await this.readOrMigratePagedChatUnlocked(agentRef, chatId)) ??(await this.writePagedChatUnlocked(agentRef, chatId, [], { removeLegacy: true }))const meta = await this.appendPagedMessagesUnlocked(agentRef, chatId, existing, newMessages)- const index = await this.getIndex(agentRef)- const chat = index.chats.find(c => c.id === chatId)- if (chat) {- const delta = aggregateMessages(newMessages)- chat.messageCount = meta.messageCount- chat.errorCount = (chat.errorCount ?? 0) + (delta.errorCount ?? 0)- chat.toolCallCount = (chat.toolCallCount ?? 0) + (delta.toolCallCount ?? 0)- chat.updatedAt = new Date().toISOString()- await this.saveIndex(agentRef, index)- }+ await this.serializeIndex(agentRef, async () => {+ const index = await this.getIndex(agentRef)+ const chat = index.chats.find(c => c.id === chatId)+ if (chat) {+ const delta = aggregateMessages(newMessages)+ chat.messageCount = meta.messageCount+ chat.errorCount = (chat.errorCount ?? 0) + (delta.errorCount ?? 0)+ chat.toolCallCount = (chat.toolCallCount ?? 0) + (delta.toolCallCount ?? 0)+ chat.updatedAt = new Date().toISOString()+ await this.saveIndex(agentRef, index)+ }+ })})}