Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
Merge origin/dev into fix/issue-1091-chat-open-latency-v2
Alfredo Lopez1b28c54c4b77
diff --cc desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsxindex d88770196,46fa0f7ae..f6c9deddf--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx@@@ -35,6 -36,11 +36,13 @@@ export interface RenderControllerResul}}+ export interface RenderControllerOptions {+ /** Observe committed controller state before its passive effects synchronize refs. */+ onLayoutCommit?: (controller: ReturnType<typeof useAgentChatController>) => void++ /** Called with the controller's return value on every render, for frame-level assertions. */++ onRender?: (controller: ReturnType<typeof useAgentChatController>) => void+ }+/*** Mounts `useAgentChatController` with sensible defaults. Override any param.*@@@ -105,8 -108,15 +110,16 @@@ export function renderControllerhostAuthorityRevision: hostAuthority.revision,...p,} as ControllerParams)- options.onRender?.(value)- return value++ options.onRender?.(controller)+ useLayoutEffect(() => {+ options.onLayoutCommit?.(controller)+ }, [+ controller.activeChatId,+ controller.chatMessages,+ controller.chatMessagesLoading,+ options.onLayoutCommit,+ ])+ return controller},{initialProps: params,diff --cc desktop-app/ui/src/hooks/domain/__tests__/switchToChat.transcriptMemo.test.tsxindex c658c50b7,000000000..5a8b5723amode 100644,000000..100644--- a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.transcriptMemo.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.transcriptMemo.test.tsx@@@ -1,619 -1,0 +1,695 @@@+// @vitest-environment jsdom+/**- * #1091 A9 — reopening a chat renders its remembered transcript at once. The- * disk check and the Host reconcile still run, but the list is never cleared- * behind a spinner while they do. Every case runs for a stateful and a- * stateless Host: the renderer has no branch by Host kind.++ * #1091 A9 — reopening a chat renders its remembered transcript as soon as the++ * selection is persisted (#976 orders the last-active write before any history++ * is shown). The disk check and the Host reconcile still run, but the list is++ * not cleared behind a spinner while they do. Every case runs for a stateful++ * and a stateless Host: the renderer has no branch by Host kind.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { makeTaskKey } from '@contexts/AgentTaskTrackerContext/types'+import { act, cleanup, waitFor } from '@testing-library/react'+import { resetComposerDraftStore } from '@lib/composerDraftStore'+import type { AgentChatMessage } from '../../../uiTypes'+import { deferred } from './__fixtures__/catalogFixtures'+import { type RenderControllerResult, renderController } from './__fixtures__/controllerHarness'+import { ipcGenericForbidden, ipcHostAccessRevoked, ipcHttpError } 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[]+ loading: boolean+}++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)++const turn = (n: number, user: string, response?: string) => ({+ number: n,+ user_input: user,+ response,+ started_at: `2026-05-28T10:0${n}:00Z`,+ completed_at: response ? `2026-05-28T10:0${n}:05Z` : undefined,+})++/** 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),+ loading: value.chatMessagesLoading,+ }),+ }+ )+}++async function settleMount() {+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())+}++async function open(controller: RenderControllerResult, host: string, chatId: string) {+ await act(async () => {+ await controller.result.current.switchToChat(host, chatId)+ })+}++/** Every frame that shows `chatId` shows `messages`, settled. At least one frame must. */+function expectOnlyTranscript(observed: Frame[], chatId: string, messages: AgentChatMessage[]) {+ const shown = observed.filter(frame => frame.activeChatId === chatId)+ expect(shown.length).toBeGreaterThan(0)+ for (const frame of shown) {+ expect(frame).toEqual({ activeChatId: chatId, contents: contentsOf(messages), loading: false })+ }+}++const blankFrame = (observed: Frame[], chatId: string) =>+ observed.some(+ frame => frame.activeChatId === chatId && frame.contents.length === 0 && frame.loading+ )++const lastHostReadChatId = () => clerum.rpc.loadSessionMessages.mock.calls.at(-1)?.[2]++describe('switchToChat transcript memo (#1091 A9)', () => {+ it.each(HOSTS)(+ 'a. %s: reopening a chat shows its transcript while the disk and Host reads are pending',+ async host => {+ const disk = { 'chat-a': transcript('chat-a'), 'chat-b': transcript('chat-b') }+ serveDisk(disk)+ const controller = mount(host)+ await settleMount()+ await open(controller, host, 'chat-a')+ const chatBRead = deferred<AgentChatMessage[]>()+ clerum.chat.loadMessages.mockImplementationOnce(() => chatBRead.promise)+ const firstB = frames.length+ let toB!: Promise<void>+ await act(async () => {+ toB = controller.result.current.switchToChat(host, 'chat-b')+ })+ // Witness: a chat that is not remembered still opens blank behind the spinner.+ expect(blankFrame(frames.slice(firstB), 'chat-b')).toBe(true)+ await act(async () => {+ chatBRead.resolve(disk['chat-b'])+ await toB+ })++ const diskRead = deferred<AgentChatMessage[]>()+ const hostRead = deferred<SessionResult>()+ clerum.chat.loadMessages.mockImplementationOnce(() => diskRead.promise)+ clerum.rpc.loadSessionMessages.mockImplementationOnce(() => hostRead.promise)+ const reopenStart = frames.length+ let reopen!: Promise<void>+ await act(async () => {+ reopen = controller.result.current.switchToChat(host, 'chat-a')+ })+ expect(clerum.chat.loadMessages).toHaveBeenLastCalledWith(host, 'chat-a', 80, undefined)+ expectOnlyTranscript(frames.slice(reopenStart), 'chat-a', disk['chat-a'])++ await act(async () => {+ diskRead.resolve(disk['chat-a'])+ })+ await waitFor(() => expect(lastHostReadChatId()).toBe('chat-a'))+ // The Host read (a wake on a suspended stateless Host) is still pending.+ expectOnlyTranscript(frames.slice(reopenStart), 'chat-a', disk['chat-a'])++ await act(async () => {+ hostRead.resolve({ agent: host, chatId: 'chat-a', state: 'idle', turns: [] })+ await reopen+ })+ expectOnlyTranscript(frames.slice(reopenStart), 'chat-a', disk['chat-a'])+ }+ )++ it.each(HOSTS)(+ 'b. %s: a reply persisted while the chat was hidden replaces the remembered transcript',+ async host => {+ const disk = { 'chat-a': transcript('chat-a'), 'chat-b': transcript('chat-b') }+ serveDisk(disk)+ const controller = mount(host)+ await settleMount()+ await open(controller, host, 'chat-a')+ await open(controller, host, 'chat-b')+ const remembered = disk['chat-a']+ disk['chat-a'] = transcript('chat-a', 3)++ const diskRead = deferred<AgentChatMessage[]>()+ clerum.chat.loadMessages.mockImplementationOnce(() => diskRead.promise)+ const reopenStart = frames.length+ let reopen!: Promise<void>+ await act(async () => {+ reopen = controller.result.current.switchToChat(host, 'chat-a')+ })+ expectOnlyTranscript(frames.slice(reopenStart), 'chat-a', remembered)++ await act(async () => {+ diskRead.resolve(disk['chat-a'])+ await reopen+ })+ expect(contentsOf(controller.result.current.chatMessages)).toEqual(contentsOf(disk['chat-a']))+ expect(blankFrame(frames.slice(reopenStart), 'chat-a')).toBe(false)+ }+ )++ it.each(HOSTS)(+ 'b3. %s: a full disk page of the same length but shifted by a new reply replaces the remembered transcript',+ async host => {+ const disk = { 'chat-a': transcript('chat-a', 80), 'chat-b': transcript('chat-b') }+ serveDisk(disk)+ const controller = mount(host)+ await settleMount()+ await open(controller, host, 'chat-a')+ await open(controller, host, 'chat-b')+ const remembered = disk['chat-a']+ // One reply persisted while A was hidden: the newest page keeps its+ // length (80) but starts one message later.+ disk['chat-a'] = transcript('chat-a', 81)+ const shiftedPage = disk['chat-a'].slice(-80)+ expect(shiftedPage).toHaveLength(remembered.length)++ const diskRead = deferred<AgentChatMessage[]>()+ clerum.chat.loadMessages.mockImplementationOnce(() => diskRead.promise)+ const reopenStart = frames.length+ let reopen!: Promise<void>+ await act(async () => {+ reopen = controller.result.current.switchToChat(host, 'chat-a')+ })+ // Witness: the reopen painted the remembered transcript first.+ expectOnlyTranscript(frames.slice(reopenStart), 'chat-a', remembered)++ await act(async () => {+ diskRead.resolve(shiftedPage)+ await reopen+ })+ expect(contentsOf(controller.result.current.chatMessages)).toEqual(contentsOf(shiftedPage))+ }+ )++ it.each(HOSTS)(+ 'b2. %s: an empty disk page (a tombstone this session has not loaded) drops the remembered transcript',+ async host => {+ const disk = { 'chat-a': transcript('chat-a'), 'chat-b': transcript('chat-b') }+ serveDisk(disk)+ const controller = mount(host)+ await settleMount()+ await open(controller, host, 'chat-a')+ await open(controller, host, 'chat-b')+ // `ChatStore.loadMessages` returns [] once the index carries a tombstone+ // for the chat; the renderer's deleted-chat set has not been refreshed.+ disk['chat-a'] = []++ const diskRead = deferred<AgentChatMessage[]>()+ clerum.chat.loadMessages.mockImplementationOnce(() => diskRead.promise)+ const reopenStart = frames.length+ let reopen!: Promise<void>+ await act(async () => {+ reopen = controller.result.current.switchToChat(host, 'chat-a')+ })+ // Witnesses: the reopen was a memo hit and it read the disk page.+ expectOnlyTranscript(frames.slice(reopenStart), 'chat-a', transcript('chat-a'))+ expect(clerum.chat.loadMessages).toHaveBeenLastCalledWith(host, 'chat-a', 80, undefined)+ await act(async () => {+ diskRead.resolve([])+ await reopen+ })+ expect(controller.result.current.chatMessages).toEqual([])++ await open(controller, host, 'chat-b')+ const againStart = frames.length+ const chatARead = deferred<AgentChatMessage[]>()+ clerum.chat.loadMessages.mockImplementationOnce(() => chatARead.promise)+ let again!: Promise<void>+ await act(async () => {+ again = controller.result.current.switchToChat(host, 'chat-a')+ })+ // The entry is gone: the next open is blank behind the spinner, not remembered.+ expect(blankFrame(frames.slice(againStart), 'chat-a')).toBe(true)+ await act(async () => {+ chatARead.resolve([])+ await again+ })+ }+ )++ it.each(HOSTS)(+ 'b4. %s: a failed disk read keeps the remembered transcript instead of treating it as a tombstone',+ async host => {+ const disk = { 'chat-a': transcript('chat-a'), 'chat-b': transcript('chat-b') }+ serveDisk(disk)+ const controller = mount(host)+ await settleMount()+ await open(controller, host, 'chat-a')+ await open(controller, host, 'chat-b')+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)+ const newestPageReads = () =>+ clerum.chat.loadMessages.mock.calls.filter(+ ([, chatId, limit, offset]) => chatId === 'chat-a' && limit === 80 && offset === undefined+ ).length+ const readsBefore = newestPageReads()+ clerum.chat.loadMessages.mockImplementationOnce(() =>+ Promise.reject(new Error('EIO: newest chat page unreadable'))+ )++ const reopenStart = frames.length+ await open(controller, host, 'chat-a')+ // Witnesses: the reopen read the newest disk page and that read failed.+ expect(newestPageReads()).toBeGreaterThan(readsBefore)+ expect(warn).toHaveBeenCalledWith(+ '[chat-history] failed to load local messages',+ expect.objectContaining({ agentRef: host, chatId: 'chat-a' })+ )+ expectOnlyTranscript(frames.slice(reopenStart), 'chat-a', disk['chat-a'])++ // The entry survived the failed read: the next reopen is still remembered.+ await open(controller, host, 'chat-b')+ const chatARead = deferred<AgentChatMessage[]>()+ clerum.chat.loadMessages.mockImplementationOnce(() => chatARead.promise)+ const againStart = frames.length+ let again!: Promise<void>+ await act(async () => {+ again = controller.result.current.switchToChat(host, 'chat-a')+ })+ expectOnlyTranscript(frames.slice(againStart), 'chat-a', disk['chat-a'])+ await act(async () => {+ chatARead.resolve(disk['chat-a'])+ await again+ })+ }+ )++ it.each(HOSTS)(+ 'c. %s: when the disk page matches, the remembered list and paging offset are kept',+ async host => {+ const disk = { 'chat-a': transcript('chat-a', 81), 'chat-b': transcript('chat-b') }+ serveDisk(disk)+ const controller = mount(host)+ await settleMount()+ await open(controller, host, 'chat-a')+ const shown = controller.result.current.chatMessages+ expect(shown).toHaveLength(80)+ expect(controller.result.current.hasOlderMessages).toBe(true)+ await open(controller, host, 'chat-b')++ await open(controller, host, 'chat-a')+ expect(controller.result.current.chatMessages).toBe(shown)+ expect(controller.result.current.hasOlderMessages).toBe(true)+ // The probe for older local messages ran on the first open only.+ const olderProbes = clerum.chat.loadMessages.mock.calls.filter(+ ([, chatId, limit, offset]) => chatId === 'chat-a' && limit === 1 && offset === 80+ )+ expect(olderProbes).toHaveLength(1)++ await act(async () => {+ await controller.result.current.handleLoadOlderMessages()+ })+ expect(clerum.chat.loadMessages).toHaveBeenLastCalledWith(host, 'chat-a', 80, 80)+ expect(contentsOf(controller.result.current.chatMessages)).toEqual(contentsOf(disk['chat-a']))+ }+ )++ it.each(HOSTS)(+ 'd. %s: a reopen from memory still re-fetches the newest turn and shows its completed answer',+ async host => {+ const question = {+ id: 'turn-1-user',+ role: 'user' as const,+ content: 'q',+ timestamp: 1,+ serverTurnNumber: 1,+ }+ serveDisk({ 'chat-a': [question], 'chat-b': transcript('chat-b') })+ let chatAReads = 0+ clerum.rpc.loadSessionMessages.mockImplementation(+ async (_hostRef: string, _agent: string, chatId: string) => {+ if (chatId !== 'chat-a') return { agent: host, chatId, state: 'idle', turns: [] }+ chatAReads += 1+ return {+ agent: host,+ chatId,+ state: 'idle',+ totalTurns: 1,+ turns: [chatAReads === 1 ? turn(1, 'q') : turn(1, 'q', 'completed answer')],+ }+ }+ )+ const controller = mount(host)+ await settleMount()+ await open(controller, host, 'chat-a')+ expect(contentsOf(controller.result.current.chatMessages)).toEqual(['q'])+ await open(controller, host, 'chat-b')++ const reopenStart = frames.length+ await open(controller, host, 'chat-a')+ expect(chatAReads).toBe(2)+ expect(clerum.rpc.loadSessionMessages).toHaveBeenLastCalledWith(+ host,+ host,+ 'chat-a',+ undefined,+ { limit: 40, afterTurn: 0 }+ )+ expect(contentsOf(controller.result.current.chatMessages)).toEqual(['q', 'completed answer'])+ expect(blankFrame(frames.slice(reopenStart), 'chat-a')).toBe(false)+ }+ )++ const invalidations = [+ ['no invalidating event (control), reopening is served from memory', 'none', false],+ ['a team change, reopening opens blank', 'team', true],+ ['a logout and login, reopening opens blank', 'logout', true],+ ['resetChat, reopening opens blank', 'reset', true],+ ['a confirmed revocation of the Host, reopening opens blank', 'revoked', true],+ ['an uncertain hold of the Host, reopening opens blank', 'uncertain', true],+ ] as const+ describe.each(HOSTS)('e. %s', host => {+ it.each(invalidations)('after %s', async (_label, event, expectBlank) => {+ const disk = { 'chat-a': transcript('chat-a'), 'chat-b': transcript('chat-b') }+ serveDisk(disk)+ const controller = mount(host)+ await settleMount()+ await open(controller, host, 'chat-a')+ if (event === 'revoked' || event === 'uncertain') {+ const denial =+ event === 'revoked'+ ? await ipcHostAccessRevoked('rpc:loadSessionMessages')+ : await ipcGenericForbidden('rpc:loadSessionMessages')+ clerum.rpc.loadSessionMessages.mockImplementationOnce(async () => {+ throw denial+ })+ }+ await open(controller, host, 'chat-b')+ if (event === 'team') {+ act(() => controller.rerender({ currentTeamId: 'team-2', chatAuthorityTeamId: 'team-2' }))+ act(() => controller.rerender({ currentTeamId: 'team-1', chatAuthorityTeamId: 'team-1' }))+ } else if (event === 'logout') {+ act(() => controller.rerender({ isAuthenticated: false }))+ act(() => controller.rerender({ isAuthenticated: true }))+ } else if (event === 'reset') {+ act(() => controller.result.current.resetChat())+ } else if (event === 'revoked' || event === 'uncertain') {+ // Witness: the denial reached the Host authority.+ expect(controller.hostAuthority.isBlocked(host)).toBe(true)+ controller.hostAuthority.release(host)+ expect(controller.hostAuthority.isBlocked(host)).toBe(false)+ }++ const diskRead = deferred<AgentChatMessage[]>()+ clerum.chat.loadMessages.mockImplementationOnce(() => diskRead.promise)+ const reopenStart = frames.length+ let reopen!: Promise<void>+ await act(async () => {+ reopen = controller.result.current.switchToChat(host, 'chat-a')+ })+ expect(clerum.chat.loadMessages).toHaveBeenLastCalledWith(host, 'chat-a', 80, undefined)+ expect(blankFrame(frames.slice(reopenStart), 'chat-a')).toBe(expectBlank)+ await act(async () => {+ diskRead.resolve(disk['chat-a'])+ await reopen+ })+ expect(contentsOf(controller.result.current.chatMessages)).toEqual(contentsOf(disk['chat-a']))+ })+ })++ it.each(HOSTS)(+ "f. %s: returning to A before B's disk read resolves keeps A on screen",+ async host => {+ const disk = { 'chat-a': transcript('chat-a'), 'chat-b': transcript('chat-b') }+ serveDisk(disk)+ const controller = mount(host)+ await settleMount()+ await open(controller, host, 'chat-a')++ const chatBRead = deferred<AgentChatMessage[]>()+ clerum.chat.loadMessages.mockImplementationOnce(() => chatBRead.promise)+ let toB!: Promise<void>+ await act(async () => {+ toB = controller.result.current.switchToChat(host, 'chat-b')+ })+ expect(clerum.chat.loadMessages).toHaveBeenLastCalledWith(host, 'chat-b', 80, undefined)+ const chatARead = deferred<AgentChatMessage[]>()+ clerum.chat.loadMessages.mockImplementationOnce(() => chatARead.promise)+ const backToA = frames.length+ let toA!: Promise<void>+ await act(async () => {+ toA = controller.result.current.switchToChat(host, 'chat-a')+ })+ expectOnlyTranscript(frames.slice(backToA), 'chat-a', disk['chat-a'])++ let chatBSettled = false+ await act(async () => {+ chatBRead.resolve(disk['chat-b'])+ await toB.then(() => {+ chatBSettled = true+ })+ })+ // Witness: B's late read did resolve while A was visible.+ expect(chatBSettled).toBe(true)+ expectOnlyTranscript(frames.slice(backToA), 'chat-a', disk['chat-a'])+ await act(async () => {+ chatARead.resolve(disk['chat-a'])+ await toA+ })+ expect(controller.result.current.activeChatId).toBe('chat-a')+ expectOnlyTranscript(frames.slice(backToA), 'chat-a', disk['chat-a'])+ }+ )++ it.each(HOSTS)(+ 'i. %s: a transcript that changes during an uncertain hold is not remembered after release',+ async host => {+ const otherHost = 'other-host'+ const disk = { 'chat-a': transcript('chat-a', 81), 'chat-b': transcript('chat-b') }+ serveDisk(disk)+ const controller = mount(host, { agentNames: [host, otherHost] })+ await settleMount()+ await open(controller, host, 'chat-a')+ await open(controller, host, 'chat-b')+ const denial = await ipcGenericForbidden('rpc:loadSessionMessages')+ clerum.rpc.loadSessionMessages.mockImplementationOnce(async () => {+ throw denial+ })+ await open(controller, host, 'chat-a')+ // Witness: the reconcile's denial put the Host on an uncertain hold with A visible.+ expect(controller.hostAuthority.isBlocked(host)).toBe(true)+ expect(controller.result.current.activeChatId).toBe('chat-a')+ expect(controller.result.current.chatMessages).toHaveLength(80)++ // The user pages older messages while the Host is held.+ await act(async () => {+ await controller.result.current.handleLoadOlderMessages()+ })+ expect(controller.result.current.chatMessages).toHaveLength(81)++ act(() => controller.rerender({ selectedAgent: otherHost, agentNames: [host, otherHost] }))+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalledWith(otherHost))+ controller.hostAuthority.release(host)+ expect(controller.hostAuthority.isBlocked(host)).toBe(false)+ // The other Host opens a chat, as the chat route does on selection.+ await open(controller, otherHost, 'chat-o')++ const diskRead = deferred<AgentChatMessage[]>()+ clerum.chat.loadMessages.mockImplementationOnce(() => diskRead.promise)+ const returnStart = frames.length+ act(() => controller.result.current.setPendingChatSelection(host, 'chat-a'))+ act(() => controller.rerender({ selectedAgent: host, agentNames: [host, otherHost] }))+ // Witness: the reopen after release reads the disk page.+ await waitFor(() =>+ expect(clerum.chat.loadMessages).toHaveBeenLastCalledWith(host, 'chat-a', 80, undefined)+ )+ expect(blankFrame(frames.slice(returnStart), 'chat-a')).toBe(true)+ await act(async () => {+ diskRead.resolve(disk['chat-a'].slice(-80))+ })+ await waitFor(() => expect(controller.result.current.chatMessages).toHaveLength(80))+ }+ )++ it.each(HOSTS)(+ '%s: a failed reconcile while the Host wakes keeps the remembered transcript and holds nothing',+ async host => {+ const disk = { 'chat-a': transcript('chat-a'), 'chat-b': transcript('chat-b') }+ serveDisk(disk)+ const onHostAccessRevoked = vi.fn()+ const onHostAuthorityUncertain = vi.fn()+ const controller = mount(host, {+ onHostAccessRevoked,+ onHostAuthorityUncertain,+ isHostAccessBlocked: () => false,+ })+ await settleMount()+ await open(controller, host, 'chat-a')++ const unavailable = await ipcHttpError(+ 'rpc:loadSessionMessages',+ 503,+ 'Service Unavailable',+ {+ code: 'host_waking',+ }+ )+ const notFound = await ipcHttpError('rpc:loadSessionMessages', 404, 'Not Found', {+ error: 'not found',+ })+ const chatAReads = () =>+ clerum.rpc.loadSessionMessages.mock.calls.filter(call => call[2] === 'chat-a').length+ for (const failure of [unavailable, notFound]) {+ await open(controller, host, 'chat-b')+ const readsBefore = chatAReads()+ // Every read of A fails while the Host wakes, including the reconcile's retries.+ clerum.rpc.loadSessionMessages.mockImplementation(+ async (_hostRef: string, _agent: string, chatId: string) => {+ if (chatId === 'chat-a') throw failure+ return { agent: host, chatId, state: 'idle', turns: [] }+ }+ )+ const reopenStart = frames.length+ await open(controller, host, 'chat-a')+ // Witness: the reconcile did reach the Host and fail.+ expect(chatAReads()).toBeGreaterThan(readsBefore)+ expectOnlyTranscript(frames.slice(reopenStart), 'chat-a', disk['chat-a'])+ }+ await waitFor(() =>+ expect(+ controller.result.current.sessionFsmStore.getState(makeTaskKey(host, 'chat-a'))?.phase+ ).toBe('offline')+ )+ expect(onHostAccessRevoked).not.toHaveBeenCalled()+ expect(onHostAuthorityUncertain).not.toHaveBeenCalled()++ // A third reopen is still served from memory.+ await open(controller, host, 'chat-b')+ const diskRead = deferred<AgentChatMessage[]>()+ clerum.chat.loadMessages.mockImplementationOnce(() => diskRead.promise)+ const reopenStart = frames.length+ let reopen!: Promise<void>+ await act(async () => {+ reopen = controller.result.current.switchToChat(host, 'chat-a')+ })+ expectOnlyTranscript(frames.slice(reopenStart), 'chat-a', disk['chat-a'])+ await act(async () => {+ diskRead.resolve(disk['chat-a'])+ await reopen+ })+ }+ )++++ it.each(HOSTS)(++ 'j. %s: the remembered transcript appears only after the selection is persisted',++ async host => {++ const disk = { 'chat-a': transcript('chat-a'), 'chat-b': transcript('chat-b') }++ serveDisk(disk)++ const controller = mount(host)++ await settleMount()++ await open(controller, host, 'chat-a')++ await open(controller, host, 'chat-b')++++ const persisted = deferred<void>()++ const diskRead = deferred<AgentChatMessage[]>()++ clerum.chat.setLastActive.mockImplementationOnce(() => persisted.promise)++ clerum.chat.loadMessages.mockImplementationOnce(() => diskRead.promise)++ const readsBefore = clerum.chat.loadMessages.mock.calls.length++ const reopenStart = frames.length++ let reopen!: Promise<void>++ await act(async () => {++ reopen = controller.result.current.switchToChat(host, 'chat-a')++ })++ // While the last-active write is pending (#976): blank, spinner, no disk read.++ expect(clerum.chat.setLastActive).toHaveBeenLastCalledWith(host, 'chat-a')++ expect(clerum.chat.loadMessages.mock.calls.length).toBe(readsBefore)++ expect(frames.at(-1)).toEqual({ activeChatId: 'chat-a', contents: [], loading: true })++++ const persistedAt = frames.length++ await act(async () => {++ persisted.resolve()++ })++ // Persisted: the remembered transcript replaces the spinner before the disk page.++ expect(clerum.chat.loadMessages).toHaveBeenLastCalledWith(host, 'chat-a', 80, undefined)++ expectOnlyTranscript(frames.slice(persistedAt), 'chat-a', disk['chat-a'])++ expect(blankFrame(frames.slice(reopenStart), 'chat-a')).toBe(true)++++ await act(async () => {++ diskRead.resolve(disk['chat-a'])++ await reopen++ })++ expectOnlyTranscript(frames.slice(persistedAt), 'chat-a', disk['chat-a'])++ }++ )++++ it.each(HOSTS)(++ 'k. %s: a failed last-active write never shows the remembered transcript',++ async host => {++ const disk = { 'chat-a': transcript('chat-a'), 'chat-b': transcript('chat-b') }++ serveDisk(disk)++ const controller = mount(host)++ await settleMount()++ await open(controller, host, 'chat-a')++ await open(controller, host, 'chat-b')++++ clerum.chat.setLastActive.mockImplementationOnce(async () => {++ throw new Error('last-active write failed')++ })++ const onCurrentError = vi.fn()++ const readsBefore = clerum.chat.loadMessages.mock.calls.length++ const reopenStart = frames.length++ await act(async () => {++ await controller.result.current++ .switchToChat(host, 'chat-a', { onCurrentError })++ .catch(() => undefined)++ })++ // Witness: the selection reached the write and reported its failure.++ expect(clerum.chat.setLastActive).toHaveBeenLastCalledWith(host, 'chat-a')++ expect(onCurrentError).toHaveBeenCalledTimes(1)++ expect(clerum.chat.loadMessages.mock.calls.length).toBe(readsBefore)++ const shownA = frames.slice(reopenStart).filter(frame => frame.activeChatId === 'chat-a')++ expect(shownA.length).toBeGreaterThan(0)++ for (const frame of shownA) expect(frame.contents).toEqual([])++ expect(controller.result.current.chatMessages).toEqual([])++ expect(controller.result.current.chatMessagesLoading).toBe(false)++ }++ )+})diff --cc desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex 5cdc3c755,a78ce8f4c..65e0533fc--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@@ -630,73 -653,10 +663,75 @@@ export function useAgentChatController(navItem,selectedAgent,})+ // #1091 A9: per-mount, like the FSM store, so test renders stay isolated.+ const transcriptMemoRef = useRef<ReturnType<typeof createTranscriptMemo> | null>(null)+ if (!transcriptMemoRef.current) {+ transcriptMemoRef.current = createTranscriptMemo(TRANSCRIPT_MEMO_LIMITS)+ }+ const transcriptMemo = transcriptMemoRef.current+ const chatTranscriptMemoKey = useCallback(+ (agentRef: string, chatId: string) =>+ transcriptMemoKey(currentAuthScopeRef.current, agentRef, chatId),+ []+ )+ // Every change to the visible transcript (send, stream, hydrate, older page)+ // goes through `chatMessages`, so recording each settled commit keeps the memo+ // current. A commit whose state does not match the visible selection is a+ // transition between chats and is skipped. A held Host or a deleted chat is+ // never recorded: its entry was withdrawn and must not come back on release.+ useEffect(() => {+ if (chatMessagesLoading || !activeChatId || !selectedAgent) return+ if (isHostAccessBlocked(selectedAgent) || isChatDeleted(selectedAgent, activeChatId)) return+ const visible = activeChatVisibilityRef.current+ if (visible.activeChatId !== activeChatId || visible.selectedAgent !== selectedAgent) return+ transcriptMemo.set(chatTranscriptMemoKey(selectedAgent, activeChatId), {+ messages: chatMessages,+ hasOlderMessages,+ loadedLocalMessageCount: loadedLocalMessageCountRef.current,+ })+ }, [+ activeChatId,+ chatMessages,+ chatMessagesLoading,+ chatTranscriptMemoKey,+ hasOlderMessages,+ isChatDeleted,+ isHostAccessBlocked,+ selectedAgent,+ transcriptMemo,+ ])++ const rememberedTranscript = useCallback(+ (agentRef: string, chatId: string): TranscriptMemoEntry | undefined => {+ if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) return undefined+ return transcriptMemo.get(chatTranscriptMemoKey(agentRef, chatId))+ },+ [chatTranscriptMemoKey, isChatDeleted, isHostAccessBlocked, transcriptMemo]+ )++ /** Show a newly selected chat: its remembered transcript, or a blank list with the spinner. */+ const presentSelectedTranscript = useCallback(+ (remembered: TranscriptMemoEntry | undefined) => {+ cancelOlderMessagesLoad()+ if (remembered) {+ chatMessagesRef.current = remembered.messages+ setChatMessages(remembered.messages)+ setChatMessagesLoading(false)+ setHasOlderMessages(remembered.hasOlderMessages)+ loadedLocalMessageCountRef.current = remembered.loadedLocalMessageCount+ return+ }+ setChatMessages([])+ setChatMessagesLoading(true)+ setHasOlderMessages(false)+ loadedLocalMessageCountRef.current = 0+ },- [cancelOlderMessagesLoad]++ [cancelOlderMessagesLoad, setChatMessagesLoading]+ )- 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+ } | null>(null)// Latest `pushToast` for the hoisted tracker callbacks (onTrackerTerminal reads// it) so that `tracker.setCallbacks` can run once (cross-ref D.3 M1) without// closing over a stale toast fn. Assigned in an effect, not the render body@@@ -1021,9 -982,7 +1057,8 @@@// login/logout / team-switch cycles (security review, hygiene).resetReplyNotificationDedupe()chatStore.clearCachedRemoteData()+ transcriptMemo.clear()setChatMessages([])- setChatMessagesLoading(false)setHasOlderMessages(false)cancelOlderMessagesLoad()loadedLocalMessageCountRef.current = 0@@@ -1045,11 -1004,10 +1081,12 @@@// 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) => {- if (isHostAccessBlocked(agentRef)) return- if (isChatDeleted(agentRef, chatId)) {- transcriptMemo.delete(chatTranscriptMemoKey(agentRef, chatId))+ const switchToChatForIntent = useCallback(+ async (agentRef: string, chatId: string, selectionIntentRevision: number) => {- if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) {++ const deleted = isChatDeleted(agentRef, chatId)++ if (deleted) transcriptMemo.delete(chatTranscriptMemoKey(agentRef, chatId))++ if (deleted || isHostAccessBlocked(agentRef)) {+ settleChatMessagesLoading(selectionIntentRevision)return}const key = makeTaskKey(agentRef, chatId)@@@ -1079,140 -1037,129 +1116,154 @@@selectedAgent: agentRef,}setActiveChatId(chatId)- if (!canReuseActiveSwitch) presentSelectedTranscript(remembered)- if (!canReuseActiveSwitch) {- setChatMessages([])- setChatMessagesLoading(true)- setHasOlderMessages(false)- cancelOlderMessagesLoad()- loadedLocalMessageCountRef.current = 0- }++ if (!canReuseActiveSwitch) presentSelectedTranscript(undefined)// 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// into chat B). The Phase-2 reconcile below re-derives state for this chat.setAgentError(null)setFailedAgentSend(null)- // Observe failures immediately while the cache loads, then propagate them- // from this selection's completion, including early returns.- const lastActive = Promise.allSettled([chatStore.setLastActive(agentRef, chatId)])+ await chatStore.setLastActive(agentRef, chatId)+ if (selectionIntentRevisionRef.current !== selectionIntentRevision) return+ if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) {+ settleChatMessagesLoading(selectionIntentRevision)+ return+ }++ unfillableServerGapUpperBoundsRef.current.delete(key)++ // Renderer-local relevance guard for a fast A→B→A switch: THIS switch's+ // reconcile is aborted the moment the user switches away. Passed into+ // `reconcileChat` as a per-call `isRelevant` (replaces the Phase-2+ // AbortController) so a background reconcile — system:resume, or a bell+ // approval on a NON-visible chat — is never subject to an active-chat guard.+ const isStillActive = () => {+ const visible = activeChatVisibilityRef.current+ return (+ !isHostAccessBlocked(agentRef) &&+ activeChatSwitchRequestRef.current === switchRequest &&+ visible.selectedAgent === agentRef &&+ visible.activeChatId === chatId+ )+ }+++ // #1091 A9: once the selection is persisted, show the remembered transcript++ // instead of the blank list while the disk page loads.++ const remembered = canReuseActiveSwitch ? undefined : rememberedTranscript(agentRef, chatId)++ if (remembered) presentSelectedTranscript(remembered)+++ // PHASE 1 — render only the newest local page. The authoritative reconcile- // below requests a delta after the newest cached server turn.- // `setLastActive` above crosses the ChatStore boundary before this ref is- // read, allowing the rendered page's effect to synchronize chatMessagesRef.++ // below requests a delta after the newest cached server turn. A reused++ // switch reads the visible page only when this request rendered it; Phase 1++ // writes chatMessagesRef together with the state it renders.+ const activeLocalPage = activeChatLocalPageRequestRef.current+ const reuseVisibleMessages =+ canReuseActiveSwitch && activeLocalPage?.request === switchRequest+ let cached: Awaited<ReturnType<typeof chatStore.loadMessages>> = []+ let loadedLocalPage = falsetry {- if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) return-- unfillableServerGapUpperBoundsRef.current.delete(key)-- // Renderer-local relevance guard for a fast A→B→A switch: THIS switch's- // reconcile is aborted the moment the user switches away. Passed into- // `reconcileChat` as a per-call `isRelevant` (replaces the Phase-2- // AbortController) so a background reconcile — system:resume, or a bell- // approval on a NON-visible chat — is never subject to an active-chat guard.- const isStillActive = () => {- const visible = activeChatVisibilityRef.current- return (- activeChatSwitchRequestRef.current === switchRequest &&- visible.selectedAgent === agentRef &&- visible.activeChatId === chatId- )+ if (reuseVisibleMessages) {+ cached = [...chatMessagesRef.current] as AgentChatMessage[]+ } else {+ cached = (await chatStore.loadMessages(+ agentRef,+ chatId,+ LOCAL_MESSAGE_PAGE_SIZE+ )) as AgentChatMessage[]}-- // PHASE 1 — render only the newest local page. The authoritative reconcile- // below requests a delta after the newest cached server turn.- let cached: Awaited<ReturnType<typeof chatStore.loadMessages>> = []- let localReadFailed = false- try {- cached = canReuseActiveSwitch- ? ([...chatMessagesRef.current] as AgentChatMessage[])- : ((await chatStore.loadMessages(- agentRef,- chatId,- LOCAL_MESSAGE_PAGE_SIZE- )) as AgentChatMessage[])- } catch (error) {- localReadFailed = true- console.warn('[chat-history] failed to load local messages', { agentRef, chatId, error })+ loadedLocalPage = true+ } catch (error) {+ console.warn('[chat-history] failed to load local messages', { agentRef, chatId, error })+ }- const hasOlderServerMessages =- nextServerBackfillBeforeTurn(cached as AgentChatMessage[]) !== undefined- const hasOlderLocalMessages =- !hasOlderServerMessages &&- cached.length === LOCAL_MESSAGE_PAGE_SIZE &&- (await hasLocalMessagesBeyond(chatStore, agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE))- if (!isStillActive()) return- if (loadedLocalPage && !reuseVisibleMessages) {- activeChatLocalPageRequestRef.current = { request: switchRequest }++ // #1091 A9: the remembered transcript is already on screen. Keep it only++ // when the disk page is its newest part; otherwise the disk page wins,++ // e.g. a reply persisted while the chat was hidden. An empty page also++ // wins: `loadMessages` returns [] for a durably tombstoned chat, which++ // this session may not have loaded into `deletedChatIdsByAgentRef` yet,++ // and recording [] drops the memo entry. A rejected read is not an empty++ // page: it says nothing about the chat, so the remembered transcript++ // stays. The Host reconcile below runs in every case.++ const keepRemembered =++ remembered !== undefined &&++ (!loadedLocalPage ||++ (cached.length > 0 &&++ sameMessageSequence(++ remembered.messages.slice(-cached.length),++ cached as AgentChatMessage[]++ )))++ if (keepRemembered) {++ cached = remembered.messages as typeof cached++ if (!isStillActive()) return++ if (loadedLocalPage) activeChatLocalPageRequestRef.current = { request: switchRequest }++ } else {++ const hasOlderServerMessages =++ nextServerBackfillBeforeTurn(cached as AgentChatMessage[]) !== undefined++ const hasOlderLocalMessages =++ !hasOlderServerMessages &&++ cached.length === LOCAL_MESSAGE_PAGE_SIZE &&++ (await hasLocalMessagesBeyond(chatStore, agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE))++ if (!isStillActive()) return++ if (loadedLocalPage && !reuseVisibleMessages) {++ activeChatLocalPageRequestRef.current = { request: switchRequest }+ }- // #1091 A9: the remembered transcript is already on screen. Keep it only- // when the disk page is its newest part; otherwise the disk page wins,- // e.g. a reply persisted while the chat was hidden. An empty page also- // wins: `loadMessages` returns [] for a durably tombstoned chat, which- // this session may not have loaded into `deletedChatIdsByAgentRef` yet,- // and recording [] drops the memo entry. A rejected read is not an empty- // page: it says nothing about the chat, so the remembered transcript- // stays. The Host reconcile below runs in every case.- const keepRemembered =- remembered !== undefined &&- (localReadFailed ||- (cached.length > 0 &&- sameMessageSequence(- remembered.messages.slice(-cached.length),- cached as AgentChatMessage[]- )))- if (keepRemembered) {- cached = remembered.messages as typeof cached- if (!isStillActive()) return- } else {- const hasOlderServerMessages =- nextServerBackfillBeforeTurn(cached as AgentChatMessage[]) !== undefined- const hasOlderLocalMessages =- !hasOlderServerMessages &&- cached.length === LOCAL_MESSAGE_PAGE_SIZE &&- (await hasLocalMessagesBeyond(chatStore, agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE))- if (!isStillActive()) return- loadedLocalMessageCountRef.current = cached.length- setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)- if (!canReuseActiveSwitch) {- // Hydrate merges onto the ref, so a replaced memo must not linger there.- chatMessagesRef.current = cached as AgentChatMessage[]- setChatMessages(cached as AgentChatMessage[])- }++ loadedLocalMessageCountRef.current = cached.length++ setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)++ if (!reuseVisibleMessages) {++ // Hydrate merges onto the ref, so a replaced memo must not linger there.++ chatMessagesRef.current = cached as AgentChatMessage[]++ setChatMessages(cached as AgentChatMessage[])+ }- // Phase 1 rendered the cache → clear the blocking spinner. The reconcile- // runs under the `syncing` indicator (RECONCILE_STARTED, dispatched by the- // reconcile gate) instead.- setChatMessagesLoading(false)- // 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- // (without it the flag is write-once-true and the badge never reappears) and- // its `clear_unread` effect mirrors the clear to disk+sidebar. The- // unconditional clear below ALSO runs because on a cold reload the FSM flag- // is fresh-`false` while the persisted disk badge is `true` — CHAT_OPENED's- // flag-gated effect wouldn't fire, so the badge must still be cleared here.- dispatchSession(key, { type: 'CHAT_OPENED' })- void chatStore.clearUnreadTerminal(agentRef, chatId)- clearUnreadInList(chatId)- scrollChatToBottom()-- // A deliberate user re-open grants a fresh re-rejoin quota — the cap only- // exists to stop the automatic stream-loss → rejoin loop (P1-stall). A- // capped chat therefore clears its offline banner when reopened + reconciled- // clean.- tracker.resetRejoinAttempts(key)-- // PHASE 2/3 — the single reconcile gate (§4.3) owns fetch+retry, ambiguous 404,- // offline, the SERVER_SNAPSHOT, the idle replace (auto-title / S4 upsert /- // epoch-anchored zombie-ack) and the live rejoin (approval re-seed).- // `taskIdHint` = the pre-await zombie's task, which drives the durable- // getTaskResult fallback + response-file attachment load; the zombie-ack- // itself no longer needs a taskId to match (R2's epoch replaces the old- // `recoveringTaskIdByKeyRef` bookkeeping).- //- // The gate re-reads the same bounded local page inside hydrate so an SSE- // terminal that lands between Phase 1 and reconciliation is included- // without transferring the complete local transcript over IPC. Note- // (best-effort): `reconcileChat` is single-flight per key — if a background- // reconcile is already in flight for THIS key, this call coalesces onto it- // and its `isRelevant`/`taskIdHint` are ignored; `hydrateActiveChatFromServer`'s- // own `isActive()` guard still prevents rendering into the wrong chat.- const zombieBefore = tracker.get(key)- const latestCachedTurn = latestServerTurnNumber(cached as AgentChatMessage[])- const reconcileFromTurn =- latestCachedTurn === undefined ? undefined : Math.max(0, latestCachedTurn - 1)- await reconcileChat(key, {- reason: 'switch_to_chat',- taskIdHint: zombieBefore?.taskId,- isRelevant: isStillActive,- messagesQuery: {- limit: SERVER_TURN_PAGE_SIZE,- ...(reconcileFromTurn !== undefined ? { afterTurn: reconcileFromTurn } : {}),- },- })- } finally {- const [lastActiveResult] = await lastActive- if (lastActiveResult.status === 'rejected') throw lastActiveResult.reason}- loadedLocalMessageCountRef.current = cached.length- setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)- if (!reuseVisibleMessages) setChatMessages(cached as AgentChatMessage[])+ // Phase 1 rendered the cache → clear the blocking spinner. The reconcile+ // runs under the `syncing` indicator (RECONCILE_STARTED, dispatched by the+ // reconcile gate) instead.+ 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+ // (without it the flag is write-once-true and the badge never reappears) and+ // its `clear_unread` effect mirrors the clear to disk+sidebar. The+ // unconditional clear below ALSO runs because on a cold reload the FSM flag+ // is fresh-`false` while the persisted disk badge is `true` — CHAT_OPENED's+ // flag-gated effect wouldn't fire, so the badge must still be cleared here.+ dispatchSession(key, { type: 'CHAT_OPENED' })+ void chatStore.clearUnreadTerminal(agentRef, chatId)+ clearUnreadInList(chatId)+ scrollChatToBottom()++ // A deliberate user re-open grants a fresh re-rejoin quota — the cap only+ // exists to stop the automatic stream-loss → rejoin loop (P1-stall). A+ // capped chat therefore clears its offline banner when reopened + reconciled+ // clean.+ tracker.resetRejoinAttempts(key)++ // PHASE 2/3 — the single reconcile gate (§4.3) owns fetch+retry, ambiguous 404,+ // offline, the SERVER_SNAPSHOT, the idle replace (auto-title / S4 upsert /+ // epoch-anchored zombie-ack) and the live rejoin (approval re-seed).+ // `taskIdHint` = the pre-await zombie's task, which drives the durable+ // getTaskResult fallback + response-file attachment load; the zombie-ack+ // itself no longer needs a taskId to match (R2's epoch replaces the old+ // `recoveringTaskIdByKeyRef` bookkeeping).+ //+ // The gate re-reads the same bounded local page inside hydrate so an SSE+ // terminal that lands between Phase 1 and reconciliation is included+ // without transferring the complete local transcript over IPC. Note+ // (best-effort): `reconcileChat` is single-flight per key — if a background+ // reconcile is already in flight for THIS key, this call coalesces onto it+ // and its `isRelevant`/`taskIdHint` are ignored; `hydrateActiveChatFromServer`'s+ // own `isActive()` guard still prevents rendering into the wrong chat.+ const zombieBefore = tracker.get(key)+ const latestCachedTurn = latestServerTurnNumber(cached as AgentChatMessage[])+ const reconcileFromTurn =+ latestCachedTurn === undefined ? undefined : Math.max(0, latestCachedTurn - 1)+ await reconcileChat(key, {+ reason: 'switch_to_chat',+ taskIdHint: zombieBefore?.taskId,+ isRelevant: isStillActive,+ messagesQuery: {+ limit: SERVER_TURN_PAGE_SIZE,+ ...(reconcileFromTurn !== undefined ? { afterTurn: reconcileFromTurn } : {}),+ },+ })},[currentTeamId,@@@ -1223,11 -1170,8 +1274,12 @@@reconcileChat,scrollChatToBottom,clearUnreadInList,+ rememberedTranscript,+ presentSelectedTranscript,+ transcriptMemo,+ chatTranscriptMemoKey,cancelOlderMessagesLoad,+ settleChatMessagesLoading,chatStore.setLastActive,chatStore.loadMessages,chatStore.clearUnreadTerminal,