Skip to content

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

TypeScript

fix(desktop-ui): r6-l1 retire settled switch error owners

Josué72977b02eb18
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/logicalSwitchErrors.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/logicalSwitchErrors.characterization.test.tsx
new file mode 100644
index 000000000..66c63e529
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/__tests__/logicalSwitchErrors.characterization.test.tsx
@@ -0,0 +1,63 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, waitFor } from '@testing-library/react'
+import { DESKTOP_ROUTES } from '@constants/navigation'
+import {
+ installAppControllerClerum,
+ renderAppController,
+} from './__fixtures__/appControllerHarness'
+import { deferred } from './__fixtures__/catalogFixtures'
+import { renderController } from './__fixtures__/controllerHarness'
+import { installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'
+
+beforeEach(() => vi.clearAllMocks())
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ uninstallMockClerum()
+})
+
+describe('logical switch error ownership', () => {
+ it.each([
+ ['failure', 'failure', 2],
+ ['success', 'failure', 1],
+ ['failure', 'success', 1],
+ ] as const)(
+ 'reports independent imperative %s followed by effect %s',
+ async (first, second, reports) => {
+ const clerum = installMockClerum()
+ await clerum.chat.create('agent-x', 'chat-old')
+ await clerum.chat.create('agent-x', 'chat-newest')
+ await clerum.chat.upsertMessages('agent-x', 'chat-newest', [
+ { id: 'newest-history', role: 'user', content: 'newest actual history', timestamp: 10 },
+ ])
+ clerum.chat.getIndex.mockImplementation(agent => clerum.readIndex(agent))
+ const controller = renderController({ navItem: DESKTOP_ROUTES.chat, loadMenuData: false })
+ await waitFor(() => expect(controller.result.current.chatListLoading).toBe(false))
+ await waitFor(() => expect(controller.result.current.chatMessagesLoading).toBe(false))
+ const setLastActive = clerum.chat.setLastActive.getMockImplementation()!
+ clerum.chat.setLastActive.mockImplementation((agent, chat) =>
+ (chat === 'chat-old' ? first : second) === 'failure'
+ ? Promise.reject(new Error(`${chat} failed`))
+ : setLastActive(agent, chat)
+ )
+ act(() => controller.result.current.setPendingChatSelection('agent-x', 'chat-old'))
+ await waitFor(() => {
+ expect(controller.result.current.activeChatId).toBe('chat-old')
+ expect(controller.result.current.chatMessagesLoading).toBe(false)
+ expect(controller.spies.pushToast).toHaveBeenCalledTimes(first === 'failure' ? 1 : 0)
+ })
+ act(() => controller.rerender({ navItem: DESKTOP_ROUTES.agents }))
+ await waitFor(() => expect(controller.result.current.chatListLoading).toBe(false))
+ act(() => controller.rerender({ navItem: DESKTOP_ROUTES.chat }))
+ await waitFor(() => {
+ expect(controller.result.current.activeChatId).toBe('chat-newest')
+ expect(controller.result.current.chatMessagesLoading).toBe(false)
+ expect(controller.spies.pushToast).toHaveBeenCalledTimes(reports)
+ expect(controller.result.current.chatMessages).toEqual(
+ second === 'success' ? [expect.objectContaining({ id: 'newest-history' })] : []
+ )
+ })
+ }
+ )
+})
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index d8eb2a09c..59c268ace 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -16,6 +16,8 @@ import {
buildChatMessageAttachments,
buildResponseFileAttachments,
} from '@lib/chatMessageAttachments'
+import { runChatSwitchRequest } from '@lib/chatSwitchRequest'
+import type { PendingChatSwitchRequest } from '@lib/chatSwitchRequest.types'
import { truncateTitle } from '@lib/chatTitle'
import {
clearAllComposerDrafts,
@@ -448,15 +450,9 @@ 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)
+ // A matching pending effect awaits this exact execution, even if it settled
+ // before the catalog read. The promise retains the outcome, never an error owner.
+ const pendingChatSwitchRequestRef = useRef<PendingChatSwitchRequest | 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
@@ -543,7 +539,6 @@ export function useAgentChatController({
const beginSelectionIntent = useCallback(
(startsHistoryLoad = false) => {
selectionIntentRevisionRef.current += 1
- selectionErrorOwnerRef.current = null
if (!startsHistoryLoad) {
setChatMessagesLoading(false)
activeChatSwitchRequestRef.current = null
@@ -561,24 +556,6 @@ 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[]>([])
@@ -1201,6 +1178,30 @@ export function useAgentChatController({
]
)
+ const runSwitchForIntent = useCallback(
+ (
+ agentRef: string,
+ chatId: string,
+ revision: number,
+ onCurrentError: (error: unknown) => void,
+ isRelevant: () => boolean = () => true
+ ) => {
+ const scope = currentAuthScopeRef.current
+ return runChatSwitchRequest(
+ () => switchToChatForIntent(agentRef, chatId, revision),
+ () =>
+ selectionIntentRevisionRef.current === revision &&
+ currentAuthScopeRef.current === scope &&
+ isRelevant(),
+ error => {
+ settleChatMessagesLoading(revision)
+ onCurrentError(error)
+ }
+ )
+ },
+ [settleChatMessagesLoading, switchToChatForIntent]
+ )
+
const switchToChat = useCallback(
async (
agentRef: string,
@@ -1212,33 +1213,23 @@ export function useAgentChatController({
// blocked or deleted chat cannot cancel another chat's pending load.
if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) return
const 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
- }
+ const promise = runSwitchForIntent(agentRef, chatId, selectionIntentRevision, error => {
+ options.onCurrentError?.(error)
+ })
+ pendingChatSwitchRequestRef.current =
+ readPendingSelection(agentRef)?.mode === 'specific'
+ ? { agentRef, chatId, revision: selectionIntentRevision, promise }
+ : null
+ await promise
},
[
beginSelectionIntent,
clearPendingSelection,
isChatDeleted,
isHostAccessBlocked,
- reportCallerOwnedSelectionError,
- settleChatMessagesLoading,
- switchToChatForIntent,
+ readPendingSelection,
+ runSwitchForIntent,
]
)
@@ -1456,7 +1447,30 @@ export function useAgentChatController({
let cancelled = false
const selectionIntentRevision = selectionIntentRevisionRef.current
const requestedSelection = readPendingSelection(selectedAgent)
- if (requestedSelection?.mode === 'specific') {
+ const pendingSwitch = pendingChatSwitchRequestRef.current
+ const sharesPendingSwitch = Boolean(
+ requestedSelection?.mode === 'specific' &&
+ pendingSwitch?.revision === selectionIntentRevision &&
+ pendingSwitch.agentRef === selectedAgent &&
+ pendingSwitch.chatId === requestedSelection.chatId
+ )
+ let switchStarted = false
+ const switchForEffect = (chatId: string) => {
+ switchStarted = true
+ if (sharesPendingSwitch) return pendingSwitch!.promise
+ return runSwitchForIntent(
+ selectedAgent,
+ chatId,
+ selectionIntentRevision,
+ error =>
+ liveDepsRef.current.pushToast(
+ `Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,
+ 'error'
+ ),
+ () => !cancelled
+ )
+ }
+ if (requestedSelection?.mode === 'specific' && !sharesPendingSwitch) {
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: requestedSelection.chatId,
@@ -1477,7 +1491,7 @@ export function useAgentChatController({
requestedSelection.isRemote === true
)
}
- } else {
+ } else if (requestedSelection?.mode !== 'specific') {
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: null,
@@ -1537,7 +1551,7 @@ export function useAgentChatController({
const latest = merged[0]
if (latest) {
autoSelectedChatIdRef.current = latest.id
- await switchToChatForIntent(selectedAgent, latest.id, selectionIntentRevision)
+ await switchForEffect(latest.id)
}
settleChatMessagesLoading(selectionIntentRevision)
return
@@ -1547,25 +1561,21 @@ export function useAgentChatController({
// Server-only chats may not appear in the local index or first server
// catalog page yet. `switchToChat` already owns the cache-first →
// server-hydrate path, so open the requested id directly.
- await switchToChatForIntent(
- selectedAgent,
- requestedSelection.chatId,
- selectionIntentRevision
- )
+ await switchForEffect(requestedSelection.chatId)
return
}
if (navItem === DESKTOP_ROUTES.chat) {
const latest = merged[0]
if (latest) {
autoSelectedChatIdRef.current = latest.id
- await switchToChatForIntent(selectedAgent, latest.id, selectionIntentRevision)
+ await switchForEffect(latest.id)
}
}
settleChatMessagesLoading(selectionIntentRevision)
})().catch(error => {
if (cancelled || selectionIntentRevisionRef.current !== selectionIntentRevision) return
settleChatMessagesLoading(selectionIntentRevision)
- if (reportCallerOwnedSelectionError(selectionIntentRevision, error)) return
+ if (switchStarted) return
liveDepsRef.current.pushToast(
`Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,
'error'
@@ -1582,9 +1592,8 @@ export function useAgentChatController({
navItem,
selectedAgent,
isHostAccessBlocked,
- reportCallerOwnedSelectionError,
settleChatMessagesLoading,
- switchToChatForIntent,
+ runSwitchForIntent,
])
// ─── Activity / progress state updaters (hoisted from sendAgentMessage so the
diff --git a/desktop-app/ui/src/lib/chatSwitchRequest.types.ts b/desktop-app/ui/src/lib/chatSwitchRequest.types.ts
new file mode 100644
index 000000000..33ed4a2a2
--- /dev/null
+++ b/desktop-app/ui/src/lib/chatSwitchRequest.types.ts
@@ -0,0 +1,6 @@
+export interface PendingChatSwitchRequest {
+ agentRef: string
+ chatId: string
+ revision: number
+ promise: Promise<void>
+}