Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): classify catalog failures across IPC
Alfredo Lopez9354cf8d8de4
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsxindex 45861dd09..86f93a2a5 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx@@ -14,6 +14,7 @@ import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'import { act, waitFor } from '@testing-library/react'import { parseSessionsListResult } from '../../../../../src/rpcProxyClient'import type { ChatIndex, SessionsListResult } from '../../../../../src/types'+import { httpErrorStatus } from '../../../lib/format'import { renderController } from './__fixtures__/controllerHarness'import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'@@ -32,6 +33,18 @@ afterEach(() => {const NOW = '2026-09-12T00:00:00.000Z'+describe('HTTP status parsing through Electron IPC', () => {+ it.each([+ ['Error invoking remote method: Error: 403 Forbidden: host_access_revoked', 403],+ ['Error invoking remote method: Error: 401 Unauthorized', 401],+ ['Error invoking remote method: Error: 503 Service Unavailable: upstream mentioned 403', 503],+ ["Error invoking remote method 'rpc:invoke': Error: 403 Forbidden", 403],+ ['request to support-401 failed', undefined],+ ])('parses %s as %s', (message, expected) => {+ expect(httpErrorStatus(message)).toBe(expected)+ })+})+/** Parse a raw wire payload through the real producer parser (T1). */function serverSessions(items: Array<{ agent: string; chatId: string; title?: string }>@@ -309,7 +322,7 @@ describe('revoked host catalog protection', () => {const blocked = new Set<string>()clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'cached-a', title: 'Cached chat' }]))clerum.rpc.listSessions.mockRejectedValue(new Error('503 Service Unavailable'))- const { result } = renderController({+ const controller = renderController({selectedAgent: 'agent-a',agentNames: ['agent-a'],onHostAccessRevoked: agentRef => blocked.add(agentRef),@@ -318,9 +331,57 @@ describe('revoked host catalog protection', () => {})await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalled())await waitFor(() =>- expect(result.current.chatList.some(chat => chat.id === 'cached-a')).toBe(true)+ expect(controller.result.current.chatList.some(chat => chat.id === 'cached-a')).toBe(true))expect(blocked.has('agent-a')).toBe(false)+ await waitFor(() => expect(controller.spies.pushToast).toHaveBeenCalledTimes(1))+ expect(controller.spies.pushToast).toHaveBeenCalledWith(+ 'Chat list for agent-a is offline. Showing saved chats.',+ 'info'+ )+ })++ it('does not show the offline toast for a client-side catalog error', async () => {+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'cached-a', title: 'Cached chat' }]))+ clerum.rpc.listSessions.mockRejectedValue(new Error('400 Bad Request: invalid cursor'))+ const controller = renderController({+ selectedAgent: 'agent-a',+ agentNames: ['agent-a'],+ })++ await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalled())+ await act(async () => {+ await Promise.resolve()+ })+ expect(controller.spies.pushToast).not.toHaveBeenCalledWith(+ expect.stringContaining('Chat list'),+ 'info'+ )+ })++ it('clears a rejected load-more cursor after a client-side cursor error', async () => {+ clerum.rpc.listSessions.mockImplementation(+ async (_agentRef: string, _teamId: string | undefined, query?: { cursor?: string }) => {+ if (query?.cursor) throw new Error('400 Bad Request: invalid cursor')+ return {+ ...serverSessions([{ agent: 'agent-x', chatId: 'remote-page-1' }]),+ nextCursor: 'cursor-invalid',+ }+ }+ )+ const controller = renderController()++ await waitFor(() => expect(controller.result.current.chatListHasMoreRemoteSessions).toBe(true))+ await act(async () => {+ await controller.result.current.loadMoreChatSessions()+ })++ expect(controller.result.current.chatListHasMoreRemoteSessions).toBe(false)+ expect(+ clerum.rpc.listSessions.mock.calls.filter(+ call => (call[2] as { cursor?: string } | undefined)?.cursor === 'cursor-invalid'+ )+ ).toHaveLength(1)})})diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex b98c215c4..81e270121 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -9,7 +9,13 @@ import type {ChatMetadata,SessionsListResult,} from '../../../../src/types'-import { isAuthorizationError, isConfirmedHostAccessRevoked } from '../../lib/format'+import {+ httpErrorStatus,+ isAuthorizationError,+ isConfirmedHostAccessRevoked,+ isHttpServerError,+ isNetworkError,+} from '../../lib/format'import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'import type { useChatStore } from '../useChatStore'import { type SessionFsmEvent, type SessionFsmStore, seedSessionSnapshots } from './sessionFsm'@@ -147,6 +153,12 @@ function isRecoverableCatalogCursorError(error: unknown): boolean {return /\b4\d\d\b/.test(message) || message.toLowerCase().includes('invalid')}+function isCatalogOutageError(error: unknown): boolean {+ const status = httpErrorStatus(error)+ if (status !== undefined) return isHttpServerError(error)+ return isNetworkError(error)+}+/*** Classify a failed rename RPC for the pending-rename queue (spec 15 §2.5). The* HTTP status rides the error message as `(NNN)` (see rpcProxyClient.renameSession@@ -226,6 +238,9 @@ export function useChatListController({const [latestChatSessions, setLatestChatSessions] = useState<LatestSidebarChatEntry[]>([])const [latestChatSessionsLoading, setLatestChatSessionsLoading] = useState(false)const catalogOfflineByAgentRef = useRef(new Set<string>())+ const catalogOfflineToastShownRef = useRef(false)+ const catalogOfflineToastQueuedRef = useRef(false)+ const catalogOfflineToastTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)const [latestCatalogMutationRevision, setLatestCatalogMutationRevision] = useState(0)// Selection requested for an agent before its chats have loaded, consumed by// the parent's agent-selection effect. Ref (not state): imperative, per-agent.@@ -300,6 +315,12 @@ export function useChatListController({authorityScopeGenerationRef.current += 1deletedChatIdsByAgentRef.current.clear()catalogOfflineByAgentRef.current.clear()+ catalogOfflineToastShownRef.current = false+ if (catalogOfflineToastTimerRef.current !== null) {+ clearTimeout(catalogOfflineToastTimerRef.current)+ catalogOfflineToastTimerRef.current = null+ }+ catalogOfflineToastQueuedRef.current = false}, [isAuthenticated, scopeKey])// R1-H1 — the pending-rename queue is per-USER identity. mcp-host keys a chat@@ -319,6 +340,33 @@ export function useChatListController({pendingRenamesRef.current.clear()}, [authUserKey])+ const reportCatalogOffline = (agentRef: string) => {+ if (!catalogOfflineByAgentRef.current.has(agentRef)) {+ catalogOfflineByAgentRef.current.add(agentRef)+ }+ if (catalogOfflineToastShownRef.current || catalogOfflineToastQueuedRef.current) return+ catalogOfflineToastQueuedRef.current = true+ catalogOfflineToastTimerRef.current = setTimeout(() => {+ catalogOfflineToastTimerRef.current = null+ catalogOfflineToastQueuedRef.current = false+ const affectedAgents = [...catalogOfflineByAgentRef.current]+ if (!affectedAgents.length || catalogOfflineToastShownRef.current) return+ catalogOfflineToastShownRef.current = true+ const scope =+ affectedAgents.length === 1+ ? `for ${affectedAgents[0]}`+ : `for ${affectedAgents.join(', ')}`+ host.current?.pushToast(`Chat list ${scope} is offline. Showing saved chats.`, 'info')+ }, 0)+ }++ const reportCatalogOnline = (agentRef: string) => {+ catalogOfflineByAgentRef.current.delete(agentRef)+ if (catalogOfflineByAgentRef.current.size === 0) {+ catalogOfflineToastShownRef.current = false+ }+ }+// Live `selectedAgent` for the stable callbacks below (they gate a chatList// write on "is this the selected agent"). A ref keeps the callbacks stable// while always reading the committed value at call time.@@ -433,15 +481,13 @@ export function useChatListController({if (!isConfirmedHostAccessRevoked(error) &&!isAuthorizationError(error) &&- !catalogOfflineByAgentRef.current.has(agentRef)- ) {- catalogOfflineByAgentRef.current.add(agentRef)- host.current?.pushToast('Chat list is offline. Showing saved chats.', 'info')- }+ isCatalogOutageError(error)+ )+ reportCatalogOffline(agentRef)}return}- catalogOfflineByAgentRef.current.delete(agentRef)+ reportCatalogOnline(agentRef)if (selectedAgentRef.current !== agentRef ||requestGenerationRef.current !== requestGeneration ||@@ -623,13 +669,15 @@ export function useChatListController({) {if (isConfirmedHostAccessRevoked(error)) onHostAccessRevoked(agentRef)else if (isAuthorizationError(error)) onHostAuthorityUncertain(agentRef)- if (+ else if (isRecoverableCatalogCursorError(error)) {+ chatListNextCursorByAgentRef.current[agentRef] = null+ setChatListHasMoreRemoteSessions(false)+ } else if (!isConfirmedHostAccessRevoked(error) &&!isAuthorizationError(error) &&- !catalogOfflineByAgentRef.current.has(agentRef)+ isCatalogOutageError(error)) {- catalogOfflineByAgentRef.current.add(agentRef)- host.current?.pushToast('Chat list is offline. Showing saved chats.', 'info')+ reportCatalogOffline(agentRef)}return}@@ -648,7 +696,7 @@ export function useChatListController({}return}- catalogOfflineByAgentRef.current.delete(agentRef)+ reportCatalogOnline(agentRef)if (requestGenerationRef.current !== requestGeneration ||getHostAuthorityEpoch(agentRef) !== hostAuthorityEpoch ||@@ -1479,15 +1527,14 @@ export function useChatListController({if (!isConfirmedHostAccessRevoked(error) &&!isAuthorizationError(error) &&- !catalogOfflineByAgentRef.current.has(agentRef)+ isCatalogOutageError(error)) {- catalogOfflineByAgentRef.current.add(agentRef)- host.current?.pushToast('Chat list is offline. Showing saved chats.', 'info')+ reportCatalogOffline(agentRef)}}return { agentRef, sessions: [] as SessionsListResult['items'] }}- catalogOfflineByAgentRef.current.delete(agentRef)+ reportCatalogOnline(agentRef)if (currentAuthorityScopeRef.current !== authorityScopeAtRequest ||getHostAuthorityEpoch(agentRef) !== hostAuthorityEpochByAgent.get(agentRef) ||diff --git a/desktop-app/ui/src/lib/format.ts b/desktop-app/ui/src/lib/format.tsindex b5ca2c31b..8d30ae2fe 100644--- a/desktop-app/ui/src/lib/format.ts+++ b/desktop-app/ui/src/lib/format.ts@@ -1,5 +1,6 @@import type { HostMessageResponse, SessionTokensLite } from '../../../src/types'import type { AppErrorKind } from '../uiTypes'+import { stripIpcWrapper } from './gfsGrantErrors'export function toPrettyJson(value: unknown): string {return JSON.stringify(value, null, 2)@@ -159,7 +160,7 @@ function errorText(err: unknown): string {}/** IPC preserves error messages but not always custom status fields. */-function httpErrorStatus(err: unknown): number | undefined {+export function httpErrorStatus(err: unknown): number | undefined {if (err && typeof err === 'object') {const status = (err as { status?: unknown; cause?: { status?: unknown } }).statusif (typeof status === 'number') return status@@ -170,12 +171,18 @@ function httpErrorStatus(err: unknown): number | undefined {// mistaken for the response status.const match =/^(?:http\s+)?(?<leading>[1-5]\d{2})\b|\b(?:http(?:\s+status)?|status(?:\s+code)?)\s*[:=]?\s*(?<labeled>[1-5]\d{2})\b|\((?<parenthesized>[1-5]\d{2})\)/i.exec(- errorText(err)+ stripIpcWrapper(errorText(err)))const status = match?.groups?.leading ?? match?.groups?.labeled ?? match?.groups?.parenthesizedreturn status ? Number(status) : undefined}+/** True when the parsed response status is in the server-error range. */+export function isHttpServerError(err: unknown): boolean {+ const status = httpErrorStatus(err)+ return status !== undefined && status >= 500 && status < 600+}+/** A transcript 404 is ambiguous: absence, authority and wake failure share it. */export function isHttp404(err: unknown): boolean {return httpErrorStatus(err) === 404diff --git a/desktop-app/ui/src/lib/gfsGrantErrors.ts b/desktop-app/ui/src/lib/gfsGrantErrors.tsindex 9b5d88bad..5f7ea6032 100644--- a/desktop-app/ui/src/lib/gfsGrantErrors.ts+++ b/desktop-app/ui/src/lib/gfsGrantErrors.ts@@ -37,7 +37,7 @@ const GFS_GRANT_ERROR_MESSAGES: Record<string, string> = {* verdict that follows it is the part a user can act on. This strips exactly* the wrapper and leaves the verdict intact.*/-const IPC_WRAPPER_PREFIX = /^Error invoking remote method '[^']*':\s*(?:[A-Za-z]*Error:\s*)?/+const IPC_WRAPPER_PREFIX = /^Error invoking remote method(?: '[^']*')?:\s*(?:[A-Za-z]*Error:\s*)?/iexport function stripIpcWrapper(message: string): string {return message.replace(IPC_WRAPPER_PREFIX, '')