Skip to content

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

TypeScript

fix(desktop-ui): preserve newer chat selection intent R1-H1

Josuéa5e93558709c
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
index 1c227c209..d0dd4986e 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
@@ -2,7 +2,7 @@ import { type Mock, inject, vi } from 'vitest'
import { mkdtempSync } from 'node:fs'
import { join } from 'node:path'
import { ChatStore } from '../../../../../../src/chatStore'
-import type { ChatDeleteFence, ChatMessage } from '../../../../../../src/types'
+import type { ChatDeleteFence, ChatIndex, ChatMessage } from '../../../../../../src/types'
import type {} from './mockClerumStoreRoot'
/**
@@ -77,6 +77,8 @@ export interface MockClerum {
hasActivityHandler: (hostRef: string) => boolean
/** What the real store holds for one chat, read straight from it. */
persistedMessages: (agentRef: string, chatId: string) => Promise<Array<Record<string, unknown>>>
+ /** The index a real ChatStore read produces for one agent. */
+ readIndex: (agentRef: string) => Promise<ChatIndex>
}
export function installMockClerum(): MockClerum {
@@ -178,6 +180,7 @@ export function installMockClerum(): MockClerum {
hasActivityHandler: (hostRef: string) => activityHandlers.has(hostRef),
persistedMessages: async (agentRef: string, chatId: string) =>
(await store.loadMessages(agentRef, chatId)) as unknown as Array<Record<string, unknown>>,
+ readIndex: (agentRef: string) => store.getIndex(agentRef),
}
Object.defineProperty(window, 'clerum', {
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
index 7e0a7078a..ff0d2631c 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
@@ -8,7 +8,9 @@
* See .specs/refactor-useAgentChatController/plan.md Fase 0 + spec.md B.4.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { act, waitFor } from '@testing-library/react'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { useAgentChatActionsValue } from '@hooks/useAgentChatActionsValue'
+import type { useAppController } from '@hooks/useAppController'
import { renderController } from './__fixtures__/controllerHarness'
import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'
@@ -356,4 +358,215 @@ describe('pendingChatSelection effect', () => {
'older-chat'
)
})
+
+ it('keeps New chat authoritative when an older specific selection load resolves', async () => {
+ const priorChatId = 'prior-chat'
+ await clerum.chat.create('agent-x', priorChatId)
+ await clerum.chat.upsertMessages('agent-x', priorChatId, [
+ {
+ id: 'prior-message',
+ role: 'user',
+ content: 'keep this in the previous chat',
+ timestamp: Date.now(),
+ },
+ ])
+ const priorChatIndex = await clerum.readIndex('agent-x')
+
+ const controller = renderController({ navItem: 'agents' })
+ await settleMount()
+ await waitFor(() => expect(controller.result.current.chatListLoading).toBe(false))
+
+ const indexCallsBeforeSelection = clerum.chat.getIndex.mock.calls.length
+ const index = deferred<Awaited<ReturnType<typeof clerum.chat.getIndex>>>()
+ clerum.chat.getIndex.mockReturnValue(index.promise)
+ const cachedMessages = deferred<Awaited<ReturnType<typeof clerum.chat.loadMessages>>>()
+ const loadMessages = clerum.chat.loadMessages.getMockImplementation()
+ if (!loadMessages) throw new Error('Expected the real ChatStore loadMessages producer')
+ clerum.chat.loadMessages.mockImplementation((agentRef, chatId, limit, offset) =>
+ agentRef === 'agent-x' && chatId === priorChatId
+ ? cachedMessages.promise
+ : loadMessages(agentRef, chatId, limit, offset)
+ )
+ clerum.rpc.invokeHostMessage.mockResolvedValue({ response: 'fresh reply' })
+
+ await act(async () => {
+ controller.result.current.setPendingChatSelection('agent-x', priorChatId)
+ controller.rerender({ navItem: 'chat' })
+ })
+ await waitFor(() =>
+ expect(clerum.chat.getIndex.mock.calls.length).toBeGreaterThan(indexCallsBeforeSelection)
+ )
+ expect(controller.result.current.chatListLoading).toBe(true)
+
+ const actions = renderHook(() =>
+ useAgentChatActionsValue(
+ controller.result.current as unknown as ReturnType<typeof useAppController>
+ )
+ )
+
+ try {
+ // Match the New chat selection transition in useAppController. Its blank
+ // state is committed while the older specific selection still awaits IPC.
+ await act(async () => {
+ controller.result.current.setPendingChatSelection('agent-x', null, {
+ suppressAutoSelect: true,
+ })
+ controller.result.current.clearActiveChat()
+ actions.rerender()
+ })
+ expect(controller.result.current.activeChatId).toBeNull()
+ expect(controller.result.current.chatMessages).toEqual([])
+
+ await act(async () => {
+ index.resolve(priorChatIndex)
+ })
+ await waitFor(() => expect(controller.result.current.chatListLoading).toBe(false))
+ if (controller.result.current.activeChatId === priorChatId) {
+ await waitFor(() =>
+ expect(clerum.chat.loadMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ priorChatId,
+ expect.any(Number),
+ undefined
+ )
+ )
+ }
+
+ // ComposerPanel receives this stable action from the production action-value
+ // factory. Calling it now models a send after the New chat commit and the
+ // older index response, while the re-opened chat's cache read stays pending.
+ await act(async () => {
+ actions.rerender()
+ await actions.result.current.handleSendAgentMessage('start the next conversation')
+ })
+
+ const request = clerum.rpc.invokeHostMessage.mock.calls.at(-1)?.[1] as
+ | { threadId?: string }
+ | undefined
+ expect(request?.threadId).not.toBe(priorChatId)
+
+ const priorMessages = await clerum.persistedMessages('agent-x', priorChatId)
+ expect(priorMessages).toEqual([
+ expect.objectContaining({ id: 'prior-message', content: 'keep this in the previous chat' }),
+ ])
+ const newChatId = request?.threadId
+ expect(newChatId).toBeTruthy()
+ expect(await clerum.persistedMessages('agent-x', newChatId!)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ role: 'user', content: 'start the next conversation' }),
+ expect.objectContaining({ role: 'assistant', content: 'fresh reply' }),
+ ])
+ )
+ } finally {
+ await act(async () => {
+ cachedMessages.resolve(await loadMessages('agent-x', priorChatId, undefined, undefined))
+ })
+ controller.unmount()
+ actions.unmount()
+ }
+ })
+
+ it('keeps a newer selection while retaining a delayed New chat in the list', async () => {
+ await clerum.chat.create('agent-x', 'selected-chat')
+ const controller = renderController({ navItem: 'agents' })
+ await settleMount()
+ await waitFor(() => expect(controller.result.current.chatListLoading).toBe(false))
+
+ const createChat = clerum.chat.create.getMockImplementation()
+ if (!createChat) throw new Error('Expected the real ChatStore create producer')
+ const releaseCreate = deferred<void>()
+ const created = deferred<Awaited<ReturnType<typeof clerum.chat.create>>>()
+ clerum.chat.create.mockImplementation(async (agentRef, chatId) => {
+ const meta = await createChat(agentRef, chatId)
+ created.resolve(meta)
+ await releaseCreate.promise
+ return meta
+ })
+
+ let createPromise!: Promise<void>
+ act(() => {
+ createPromise = controller.result.current.handleCreateChat()
+ })
+ const createdChat = await created.promise
+
+ await act(async () => {
+ await controller.result.current.switchToChat('agent-x', 'selected-chat')
+ })
+
+ await act(async () => {
+ releaseCreate.resolve()
+ await createPromise
+ })
+
+ expect(controller.result.current.activeChatId).toBe('selected-chat')
+ expect(controller.result.current.chatList).toEqual(
+ expect.arrayContaining([expect.objectContaining({ id: createdChat.id })])
+ )
+ controller.unmount()
+ })
+
+ it('keeps an accepted blank-chat send bound when New chat arrives during creation', async () => {
+ const controller = renderController({ navItem: 'chat' })
+ await settleMount()
+ await waitFor(() => expect(controller.result.current.chatListLoading).toBe(false))
+
+ const createChat = clerum.chat.create.getMockImplementation()
+ if (!createChat) throw new Error('Expected the real ChatStore create producer')
+ const releaseCreate = deferred<void>()
+ const created = deferred<Awaited<ReturnType<typeof clerum.chat.create>>>()
+ clerum.chat.create.mockImplementation(async (agentRef, chatId) => {
+ const meta = await createChat(agentRef, chatId)
+ created.resolve(meta)
+ await releaseCreate.promise
+ return meta
+ })
+ clerum.rpc.invokeHostMessage.mockResolvedValue({ response: 'sent reply' })
+
+ const actions = renderHook(() =>
+ useAgentChatActionsValue(
+ controller.result.current as unknown as ReturnType<typeof useAppController>
+ )
+ )
+ let sendPromise!: Promise<void>
+ act(() => {
+ sendPromise = actions.result.current.handleSendAgentMessage('accepted before New chat')
+ })
+ const createdChat = await created.promise
+
+ try {
+ await act(async () => {
+ controller.result.current.setPendingChatSelection('agent-x', null, {
+ suppressAutoSelect: true,
+ })
+ controller.result.current.clearActiveChat()
+ actions.rerender()
+ })
+ expect(controller.result.current.activeChatId).toBeNull()
+ expect(controller.result.current.chatMessages).toEqual([])
+
+ await act(async () => {
+ releaseCreate.resolve()
+ await sendPromise
+ })
+
+ const request = clerum.rpc.invokeHostMessage.mock.calls.at(-1)?.[1] as
+ | { threadId?: string }
+ | undefined
+ expect(request?.threadId).toBe(createdChat.id)
+ expect(await clerum.persistedMessages('agent-x', createdChat.id)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ role: 'user', content: 'accepted before New chat' }),
+ expect.objectContaining({ role: 'assistant', content: 'sent reply' }),
+ ])
+ )
+ expect(controller.result.current.activeChatId).toBeNull()
+ } finally {
+ releaseCreate.resolve()
+ await act(async () => {
+ await sendPromise.catch(() => undefined)
+ })
+ actions.unmount()
+ controller.unmount()
+ }
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx
index e06ccaf61..a4f6179ca 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx
@@ -234,7 +234,7 @@ describe('sendAgentMessage — auto-title on send (B10)', () => {
})
describe('sendAgentMessage — new chat target', () => {
- it('does not reuse the prior chat when a send races the New chat selection commit', async () => {
+ it('keeps a retained raw send callback off the prior chat after New chat clears it', async () => {
const priorChatId = 'prior-chat'
await clerum.chat.create('agent-x', priorChatId)
await clerum.chat.upsertMessages('agent-x', priorChatId, [
@@ -254,10 +254,10 @@ describe('sendAgentMessage — new chat target', () => {
})
expect(result.current.activeChatId).toBe(priorChatId)
- // A composer event queued from the current conversation can run while the
- // new chat's list request is still unresolved. Model useAppController's
- // blank selection and route transition, then hold that selection load.
- const sendImmediately = result.current.handleSendAgentMessage
+ // Retain the raw hook callback before New chat commits. This is deliberately
+ // callback-hardening coverage; pendingChatSelection.characterization covers
+ // the production stable action after a superseded list load resolves.
+ const retainedRawSend = result.current.handleSendAgentMessage
clerum.chat.getIndex.mockClear()
clerum.chat.getIndex.mockReturnValue(new Promise(() => undefined))
await act(async () => {
@@ -270,7 +270,7 @@ describe('sendAgentMessage — new chat target', () => {
expect(result.current.chatMessages).toEqual([])
await act(async () => {
- await sendImmediately('start the next conversation')
+ await retainedRawSend('start the next conversation')
})
const request = clerum.rpc.invokeHostMessage.mock.calls.at(-1)?.[1] as
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index b0e610a44..c0b470142 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -424,6 +424,11 @@ export function useAgentChatController({
const tracker = useAgentTaskTracker()
const [activeChatId, setActiveChatId] = useState<string | null>(null)
+ const selectionIntentRevisionRef = useRef(0)
+ const beginSelectionIntent = useCallback(() => {
+ selectionIntentRevisionRef.current += 1
+ return selectionIntentRevisionRef.current
+ }, [])
// 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`.
@@ -877,6 +882,7 @@ export function useAgentChatController({
}, [])
const resetChat = useCallback(() => {
+ beginSelectionIntent()
clearAllComposerDrafts()
setActivityByAgentMessage({})
setProgressByAgentMessage({})
@@ -919,6 +925,7 @@ export function useAgentChatController({
setFailedAgentSend(null)
}, [
resetComposerAttachments,
+ beginSelectionIntent,
clearList,
tracker,
fsm,
@@ -930,8 +937,9 @@ export function useAgentChatController({
// Unified switch (post-D.4): cache-first render → server reconcile → tracker
// rejoin. No `isRemote` branch — the server is the source of truth for every
// chat, and a task in flight is rejoined via the tracker D.3 already mounts.
- const switchToChat = useCallback(
- async (agentRef: string, chatId: string) => {
+ const switchToChatForIntent = useCallback(
+ async (agentRef: string, chatId: string, selectionIntentRevision: number) => {
+ if (selectionIntentRevisionRef.current !== selectionIntentRevision) return
if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) return
const key = makeTaskKey(agentRef, chatId)
const visibleBeforeSwitch = activeChatVisibilityRef.current
@@ -973,7 +981,12 @@ export function useAgentChatController({
setAgentError(null)
setFailedAgentSend(null)
await chatStore.setLastActive(agentRef, chatId)
- if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) return
+ if (
+ selectionIntentRevisionRef.current !== selectionIntentRevision ||
+ isHostAccessBlocked(agentRef) ||
+ isChatDeleted(agentRef, chatId)
+ )
+ return
unfillableServerGapUpperBoundsRef.current.delete(key)
@@ -1082,6 +1095,15 @@ export function useAgentChatController({
]
)
+ const switchToChat = useCallback(
+ async (agentRef: string, chatId: string) => {
+ const selectionIntentRevision = beginSelectionIntent()
+ clearPendingSelection(agentRef, chatId)
+ await switchToChatForIntent(agentRef, chatId, selectionIntentRevision)
+ },
+ [beginSelectionIntent, clearPendingSelection, switchToChatForIntent]
+ )
+
// §5d: chat CRUD (handleCreateChat / handleRename[ForAgent] / handleDelete[ForAgent])
// now lives in `useChatListController` — it owns both lists and mutates them
// in sync. The active-chat concerns it needs (switchToChat, scrollChatToBottom,
@@ -1099,6 +1121,9 @@ export function useAgentChatController({
useEffect(() => {
chatListHostRef.current = {
switchToChat,
+ beginSelectionIntent,
+ getSelectionIntentRevision: () => selectionIntentRevisionRef.current,
+ clearPendingSelection,
scrollChatToBottom,
dispatchSession,
clearComposerDraft,
@@ -1289,6 +1314,7 @@ export function useAgentChatController({
}
let cancelled = false
+ const selectionIntentRevision = selectionIntentRevisionRef.current
const requestedSelection = readPendingSelection(selectedAgent)
if (requestedSelection?.mode === 'specific') {
activeChatVisibilityRef.current = {
@@ -1329,6 +1355,10 @@ export function useAgentChatController({
const result = await loadChatList(selectedAgent)
if (cancelled || isHostAccessBlocked(selectedAgent)) return
setChatListLoading(false)
+ // A newer selection intent, including an explicit blank New chat, owns
+ // the active chat even when its chatId is null. Do not consume its pending
+ // selection or replay this older request after the list load completes.
+ if (selectionIntentRevisionRef.current !== selectionIntentRevision) return
if (!result) {
setChatMessagesLoading(false)
return
@@ -1365,9 +1395,11 @@ export function useAgentChatController({
const latest = merged[0]
if (latest) {
autoSelectedChatIdRef.current = latest.id
- await switchToChat(selectedAgent, latest.id)
+ await switchToChatForIntent(selectedAgent, latest.id, selectionIntentRevision)
+ }
+ if (selectionIntentRevisionRef.current === selectionIntentRevision) {
+ setChatMessagesLoading(false)
}
- setChatMessagesLoading(false)
return
}
if (requestedSelection?.mode === 'specific') {
@@ -1375,23 +1407,36 @@ 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 switchToChat(selectedAgent, requestedSelection.chatId)
+ await switchToChatForIntent(
+ selectedAgent,
+ requestedSelection.chatId,
+ selectionIntentRevision
+ )
return
}
if (navItem === DESKTOP_ROUTES.chat) {
const latest = merged[0]
if (latest) {
autoSelectedChatIdRef.current = latest.id
- await switchToChat(selectedAgent, latest.id)
+ await switchToChatForIntent(selectedAgent, latest.id, selectionIntentRevision)
}
}
- setChatMessagesLoading(false)
+ if (selectionIntentRevisionRef.current === selectionIntentRevision) {
+ setChatMessagesLoading(false)
+ }
})()
return () => {
cancelled = true
}
- }, [cancelOlderMessagesLoad, currentTeamId, navItem, selectedAgent, isHostAccessBlocked])
+ }, [
+ cancelOlderMessagesLoad,
+ currentTeamId,
+ navItem,
+ selectedAgent,
+ isHostAccessBlocked,
+ switchToChatForIntent,
+ ])
const mapComposerAttachmentsToHostRequest = (
attachments: ComposerImageAttachment[]
@@ -2823,10 +2868,12 @@ export function useAgentChatController({
releaseSendSetup()
return
}
- // This ref is the synchronous authority for the send target. Do not fall
- // back to `activeChatId`: a New chat clear can precede React's next render,
- // leaving that state value captured from the previous conversation.
+ // This ref is the synchronous authority for the send target. A blank
+ // composer send also supersedes a pending latest/blank selection so an old
+ // list response cannot replace the chat created by this send.
let sendChatId = currentChatId
+ const sendSelectionIntentRevision = currentChatId ? null : beginSelectionIntent()
+ if (sendSelectionIntentRevision !== null) clearPendingSelection(sendAgent)
const sendStillAuthorized = () =>
sendScope === sendScopeGeneration.current &&
sendScopeIdentity === currentAuthScopeRef.current &&
@@ -2867,7 +2914,13 @@ export function useAgentChatController({
chatStore.setPendingModel(sendAgent, chatId, preChatModel)
chatStore.clearPreChatModel(sendAgent)
}
- if (wasSendChatVisible) {
+ if (
+ wasSendChatVisible &&
+ sendSelectionIntentRevision !== null &&
+ selectionIntentRevisionRef.current === sendSelectionIntentRevision &&
+ activeChatVisibilityRef.current.selectedAgent === sendAgent &&
+ activeChatVisibilityRef.current.activeChatId === null
+ ) {
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: chatId,
@@ -3370,6 +3423,8 @@ export function useAgentChatController({
},
[
selectedAgent,
+ beginSelectionIntent,
+ clearPendingSelection,
isHostAccessBlocked,
isChatDeleted,
revokeHostAccess,
@@ -3391,6 +3446,7 @@ export function useAgentChatController({
appendAssistantMessage,
appendNewEntry,
bumpActivity,
+ selectionIntentRevisionRef,
]
)
@@ -3575,6 +3631,7 @@ export function useAgentChatController({
} = {}
) => {
if (isHostAccessBlocked(agentName) || (chatId && isChatDeleted(agentName, chatId))) return
+ beginSelectionIntent()
if (options.selectLatest) {
writePendingSelection(agentName, { mode: 'latest', chatId: null })
return
@@ -3608,6 +3665,7 @@ export function useAgentChatController({
},
[
cancelOlderMessagesLoad,
+ beginSelectionIntent,
currentTeamId,
writePendingSelection,
upsertProvisionalEntry,
@@ -3617,6 +3675,7 @@ export function useAgentChatController({
)
const clearActiveChat = useCallback(() => {
+ beginSelectionIntent()
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: null,
@@ -3632,7 +3691,7 @@ export function useAgentChatController({
// error/resend banner so it doesn't bleed into the next active chat.
setAgentError(null)
setFailedAgentSend(null)
- }, [cancelOlderMessagesLoad])
+ }, [beginSelectionIntent, cancelOlderMessagesLoad])
const groupedMessages = useMemo(() => {
const groups: Array<{ role: 'user' | 'assistant' | 'system'; items: AgentChatMessage[] }> = []
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index 154f4f3f9..5fe0fd97d 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -101,6 +101,9 @@ export type PendingChatSelection =
*/
export interface ChatListControllerHost {
switchToChat: (agentRef: string, chatId: string) => Promise<void>
+ beginSelectionIntent: () => number
+ getSelectionIntentRevision: () => number
+ clearPendingSelection: (agentRef: string, preserveSpecificChatId?: string) => void
scrollChatToBottom: () => void
dispatchSession: (chatKey: string, event: SessionFsmEvent) => void
clearComposerDraft: (chatId: string) => void
@@ -504,6 +507,7 @@ export function useChatListController({
const authorityScopeGeneration = authorityScopeGenerationRef.current
const authorityScopeAtRequest = currentAuthorityScopeRef.current
const hostAuthorityEpoch = getHostAuthorityEpoch(agentRef)
+ const selectionIntentRevisionAtRequest = host.current?.getSelectionIntentRevision()
chatListNextCursorByAgentRef.current[agentRef] = null
if (selectedAgentRef.current === agentRef) {
setChatListHasMoreRemoteSessions(false)
@@ -636,6 +640,8 @@ export function useChatListController({
activeChatId !== latestServerSession.chatId &&
serverIsNewerThanSelection &&
currentHost.shouldAutoSelectLatest() &&
+ selectionIntentRevisionAtRequest !== undefined &&
+ currentHost.getSelectionIntentRevision() === selectionIntentRevisionAtRequest &&
!suppressAutoSelection
) {
currentHost.markAutoSelectedChat(latestServerSession.chatId)
@@ -668,6 +674,7 @@ export function useChatListController({
getHostAuthorityEpoch,
isHostAccessBlocked,
onHostAccessRevoked,
+ host,
]
)
@@ -987,9 +994,20 @@ export function useChatListController({
},
[]
)
- const clearPendingSelection = useCallback((agentName: string) => {
- delete pendingChatSelectionByAgentRef.current[agentName]
- }, [])
+ const clearPendingSelection = useCallback(
+ (agentName: string, preserveSpecificChatId?: string) => {
+ const pendingSelection = pendingChatSelectionByAgentRef.current[agentName]
+ // Keep a matching intent for the agent-selection effect when a direct
+ // switch and route change are committed in the same turn.
+ if (
+ pendingSelection?.mode === 'specific' &&
+ pendingSelection.chatId === preserveSpecificChatId
+ )
+ return
+ delete pendingChatSelectionByAgentRef.current[agentName]
+ },
+ []
+ )
const isChatDeleted = useCallback(
(agentRef: string, chatId: string) =>
deletedChatIdsByAgentRef.current.get(agentRef)?.has(chatId) ?? false,
@@ -1001,17 +1019,20 @@ export function useChatListController({
const handleCreateChat = useCallback(async () => {
const agentRef = selectedAgentRef.current
if (!agentRef) return
+ const selectionIntentRevision = host.current?.beginSelectionIntent()
+ host.current?.clearPendingSelection(agentRef)
const requestGeneration = requestGenerationRef.current
const chatId = crypto.randomUUID()
const meta = await chatStore.createChat(agentRef, chatId)
chatStore.clearCachedRemoteData()
- if (
- selectedAgentRef.current !== agentRef ||
- requestGenerationRef.current !== requestGeneration
- ) {
+ if (selectedAgentRef.current !== agentRef || requestGenerationRef.current !== requestGeneration)
return
- }
appendNewEntry(agentRef, meta)
+ if (
+ selectionIntentRevision !== undefined &&
+ host.current?.getSelectionIntentRevision() !== selectionIntentRevision
+ )
+ return
host.current?.markAutoSelectedChat(null)
await host.current?.switchToChat(agentRef, chatId)
host.current?.scrollChatToBottom()