Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
perf(desktop): open a chat without waiting for the last-active write
Alfredo Lopez63e3a5f92882
diff --git a/desktop-app/src/__tests__/chatStore.lastActive.test.ts b/desktop-app/src/__tests__/chatStore.lastActive.test.tsnew file mode 100644index 000000000..0c871e42f--- /dev/null+++ b/desktop-app/src/__tests__/chatStore.lastActive.test.ts@@ -0,0 +1,81 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { promises as fs } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { ChatStore } from '../chatStore.js'++let tempDir: string+let store: ChatStore++beforeEach(async () => {+ tempDir = await fs.mkdtemp(join(tmpdir(), 'chatstore-last-active-'))+ store = new ChatStore(tempDir)+ store.setAuthorityScope({ environmentKey: 'env-test', userId: 'user-test', teamId: 'team-test' })+ await store.createChat('agent-1', 'chat-a')+ await store.createChat('agent-1', 'chat-b')+ await store.setLastActiveChatId('agent-1', 'chat-a')+})++afterEach(async () => {+ vi.restoreAllMocks()+ await fs.rm(tempDir, { recursive: true, force: true })+})++describe('ChatStore last-active index writes', () => {+ it('reads the committed index without writing or syncing an unchanged selection, but writes a changed one', async () => {+ const read = vi.spyOn(fs, 'readFile')+ const write = vi.spyOn(fs, 'writeFile')+ const open = vi.spyOn(fs, 'open')+ const rename = vi.spyOn(fs, 'rename')+ const indexPath = join(tempDir, 'agent-1', 'index.json')++ await store.setLastActiveChatId('agent-1', 'chat-a')++ expect(read).toHaveBeenCalledWith(indexPath, 'utf-8')+ expect(write).not.toHaveBeenCalled()+ expect(open).not.toHaveBeenCalled()+ expect(rename).not.toHaveBeenCalled()++ await store.setLastActiveChatId('agent-1', 'chat-b')++ expect(read).toHaveBeenCalledTimes(2)+ expect(write).toHaveBeenCalledTimes(1)+ expect(write).toHaveBeenCalledWith(`${indexPath}.tmp`, expect.any(String), { mode: 0o600 })+ expect(open).toHaveBeenCalledWith(`${indexPath}.tmp`, 'r')+ expect(rename).toHaveBeenCalledWith(`${indexPath}.tmp`, indexPath)+ expect(await store.getLastActiveChatId('agent-1')).toBe('chat-b')+ })++ it('serializes A to B to A in click order and compares each selection to the latest committed value', async () => {+ const readIndex = vi.spyOn(store, 'getIndex')+ const write = vi.spyOn(fs, 'writeFile')++ await Promise.all([+ store.setLastActiveChatId('agent-1', 'chat-a'),+ store.setLastActiveChatId('agent-1', 'chat-b'),+ store.setLastActiveChatId('agent-1', 'chat-a'),+ ])++ expect(readIndex.mock.calls).toEqual([['agent-1'], ['agent-1'], ['agent-1']])+ expect(write.mock.calls.map(call => JSON.parse(String(call[1])).lastActiveChatId)).toEqual([+ 'chat-b',+ 'chat-a',+ ])+ expect(await store.getLastActiveChatId('agent-1')).toBe('chat-a')+ })++ it('skips a duplicate queued selection only after the preceding write has committed', async () => {+ const readIndex = vi.spyOn(store, 'getIndex')+ const write = vi.spyOn(fs, 'writeFile')++ await Promise.all([+ store.setLastActiveChatId('agent-1', 'chat-b'),+ store.setLastActiveChatId('agent-1', 'chat-b'),+ ])++ expect(readIndex.mock.calls).toEqual([['agent-1'], ['agent-1']])+ expect(write).toHaveBeenCalledTimes(1)+ expect(JSON.parse(String(write.mock.calls[0]![1])).lastActiveChatId).toBe('chat-b')+ expect(await store.getLastActiveChatId('agent-1')).toBe('chat-b')+ })+})diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex 92459aed7..08eb4885a 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -1755,6 +1755,7 @@ export class ChatStore {return this.serializeIndex(agentRef, async () => {const index = await this.getIndex(agentRef)if (this.isDeletedInScope(index, chatId)) return+ if (index.lastActiveChatId === chatId) returnindex.lastActiveChatId = chatIdawait this.saveIndex(agentRef, index)})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.concurrentLastActive.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.concurrentLastActive.test.tsxnew file mode 100644index 000000000..49c103ae5--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.concurrentLastActive.test.tsx@@ -0,0 +1,232 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup, waitFor } from '@testing-library/react'+import { resetComposerDraftStore } from '@lib/composerDraftStore'+import { deferred, localIndex } from './__fixtures__/catalogFixtures'+import { renderController } from './__fixtures__/controllerHarness'+import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'++let clerum: MockClerum+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const cachedMessages = [+ { id: 'cached-user', role: 'user' as const, content: 'Cached question', timestamp: 1 },+ { id: 'cached-assistant', role: 'assistant' as const, content: 'Cached answer', timestamp: 2 },+]++beforeEach(() => {+ clerum = installMockClerum()+ clerum.chat.loadMessages.mockResolvedValue(cachedMessages)+})++afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ resetComposerDraftStore()+ uninstallMockClerum()+})++async function settleMount() {+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())+}++describe('switchToChat last-active persistence', () => {+ it('loads and renders cached messages before last-active persistence resolves, then waits for it', async () => {+ const lastActive = deferred<void>()+ clerum.chat.setLastActive.mockReturnValueOnce(lastActive.promise)+ const { result } = renderController()+ await settleMount()+ let selection!: Promise<void>+ let completed = false++ await act(async () => {+ selection = result.current.switchToChat('agent-x', 'chat-a').then(() => {+ completed = true+ })+ })+ try {+ await waitFor(() => {+ expect(clerum.chat.loadMessages).toHaveBeenCalledWith('agent-x', 'chat-a', 80, undefined)+ expect(result.current.activeChatId).toBe('chat-a')+ expect(result.current.chatMessages).toEqual(cachedMessages)+ expect(result.current.chatMessagesLoading).toBe(false)+ })+ expect(clerum.chat.setLastActive).toHaveBeenCalledWith('agent-x', 'chat-a')+ expect(completed).toBe(false)+ } finally {+ await act(async () => {+ lastActive.resolve()+ await selection+ })+ }++ expect(completed).toBe(true)+ expect(result.current.chatMessages).toEqual(cachedMessages)+ })++ it('rejects the selection with a deferred persistence error after its cached messages render', async () => {+ const lastActive = deferred<void>()+ const failure = new Error('Last-active index is not writable')+ clerum.chat.setLastActive.mockReturnValueOnce(lastActive.promise)+ const { result } = renderController()+ await settleMount()+ let selection!: Promise<void>++ await act(async () => {+ selection = result.current.switchToChat('agent-x', 'chat-a')+ })+ const rejection = expect(selection).rejects.toBe(failure)+ try {+ await waitFor(() => expect(result.current.chatMessages).toEqual(cachedMessages))+ expect(clerum.chat.loadMessages).toHaveBeenCalledWith('agent-x', 'chat-a', 80, undefined)+ expect(clerum.chat.setLastActive).toHaveBeenCalledWith('agent-x', 'chat-a')+ } finally {+ await act(async () => {+ lastActive.reject(failure)+ await rejection+ })+ }++ expect(result.current.activeChatId).toBe('chat-a')+ expect(result.current.chatMessages).toEqual(cachedMessages)+ expect(result.current.chatMessagesLoading).toBe(false)+ })++ it('observes an early persistence rejection while the cache read is still pending', async () => {+ const lastActive = deferred<void>()+ const cache = deferred<typeof cachedMessages>()+ const failure = new Error('Last-active write failed before the cache read')+ clerum.chat.setLastActive.mockReturnValueOnce(lastActive.promise)+ clerum.chat.loadMessages.mockReturnValueOnce(cache.promise)+ const { result } = renderController()+ await settleMount()+ let selection!: Promise<void>+ let rejected = false+ let rejection!: Promise<void>++ await act(async () => {+ selection = result.current.switchToChat('agent-x', 'chat-a')+ rejection = expect(selection)+ .rejects.toBe(failure)+ .then(() => {+ rejected = true+ })+ lastActive.reject(failure)+ })+ try {+ expect(clerum.chat.loadMessages).toHaveBeenCalledWith('agent-x', 'chat-a', 80, undefined)+ expect(rejected).toBe(false)+ expect(result.current.chatMessagesLoading).toBe(true)+ } finally {+ await act(async () => {+ cache.resolve(cachedMessages)+ await rejection+ })+ }++ expect(rejected).toBe(true)+ expect(result.current.chatMessages).toEqual(cachedMessages)+ })++ it('keeps a superseded selection persistence error attached to its own promise', async () => {+ const lastActive = deferred<void>()+ const failure = new Error('Chat A last-active write failed')+ const chatBMessages = [{ id: 'b-user', role: 'user' as const, content: 'Chat B', timestamp: 3 }]+ clerum.chat.setLastActive.mockReturnValueOnce(lastActive.promise)+ clerum.chat.loadMessages.mockImplementation(async (_agentRef: string, chatId: string) =>+ chatId === 'chat-a' ? cachedMessages : chatBMessages+ )+ const { result } = renderController()+ await settleMount()+ let selectionA!: Promise<void>++ await act(async () => {+ selectionA = result.current.switchToChat('agent-x', 'chat-a')+ })+ const rejection = expect(selectionA).rejects.toBe(failure)+ try {+ await waitFor(() => expect(result.current.chatMessages).toEqual(cachedMessages))+ await act(async () => {+ await result.current.switchToChat('agent-x', 'chat-b')+ })+ expect(result.current.activeChatId).toBe('chat-b')+ expect(result.current.chatMessages).toEqual(chatBMessages)+ expect(clerum.chat.setLastActive.mock.calls.map(call => call.slice(0, 2))).toEqual([+ ['agent-x', 'chat-a'],+ ['agent-x', 'chat-b'],+ ])+ } finally {+ await act(async () => {+ lastActive.reject(failure)+ await rejection+ })+ }++ expect(result.current.activeChatId).toBe('chat-b')+ expect(result.current.chatMessages).toEqual(chatBMessages)+ })++ it('checks a blocked Host before reading cached messages', async () => {+ const isHostAccessBlocked = vi.fn(() => false)+ const { result } = renderController({ isHostAccessBlocked })+ await settleMount()+ isHostAccessBlocked.mockReturnValue(true)+ isHostAccessBlocked.mockClear()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'chat-a')+ })++ expect(isHostAccessBlocked).toHaveBeenCalledWith('agent-x')+ expect(clerum.chat.loadMessages).not.toHaveBeenCalled()+ })++ it('checks a durable deleted-chat tombstone before reading cached messages', async () => {+ const isHostAccessBlocked = vi.fn(() => false)+ clerum.chat.getIndex.mockResolvedValue(+ localIndex([{ id: 'chat-b', title: 'Chat B' }], ['chat-a'])+ )+ const { result } = renderController({ isHostAccessBlocked })+ await waitFor(() => expect(result.current.chatList.map(chat => chat.id)).toEqual(['chat-b']))+ expect(clerum.chat.getIndex).toHaveBeenCalledWith('agent-x')+ isHostAccessBlocked.mockClear()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'chat-a')+ })++ expect(isHostAccessBlocked).toHaveBeenCalledWith('agent-x')+ expect(clerum.chat.loadMessages).not.toHaveBeenCalled()+ })++ it('rechecks Host access after starting persistence and awaits it even when the guard returns', async () => {+ const isHostAccessBlocked = vi.fn(() => false)+ const lastActive = deferred<void>()+ clerum.chat.setLastActive.mockImplementationOnce(() => {+ isHostAccessBlocked.mockReturnValue(true)+ return lastActive.promise+ })+ const { result } = renderController({ isHostAccessBlocked })+ await settleMount()+ let selection!: Promise<void>+ let completed = false++ await act(async () => {+ selection = result.current.switchToChat('agent-x', 'chat-a').then(() => {+ completed = true+ })+ })+ try {+ expect(clerum.chat.setLastActive).toHaveBeenCalledWith('agent-x', 'chat-a')+ expect(clerum.chat.loadMessages).not.toHaveBeenCalled()+ expect(completed).toBe(false)+ } finally {+ await act(async () => {+ lastActive.resolve()+ await selection+ })+ }++ expect(completed).toBe(true)+ })+})diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex 79394edf9..300f6b9e7 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -1010,99 +1010,106 @@ export function useAgentChatController({// into chat B). The Phase-2 reconcile below re-derives state for this chat.setAgentError(null)setFailedAgentSend(null)- await chatStore.setLastActive(agentRef, chatId)- if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) return+ // Observe failures immediately while the cache loads, then propagate them+ // from this selection's completion, including early returns.+ const lastActive = Promise.allSettled([chatStore.setLastActive(agentRef, chatId)])+ try {+ if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) return++ unfillableServerGapUpperBoundsRef.current.delete(key)++ // Renderer-local relevance guard for a fast A→B→A switch: THIS switch's+ // reconcile is aborted the moment the user switches away. Passed into+ // `reconcileChat` as a per-call `isRelevant` (replaces the Phase-2+ // AbortController) so a background reconcile — system:resume, or a bell+ // approval on a NON-visible chat — is never subject to an active-chat guard.+ const isStillActive = () => {+ const visible = activeChatVisibilityRef.current+ return (+ activeChatSwitchRequestRef.current === switchRequest &&+ visible.selectedAgent === agentRef &&+ visible.activeChatId === chatId+ )+ }- unfillableServerGapUpperBoundsRef.current.delete(key)-- // Renderer-local relevance guard for a fast A→B→A switch: THIS switch's- // reconcile is aborted the moment the user switches away. Passed into- // `reconcileChat` as a per-call `isRelevant` (replaces the Phase-2- // AbortController) so a background reconcile — system:resume, or a bell- // approval on a NON-visible chat — is never subject to an active-chat guard.- const isStillActive = () => {- const visible = activeChatVisibilityRef.current- return (- activeChatSwitchRequestRef.current === switchRequest &&- visible.selectedAgent === agentRef &&- visible.activeChatId === chatId- )+ // PHASE 1 — render only the newest local page. The authoritative reconcile+ // below requests a delta after the newest cached server turn.+ let cached: Awaited<ReturnType<typeof chatStore.loadMessages>> = []+ try {+ cached = canReuseActiveSwitch+ ? ([...chatMessagesRef.current] as AgentChatMessage[])+ : ((await chatStore.loadMessages(+ agentRef,+ chatId,+ LOCAL_MESSAGE_PAGE_SIZE+ )) as AgentChatMessage[])+ } catch (error) {+ console.warn('[chat-history] failed to load local messages', { agentRef, chatId, error })+ }+ const hasOlderServerMessages =+ nextServerBackfillBeforeTurn(cached as AgentChatMessage[]) !== undefined+ const hasOlderLocalMessages =+ !hasOlderServerMessages &&+ cached.length === LOCAL_MESSAGE_PAGE_SIZE &&+ (await hasLocalMessagesBeyond(chatStore, agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE))+ if (!isStillActive()) return+ loadedLocalMessageCountRef.current = cached.length+ setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)+ if (!canReuseActiveSwitch) setChatMessages(cached as AgentChatMessage[])+ // Phase 1 rendered the cache → clear the blocking spinner. The reconcile+ // runs under the `syncing` indicator (RECONCILE_STARTED, dispatched by the+ // reconcile gate) instead.+ setChatMessagesLoading(false)+ // D.5: opening the chat clears its "completed_unread" badge. CHAT_OPENED+ // resets the FSM's `unreadTerminal` flag so a LATER hidden terminal re-marks+ // (without it the flag is write-once-true and the badge never reappears) and+ // its `clear_unread` effect mirrors the clear to disk+sidebar. The+ // unconditional clear below ALSO runs because on a cold reload the FSM flag+ // is fresh-`false` while the persisted disk badge is `true` — CHAT_OPENED's+ // flag-gated effect wouldn't fire, so the badge must still be cleared here.+ dispatchSession(key, { type: 'CHAT_OPENED' })+ void chatStore.clearUnreadTerminal(agentRef, chatId)+ clearUnreadInList(chatId)+ scrollChatToBottom()++ // A deliberate user re-open grants a fresh re-rejoin quota — the cap only+ // exists to stop the automatic stream-loss → rejoin loop (P1-stall). A+ // capped chat therefore clears its offline banner when reopened + reconciled+ // clean.+ tracker.resetRejoinAttempts(key)++ // PHASE 2/3 — the single reconcile gate (§4.3) owns fetch+retry, ambiguous 404,+ // offline, the SERVER_SNAPSHOT, the idle replace (auto-title / S4 upsert /+ // epoch-anchored zombie-ack) and the live rejoin (approval re-seed).+ // `taskIdHint` = the pre-await zombie's task, which drives the durable+ // getTaskResult fallback + response-file attachment load; the zombie-ack+ // itself no longer needs a taskId to match (R2's epoch replaces the old+ // `recoveringTaskIdByKeyRef` bookkeeping).+ //+ // The gate re-reads the same bounded local page inside hydrate so an SSE+ // terminal that lands between Phase 1 and reconciliation is included+ // without transferring the complete local transcript over IPC. Note+ // (best-effort): `reconcileChat` is single-flight per key — if a background+ // reconcile is already in flight for THIS key, this call coalesces onto it+ // and its `isRelevant`/`taskIdHint` are ignored; `hydrateActiveChatFromServer`'s+ // own `isActive()` guard still prevents rendering into the wrong chat.+ const zombieBefore = tracker.get(key)+ const latestCachedTurn = latestServerTurnNumber(cached as AgentChatMessage[])+ const reconcileFromTurn =+ latestCachedTurn === undefined ? undefined : Math.max(0, latestCachedTurn - 1)+ await reconcileChat(key, {+ reason: 'switch_to_chat',+ taskIdHint: zombieBefore?.taskId,+ isRelevant: isStillActive,+ messagesQuery: {+ limit: SERVER_TURN_PAGE_SIZE,+ ...(reconcileFromTurn !== undefined ? { afterTurn: reconcileFromTurn } : {}),+ },+ })+ } finally {+ const [lastActiveResult] = await lastActive+ if (lastActiveResult.status === 'rejected') throw lastActiveResult.reason}-- // PHASE 1 — render only the newest local page. The authoritative reconcile- // below requests a delta after the newest cached server turn.- let cached: Awaited<ReturnType<typeof chatStore.loadMessages>> = []- try {- cached = canReuseActiveSwitch- ? ([...chatMessagesRef.current] as AgentChatMessage[])- : ((await chatStore.loadMessages(- agentRef,- chatId,- LOCAL_MESSAGE_PAGE_SIZE- )) as AgentChatMessage[])- } catch (error) {- console.warn('[chat-history] failed to load local messages', { agentRef, chatId, error })- }- const hasOlderServerMessages =- nextServerBackfillBeforeTurn(cached as AgentChatMessage[]) !== undefined- const hasOlderLocalMessages =- !hasOlderServerMessages &&- cached.length === LOCAL_MESSAGE_PAGE_SIZE &&- (await hasLocalMessagesBeyond(chatStore, agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE))- if (!isStillActive()) return- loadedLocalMessageCountRef.current = cached.length- setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)- if (!canReuseActiveSwitch) setChatMessages(cached as AgentChatMessage[])- // Phase 1 rendered the cache → clear the blocking spinner. The reconcile- // runs under the `syncing` indicator (RECONCILE_STARTED, dispatched by the- // reconcile gate) instead.- setChatMessagesLoading(false)- // D.5: opening the chat clears its "completed_unread" badge. CHAT_OPENED- // resets the FSM's `unreadTerminal` flag so a LATER hidden terminal re-marks- // (without it the flag is write-once-true and the badge never reappears) and- // its `clear_unread` effect mirrors the clear to disk+sidebar. The- // unconditional clear below ALSO runs because on a cold reload the FSM flag- // is fresh-`false` while the persisted disk badge is `true` — CHAT_OPENED's- // flag-gated effect wouldn't fire, so the badge must still be cleared here.- dispatchSession(key, { type: 'CHAT_OPENED' })- void chatStore.clearUnreadTerminal(agentRef, chatId)- clearUnreadInList(chatId)- scrollChatToBottom()-- // A deliberate user re-open grants a fresh re-rejoin quota — the cap only- // exists to stop the automatic stream-loss → rejoin loop (P1-stall). A- // capped chat therefore clears its offline banner when reopened + reconciled- // clean.- tracker.resetRejoinAttempts(key)-- // PHASE 2/3 — the single reconcile gate (§4.3) owns fetch+retry, ambiguous 404,- // offline, the SERVER_SNAPSHOT, the idle replace (auto-title / S4 upsert /- // epoch-anchored zombie-ack) and the live rejoin (approval re-seed).- // `taskIdHint` = the pre-await zombie's task, which drives the durable- // getTaskResult fallback + response-file attachment load; the zombie-ack- // itself no longer needs a taskId to match (R2's epoch replaces the old- // `recoveringTaskIdByKeyRef` bookkeeping).- //- // The gate re-reads the same bounded local page inside hydrate so an SSE- // terminal that lands between Phase 1 and reconciliation is included- // without transferring the complete local transcript over IPC. Note- // (best-effort): `reconcileChat` is single-flight per key — if a background- // reconcile is already in flight for THIS key, this call coalesces onto it- // and its `isRelevant`/`taskIdHint` are ignored; `hydrateActiveChatFromServer`'s- // own `isActive()` guard still prevents rendering into the wrong chat.- const zombieBefore = tracker.get(key)- const latestCachedTurn = latestServerTurnNumber(cached as AgentChatMessage[])- const reconcileFromTurn =- latestCachedTurn === undefined ? undefined : Math.max(0, latestCachedTurn - 1)- await reconcileChat(key, {- reason: 'switch_to_chat',- taskIdHint: zombieBefore?.taskId,- isRelevant: isStillActive,- messagesQuery: {- limit: SERVER_TURN_PAGE_SIZE,- ...(reconcileFromTurn !== undefined ? { afterTurn: reconcileFromTurn } : {}),- },- })},[currentTeamId,