Skip to content

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

TypeScript

fix(desktop): track an unconfirmed chat selection explicitly

Alfredo Lopez15e0095614c3
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.provisionalSelection.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.provisionalSelection.test.tsx
new file mode 100644
index 000000000..9d3ecf15c
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.provisionalSelection.test.tsx
@@ -0,0 +1,425 @@
+// @vitest-environment jsdom
+/**
+ * #1091 A17 — a remembered transcript painted on a click is provisional until
+ * its last-active write and first local page settle. Only the click that owns
+ * it confirms or withdraws it; an invalidation withdraws it at once; New chat
+ * restores it; paging and send refuse it. Rows 1, 2 and 4 of the A17 table are
+ * tests j, k and m in `switchToChat.transcriptMemo.test.tsx`; row 14 (blank
+ * path) is #976's `createChatFailure*` suites. Every case runs for a stateful
+ * and a stateless Host.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, waitFor } from '@testing-library/react'
+import {
+ getComposerDraft,
+ resetComposerDraftStore,
+ setComposerDraft,
+} from '@lib/composerDraftStore'
+import type { AgentChatMessage } from '../../../uiTypes'
+import { deferred } from './__fixtures__/catalogFixtures'
+import { type RenderControllerResult, renderController } from './__fixtures__/controllerHarness'
+import { ipcGenericForbidden } from './__fixtures__/ipcErrors'
+import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const HOSTS = ['chatllm', 'chatllm-stateless'] as const
+
+let clerum: MockClerum
+type SessionResult = Awaited<ReturnType<typeof clerum.rpc.loadSessionMessages>>
+
+interface Frame {
+ activeChatId: string | null
+ contents: string[]
+}
+
+let frames: Frame[] = []
+
+beforeEach(() => {
+ frames = []
+ clerum = installMockClerum()
+})
+
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ resetComposerDraftStore()
+ uninstallMockClerum()
+})
+
+function transcript(chatId: string, count = 2): AgentChatMessage[] {
+ return Array.from({ length: count }, (_, index) => ({
+ id: `${chatId}-${index + 1}`,
+ role: index % 2 === 0 ? ('user' as const) : ('assistant' as const),
+ content: `${chatId} message ${index + 1}`,
+ timestamp: index + 1,
+ }))
+}
+
+const contentsOf = (messages: AgentChatMessage[]) => messages.map(message => message.content)
+
+/** The disk cache, paged from the newest message like `ChatStore.loadMessages`. */
+function serveDisk(disk: Record<string, AgentChatMessage[]>) {
+ clerum.chat.loadMessages.mockImplementation(
+ async (_agentRef: string, chatId: string, limit = 80, offset = 0) => {
+ const messages = disk[chatId] ?? []
+ const end = Math.max(0, messages.length - offset)
+ return messages.slice(Math.max(0, end - limit), end)
+ }
+ )
+}
+
+function mount(
+ host: string,
+ overrides: Parameters<typeof renderController>[0] = {}
+): RenderControllerResult {
+ return renderController(
+ { selectedAgent: host, agentNames: [host], ...overrides },
+ {
+ onRender: value =>
+ frames.push({ activeChatId: value.activeChatId, contents: contentsOf(value.chatMessages) }),
+ }
+ )
+}
+
+async function open(controller: RenderControllerResult, host: string, chatId: string) {
+ await act(async () => {
+ await controller.result.current.switchToChat(host, chatId)
+ })
+}
+
+/** Mount, open A then B, so A is remembered; return the controller and the disk. */
+async function rememberA(host: string, aCount = 2) {
+ const disk = { 'chat-a': transcript('chat-a', aCount), 'chat-b': transcript('chat-b') }
+ serveDisk(disk)
+ const controller = mount(host)
+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
+ await open(controller, host, 'chat-a')
+ await open(controller, host, 'chat-b')
+ return { controller, disk }
+}
+
+/** Click A with its last-active write held; the remembered transcript is on screen. */
+async function clickHeld(
+ controller: RenderControllerResult,
+ host: string,
+ options: { onCurrentError?: (error: unknown) => void } = {}
+) {
+ const write = deferred<void>()
+ clerum.chat.setLastActive.mockImplementationOnce(() => write.promise)
+ let click!: Promise<void>
+ await act(async () => {
+ click = controller.result.current.switchToChat(host, 'chat-a', options).catch(() => undefined)
+ })
+ return { write, click }
+}
+
+const chatAReads = () =>
+ clerum.chat.loadMessages.mock.calls.filter(call => call[1] === 'chat-a').length
+
+const shows = (controller: RenderControllerResult) =>
+ contentsOf(controller.result.current.chatMessages)
+
+describe('provisional selection (#1091 A17)', () => {
+ it.each(HOSTS)(
+ '3. %s: double click, first write ok and second fails: blank, one error, no page',
+ async host => {
+ const { controller, disk } = await rememberA(host)
+ const firstError = vi.fn()
+ const secondError = vi.fn()
+ const first = await clickHeld(controller, host, { onCurrentError: firstError })
+ const second = await clickHeld(controller, host, { onCurrentError: secondError })
+ const readsBefore = chatAReads()
+ await act(async () => {
+ first.write.resolve()
+ await first.click
+ })
+ // Witness: the remembered transcript is still up after the superseded write.
+ expect(shows(controller)).toEqual(contentsOf(disk['chat-a']))
+ await act(async () => {
+ second.write.reject(new Error('last-active write failed'))
+ await second.click
+ })
+ expect(controller.result.current.activeChatId).toBe('chat-a')
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(controller.result.current.chatMessagesLoading).toBe(false)
+ expect(secondError).toHaveBeenCalledTimes(1)
+ expect(firstError).not.toHaveBeenCalled()
+ expect(chatAReads()).toBe(readsBefore)
+ }
+ )
+
+ it.each(HOSTS)('5. %s: double click, both writes fail: blank and one error', async host => {
+ const { controller, disk } = await rememberA(host)
+ const firstError = vi.fn()
+ const secondError = vi.fn()
+ const first = await clickHeld(controller, host, { onCurrentError: firstError })
+ const second = await clickHeld(controller, host, { onCurrentError: secondError })
+ const readsBefore = chatAReads()
+ await act(async () => {
+ first.write.reject(new Error('first write failed'))
+ await first.click
+ })
+ // The superseded failure does not withdraw the newer click's transcript.
+ expect(shows(controller)).toEqual(contentsOf(disk['chat-a']))
+ await act(async () => {
+ second.write.reject(new Error('second write failed'))
+ await second.click
+ })
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(secondError).toHaveBeenCalledTimes(1)
+ expect(firstError).not.toHaveBeenCalled()
+ expect(chatAReads()).toBe(readsBefore)
+ })
+
+ it.each(HOSTS)(
+ "6. %s: the first click's pending page never paints after the second click's write fails",
+ async host => {
+ const { controller, disk } = await rememberA(host)
+ const first = await clickHeld(controller, host)
+ const firstPage = deferred<AgentChatMessage[]>()
+ clerum.chat.loadMessages.mockImplementationOnce(() => firstPage.promise)
+ await act(async () => {
+ first.write.resolve()
+ })
+ // Witness: the first click reached its local page read.
+ expect(clerum.chat.loadMessages).toHaveBeenLastCalledWith(host, 'chat-a', 80, undefined)
+ const secondError = vi.fn()
+ const second = await clickHeld(controller, host, { onCurrentError: secondError })
+ await act(async () => {
+ second.write.reject(new Error('last-active write failed'))
+ await second.click
+ })
+ expect(controller.result.current.chatMessages).toEqual([])
+ const withdrawnAt = frames.length
+ const newerPage = transcript('chat-a', 3)
+ let firstSettled = false
+ await act(async () => {
+ firstPage.resolve(newerPage)
+ await first.click.then(() => {
+ firstSettled = true
+ })
+ })
+ expect(firstSettled).toBe(true)
+ expect(secondError).toHaveBeenCalledTimes(1)
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(frames.slice(withdrawnAt).some(frame => frame.contents.length > 0)).toBe(false)
+ // The page differed from the remembered transcript, so it would have painted.
+ expect(contentsOf(newerPage)).not.toEqual(contentsOf(disk['chat-a']))
+ }
+ )
+
+ it.each(HOSTS)(
+ '7. %s: an uncertain hold through a real 403 during the write withdraws at once',
+ async host => {
+ const { controller, disk } = await rememberA(host)
+ // B's Host read is still pending when the user returns to A.
+ const chatBHostRead = deferred<SessionResult>()
+ clerum.rpc.loadSessionMessages.mockImplementationOnce(() => chatBHostRead.promise)
+ let toB!: Promise<void>
+ await act(async () => {
+ toB = controller.result.current.switchToChat(host, 'chat-b').catch(() => undefined)
+ })
+ await waitFor(() =>
+ expect(clerum.rpc.loadSessionMessages.mock.calls.at(-1)?.[2]).toBe('chat-b')
+ )
+ const { write, click } = await clickHeld(controller, host)
+ expect(shows(controller)).toEqual(contentsOf(disk['chat-a']))
+ const readsBefore = chatAReads()
+ const denial = await ipcGenericForbidden('rpc:loadSessionMessages')
+ await act(async () => {
+ chatBHostRead.reject(denial)
+ await toB
+ })
+ // Witness: the denial reached the Host authority through the reconcile.
+ expect(controller.hostAuthority.isBlocked(host)).toBe(true)
+ expect(controller.result.current.chatMessages).toEqual([])
+ await act(async () => {
+ write.resolve()
+ await click
+ })
+ expect(controller.result.current.activeChatId).toBe('chat-a')
+ expect(controller.result.current.chatMessages).toEqual([])
+ expect(controller.result.current.chatMessagesLoading).toBe(false)
+ expect(chatAReads()).toBe(readsBefore)
+ }
+ )
+
+ it.each(HOSTS)(
+ '8. %s: an uncertain hold on another Host keeps the remembered transcript',
+ async host => {
+ const other = 'other-host'
+ const disk = {
+ 'chat-a': transcript('chat-a'),
+ 'chat-x': transcript('chat-x'),
+ }
+ serveDisk(disk)
+ const controller = mount(host, { agentNames: [host, other] })
+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
+ await open(controller, host, 'chat-a')
+ const otherHostRead = deferred<SessionResult>()
+ clerum.rpc.loadSessionMessages.mockImplementationOnce(() => otherHostRead.promise)
+ let toX!: Promise<void>
+ await act(async () => {
+ toX = controller.result.current.switchToChat(other, 'chat-x').catch(() => undefined)
+ })
+ await waitFor(() =>
+ expect(clerum.rpc.loadSessionMessages.mock.calls.at(-1)?.[2]).toBe('chat-x')
+ )
+ const { write, click } = await clickHeld(controller, host)
+ const denial = await ipcGenericForbidden('rpc:loadSessionMessages')
+ await act(async () => {
+ otherHostRead.reject(denial)
+ await toX
+ })
+ // Witness: the other Host is held, this one is not.
+ expect(controller.hostAuthority.isBlocked(other)).toBe(true)
+ expect(controller.hostAuthority.isBlocked(host)).toBe(false)
+ expect(shows(controller)).toEqual(contentsOf(disk['chat-a']))
+ await act(async () => {
+ write.resolve()
+ await click
+ })
+ expect(controller.result.current.activeChatId).toBe('chat-a')
+ expect(shows(controller)).toEqual(contentsOf(disk['chat-a']))
+ }
+ )
+
+ it.each(HOSTS)('9. %s: deleting the chat during the write withdraws it for good', async host => {
+ const { controller, disk } = await rememberA(host)
+ const { write, click } = await clickHeld(controller, host)
+ expect(shows(controller)).toEqual(contentsOf(disk['chat-a']))
+ clerum.chat.delete.mockResolvedValueOnce({ cleanupPending: false })
+ await act(async () => {
+ const deletion = await controller.result.current.captureChatDeleteFence(host)
+ await controller.result.current.handleDeleteChat('chat-a', deletion)
+ })
+ // Witness: the delete reached the store and moved the view off the chat.
+ expect(clerum.chat.delete).toHaveBeenCalledWith(host, 'chat-a', expect.anything())
+ expect(controller.result.current.activeChatId).not.toBe('chat-a')
+ const deletedAt = frames.length
+ await act(async () => {
+ write.resolve()
+ await click
+ })
+ await open(controller, host, 'chat-a')
+ const aContents = contentsOf(disk['chat-a'])
+ expect(
+ frames
+ .slice(deletedAt)
+ .some(frame => frame.contents.some(content => aContents.includes(content)))
+ ).toBe(false)
+ })
+
+ it.each(HOSTS)(
+ '10. %s: a failed New chat during a remembered reopen restores the chat through a fresh switch',
+ async host => {
+ const { controller, disk } = await rememberA(host)
+ // A reply landed on disk while A was hidden.
+ disk['chat-a'] = transcript('chat-a', 3)
+ const { write, click } = await clickHeld(controller, host)
+ const writesBefore = clerum.chat.setLastActive.mock.calls.length
+ const createError = new Error('local chat creation failed')
+ clerum.chat.create.mockRejectedValueOnce(createError)
+ let observed: unknown
+ await act(async () => {
+ await controller.result.current.handleCreateChat().catch(error => {
+ observed = error
+ })
+ })
+ expect(observed).toBe(createError)
+ await waitFor(() => expect(shows(controller)).toEqual(contentsOf(disk['chat-a'])))
+ expect(controller.result.current.activeChatId).toBe('chat-a')
+ // The restore issued its own last-active write and opened the chat.
+ expect(clerum.chat.setLastActive.mock.calls.slice(writesBefore)).toContainEqual([
+ host,
+ 'chat-a',
+ ])
+ expect(clerum.chat.clearUnreadTerminal).toHaveBeenLastCalledWith(host, 'chat-a')
+ await act(async () => {
+ write.resolve()
+ await click
+ })
+ expect(shows(controller)).toEqual(contentsOf(disk['chat-a']))
+ }
+ )
+
+ it.each(HOSTS)(
+ '11. %s: a failed New chat after a newer navigation restores nothing',
+ async host => {
+ const { controller } = await rememberA(host)
+ const { write, click } = await clickHeld(controller, host)
+ const create = deferred<never>()
+ clerum.chat.create.mockImplementationOnce(() => create.promise)
+ let creating!: Promise<unknown>
+ await act(async () => {
+ creating = controller.result.current.handleCreateChat().catch(error => error)
+ })
+ // Witness: the create is in flight.
+ expect(clerum.chat.create).toHaveBeenCalledTimes(1)
+ await open(controller, host, 'chat-b')
+ const navigatedAt = frames.length
+ await act(async () => {
+ create.reject(new Error('local chat creation failed'))
+ await creating
+ write.resolve()
+ await click
+ })
+ expect(controller.result.current.activeChatId).toBe('chat-b')
+ expect(clerum.chat.setLastActive).toHaveBeenLastCalledWith(host, 'chat-b')
+ expect(frames.slice(navigatedAt).every(frame => frame.activeChatId === 'chat-b')).toBe(true)
+ }
+ )
+
+ it.each(HOSTS)(
+ '12. %s: load older is refused while provisional and pages after confirmation',
+ async host => {
+ const { controller } = await rememberA(host, 100)
+ const { write, click } = await clickHeld(controller, host)
+ // Witness: the remembered transcript restored its older-history flag.
+ expect(controller.result.current.hasOlderMessages).toBe(true)
+ const shown = shows(controller)
+ expect(shown).toHaveLength(80)
+ const readsBefore = chatAReads()
+ await act(async () => {
+ await controller.result.current.handleLoadOlderMessages()
+ })
+ expect(chatAReads()).toBe(readsBefore)
+ expect(shows(controller)).toEqual(shown)
+ await act(async () => {
+ write.resolve()
+ await click
+ })
+ await act(async () => {
+ await controller.result.current.handleLoadOlderMessages()
+ })
+ expect(clerum.chat.loadMessages).toHaveBeenLastCalledWith(host, 'chat-a', 80, 80)
+ expect(shows(controller)).toHaveLength(100)
+ }
+ )
+
+ it.each(HOSTS)(
+ '13. %s: send is refused while provisional, keeps the draft, and works after confirmation',
+ async host => {
+ const { controller, disk } = await rememberA(host)
+ const { write, click } = await clickHeld(controller, host)
+ act(() => setComposerDraft('chat-a', 'hello', host))
+ await act(async () => {
+ await controller.result.current.handleSendAgentMessage('hello')
+ })
+ expect(clerum.rpc.invokeHostMessage).not.toHaveBeenCalled()
+ expect(getComposerDraft('chat-a', host)).toBe('hello')
+ expect(shows(controller)).toEqual(contentsOf(disk['chat-a']))
+ await act(async () => {
+ write.resolve()
+ await click
+ })
+ await act(async () => {
+ await controller.result.current.handleSendAgentMessage('hello')
+ })
+ // Liveness: the same send dispatches once the selection is confirmed.
+ expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)
+ expect(shows(controller)).toContain('hello')
+ }
+ )
+})
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index 8f99850d0..d9ac44757 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -17,7 +17,7 @@ import {
buildResponseFileAttachments,
} from '@lib/chatMessageAttachments'
import { runChatSwitchRequest } from '@lib/chatSwitchRequest'
-import type { PendingChatSwitchRequest } from '@lib/chatSwitchRequest.types'
+import type { PendingChatSwitchRequest, ProvisionalSelection } from '@lib/chatSwitchRequest.types'
import { truncateTitle } from '@lib/chatTitle'
import {
clearAllComposerDrafts,
@@ -544,8 +544,49 @@ export function useAgentChatController({
chatMessagesLoadingRef.current = loading
setChatMessagesLoadingState(loading)
}, [])
+ const [hasOlderMessages, setHasOlderMessages] = useState(false)
+ const [olderMessagesLoading, setOlderMessagesLoading] = useState(false)
+ const chatMessagesRef = useRef<AgentChatMessage[]>([])
+ const loadedLocalMessageCountRef = useRef(0)
+ const olderMessagesRequestRef = useRef<symbol | null>(null)
+ const unfillableServerGapUpperBoundsRef = useRef<Map<string, Set<number>>>(new Map())
+
+ const cancelOlderMessagesLoad = useCallback(() => {
+ olderMessagesRequestRef.current = null
+ setOlderMessagesLoading(false)
+ }, [])
+
+ // #1091 A17: a chat shown from memory before its last-active write and first
+ // local page settled. Without the memo this state was the blank view with the
+ // spinner, and every path below relied on that. `revision` is the selection
+ // intent that owns it; a same-row click takes it over.
+ const provisionalSelectionRef = useRef<ProvisionalSelection | null>(null)
+ const provisionalSelectionFor = useCallback((agentRef: string | null, chatId: string | null) => {
+ const selection = provisionalSelectionRef.current
+ return selection &&
+ selection.request === activeChatSwitchRequestRef.current &&
+ selection.agentRef === agentRef &&
+ selection.chatId === chatId
+ ? selection
+ : null
+ }, [])
+ /** Withdraw an unconfirmed transcript: the view returns to what the base showed, blank. */
+ const withdrawProvisionalSelection = useCallback(() => {
+ if (!provisionalSelectionRef.current) return
+ provisionalSelectionRef.current = null
+ // Retire the request so a page an older click already started cannot publish.
+ activeChatSwitchRequestRef.current = null
+ activeChatSwitchKeyRef.current = null
+ activeChatLocalPageRequestRef.current = null
+ cancelOlderMessagesLoad()
+ chatMessagesRef.current = []
+ setChatMessages([])
+ setHasOlderMessages(false)
+ loadedLocalMessageCountRef.current = 0
+ }, [cancelOlderMessagesLoad])
const beginSelectionIntent = useCallback(
(startsHistoryLoad = false) => {
+ if (!startsHistoryLoad) withdrawProvisionalSelection()
selectionIntentRevisionRef.current += 1
if (!startsHistoryLoad) {
setChatMessagesLoading(false)
@@ -554,7 +595,7 @@ export function useAgentChatController({
}
return selectionIntentRevisionRef.current
},
- [setChatMessagesLoading]
+ [setChatMessagesLoading, withdrawProvisionalSelection]
)
const settleChatMessagesLoading = useCallback(
(selectionIntentRevision: number) => {
@@ -564,17 +605,6 @@ export function useAgentChatController({
},
[setChatMessagesLoading]
)
- const [hasOlderMessages, setHasOlderMessages] = useState(false)
- const [olderMessagesLoading, setOlderMessagesLoading] = useState(false)
- const chatMessagesRef = useRef<AgentChatMessage[]>([])
- const loadedLocalMessageCountRef = useRef(0)
- const olderMessagesRequestRef = useRef<symbol | null>(null)
- const unfillableServerGapUpperBoundsRef = useRef<Map<string, Set<number>>>(new Map())
-
- const cancelOlderMessagesLoad = useCallback(() => {
- olderMessagesRequestRef.current = null
- setOlderMessagesLoading(false)
- }, [])
const ignoredServerGapUpperBounds = useCallback((agentRef: string, chatId: string) => {
return unfillableServerGapUpperBoundsRef.current.get(makeTaskKey(agentRef, chatId))
@@ -1116,30 +1146,22 @@ export function useAgentChatController({
selectedAgent: agentRef,
}
setActiveChatId(chatId)
- // #1091 A9: a remembered transcript is shown at once; without one the
- // view is blank with the spinner. History is still read only after the
- // last-active write below, and the remembered transcript is withdrawn
- // when that write fails or the chat stops being viewable meanwhile.
+ // #1091 A9/A17: a remembered transcript is shown at once and stays
+ // provisional until the last-active write and the first local page below
+ // settle; without one the view is blank with the spinner. History is read
+ // only after the write.
const remembered = canReuseActiveSwitch ? undefined : rememberedTranscript(agentRef, chatId)
- if (!canReuseActiveSwitch) presentSelectedTranscript(remembered)
- // Clears the remembered transcript while this selection intent still owns
- // the visible chat; a newer click on the same row owns it from then on.
- const withdrawRemembered = () => {
- const view = activeChatVisibilityRef.current
- if (
- !remembered ||
- selectionIntentRevisionRef.current !== selectionIntentRevision ||
- view.selectedAgent !== agentRef ||
- view.activeChatId !== chatId
- ) {
- return
- }
- cancelOlderMessagesLoad()
- chatMessagesRef.current = []
- setChatMessages([])
- setHasOlderMessages(false)
- loadedLocalMessageCountRef.current = 0
+ if (!canReuseActiveSwitch) {
+ presentSelectedTranscript(remembered)
+ provisionalSelectionRef.current = remembered
+ ? { request: switchRequest, revision: selectionIntentRevision, agentRef, chatId }
+ : null
+ } else if (provisionalSelectionRef.current?.request === switchRequest) {
+ provisionalSelectionRef.current.revision = selectionIntentRevision
}
+ const ownsProvisionalSelection = () =>
+ provisionalSelectionRef.current?.request === switchRequest &&
+ provisionalSelectionRef.current.revision === selectionIntentRevision
// The error/resend banner is per-chat view state, not global: clear it on
// every chat switch (same-agent switches don't trip the selectedAgent
// cleanup effect, so without this a stream error from chat A would bleed
@@ -1149,10 +1171,15 @@ export function useAgentChatController({
try {
await chatStore.setLastActive(agentRef, chatId)
} catch (error) {
- withdrawRemembered()
+ if (ownsProvisionalSelection()) withdrawProvisionalSelection()
throw error
}
- if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) withdrawRemembered()
+ if (
+ (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) &&
+ ownsProvisionalSelection()
+ ) {
+ withdrawProvisionalSelection()
+ }
if (selectionIntentRevisionRef.current !== selectionIntentRevision) return
if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) {
settleChatMessagesLoading(selectionIntentRevision)
@@ -1240,7 +1267,8 @@ export function useAgentChatController({
}
// Phase 1 rendered the cache → clear the blocking spinner. The reconcile
// runs under the `syncing` indicator (RECONCILE_STARTED, dispatched by the
- // reconcile gate) instead.
+ // reconcile gate) instead. The selection is confirmed from here on.
+ if (ownsProvisionalSelection()) provisionalSelectionRef.current = null
settleChatMessagesLoading(selectionIntentRevision)
// D.5: opening the chat clears its "completed_unread" badge. CHAT_OPENED
// resets the FSM's `unreadTerminal` flag so a LATER hidden terminal re-marks
@@ -1302,7 +1330,7 @@ export function useAgentChatController({
presentSelectedTranscript,
transcriptMemo,
chatTranscriptMemoKey,
- cancelOlderMessagesLoad,
+ withdrawProvisionalSelection,
settleChatMessagesLoading,
chatStore.setLastActive,
chatStore.loadMessages,
@@ -1401,7 +1429,13 @@ export function useAgentChatController({
dispatchSession,
clearComposerDraft,
getActiveChatId: () => activeChatVisibilityRef.current.activeChatId,
- getChatMessagesLoading: () => chatMessagesLoadingRef.current,
+ getChatSwitchInFlight: () => {
+ const view = activeChatVisibilityRef.current
+ return (
+ chatMessagesLoadingRef.current ||
+ provisionalSelectionFor(view.selectedAgent, view.activeChatId) !== null
+ )
+ },
getAutoSelectedChatId: () => autoSelectedChatIdRef.current,
markAutoSelectedChat: chatId => {
autoSelectedChatIdRef.current = chatId
@@ -1435,6 +1469,8 @@ export function useAgentChatController({
const handleLoadOlderMessages = useCallback(async () => {
if (!selectedAgent || !activeChatId || olderMessagesRequestRef.current) return
+ // An unconfirmed selection is read-only: no history is read before its write.
+ if (provisionalSelectionFor(selectedAgent, activeChatId)) return
const requestAgent = selectedAgent
const requestChatId = activeChatId
const requestScope = sendScopeGeneration.current
@@ -1570,6 +1606,7 @@ export function useAgentChatController({
markServerGapUnfillable,
selectedAgent,
isHostAccessBlocked,
+ provisionalSelectionFor,
tracker,
])
@@ -3125,6 +3162,8 @@ export function useAgentChatController({
// switchToChat) rather than state, which may not have committed yet.
const currentChatId = activeChatVisibilityRef.current.activeChatId
if (currentChatId && isChatDeleted(selectedAgent, currentChatId)) return
+ // An unconfirmed selection is read-only; the draft stays in the composer.
+ if (currentChatId && provisionalSelectionFor(selectedAgent, currentChatId)) return
if (currentChatId && tracker.get(makeTaskKey(selectedAgent, currentChatId))) return
if (agentSendInFlightRef.current) return
const sendAgent = selectedAgent
@@ -3857,6 +3896,7 @@ export function useAgentChatController({
clearPendingSelection,
isHostAccessBlocked,
isChatDeleted,
+ provisionalSelectionFor,
revokeHostAccess,
holdHostAccess,
composerImageAttachments,
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index 2099b2f52..061ca1023 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -114,7 +114,8 @@ export interface ChatListControllerHost {
dispatchSession: (chatKey: string, event: SessionFsmEvent) => void
clearComposerDraft: (chatId: string) => void
getActiveChatId: () => string | null
- getChatMessagesLoading: () => boolean
+ /** True while a chat switch is unconfirmed: its history is loading, or a remembered transcript is shown before its last-active write settles. */
+ getChatSwitchInFlight: () => boolean
getAutoSelectedChatId: () => string | null
markAutoSelectedChat: (chatId: string | null) => void
shouldAutoSelectLatest: () => boolean
@@ -1051,7 +1052,7 @@ export function useChatListController({
if (!agentRef) return
const pendingSelection = readPendingSelection(agentRef)
const activeChatIdAtCreate = host.current?.getActiveChatId() ?? null
- const chatMessagesLoadingAtCreate = host.current?.getChatMessagesLoading() ?? false
+ const chatSwitchInFlightAtCreate = host.current?.getChatSwitchInFlight() ?? false
const selectionIntentRevision = host.current?.beginSelectionIntent()
host.current?.clearPendingSelection(agentRef)
const requestGeneration = requestGenerationRef.current
@@ -1077,7 +1078,7 @@ export function useChatListController({
const restoreChatId =
pendingSelection?.mode === 'specific'
? pendingSelection.chatId
- : chatMessagesLoadingAtCreate
+ : chatSwitchInFlightAtCreate
? activeChatIdAtCreate
: null
if (restoreChatId) {
diff --git a/desktop-app/ui/src/lib/chatSwitchRequest.types.ts b/desktop-app/ui/src/lib/chatSwitchRequest.types.ts
index 563971d80..534f68ec7 100644
--- a/desktop-app/ui/src/lib/chatSwitchRequest.types.ts
+++ b/desktop-app/ui/src/lib/chatSwitchRequest.types.ts
@@ -6,3 +6,13 @@ export interface PendingChatSwitchRequest {
state: 'pending' | 'fulfilled' | 'rejected'
promise: Promise<void>
}
+
+/** A chat shown from memory whose last-active write and first local page have not settled. */
+export interface ProvisionalSelection {
+ /** The switch request that painted it. */
+ request: symbol
+ /** The selection intent that owns it; a same-row click takes it over. */
+ revision: number
+ agentRef: string
+ chatId: string
+}