Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop,hcc): harden revoked reads and draining holds
Alfredo Lopezb70a66e5e096
diff --git a/desktop-app/src/__tests__/rpcProxyClient.test.ts b/desktop-app/src/__tests__/rpcProxyClient.test.tsindex c7f5de222..88ffea848 100644--- a/desktop-app/src/__tests__/rpcProxyClient.test.ts+++ b/desktop-app/src/__tests__/rpcProxyClient.test.ts@@ -44,6 +44,37 @@ describe('RpcProxyClient.listSessions', () => {})+ it('projects the exact Host access denial from catalog and transcript reads', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({+ ok: false,+ status: 403,+ text: async () => JSON.stringify({ error: 'Forbidden: user cannot access this host' }),+ })+ )++ await expect(client.listSessions('token', 'host')).rejects.toThrow(+ '403 Forbidden: host_access_revoked'+ )+ await expect(client.loadSessionMessages('token', 'host', 'agent-a', 'chat-a')).rejects.toThrow(+ '403 Forbidden: host_access_revoked'+ )+ })++ it('keeps a generic catalog 403 uncertain', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({+ ok: false,+ status: 403,+ text: async () => JSON.stringify({ error: 'missing scope' }),+ })+ )++ await expect(client.listSessions('token', 'host')).rejects.toThrow('List sessions failed (403)')+ })+it('accepts legacy session catalog responses that omit optional metadata', async () => {vi.stubGlobal('fetch',diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex 38d15fd58..b142d00b1 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -1463,14 +1463,30 @@ export function registerIpcHandlers(service: AppService): void {ipcMain.handle('chat:rename',- async (event, payload: { agentRef: string; chatId: string; title: string }) => {+ async (+ event,+ payload: {+ agentRef: string+ chatId: string+ title: string+ bindingGeneration: number+ }+ ) => {assertTrustedSender(event)const agentRef = sanitizeString(payload?.agentRef)const chatId = sanitizeString(payload?.chatId)const title = sanitizeString(payload?.title)if (!agentRef || !chatId || !title)throw new Error('agentRef, chatId, and title are required')- await requireChatStore().renameChat(agentRef, chatId, title)+ const bindingGeneration = payload?.bindingGeneration+ if (typeof bindingGeneration !== 'number' || !Number.isSafeInteger(bindingGeneration)) {+ throw new Error('A valid chat store binding generation is required')+ }+ await requireChatStoreForBindingGeneration(bindingGeneration).renameChat(+ agentRef,+ chatId,+ title+ )})@@ -1522,7 +1538,7 @@ export function registerIpcHandlers(service: AppService): void {throw new Error('Chat deletion authority changed before confirmation')}const store = requireChatStoreForBindingGeneration(fence.bindingGeneration)- await store.deleteChat(agentRef, chatId, fence.authorityScope)+ return await store.deleteChat(agentRef, chatId, fence.authorityScope)})diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex ced4b55f9..a87185b12 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -578,8 +578,8 @@ const clerum = Object.freeze({list: (agentRef: string) => ipcRenderer.invoke('chat:list', { agentRef }),create: (agentRef: string, chatId: string) =>ipcRenderer.invoke('chat:create', { agentRef, chatId }),- rename: (agentRef: string, chatId: string, title: string) =>- ipcRenderer.invoke('chat:rename', { agentRef, chatId, title }),+ rename: (agentRef: string, chatId: string, title: string, bindingGeneration: number) =>+ ipcRenderer.invoke('chat:rename', { agentRef, chatId, title, bindingGeneration }),getBindingGeneration: () => ipcRenderer.invoke('chat:bindingGeneration'),captureDeleteFence: (expectedAuthorityScope: import('./types.js').ChatAuthorityScope) =>ipcRenderer.invoke('chat:captureDeleteFence', { expectedAuthorityScope }),diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex 5dbd6480a..a17977719 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -698,7 +698,12 @@ declare global {chat: {list: (agentRef: string) => Promise<ChatMetadata[]>create: (agentRef: string, chatId: string) => Promise<ChatMetadata>- rename: (agentRef: string, chatId: string, title: string) => Promise<void>+ rename: (+ agentRef: string,+ chatId: string,+ title: string,+ bindingGeneration: number+ ) => Promise<void>getBindingGeneration: () => Promise<number>captureDeleteFence: (expectedAuthorityScope: ChatAuthorityScope) => Promise<ChatDeleteFence>delete: (diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.tsindex 5fdcaabe2..de5292bfe 100644--- a/desktop-app/src/rpcProxyClient.ts+++ b/desktop-app/src/rpcProxyClient.ts@@ -456,6 +456,33 @@ function errorCodeFromBody(body: string): string | null {}}+function exactHostAccessRevokedError(status: number, body: string): ApiError | null {+ const denied =+ status === 403 && errorCodeFromBody(body) === 'Forbidden: user cannot access this host'+ return denied ? new ApiError('403 Forbidden: host_access_revoked', 403, body) : null+}++function projectHostAccessRevoked(error: unknown): unknown {+ if (!(error instanceof ApiError)) return error+ return exactHostAccessRevokedError(error.status, error.bodyText) ?? error+}++async function projectHostAccessRevokedInPromise<T>(promise: Promise<T>): Promise<T> {+ try {+ return await promise+ } catch (error) {+ throw projectHostAccessRevoked(error)+ }+}++function requestJsonProjected<T>(+ method: Parameters<typeof requestJson>[0],+ url: Parameters<typeof requestJson>[1],+ options: Parameters<typeof requestJson>[2]+): Promise<T> {+ return projectHostAccessRevokedInPromise(requestJson<T>(method, url, options))+}+export class RpcProxyClient {async health(): Promise<{ status: string }> {return requestJson<{ status: string }>('GET', url('/health'))@@ -513,23 +540,14 @@ export class RpcProxyClient {options?: { async?: boolean }): Promise<HostMessageResponse> {const query = options?.async ? '?async=true' : ''- return requestJson<HostMessageResponse>(+ return requestJsonProjected<HostMessageResponse>('POST',url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/messages${query}`),{token: rpcAccessToken,body: payload,}- ).catch(error => {- if (- error instanceof ApiError &&- error.status === 403 &&- errorCodeFromBody(error.bodyText) === 'Forbidden: user cannot access this host'- ) {- throw new ApiError('403 Forbidden: host_access_revoked', 403, error.bodyText)- }- throw error- })+ )}async getTaskResult(@@ -537,7 +555,7 @@ export class RpcProxyClient {hostRef: string,taskId: string): Promise<HostMessageResponse> {- return requestJson<HostMessageResponse>(+ return requestJsonProjected<HostMessageResponse>('GET',url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/tasks/${encodeURIComponent(taskId)}/result`@@ -1005,6 +1023,8 @@ export class RpcProxyClient {})if (!response.ok) {const body = await response.text()+ const hostAccessRevoked = exactHostAccessRevokedError(response.status, body)+ if (hostAccessRevoked) throw hostAccessRevokedthrow new ApiError(`List sessions failed (${response.status}): ${body}`,response.status,@@ -1047,6 +1067,8 @@ export class RpcProxyClient {}if (!response.ok) {const body = await response.text()+ const hostAccessRevoked = exactHostAccessRevokedError(response.status, body)+ if (hostAccessRevoked) throw hostAccessRevokedthrow new ApiError(`Load session messages failed (${response.status}): ${body}`,response.status,diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.tsindex 8072118e3..98940595b 100644--- a/desktop-app/test/ipc.test.ts+++ b/desktop-app/test/ipc.test.ts@@ -201,7 +201,10 @@ describe('ipc host status stream handlers', () => {const fence = await Promise.resolve(capture?.(event, { expectedAuthorityScope: authorityScope }))- await Promise.resolve(remove?.(event, { version: 3, agentRef: 'agent-x', chatId: 'c1', fence }))+ const result = await Promise.resolve(+ remove?.(event, { version: 3, agentRef: 'agent-x', chatId: 'c1', fence })+ )+ expect(result).toEqual({ cleanupPending: false })const index = await requireChatStore().getIndex('agent-x')expect(index.deletedChatTombstones).toContainEqual({ chatId: 'c1', authorityScope })expect(index.pendingChatCleanup).toEqual([])diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsxindex 51cac4051..e5e09702f 100644--- a/desktop-app/ui/src/App.tsx+++ b/desktop-app/ui/src/App.tsx@@ -2213,8 +2213,12 @@ export function App() {const notifValue = React.useMemo(() => ({- notifications: vm.notifications,- unreadNotificationCount: vm.unreadNotificationCount,+ notifications: vm.notifications.filter(+ notification => !vm.isHostAccessBlocked(notification.agentName)+ ),+ unreadNotificationCount: vm.notifications.filter(+ notification => !vm.isHostAccessBlocked(notification.agentName) && !notification.read+ ).length,notificationActionById: vm.notificationActionById,pendingApprovals: vm.pendingApprovals,pendingApprovalsLoading: vm.pendingApprovalsLoading,@@ -2242,13 +2246,13 @@ export function App() {vm.markNotificationsRead,vm.notificationActionById,vm.notifications,+ vm.isHostAccessBlocked,vm.pendingApprovalActionId,vm.pendingApprovals,vm.pendingApprovalsLoading,vm.removeNotification,vm.resolveApprovalNotification,vm.toasts,- vm.unreadNotificationCount,])diff --git a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsxindex 0d57e86af..618910fe3 100644--- a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx+++ b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx@@ -93,6 +93,8 @@ const appHeaderHarness = vi.hoisted(() => ({// Captured from context so tests can drive the "open conversation" gesture the// notification tray fires.openNotification: null as null | ((notification: AppNotification) => Promise<void>),+ notifications: [] as AppNotification[],+ unreadNotificationCount: 0,}))vi.mock('@hooks/useAppController', () => ({ useAppController: vi.fn() }))@@ -100,7 +102,10 @@ vi.mock('@hooks/useAgentChatActionsValue', () => ({ useAgentChatActionsValue: ()vi.mock('@components/AppHeader', () => ({AppHeader: (props: NonNullable<typeof appHeaderHarness.props>) => {appHeaderHarness.props = props- appHeaderHarness.openNotification = useNotificationsContext().handleOpenNotification+ const notificationsContext = useNotificationsContext()+ appHeaderHarness.openNotification = notificationsContext.handleOpenNotification+ appHeaderHarness.notifications = notificationsContext.notifications+ appHeaderHarness.unreadNotificationCount = notificationsContext.unreadNotificationCountreturn null},}))@@ -406,6 +411,8 @@ describe('App chat drawer — reopen preserves the last-viewed chat', () => {sandboxUiPageHarness.props = nullappHeaderHarness.props = nullappHeaderHarness.openNotification = null+ appHeaderHarness.notifications = []+ appHeaderHarness.unreadNotificationCount = 0currentController = makeController()vi.mocked(useAppController).mockImplementation(() => useReactiveController(currentController))Object.defineProperty(window, 'clerum', {@@ -478,6 +485,26 @@ describe('App chat drawer — reopen preserves the last-viewed chat', () => {expect(screen.getByRole('button', { name: 'Open chats' }).textContent).toContain('Second chat')})+ it('hides already-delivered notifications for a revoked Host', () => {+ const notification = {+ id: 'approval-1',+ kind: 'approval_required',+ agentName: 'alpha',+ text: 'Approval required',+ timestamp: 1,+ read: false,+ } as AppNotification+ currentController = makeController({+ notifications: [notification],+ isHostAccessBlocked: vi.fn(() => true),+ } as Partial<AppController>)++ render(<App />)++ expect(appHeaderHarness.notifications).toEqual([])+ expect(appHeaderHarness.unreadNotificationCount).toBe(0)+ })+// The header's "Open chat in full screen" CTA must EJECT the drawer's ACTIVE// conversation — the one the user switched to inside the drawer, not the launch// origin — to the full-screen chat route. That is the non-drawer branch ofdiff --git a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsxindex 3958fa963..3eb511eb4 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx@@ -218,7 +218,8 @@ describe('sendAgentMessage — auto-title on send (B10)', () => {expect(clerum.chat.rename).toHaveBeenCalledWith('agent-x',createdChatId,- 'summarize the quarterly report'+ 'summarize the quarterly report',+ 1))})diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex dcbea1bb8..df239312d 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -261,6 +261,11 @@ export function useChatListController({>(new Map())const pendingRenameKey = (agentRef: string, chatId: string): string => `${agentRef}:${chatId}`+ const authUserKeyRef = useRef(authUserKey)++ useEffect(() => {+ authUserKeyRef.current = authUserKey+ }, [authUserKey])const pendingRenameStateFor = useCallback((agentRef: string, chatId: string): PendingRename => {return pendingRenamesRef.current.get(pendingRenameKey(agentRef, chatId))?.state ?? 'none'@@ -918,7 +923,7 @@ export function useChatListController({const bindingGeneration = await chatStore.getBindingGeneration()if (!stillOwned()) returnconst updatedAt = new Date().toISOString()- await chatStore.renameChat(agentRef, chatId, newTitle)+ await chatStore.renameChat(agentRef, chatId, newTitle, bindingGeneration)if (requestGenerationRef.current !== requestGeneration) returnsetLatestChatSessions(prev =>prev@@ -1118,6 +1123,7 @@ export function useChatListController({const handleRenameChatForAgent = useCallback(async (agentRef: string, chatId: string, newTitle: string) => {if (!agentRef) return+ const authUserKeyAtRequest = authUserKeyRef.currentconst key = pendingRenameKey(agentRef, chatId)// FIX 2: the rollback target is the title BEFORE the pending chain began.// If a rename is already pending for this key, preserve its `previousTitle`@@ -1129,9 +1135,11 @@ export function useChatListController({previousTitle = existing.previousTitle} else {const index = await chatStore.getIndex(agentRef)+ if (authUserKeyRef.current !== authUserKeyAtRequest) returnpreviousTitle = index.chats.find(c => c.id === chatId)?.title ?? ''}await applyLocalTitleOnly(agentRef, chatId, newTitle)+ if (authUserKeyRef.current !== authUserKeyAtRequest) return// Replace any prior entry: this is now the current rename for the key. A// still-in-flight older attempt will no-op on completion (identity guard).const entry = {@@ -1147,7 +1155,7 @@ export function useChatListController({pendingRenamesRef.current.set(key, entry)await attemptRenameRpc(entry)},- [chatStore, applyLocalTitleOnly, attemptRenameRpc]+ [authUserKey, chatStore, applyLocalTitleOnly, attemptRenameRpc])const handleRenameChat = useCallback(diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.tsindex 765f70de2..bcfd120f2 100644--- a/desktop-app/ui/src/hooks/useChatStore.ts+++ b/desktop-app/ui/src/hooks/useChatStore.ts@@ -66,8 +66,8 @@ export function useChatStore() {[])const renameChat = useCallback(- (agentRef: string, chatId: string, title: string) =>- window.clerum.chat.rename(agentRef, chatId, title),+ (agentRef: string, chatId: string, title: string, bindingGeneration: number) =>+ window.clerum.chat.rename(agentRef, chatId, title, bindingGeneration),[])const getBindingGeneration = useCallback(() => window.clerum.chat.getBindingGeneration(), [])diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex ab259ecf7..28f6525e2 100644--- a/host-context-controller/package-lock.json+++ b/host-context-controller/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-host-context-controller",- "version": "0.1.355",+ "version": "0.1.356","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.355",+ "version": "0.1.356","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex 3ecf6f0af..0a57cd12e 100644--- a/host-context-controller/package.json+++ b/host-context-controller/package.json@@ -1,6 +1,6 @@{"name": "clerum-host-context-controller",- "version": "0.1.355",+ "version": "0.1.356","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/statelessLifecycleTracker.ts b/host-context-controller/src/statelessLifecycleTracker.tsindex ae7d93a99..c25520012 100644--- a/host-context-controller/src/statelessLifecycleTracker.ts+++ b/host-context-controller/src/statelessLifecycleTracker.ts@@ -440,7 +440,7 @@ export class StatelessLifecycleTracker implements HeartbeatLifecycleTracker {}if (effective.suspensionBlocked) {this.clearDrainGrace(hostRef)- await this.cancelDrainOnEvidence(hostRef, host)+ await this.cancelDrainOnEvidence(hostRef, host, true)return { drain: false }}this.noteWakeHandledGeneration(hostRef, host)@@ -615,9 +615,18 @@ export class StatelessLifecycleTracker implements HeartbeatLifecycleTracker {* a suspended Host is exclusively the wake fast-path's job). Loud, not* fatal on failure — the emitter keeps beating while fenced, so the* revert retries on the next polled heartbeat.+ *+ * When CommunicationChannel authority is unknown, the cached Host may still+ * say `active` while the durable CR already says `draining`. The caller then+ * bypasses the cache precheck so this fresh-read writer can safely revert the+ * durable `draining` state (and no-op for active/suspended).*/- private async cancelDrainOnEvidence(hostRef: string, host: HostCRD): Promise<void> {- if ((host.status?.lifecycle?.state ?? 'active') !== 'draining') {+ private async cancelDrainOnEvidence(+ hostRef: string,+ host: HostCRD,+ bypassCachedState = false+ ): Promise<void> {+ if (!bypassCachedState && (host.status?.lifecycle?.state ?? 'active') !== 'draining') {return}try {diff --git a/host-context-controller/test/statelessLifecycleTracker.test.ts b/host-context-controller/test/statelessLifecycleTracker.test.tsindex 3d057643b..b540c2bc0 100644--- a/host-context-controller/test/statelessLifecycleTracker.test.ts+++ b/host-context-controller/test/statelessLifecycleTracker.test.ts@@ -190,6 +190,26 @@ describe('StatelessLifecycleTracker — D8 idle rule', () => {expect(port.suspendHostFromHeartbeat).not.toHaveBeenCalled()})+ it('reverts a durable draining Host through a fresh read when a cached Host is stale', async () => {+ const port = makePort()+ const cachedHost = makeHost({ lifecycle: { state: 'active', wakeHandledGeneration: 3 } })+ port.getEffectiveLifecycle.mockReturnValue({+ stateless: true,+ state: 'active',+ suspensionBlocked: true,+ })+ port.readFreshHost.mockResolvedValue(+ makeHost({ lifecycle: { state: 'draining', wakeHandledGeneration: 3 } })+ )+ const tracker = makeTracker({ port, host: cachedHost })++ await expect(tracker.handleHeartbeat(payload({ state: 'draining' }))).resolves.toEqual({+ drain: false,+ })+ expect(port.markHostActiveFromHeartbeat).toHaveBeenCalledWith(cachedHost)+ expect(port.suspendHostFromHeartbeat).not.toHaveBeenCalled()+ })+it('answers drain:false for an unknown host', async () => {const port = makePort()const tracker = new StatelessLifecycleTracker({