Skip to content

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

TypeScript

fix(desktop): guard stale sidebar updates

Josué7a717ad3834b
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
index b1d052fa3..3f6212248 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
@@ -1197,6 +1197,110 @@ describe('useAgentChatController — characterization (D.0)', () => {
expect(result.current.chatList.map(chat => chat.id)).toEqual(['fresh-agent-x-chat'])
})
+ it('does not let a stale load retry failure clear a freshly loaded sidebar', async () => {
+ type Index = Awaited<ReturnType<typeof clerum.chat.getIndex>>
+ const firstLoad = deferred<Index>()
+ let calls = 0
+ clerum.chat.getIndex.mockImplementation(() => {
+ calls += 1
+ if (calls === 1) return firstLoad.promise
+ if (calls === 2) {
+ return Promise.resolve({
+ version: 2,
+ lastActiveChatId: null,
+ onboardingDismissed: false,
+ chats: [
+ {
+ id: 'fresh-chat',
+ title: 'Fresh chat',
+ createdAt: '2026-05-04T00:00:00Z',
+ updatedAt: '2026-05-04T00:00:00Z',
+ messageCount: 1,
+ },
+ ],
+ })
+ }
+ return Promise.reject(new Error('stale retry failed'))
+ })
+ const { result, rerender } = renderController({
+ currentTeamId: 'team-1',
+ loadMenuData: false,
+ })
+ await waitFor(() => expect(calls).toBe(1))
+
+ await act(async () => {
+ firstLoad.reject(new Error('initial transient'))
+ await Promise.resolve()
+ })
+ rerender({ currentTeamId: 'team-2', loadMenuData: false })
+ await waitFor(() =>
+ expect(result.current.chatList.map(chat => chat.id)).toEqual(['fresh-chat'])
+ )
+
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 350))
+ })
+ expect(calls).toBe(2)
+ expect(result.current.chatList.map(chat => chat.id)).toEqual(['fresh-chat'])
+ })
+
+ it('does not append a created chat after the selected agent changes', async () => {
+ type ChatMeta = Awaited<ReturnType<typeof clerum.chat.create>>
+ const created = deferred<ChatMeta>()
+ clerum.chat.getIndex.mockImplementation(async (agentRef: string) => ({
+ version: 2,
+ lastActiveChatId: null,
+ onboardingDismissed: false,
+ chats:
+ agentRef === 'agent-y'
+ ? [
+ {
+ id: 'agent-y-chat',
+ title: 'Agent Y chat',
+ createdAt: '2026-05-04T00:00:00Z',
+ updatedAt: '2026-05-04T00:00:00Z',
+ messageCount: 1,
+ },
+ ]
+ : [],
+ }))
+ clerum.chat.create.mockImplementation(() => created.promise)
+ const { result, rerender } = renderController({
+ agentNames: ['agent-x', 'agent-y'],
+ loadMenuData: false,
+ })
+ await settleMount()
+
+ let createPromise!: Promise<void>
+ act(() => {
+ createPromise = result.current.handleCreateChat()
+ })
+ await waitFor(() => expect(clerum.chat.create).toHaveBeenCalledWith('agent-x', 'uuid-1'))
+
+ rerender({
+ selectedAgent: 'agent-y',
+ agentNames: ['agent-x', 'agent-y'],
+ loadMenuData: false,
+ })
+ await waitFor(() =>
+ expect(result.current.chatList.map(chat => chat.id)).toEqual(['agent-y-chat'])
+ )
+
+ await act(async () => {
+ created.resolve({
+ id: 'uuid-1',
+ title: 'New Chat',
+ createdAt: '2026-05-05T00:00:00Z',
+ updatedAt: '2026-05-05T00:00:00Z',
+ messageCount: 0,
+ })
+ await createPromise
+ })
+
+ expect(result.current.chatList.map(chat => chat.id)).toEqual(['agent-y-chat'])
+ expect(clerum.chat.setLastActive).not.toHaveBeenCalledWith('agent-x', 'uuid-1')
+ })
+
it('renders local sessions without waiting for remote listSessions', async () => {
clerum.chat.getIndex.mockResolvedValue({
version: 1,
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index b5aa2ee6c..e0a0fc0a6 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -166,8 +166,10 @@ export function useChatListController({
// ─── chatList loader (agent-scoped) ───
const loadChatListOnce = useCallback(
- async (agentRef: string): Promise<{ index: ChatIndex; merged: SidebarChatEntry[] }> => {
- const requestGeneration = ++requestGenerationRef.current
+ async (
+ agentRef: string,
+ requestGeneration: number
+ ): Promise<{ index: ChatIndex; merged: SidebarChatEntry[] }> => {
chatListNextCursorByAgentRef.current[agentRef] = null
if (selectedAgentRef.current === agentRef) {
setChatListHasMoreRemoteSessions(false)
@@ -364,6 +366,7 @@ export function useChatListController({
const loadChatList = useCallback(
async (agentRef: string): Promise<{ index: ChatIndex; merged: SidebarChatEntry[] } | null> => {
+ const requestGeneration = ++requestGenerationRef.current
// One retry with a short backoff: during boot a concurrent team-switch /
// access-catalog refresh can momentarily rebind the main-process chat
// store, rejecting `getIndex` with "Not authenticated". Swallowing that
@@ -371,14 +374,23 @@ export function useChatListController({
// is re-selected, so give the store one chance to settle.
for (let attempt = 0; ; attempt++) {
try {
- return await loadChatListOnce(agentRef)
+ return await loadChatListOnce(agentRef, requestGeneration)
} catch (err) {
if (attempt === 0) {
await new Promise(resolve => setTimeout(resolve, 300))
+ if (
+ selectedAgentRef.current !== agentRef ||
+ requestGenerationRef.current !== requestGeneration
+ ) {
+ return null
+ }
continue
}
console.warn('[loadChatList] failed after retry, clearing list', { agentRef, err })
- if (selectedAgentRef.current === agentRef) {
+ if (
+ selectedAgentRef.current === agentRef &&
+ requestGenerationRef.current === requestGeneration
+ ) {
setChatList([])
}
return null
@@ -534,9 +546,16 @@ export function useChatListController({
const handleCreateChat = useCallback(async () => {
const agentRef = selectedAgentRef.current
if (!agentRef) return
+ const requestGeneration = requestGenerationRef.current
const chatId = crypto.randomUUID()
const meta = await chatStore.createChat(agentRef, chatId)
chatStore.clearCachedRemoteData()
+ if (
+ selectedAgentRef.current !== agentRef ||
+ requestGenerationRef.current !== requestGeneration
+ ) {
+ return
+ }
appendNewEntry(agentRef, meta)
host.current?.markAutoSelectedChat(null)
await host.current?.switchToChat(agentRef, chatId)
@@ -546,8 +565,10 @@ export function useChatListController({
const handleRenameChatForAgent = useCallback(
async (agentRef: string, chatId: string, newTitle: string) => {
if (!agentRef) return
+ const requestGeneration = requestGenerationRef.current
const updatedAt = new Date().toISOString()
await chatStore.renameChat(agentRef, chatId, newTitle)
+ if (requestGenerationRef.current !== requestGeneration) return
setLatestChatSessions(prev =>
prev
.map(chat =>
@@ -578,6 +599,7 @@ export function useChatListController({
const handleDeleteChatForAgent = useCallback(
async (agentRef: string, chatId: string) => {
if (!agentRef) return
+ const requestGeneration = requestGenerationRef.current
// Stop following any in-flight task for this chat first: ack tears down the
// SSE + connect/watchdog timers, so a later terminal can't fire onTerminal
// and resurrect the just-deleted chat file via appendAssistantMessage.
@@ -589,6 +611,7 @@ export function useChatListController({
host.current?.dispatchSession(deletedKey, { type: 'CHAT_DELETED' })
await chatStore.deleteChat(agentRef, chatId)
chatStore.clearCachedRemoteData()
+ if (requestGenerationRef.current !== requestGeneration) return
host.current?.clearComposerDraft(chatId)
removeLatestChatSession(agentRef, chatId)
// Post-await guards read the LIVE committed values (selectedAgentRef /