Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-ui): r9-m2 report each switch failure once
Josué53742e1c4c5f
diff --git a/desktop-app/ui/src/hooks/__tests__/selectionError.r9.characterization.test.tsx b/desktop-app/ui/src/hooks/__tests__/selectionError.r9.characterization.test.tsxnew file mode 100644index 000000000..0894a6921--- /dev/null+++ b/desktop-app/ui/src/hooks/__tests__/selectionError.r9.characterization.test.tsx@@ -0,0 +1,144 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, waitFor } from '@testing-library/react'+import { DESKTOP_ROUTES } from '@constants/navigation'+import {+ installAppControllerClerum,+ renderAppController,+} from '../domain/__tests__/__fixtures__/appControllerHarness'+import { deferred } from '../domain/__tests__/__fixtures__/catalogFixtures'+import { renderController } from '../domain/__tests__/__fixtures__/controllerHarness'+import { installMockClerum, uninstallMockClerum } from '../domain/__tests__/__fixtures__/mockClerum'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++describe('Round 9 selection error ownership', () => {+ let unmount: (() => void) | null = null++ beforeEach(() => {+ vi.clearAllMocks()+ })++ afterEach(() => {+ unmount?.()+ unmount = null+ vi.restoreAllMocks()+ uninstallMockClerum()+ })++ it('reports one failed launch-from-chat switch when the route effect coalesces it', async () => {+ const { clerum } = installAppControllerClerum({ agentNames: ['agent-x'] })+ await clerum.chat.create('agent-x', 'chat-1')+ await clerum.chat.create('agent-x', 'chat-2')+ 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-x', { chatId: 'chat-1', selectLatest: false })+ })+ await waitFor(() => expect(app.result.current.activeChatId).toBe('chat-1'))+ await waitFor(() => expect(app.result.current.chatMessagesLoading).toBe(false))++ clerum.chat.setLastActive.mockRejectedValue(new Error('chat store write failed'))+ act(() => {+ app.result.current.handleNavSelect(DESKTOP_ROUTES.apps)+ app.result.current.handleSelectChatAgent('agent-x', {+ chatId: 'chat-2',+ selectLatest: false,+ keepNavItem: true,+ })+ })++ await waitFor(() => expect(app.result.current.chatMessagesLoading).toBe(false))+ await waitFor(() =>+ expect(+ app.result.current.toasts.filter(toast =>+ toast.text.includes('Could not open conversation')+ )+ ).toHaveLength(1)+ )+ expect(app.result.current.navItem).toBe(DESKTOP_ROUTES.apps)+ expect(app.result.current.activeChatId).toBe('chat-2')+ expect(app.result.current.statusText).toContain('Could not open conversation')+ })++ it('does not report a rejected switch after a newer conversation owns the view', async () => {+ const { clerum } = installAppControllerClerum({ agentNames: ['agent-x'] })+ await clerum.chat.create('agent-x', 'chat-1')+ await clerum.chat.create('agent-x', 'chat-2')+ await clerum.chat.create('agent-x', 'chat-3')+ const originalSetLastActive = clerum.chat.setLastActive.getMockImplementation()+ if (!originalSetLastActive) throw new Error('Expected the setLastActive test mock')+ const entered = deferred<void>()+ const release = deferred<void>()+ let held = false+ clerum.chat.setLastActive.mockImplementation(async (agentRef, chatId) => {+ if (agentRef === 'agent-x' && chatId === 'chat-2' && !held) {+ held = true+ entered.resolve()+ await release.promise+ throw new Error('stale chat store write failed')+ }+ return originalSetLastActive(agentRef, chatId)+ })+ 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-x', { chatId: 'chat-1', selectLatest: false })+ })+ await waitFor(() => expect(app.result.current.activeChatId).toBe('chat-1'))+ await waitFor(() => expect(app.result.current.chatMessagesLoading).toBe(false))++ act(() => {+ app.result.current.handleSelectChatAgent('agent-x', { chatId: 'chat-2', selectLatest: false })+ })+ await entered.promise+ act(() => {+ app.result.current.handleSelectChatAgent('agent-x', { chatId: 'chat-3', selectLatest: false })+ })+ await waitFor(() => expect(app.result.current.activeChatId).toBe('chat-3'))+ await waitFor(() => expect(app.result.current.chatMessagesLoading).toBe(false))++ await act(async () => {+ release.resolve()+ })+ await waitFor(() =>+ expect(+ app.result.current.toasts.filter(toast =>+ toast.text.includes('stale chat store write failed')+ )+ ).toHaveLength(0)+ )+ expect(app.result.current.activeChatId).toBe('chat-3')+ expect(app.result.current.statusText).not.toContain('stale chat store write failed')+ })++ it('settles and reports a failed pending selection from the selection effect', async () => {+ const clerum = installMockClerum()+ await clerum.chat.create('agent-x', 'requested-chat')+ const controller = renderController({ navItem: 'agents', loadMenuData: false })+ unmount = controller.unmount++ await waitFor(() => expect(controller.result.current.chatListLoading).toBe(false))+ clerum.chat.setLastActive.mockRejectedValue(new Error('chat store write failed'))++ await act(async () => {+ controller.result.current.setPendingChatSelection('agent-x', 'requested-chat')+ controller.rerender({ navItem: 'chat' })+ })++ await waitFor(() => {+ expect(controller.result.current.activeChatId).toBe('requested-chat')+ expect(controller.result.current.chatMessagesLoading).toBe(false)+ expect(controller.spies.pushToast).toHaveBeenCalledWith(+ 'Could not open conversation: chat store write failed',+ 'error'+ )+ })+ })+})diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex 8cf9b2c43..d8eb2a09c 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -448,6 +448,15 @@ export function useAgentChatController({const [activeChatId, setActiveChatId] = useState<string | null>(null)const selectionIntentRevisionRef = useRef(0)+ // A caller that starts an imperative switch while the selection effect is+ // replaying the same pending request owns that request's failure feedback.+ // The controller dispatches it only while that revision is current; the+ // effect consumes the same owner instead of presenting a duplicate toast.+ const selectionErrorOwnerRef = useRef<{+ revision: number+ onCurrentError: (error: unknown) => void+ reported: boolean+ } | null>(null)const activeChatSwitchRequestRef = useRef<symbol | null>(null)const activeChatSwitchKeyRef = useRef<string | null>(null)// Fase 2b (§4.1): the SessionFSM is now the SINGLE writer of the per-chat@@ -534,6 +543,7 @@ export function useAgentChatController({const beginSelectionIntent = useCallback((startsHistoryLoad = false) => {selectionIntentRevisionRef.current += 1+ selectionErrorOwnerRef.current = nullif (!startsHistoryLoad) {setChatMessagesLoading(false)activeChatSwitchRequestRef.current = null@@ -551,6 +561,24 @@ export function useAgentChatController({},[setChatMessagesLoading])+ const reportCallerOwnedSelectionError = useCallback(+ (selectionIntentRevision: number, error: unknown) => {+ const owner = selectionErrorOwnerRef.current+ if (+ !owner ||+ owner.revision !== selectionIntentRevision ||+ selectionIntentRevisionRef.current !== selectionIntentRevision+ ) {+ return false+ }+ if (!owner.reported) {+ owner.reported = true+ owner.onCurrentError(error)+ }+ return true+ },+ []+ )const [hasOlderMessages, setHasOlderMessages] = useState(false)const [olderMessagesLoading, setOlderMessagesLoading] = useState(false)const chatMessagesRef = useRef<AgentChatMessage[]>([])@@ -1174,17 +1202,32 @@ export function useAgentChatController({)const switchToChat = useCallback(- async (agentRef: string, chatId: string) => {+ async (+ agentRef: string,+ chatId: string,+ options: { onCurrentError?: (error: unknown) => void } = {}+ ) => {// A rejected target does not take ownership of the visible view. Check// these guards before advancing the history-selection revision so a// blocked or deleted chat cannot cancel another chat's pending load.if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) returnconst selectionIntentRevision = beginSelectionIntent(true)+ if (options.onCurrentError) {+ selectionErrorOwnerRef.current = {+ revision: selectionIntentRevision,+ onCurrentError: options.onCurrentError,+ reported: false,+ }+ }clearPendingSelection(agentRef, chatId)try {await switchToChatForIntent(agentRef, chatId, selectionIntentRevision)+ if (selectionErrorOwnerRef.current?.revision === selectionIntentRevision) {+ selectionErrorOwnerRef.current = null+ }} catch (error) {settleChatMessagesLoading(selectionIntentRevision)+ reportCallerOwnedSelectionError(selectionIntentRevision, error)throw error}},@@ -1193,6 +1236,7 @@ export function useAgentChatController({clearPendingSelection,isChatDeleted,isHostAccessBlocked,+ reportCallerOwnedSelectionError,settleChatMessagesLoading,switchToChatForIntent,]@@ -1521,7 +1565,8 @@ export function useAgentChatController({})().catch(error => {if (cancelled || selectionIntentRevisionRef.current !== selectionIntentRevision) returnsettleChatMessagesLoading(selectionIntentRevision)- pushToast(+ if (reportCallerOwnedSelectionError(selectionIntentRevision, error)) return+ liveDepsRef.current.pushToast(`Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,'error')@@ -1537,7 +1582,7 @@ export function useAgentChatController({navItem,selectedAgent,isHostAccessBlocked,- pushToast,+ reportCallerOwnedSelectionError,settleChatMessagesLoading,switchToChatForIntent,])@@ -3928,12 +3973,14 @@ export function useAgentChatController({if (options.title) {upsertProvisionalEntry(chatId!, options.title, options.isRemote === true)}- void switchToChat(agentName, chatId!).catch(error => {- pushToast(- `Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,- 'error'- )- })+ void switchToChat(agentName, chatId!, {+ onCurrentError: error => {+ pushToast(+ `Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,+ 'error'+ )+ },+ }).catch(() => undefined)return}// A same-agent no-chat notification can record a pending none selectiondiff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex 62388ee01..a5814a6e3 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -125,7 +125,11 @@ export function isCreateFailureRecoveryOwned(owner: CreateFailureRecoveryOwner):* callbacks always reach the latest closures without recreating themselves.*/export interface ChatListControllerHost {- switchToChat: (agentRef: string, chatId: string) => Promise<void>+ switchToChat: (+ agentRef: string,+ chatId: string,+ options?: { onCurrentError?: (error: unknown) => void }+ ) => Promise<void>beginSelectionIntent: () => numbergetSelectionIntentRevision: () => numberclearPendingSelection: (agentRef: string, preserveSpecificChatId?: string) => void@@ -671,15 +675,16 @@ export function useChatListController({!suppressAutoSelection) {currentHost.markAutoSelectedChat(latestServerSession.chatId)- const switchRequest = currentHost.switchToChat(agentRef, latestServerSession.chatId)- const switchSelectionRevision = currentHost.getSelectionIntentRevision()- void switchRequest.catch(error => {- if (currentHost.getSelectionIntentRevision() !== switchSelectionRevision) return- currentHost.pushToast(- `Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,- 'error'- )- })+ void currentHost+ .switchToChat(agentRef, latestServerSession.chatId, {+ onCurrentError: error => {+ currentHost.pushToast(+ `Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,+ 'error'+ )+ },+ })+ .catch(() => undefined)}// Persist server freshness into the local index (spec §5.3): keeps thediff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.tsindex 33dde9b19..314d84649 100644--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@ -1030,12 +1030,16 @@ export function useAppController() {) {// D.4: switchToChat is now a single unified path (no isRemote) — the// server is the source of truth and hydrates server-only chats itself.- void chat.switchToChat(agentName, targetChatId).catch(error => {- fullSetStatus(- `Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,- 'error'- )- })+ void chat+ .switchToChat(agentName, targetChatId, {+ onCurrentError: error => {+ fullSetStatus(+ `Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,+ 'error'+ )+ },+ })+ .catch(() => undefined)nav.setSelectedAgentRoute(AGENT_WORKSPACE_ROUTES.connectors)// Activate the chat tab (dedupes/focuses by chatId). We are already on// the chat route, so `navItem` stays `chat` — same-commit derivation, no@@ -1078,12 +1082,16 @@ export function useAppController() {// effect replays into its `specific` branch instead of the reset branch;// both switches target the same chat and `switchToChat` coalesces them.if (options.keepNavItem && targetChatId && nav.selectedAgent === agentName) {- void chat.switchToChat(agentName, targetChatId).catch(error => {- fullSetStatus(- `Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,- 'error'- )- })+ void chat+ .switchToChat(agentName, targetChatId, {+ onCurrentError: error => {+ fullSetStatus(+ `Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,+ 'error'+ )+ },+ })+ .catch(() => undefined)}},[