Skip to content

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

TypeScript

fix(desktop-ui): invalidate the session catalog cache when a Host is held

Alfredo Lopez30ecd0dfeacd
diff --git a/desktop-app/ui/src/hooks/__tests__/useAppController.hostHoldCatalogCache.test.tsx b/desktop-app/ui/src/hooks/__tests__/useAppController.hostHoldCatalogCache.test.tsx
new file mode 100644
index 000000000..ea6930712
--- /dev/null
+++ b/desktop-app/ui/src/hooks/__tests__/useAppController.hostHoldCatalogCache.test.tsx
@@ -0,0 +1,99 @@
+// @vitest-environment jsdom
+/**
+ * F4: the renderer shares one in-flight `listSessions` request per
+ * scope/Host/query for five seconds. A request issued before a Host hold is
+ * answered with the authority that held before the hold; handing it to a reader
+ * that starts after `verifyHostAccess` released the hold would let that stale
+ * answer re-hold a Host the user was just cleared for. Holding a Host therefore
+ * invalidates its cached catalog requests.
+ *
+ * The held Host is deliberately not the selected one: a revoked hold of the
+ * selected agent already clears the whole cache through the chat controller's
+ * teardown, which would hide the defect.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { act, waitFor } from '@testing-library/react'
+import type { SessionsListResult } from '../../../../src/types'
+import {
+ installAppControllerClerum,
+ renderAppController,
+} from '../domain/__tests__/__fixtures__/appControllerHarness'
+import {
+ deferred,
+ localIndex,
+ serverSessions,
+} from '../domain/__tests__/__fixtures__/catalogFixtures'
+import { ipcHostAccessRevoked } from '../domain/__tests__/__fixtures__/ipcErrors'
+import { uninstallMockClerum } from '../domain/__tests__/__fixtures__/mockClerum'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+type ListSessionsQuery = { agent?: string; limit?: number; cursor?: string }
+
+describe('useAppController Host hold and the session catalog cache', () => {
+ let unmount: (() => void) | null = null
+
+ afterEach(() => {
+ unmount?.()
+ unmount = null
+ vi.restoreAllMocks()
+ uninstallMockClerum()
+ })
+
+ it('does not hand a pre-hold catalog request to a reader after the hold is released', async () => {
+ const { clerum } = installAppControllerClerum({ agentNames: ['agent-x', 'agent-y'] })
+ const staleCatalog = deferred<SessionsListResult>()
+ let heldHostPageReads = 0
+ clerum.chat.getIndex.mockImplementation(async (agentRef: string) =>
+ agentRef === 'agent-x' ? localIndex([{ id: 'c1', title: 'old' }]) : localIndex([])
+ )
+ clerum.rpc.listSessions.mockImplementation(
+ async (hostRef: string, _teamId: string | undefined, query?: ListSessionsQuery) => {
+ if (query?.limit === 1 || hostRef !== 'agent-x') return serverSessions([])
+ heldHostPageReads += 1
+ if (heldHostPageReads === 1) return staleCatalog.promise
+ return serverSessions([{ agent: 'agent-x', chatId: 'c1', title: 'old' }])
+ }
+ )
+ clerum.rpc.renameSession.mockRejectedValue(await ipcHostAccessRevoked('rpc:renameSession'))
+
+ const app = renderAppController()
+ unmount = app.unmount
+ await waitFor(() => expect(app.result.current.isAuthenticated).toBe(true))
+ await waitFor(() => expect(app.result.current.initialExperienceLoading).toBe(false))
+ act(() => {
+ app.result.current.handleSelectChatAgent('agent-y')
+ })
+ // The cross-agent preview's catalog read for agent-x is in flight and
+ // stays so across the hold.
+ await waitFor(() => expect(heldHostPageReads).toBe(1))
+
+ await act(async () => {
+ await app.result.current.handleRenameChatForAgent('agent-x', 'c1', 'new')
+ })
+ // Witness: the rename's confirmed revocation held agent-x.
+ expect(clerum.rpc.renameSession).toHaveBeenCalledWith('agent-x', 'agent-x', 'c1', 'new')
+ expect(app.result.current.isHostAccessBlocked('agent-x')).toBe(true)
+
+ act(() => {
+ app.result.current.handleSelectChatAgent('agent-x')
+ })
+ await waitFor(() => expect(app.result.current.isHostAccessBlocked('agent-x')).toBe(false))
+ // The post-release reader issued its own catalog request instead of
+ // sharing the pre-hold one.
+ await waitFor(() => expect(heldHostPageReads).toBe(2))
+ await waitFor(() =>
+ expect(app.result.current.chatList.some(chat => chat.id === 'c1')).toBe(true)
+ )
+
+ await act(async () => {
+ staleCatalog.reject(await ipcHostAccessRevoked('rpc:listSessions'))
+ await staleCatalog.promise.catch(() => undefined)
+ })
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 20))
+ })
+
+ expect(app.result.current.isHostAccessBlocked('agent-x')).toBe(false)
+ })
+})
diff --git a/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx
index 9503dfad9..9eaf73cec 100644
--- a/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx
+++ b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx
@@ -48,6 +48,39 @@ describe('useChatStore remote request cache', () => {
expect(listSessions).toHaveBeenCalledTimes(2)
})
+ // F4: holding a Host drops its cached catalog requests (every query) and
+ // leaves every other Host's entries shared. The scope itself contains ':',
+ // so the Host is matched on the entry, not parsed out of the key.
+ it('invalidates only the held Host catalog entries', async () => {
+ const listSessions = vi.fn(async () => ({ items: [] }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { rpc: { listSessions } },
+ })
+ const { result } = renderHook(() => useChatStore())
+ const readAll = () =>
+ Promise.all([
+ result.current.listSessions('host', { agent: 'host', limit: 50 }),
+ result.current.listSessions('host', { agent: 'host', limit: 50, cursor: 'page-2' }),
+ result.current.listSessions('host-b', { agent: 'host-b', limit: 50 }),
+ ])
+ const callsFor = (hostRef: string) =>
+ listSessions.mock.calls.filter(call => (call as unknown[])[0] === hostRef).length
+
+ result.current.setRemoteCacheScope('authenticated:user-f4:team-f4')
+ await readAll()
+ await readAll()
+ // Witness: the cache is live (three distinct keys, one upstream call each).
+ expect(callsFor('host')).toBe(2)
+ expect(callsFor('host-b')).toBe(1)
+
+ result.current.invalidateSessionCatalog('host')
+ await readAll()
+
+ expect(callsFor('host')).toBe(4)
+ expect(callsFor('host-b')).toBe(1)
+ })
+
// #654 M12 — the host-model catalog has exactly one cache, in
// `hostModelSelectionStore`, which also owns revision ordering. A second TTL
// layer here could only serve a response read BEFORE a write, which is the
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index d00ec2320..57b371f67 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -58,6 +58,7 @@ import {
createResetWorkflowSelection,
} from './domain/useWorkflowController.types'
import { scheduleAfterFirstPaint } from './scheduleAfterFirstPaint'
+import { useChatStore } from './useChatStore'
// U5 cold-start buffer: how long an OAuth completion whose sessions are not yet
// seeded is retried against later snapshots before it is discarded. Long enough
@@ -339,14 +340,18 @@ export function useAppController() {
hostAuthority.reset()
setHostAuthorityRevision(revision => revision + 1)
}, [authorityScope, hostAuthority])
+ const { invalidateSessionCatalog } = useChatStore()
const blockHostAccess = useCallback(
(agentRef: string, kind: HostAuthorityHoldKind) => {
+ // F4: a catalog request issued before the hold must not be shared with a
+ // reader that starts after `verifyHostAccess` releases it.
+ invalidateSessionCatalog(agentRef)
if (!hostAuthority.hold(agentRef, kind)) return
setHostAuthorityRevision(revision => revision + 1)
if (selectedAgentRef.current === agentRef) nav.setSelectedAgent(null)
void agentsData.refresh()
},
- [agentsData.refresh, hostAuthority, nav.setSelectedAgent]
+ [agentsData.refresh, hostAuthority, invalidateSessionCatalog, nav.setSelectedAgent]
)
const onHostAccessRevoked = useCallback(
(agentRef: string) => blockHostAccess(agentRef, 'revoked'),
diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.ts
index 57dcbe10a..91302ecbe 100644
--- a/desktop-app/ui/src/hooks/useChatStore.ts
+++ b/desktop-app/ui/src/hooks/useChatStore.ts
@@ -40,6 +40,8 @@ const SESSION_CATALOG_TTL_MS = 5_000
type CachedRequest<T> = {
expiresAt: number
+ /** Host the request was issued against; the key's scope segment may contain ':'. */
+ hostRef: string
promise: Promise<T>
}
@@ -168,6 +170,7 @@ export function useChatStore() {
})
sessionCatalogRequests.set(key, {
expiresAt: Date.now() + SESSION_CATALOG_TTL_MS,
+ hostRef,
promise,
})
return promise
@@ -210,6 +213,14 @@ export function useChatStore() {
sessionCatalogRequests.clear()
sessionCatalogSource = null
}, [])
+ // F4: a catalog request issued before a Host hold carries the authority of
+ // that moment. Dropping it when the Host is held keeps a reader that starts
+ // after `verifyHostAccess` released the hold from sharing it.
+ const invalidateSessionCatalog = useCallback((hostRef: string) => {
+ for (const [key, cached] of sessionCatalogRequests) {
+ if (cached.hostRef === hostRef) sessionCatalogRequests.delete(key)
+ }
+ }, [])
const setRemoteCacheScope = useCallback((scope: string) => {
if (remoteCacheScope === scope) return
remoteCacheScope = scope
@@ -280,6 +291,7 @@ export function useChatStore() {
setHostModel,
renameSession,
clearCachedRemoteData,
+ invalidateSessionCatalog,
setRemoteCacheScope,
setPendingModel,
getPendingModel,