Skip to content

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

TypeScript

fix(desktop-ui): settle selection-owned loading state

Josuéfb08c20e4334
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/selectionGuardCoverage.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/selectionGuardCoverage.characterization.test.tsx
index e9260cfce..4af41d770 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/selectionGuardCoverage.characterization.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/selectionGuardCoverage.characterization.test.tsx
@@ -99,7 +99,7 @@ function holdSessionMessages(chatId: string) {
if (held && requestedChatId === chatId) returned.resolve()
return result
})
- return { entered, release, returned }
+ return { entered, release, returned, hasEntered: () => held }
}
function holdLastActive(chatId: string) {
@@ -138,7 +138,7 @@ function holdLocalMessages(chatId: string) {
if (held && requestedChatId === chatId) returned.resolve()
return messages
})
- return { entered, release, returned }
+ return { entered, release, returned, hasEntered: () => held }
}
describe('selection intent and continuation guards', () => {
@@ -265,25 +265,74 @@ describe('selection intent and continuation guards', () => {
controller.unmount()
})
- it('lets a newer pending specific selection supersede the old list request', async () => {
+ it('keeps a newer chat switch while an older specific list request resolves', async () => {
await clerum.chat.create('agent-x', 'older-selection')
await clerum.chat.create('agent-x', 'newer-selection')
+ await clerum.chat.upsertMessages('agent-x', 'newer-selection', [
+ { id: 'newer-selection-message', role: 'user', content: 'newer history', timestamp: 1 },
+ ])
const controller = renderController({ navItem: 'agents' })
await waitForListIdle(controller)
const { heldIndex, chatIndex } = await startSpecificIndexLoad(controller, 'older-selection')
+ const heldHistory = holdLocalMessages('newer-selection')
+ const heldSession = holdSessionMessages('newer-selection')
+ let localHistoryEntered = false
+ let serverHistoryEntered = false
act(() => controller.result.current.setPendingChatSelection('agent-x', 'newer-selection'))
expect(controller.result.current.activeChatId).toBe('newer-selection')
expect(controller.result.current.chatMessagesLoading).toBe(true)
- await act(async () => {
- heldIndex.resolve(chatIndex)
- })
- await waitFor(() => expect(controller.result.current.chatListLoading).toBe(false))
- expect(controller.result.current.activeChatId).toBe('newer-selection')
- expect(controller.result.current.chatMessages).toEqual([])
- expect(controller.result.current.chatMessagesLoading).toBe(true)
- controller.unmount()
+ try {
+ await waitFor(() => expect(heldHistory.hasEntered()).toBe(true))
+ localHistoryEntered = true
+ await act(async () => {
+ await heldHistory.entered.promise
+ })
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(controller.result.current.chatMessagesLoading).toBe(true)
+
+ await act(async () => {
+ heldIndex.resolve(chatIndex)
+ })
+ await waitFor(() => expect(controller.result.current.chatListLoading).toBe(false))
+ expect(controller.result.current.activeChatId).toBe('newer-selection')
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(controller.result.current.chatMessagesLoading).toBe(true)
+
+ await act(async () => {
+ heldHistory.release.resolve()
+ await heldHistory.returned.promise
+ })
+ await waitFor(() => expect(heldSession.hasEntered()).toBe(true))
+ serverHistoryEntered = true
+ await act(async () => {
+ await heldSession.entered.promise
+ })
+ expect(controller.result.current.chatMessages).toEqual(
+ expect.arrayContaining([expect.objectContaining({ id: 'newer-selection-message' })])
+ )
+ expect(controller.result.current.chatMessagesLoading).toBe(false)
+
+ await act(async () => {
+ heldSession.release.resolve()
+ await heldSession.returned.promise
+ })
+ const newerChatKey = makeTaskKey('agent-x', 'newer-selection')
+ await waitFor(() => {
+ expect(controller.result.current.sessionStateByChatKey[newerChatKey]?.syncing).toBe(false)
+ })
+ } finally {
+ heldHistory.release.resolve()
+ heldSession.release.resolve()
+ await act(async () => {
+ heldIndex.resolve(chatIndex)
+ if (localHistoryEntered) await heldHistory.returned.promise
+ if (serverHistoryEntered) await heldSession.returned.promise
+ })
+ await waitFor(() => expect(controller.result.current.chatListLoading).toBe(false))
+ controller.unmount()
+ }
})
it('keeps clearActiveChat blank when a prior specific index resolves', async () => {
@@ -322,91 +371,141 @@ describe('selection intent and continuation guards', () => {
controller.unmount()
})
- it.each(['latest', 'implicit'] as const)(
- 'does not let an older %s completion clear a newer selection spinner',
- async mode => {
- clerum.rpc.listSessions.mockResolvedValue(remoteCatalog())
- clerum.rpc.loadSessionMessages.mockResolvedValue(
- await serverSessionMessages('agent-x', 'catalog-latest')
- )
- const heldSession = holdSessionMessages('catalog-latest')
- const observedLoading: boolean[] = []
- const controller = renderController(
- {
- navItem: mode === 'latest' ? 'agents' : 'chat',
- loadMenuData: false,
- },
- { onLayoutCommit: view => observedLoading.push(view.chatMessagesLoading) }
- )
- if (mode === 'latest') {
- await waitForListIdle(controller)
- await act(async () => {
- controller.result.current.setPendingChatSelection('agent-x', null, {
- selectLatest: true,
- })
- controller.rerender({ navItem: 'chat' })
- })
- }
- try {
+ it('does not let an older session reconciliation clear a newer selection spinner', async () => {
+ await clerum.chat.create('agent-x', 'newer-chat')
+ await clerum.chat.upsertMessages('agent-x', 'newer-chat', [
+ { id: 'newer-chat-message', role: 'user', content: 'newer history', timestamp: 1 },
+ ])
+ clerum.rpc.listSessions.mockResolvedValue(remoteCatalog())
+ clerum.rpc.loadSessionMessages.mockResolvedValue(
+ await serverSessionMessages('agent-x', 'catalog-latest')
+ )
+ const heldSession = holdSessionMessages('catalog-latest')
+ const heldNewerHistory = holdLocalMessages('newer-chat')
+ const observedLoading: boolean[] = []
+ const controller = renderController(
+ { navItem: 'agents', loadMenuData: false },
+ { onLayoutCommit: view => observedLoading.push(view.chatMessagesLoading) }
+ )
+ let olderSwitch: Promise<void> | undefined
+ let newerSwitch: Promise<void> | undefined
+
+ try {
+ await waitForListIdle(controller)
+ act(() => {
+ olderSwitch = controller.result.current.handleSelectChat('catalog-latest')
+ })
+ await act(async () => {
await heldSession.entered.promise
- const latestKey = makeTaskKey('agent-x', 'catalog-latest')
- expect(controller.result.current.sessionStateByChatKey[latestKey]?.syncing).toBe(true)
- expect(controller.result.current.activeChatId).toBe('catalog-latest')
- expect(controller.result.current.chatMessagesLoading).toBe(false)
+ })
+ const latestKey = makeTaskKey('agent-x', 'catalog-latest')
+ expect(controller.result.current.sessionStateByChatKey[latestKey]?.syncing).toBe(true)
+ expect(controller.result.current.activeChatId).toBe('catalog-latest')
+ expect(controller.result.current.chatMessagesLoading).toBe(false)
+
+ const loadingObservationStart = observedLoading.length
+ act(() => {
+ newerSwitch = controller.result.current.handleSelectChat('newer-chat')
+ })
+ await act(async () => {
+ await heldNewerHistory.entered.promise
+ })
+ expect(controller.result.current.activeChatId).toBe('newer-chat')
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(controller.result.current.chatMessagesLoading).toBe(true)
- const loadingObservationStart = observedLoading.length
- act(() => controller.result.current.setPendingChatSelection('agent-x', 'newer-chat'))
- expect(controller.result.current.activeChatId).toBe('newer-chat')
- expect(controller.result.current.chatMessagesLoading).toBe(true)
+ await act(async () => {
+ heldSession.release.resolve()
+ await heldSession.returned.promise
+ await olderSwitch
+ })
+ expect(controller.result.current.sessionStateByChatKey[latestKey]?.syncing).toBe(false)
+ expect(controller.result.current.activeChatId).toBe('newer-chat')
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(controller.result.current.chatMessagesLoading).toBe(true)
+ expect(observedLoading.slice(loadingObservationStart)).not.toContain(false)
- await act(async () => {
- heldSession.release.resolve()
- await heldSession.returned.promise
- })
- await waitFor(() =>
- expect(controller.result.current.sessionStateByChatKey[latestKey]?.syncing).toBe(false)
+ await act(async () => {
+ heldNewerHistory.release.resolve()
+ await heldNewerHistory.returned.promise
+ await newerSwitch
+ })
+ await waitFor(() => {
+ expect(controller.result.current.chatMessages).toEqual(
+ expect.arrayContaining([expect.objectContaining({ id: 'newer-chat-message' })])
)
- await act(async () => {
- await new Promise(resolve => setTimeout(resolve, 0))
- })
- expect(controller.result.current.activeChatId).toBe('newer-chat')
- expect(controller.result.current.chatMessages).toEqual([])
- expect(controller.result.current.chatMessagesLoading).toBe(true)
- expect(observedLoading.slice(loadingObservationStart)).not.toContain(false)
- } finally {
- heldSession.release.resolve()
- controller.unmount()
- }
+ expect(controller.result.current.chatMessagesLoading).toBe(false)
+ })
+ } finally {
+ heldSession.release.resolve()
+ heldNewerHistory.release.resolve()
+ await olderSwitch?.catch(() => undefined)
+ await newerSwitch?.catch(() => undefined)
+ controller.unmount()
}
- )
+ })
it('skips stale local history after a newer selection wins during setLastActive', async () => {
await clerum.chat.create('agent-x', 'slow-chat')
await clerum.chat.create('agent-x', 'newer-chat')
+ await clerum.chat.upsertMessages('agent-x', 'newer-chat', [
+ { id: 'newer-chat-message', role: 'user', content: 'newer history', timestamp: 1 },
+ ])
const heldLastActive = holdLastActive('slow-chat')
const controller = renderController()
await waitForListIdle(controller)
+ const heldNewerHistory = holdLocalMessages('newer-chat')
let switchPromise!: Promise<void>
+ let newerSwitch: Promise<void> | undefined
act(() => {
switchPromise = controller.result.current.switchToChat('agent-x', 'slow-chat')
})
await heldLastActive.entered.promise
- act(() => controller.result.current.setPendingChatSelection('agent-x', 'newer-chat'))
- expect(controller.result.current.activeChatId).toBe('newer-chat')
-
- await act(async () => {
- heldLastActive.release.resolve()
- await switchPromise
+ act(() => {
+ newerSwitch = controller.result.current.handleSelectChat('newer-chat')
})
+ await heldNewerHistory.entered.promise
expect(controller.result.current.activeChatId).toBe('newer-chat')
expect(controller.result.current.chatMessages).toEqual([])
expect(controller.result.current.chatMessagesLoading).toBe(true)
- expect(clerum.chat.loadMessages).not.toHaveBeenCalled()
- controller.unmount()
+
+ try {
+ await act(async () => {
+ heldLastActive.release.resolve()
+ await switchPromise
+ })
+ await waitFor(() => {
+ expect(controller.result.current.activeChatId).toBe('newer-chat')
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(controller.result.current.chatMessagesLoading).toBe(true)
+ })
+ expect(
+ clerum.chat.loadMessages.mock.calls.some(
+ ([agentRef, chatId]) => agentRef === 'agent-x' && chatId === 'slow-chat'
+ )
+ ).toBe(false)
+
+ await act(async () => {
+ heldNewerHistory.release.resolve()
+ await heldNewerHistory.returned.promise
+ await newerSwitch
+ })
+ await waitFor(() => {
+ expect(controller.result.current.chatMessages).toEqual(
+ expect.arrayContaining([expect.objectContaining({ id: 'newer-chat-message' })])
+ )
+ expect(controller.result.current.chatMessagesLoading).toBe(false)
+ })
+ } finally {
+ heldLastActive.release.resolve()
+ heldNewerHistory.release.resolve()
+ await newerSwitch?.catch(() => undefined)
+ controller.unmount()
+ }
})
- it('does not expose cached history when Host authority becomes uncertain after setLastActive', async () => {
+ it('settles loading without exposing cached history when Host authority becomes uncertain', async () => {
await clerum.chat.create('agent-x', 'guarded-chat')
await clerum.chat.upsertMessages('agent-x', 'guarded-chat', [
{
@@ -434,7 +533,7 @@ describe('selection intent and continuation guards', () => {
})
expect(controller.result.current.activeChatId).toBe('guarded-chat')
expect(controller.result.current.chatMessages).toEqual([])
- expect(controller.result.current.chatMessagesLoading).toBe(true)
+ expect(controller.result.current.chatMessagesLoading).toBe(false)
expect(clerum.chat.loadMessages).not.toHaveBeenCalled()
controller.unmount()
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/selectionLoadingOwnership.r7.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/selectionLoadingOwnership.r7.characterization.test.tsx
index 4a316817c..9bc38df49 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/selectionLoadingOwnership.r7.characterization.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/selectionLoadingOwnership.r7.characterization.test.tsx
@@ -36,6 +36,26 @@ function holdLastActive(chatId: string) {
return { entered, release, returned }
}
+function holdLocalMessages(chatId: string) {
+ const original = clerum.chat.loadMessages.getMockImplementation()
+ if (!original) throw new Error('Expected the ChatStore-backed loadMessages test implementation')
+ const entered = deferred<void>()
+ const release = deferred<void>()
+ const returned = deferred<void>()
+ let held = false
+ clerum.chat.loadMessages.mockImplementation(async (agentRef, selectedChatId, ...args) => {
+ if (agentRef === 'agent-x' && selectedChatId === chatId && !held) {
+ held = true
+ entered.resolve()
+ await release.promise
+ }
+ const messages = await original(agentRef, selectedChatId, ...args)
+ if (held && selectedChatId === chatId) returned.resolve()
+ return messages
+ })
+ return { entered, release, returned }
+}
+
describe('Round 7 selection loading ownership', () => {
it('settles a held implicit switch when a newer no-chat intent arrives', async () => {
await clerum.chat.create('agent-x', 'chat-a')
@@ -79,13 +99,40 @@ describe('Round 7 selection loading ownership', () => {
await clerum.chat.create('agent-x', 'chat-a')
clerum.chat.getIndex.mockImplementation(agentRef => clerum.readIndex(agentRef))
const heldSwitch = holdLastActive('chat-a')
+ const heldHistory = holdLocalMessages('chat-b')
const controller = renderController({ navItem: 'chat', loadMenuData: false })
+ let localHistoryEntered = false
+ let requestedSwitch!: Promise<void>
try {
await act(async () => {
await heldSwitch.entered.promise
})
- act(() => controller.result.current.setPendingChatSelection('agent-x', 'chat-b'))
+ act(() => {
+ requestedSwitch = controller.result.current.handleSelectChat('chat-b')
+ })
+ await act(async () => {
+ await heldHistory.entered.promise
+ localHistoryEntered = true
+ })
+
+ expect(controller.result.current.activeChatId).toBe('chat-b')
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(controller.result.current.chatMessagesLoading).toBe(true)
+
+ await act(async () => {
+ heldSwitch.release.resolve()
+ await heldSwitch.returned.promise
+ })
+ expect(controller.result.current.activeChatId).toBe('chat-b')
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(controller.result.current.chatMessagesLoading).toBe(true)
+
+ await act(async () => {
+ heldHistory.release.resolve()
+ await heldHistory.returned.promise
+ await requestedSwitch
+ })
await waitFor(() => {
expect(controller.result.current.activeChatId).toBe('chat-b')
@@ -95,10 +142,6 @@ describe('Round 7 selection loading ownership', () => {
expect(controller.result.current.chatMessagesLoading).toBe(false)
})
- await act(async () => {
- heldSwitch.release.resolve()
- await heldSwitch.returned.promise
- })
expect(controller.result.current.activeChatId).toBe('chat-b')
expect(controller.result.current.chatMessages).toEqual(
expect.arrayContaining([expect.objectContaining({ id: 'chat-b-message' })])
@@ -106,8 +149,11 @@ describe('Round 7 selection loading ownership', () => {
expect(controller.result.current.chatMessagesLoading).toBe(false)
} finally {
heldSwitch.release.resolve()
+ heldHistory.release.resolve()
await act(async () => {
await heldSwitch.returned.promise
+ if (localHistoryEntered) await heldHistory.returned.promise
+ await requestedSwitch?.catch(() => undefined)
})
controller.unmount()
}
@@ -161,6 +207,52 @@ describe('Round 7 selection loading ownership', () => {
}
})
+ it('settles the current spinner when a newer chat switch targets a deleted chat', async () => {
+ await clerum.chat.create('agent-x', 'chat-a')
+ await clerum.chat.create('agent-x', 'chat-b')
+ const heldSwitch = holdLastActive('chat-a')
+ const controller = renderController({ loadMenuData: false })
+ let switchPromise!: Promise<void>
+
+ try {
+ await waitFor(() => expect(controller.result.current.chatListLoading).toBe(false))
+ act(() => {
+ switchPromise = controller.result.current.handleSelectChat('chat-a')
+ })
+ await act(async () => {
+ await heldSwitch.entered.promise
+ })
+ expect(controller.result.current.chatMessagesLoading).toBe(true)
+
+ await act(async () => {
+ const deletion = await controller.result.current.captureChatDeleteFence('agent-x')
+ await controller.result.current.handleDeleteChat('chat-b', deletion)
+ await controller.result.current.switchToChat('agent-x', 'chat-b')
+ })
+ expect(controller.result.current.activeChatId).toBe('chat-a')
+ expect(controller.result.current.chatMessagesLoading).toBe(false)
+
+ await act(async () => {
+ heldSwitch.release.resolve()
+ await switchPromise
+ })
+ expect(controller.result.current.activeChatId).toBe('chat-a')
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(controller.result.current.chatMessagesLoading).toBe(false)
+ expect(
+ clerum.chat.loadMessages.mock.calls.some(
+ ([agentRef, chatId]) => agentRef === 'agent-x' && chatId === 'chat-b'
+ )
+ ).toBe(false)
+ } finally {
+ heldSwitch.release.resolve()
+ await act(async () => {
+ await switchPromise?.catch(() => undefined)
+ })
+ controller.unmount()
+ }
+ })
+
it('restores a same-tick chat switch when New chat creation fails', async () => {
await clerum.chat.create('agent-x', 'chat-b')
await clerum.chat.upsertMessages('agent-x', 'chat-b', [
@@ -343,9 +435,8 @@ describe('Round 7 selection loading ownership', () => {
await createPromise
})
expect(observedError).toBe(createError)
- expect(controller.result.current.chatMessages).not.toEqual(
- expect.arrayContaining([expect.objectContaining({ id: 'team-one-message' })])
- )
+ expect(controller.result.current.activeChatId).toBeNull()
+ expect(controller.result.current.chatMessages).toEqual([])
expect(controller.result.current.chatMessagesLoading).toBe(false)
} finally {
createGate.reject(createError)
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index 679499030..8a43f4ad2 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -448,6 +448,8 @@ export function useAgentChatController({
const [activeChatId, setActiveChatId] = useState<string | null>(null)
const selectionIntentRevisionRef = useRef(0)
+ 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
// session projection. `sessionStateByChatKey` (the public contract) is derived
// from the reducer's map via `useSyncExternalStore` + `projectSessionState`.
@@ -533,7 +535,11 @@ export function useAgentChatController({
const beginSelectionIntent = useCallback(
(startsHistoryLoad = false) => {
selectionIntentRevisionRef.current += 1
- if (!startsHistoryLoad) setChatMessagesLoading(false)
+ if (!startsHistoryLoad) {
+ setChatMessagesLoading(false)
+ activeChatSwitchRequestRef.current = null
+ activeChatSwitchKeyRef.current = null
+ }
return selectionIntentRevisionRef.current
},
[setChatMessagesLoading]
@@ -643,8 +649,6 @@ export function useAgentChatController({
navItem,
selectedAgent,
})
- const activeChatSwitchRequestRef = useRef<symbol | null>(null)
- const activeChatSwitchKeyRef = useRef<string | null>(null)
// Correlate the visible local page to the switch request that loaded it.
const activeChatLocalPageRequestRef = useRef<{
request: symbol
@@ -1059,7 +1063,6 @@ export function useAgentChatController({
const isStillActive = () => {
const visible = activeChatVisibilityRef.current
return (
- selectionIntentRevisionRef.current === selectionIntentRevision &&
!isHostAccessBlocked(agentRef) &&
activeChatSwitchRequestRef.current === switchRequest &&
visible.selectedAgent === agentRef &&
@@ -3928,6 +3931,7 @@ export function useAgentChatController({
options: {
selectLatest?: boolean
suppressAutoSelect?: boolean
+ deferSwitch?: boolean
title?: string
isRemote?: boolean
} = {}
@@ -3936,7 +3940,12 @@ export function useAgentChatController({
const selectsSpecificChat = Boolean(
chatId && !options.selectLatest && !options.suppressAutoSelect
)
- if (selectsSpecificChat && selectedAgent === agentName && navItem === DESKTOP_ROUTES.chat) {
+ if (
+ selectsSpecificChat &&
+ !options.deferSwitch &&
+ selectedAgent === agentName &&
+ navItem === DESKTOP_ROUTES.chat
+ ) {
clearPendingSelection(agentName)
if (options.title) {
upsertProvisionalEntry(chatId!, options.title, options.isRemote === true)
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index f84164de3..2897e62c9 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -1042,11 +1042,13 @@ export function useAppController() {
const pendingSelectionOptions: {
selectLatest: boolean
suppressAutoSelect: boolean
+ deferSwitch: boolean
title?: string
isRemote?: boolean
} = {
selectLatest: shouldSelectLatest,
suppressAutoSelect: !shouldSelectLatest && !targetChatId,
+ deferSwitch: options.keepNavItem === true,
}
if (options.title) pendingSelectionOptions.title = options.title
if (options.isRemote !== undefined) pendingSelectionOptions.isRemote = options.isRemote